@restatedev/agents 0.0.0 → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +672 -2
- package/dist/calls.d.ts +29 -0
- package/dist/calls.d.ts.map +1 -0
- package/dist/calls.js +91 -0
- package/dist/calls.js.map +1 -0
- package/dist/claude/conversation.d.ts +33 -0
- package/dist/claude/conversation.d.ts.map +1 -0
- package/dist/claude/conversation.js +95 -0
- package/dist/claude/conversation.js.map +1 -0
- package/dist/claude/index.d.ts +77 -0
- package/dist/claude/index.d.ts.map +1 -0
- package/dist/claude/index.js +269 -0
- package/dist/claude/index.js.map +1 -0
- package/dist/client.d.ts +81 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +88 -0
- package/dist/client.js.map +1 -0
- package/dist/common.d.ts +261 -0
- package/dist/common.d.ts.map +1 -0
- package/dist/common.js +438 -0
- package/dist/common.js.map +1 -0
- package/dist/deepseek/index.d.ts +68 -0
- package/dist/deepseek/index.d.ts.map +1 -0
- package/dist/deepseek/index.js +363 -0
- package/dist/deepseek/index.js.map +1 -0
- package/dist/deepseek/persistence.d.ts +61 -0
- package/dist/deepseek/persistence.d.ts.map +1 -0
- package/dist/deepseek/persistence.js +224 -0
- package/dist/deepseek/persistence.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/langgraph/checkpointer.d.ts +29 -0
- package/dist/langgraph/checkpointer.d.ts.map +1 -0
- package/dist/langgraph/checkpointer.js +275 -0
- package/dist/langgraph/checkpointer.js.map +1 -0
- package/dist/langgraph/index.d.ts +66 -0
- package/dist/langgraph/index.d.ts.map +1 -0
- package/dist/langgraph/index.js +265 -0
- package/dist/langgraph/index.js.map +1 -0
- package/dist/log.d.ts +29 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +145 -0
- package/dist/log.js.map +1 -0
- package/dist/object.d.ts +169 -0
- package/dist/object.d.ts.map +1 -0
- package/dist/object.js +221 -0
- package/dist/object.js.map +1 -0
- package/dist/opencode/db.d.ts +40 -0
- package/dist/opencode/db.d.ts.map +1 -0
- package/dist/opencode/db.js +161 -0
- package/dist/opencode/db.js.map +1 -0
- package/dist/opencode/index.d.ts +100 -0
- package/dist/opencode/index.d.ts.map +1 -0
- package/dist/opencode/index.js +436 -0
- package/dist/opencode/index.js.map +1 -0
- package/dist/output.d.ts +17 -0
- package/dist/output.d.ts.map +1 -0
- package/dist/output.js +81 -0
- package/dist/output.js.map +1 -0
- package/dist/pi/index.d.ts +89 -0
- package/dist/pi/index.d.ts.map +1 -0
- package/dist/pi/index.js +293 -0
- package/dist/pi/index.js.map +1 -0
- package/dist/pi/storage.d.ts +5 -0
- package/dist/pi/storage.d.ts.map +1 -0
- package/dist/pi/storage.js +41 -0
- package/dist/pi/storage.js.map +1 -0
- package/dist/signals.d.ts +154 -0
- package/dist/signals.d.ts.map +1 -0
- package/dist/signals.js +256 -0
- package/dist/signals.js.map +1 -0
- package/dist/tools.d.ts +158 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +211 -0
- package/dist/tools.js.map +1 -0
- package/dist/webhook.d.ts +71 -0
- package/dist/webhook.d.ts.map +1 -0
- package/dist/webhook.js +102 -0
- package/dist/webhook.js.map +1 -0
- package/package.json +218 -5
- package/src/calls.ts +138 -0
- package/src/claude/README.md +84 -0
- package/src/claude/conversation.ts +114 -0
- package/src/claude/index.ts +364 -0
- package/src/client.ts +176 -0
- package/src/common.ts +550 -0
- package/src/deepseek/README.md +110 -0
- package/src/deepseek/index.ts +464 -0
- package/src/deepseek/persistence.ts +293 -0
- package/src/index.ts +24 -0
- package/src/langgraph/README.md +87 -0
- package/src/langgraph/checkpointer.ts +364 -0
- package/src/langgraph/index.ts +349 -0
- package/src/log.ts +193 -0
- package/src/object.ts +319 -0
- package/src/opencode/README.md +125 -0
- package/src/opencode/db.ts +223 -0
- package/src/opencode/index.ts +559 -0
- package/src/output.ts +95 -0
- package/src/pi/README.md +105 -0
- package/src/pi/index.ts +382 -0
- package/src/pi/storage.ts +65 -0
- package/src/signals.ts +386 -0
- package/src/tools.ts +343 -0
- package/src/webhook.ts +161 -0
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
// DeepSeek Harness agents in Restate virtual objects: the session (the
|
|
2
|
+
// harness's event log) is in the object's database (persistence.ts).
|
|
3
|
+
//
|
|
4
|
+
// const assistant = deepseek.agent({ name: 'assistant', tools: [weather] });
|
|
5
|
+
//
|
|
6
|
+
// or a handler of an object of your own: `handlers: { chat: deepseek.chat() }`,
|
|
7
|
+
// with options for each invocation: `deepseek.chat(async (ctx) => ({ system }))`,
|
|
8
|
+
// or a prompt of your own handler: `deepseek.prompt(ctx, text, options)`
|
|
9
|
+
//
|
|
10
|
+
// The model is `model`, or else MODEL, or else deepseek/deepseek-flash:
|
|
11
|
+
// DeepSeek's (@deepseek-ai/dsh-llm-deepseek-api-key), with DEEPSEEK_API_KEY,
|
|
12
|
+
// or any model pi-ai knows (@deepseek-ai/dsh-llm-pi-ai), with its provider's
|
|
13
|
+
// key: `openai/gpt-6-sol` with OPENAI_API_KEY, say.
|
|
14
|
+
//
|
|
15
|
+
// The handler is not replayed: a retried attempt (a crash, a lost connection)
|
|
16
|
+
// boots the harness again and resumes the session from the stored log.
|
|
17
|
+
// - The harness's session checkpoint policy stores the log before each model
|
|
18
|
+
// request and before each tool body: a tool runs only once its call is
|
|
19
|
+
// stored.
|
|
20
|
+
// - A crash leaves the turn open. Resuming closes it, and gives each tool
|
|
21
|
+
// call that was stored without a result an error result saying its outcome
|
|
22
|
+
// is unknown; the handler then asks the agent to continue. The model sees
|
|
23
|
+
// the unknown outcome: a tool that must not run twice needs a way for the
|
|
24
|
+
// model to name the call it retries (such as a `retryOf` argument).
|
|
25
|
+
// - A tool's error fails the attempt, which Restate retries (the harness
|
|
26
|
+
// would hand it to the model as the tool's result).
|
|
27
|
+
// - A message is answered once per invocation: its message carries the
|
|
28
|
+
// invocation id, and a retried attempt returns the answer of the turn that
|
|
29
|
+
// finished it.
|
|
30
|
+
import * as restate from '@restatedev/sessions';
|
|
31
|
+
import type { Database } from '@restatedev/sessions';
|
|
32
|
+
import { Context } from '@deepseek-ai/cordis';
|
|
33
|
+
import { AgentRegistry } from '@deepseek-ai/dsh-agent';
|
|
34
|
+
import { AgentLoop } from '@deepseek-ai/dsh-agent-loop';
|
|
35
|
+
import * as deepseek from '@deepseek-ai/dsh-llm-deepseek-api-key';
|
|
36
|
+
import * as piAi from '@deepseek-ai/dsh-llm-pi-ai';
|
|
37
|
+
import { LlmRuntime, MessageId, freezeMessage, type Message, type UserMessage } from '@deepseek-ai/dsh-llm';
|
|
38
|
+
import { SessionId, SessionStore, type SessionEvent } from '@deepseek-ai/dsh-session';
|
|
39
|
+
import * as checkpoints from '@deepseek-ai/dsh-session-checkpoint-policy';
|
|
40
|
+
import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection';
|
|
41
|
+
import { SystemPrompt } from '@deepseek-ai/dsh-system-prompt';
|
|
42
|
+
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
43
|
+
import {
|
|
44
|
+
defineTool,
|
|
45
|
+
type InferArgs,
|
|
46
|
+
type ParameterSchemaSpec,
|
|
47
|
+
type ValueSchemaSpec,
|
|
48
|
+
type ToolDefinition,
|
|
49
|
+
type ToolRunContext,
|
|
50
|
+
ToolRuntime,
|
|
51
|
+
} from '@deepseek-ai/dsh-tools';
|
|
52
|
+
import {
|
|
53
|
+
aborted,
|
|
54
|
+
CANCELLED,
|
|
55
|
+
chatHandler,
|
|
56
|
+
checkModelName,
|
|
57
|
+
type Configure,
|
|
58
|
+
configured,
|
|
59
|
+
fromTool,
|
|
60
|
+
messagesHandler,
|
|
61
|
+
ModelError,
|
|
62
|
+
modelOf,
|
|
63
|
+
nextPromptId,
|
|
64
|
+
providerOf,
|
|
65
|
+
refusal,
|
|
66
|
+
stopSignalOf,
|
|
67
|
+
storedAnswer,
|
|
68
|
+
toolCallEnded,
|
|
69
|
+
toolCallStarted,
|
|
70
|
+
transcribing,
|
|
71
|
+
Transcript,
|
|
72
|
+
UNANSWERED,
|
|
73
|
+
} from '../common.ts';
|
|
74
|
+
import { type Answer, withOutput } from '../output.ts';
|
|
75
|
+
import { type Definition, sessionObject } from '../object.ts';
|
|
76
|
+
import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
|
|
77
|
+
import type { z } from 'zod';
|
|
78
|
+
import { SqlSessionPersistence, storedEvents } from './persistence.ts';
|
|
79
|
+
|
|
80
|
+
export { SqlSessionPersistence };
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A tool whose result is text: `defineTool` of @deepseek-ai/dsh-tools, with
|
|
84
|
+
* the output that takes.
|
|
85
|
+
*/
|
|
86
|
+
const textTool = <const S extends ParameterSchemaSpec>(options: {
|
|
87
|
+
name: string;
|
|
88
|
+
description: string;
|
|
89
|
+
parameters: S;
|
|
90
|
+
execute: (args: InferArgs<S>, exec: ToolRunContext) => Promise<string>;
|
|
91
|
+
}): ToolDefinition =>
|
|
92
|
+
defineTool<S, { type: 'string' }>({
|
|
93
|
+
...options,
|
|
94
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
/** The default model. */
|
|
98
|
+
const DEEPSEEK_MODEL = 'deepseek/deepseek-flash';
|
|
99
|
+
|
|
100
|
+
/** A model as the harness names it: its provider route, and its id there. */
|
|
101
|
+
interface Route {
|
|
102
|
+
provider: string;
|
|
103
|
+
model: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* `model` (`provider/model-id`) as the harness's route: DeepSeek's own
|
|
108
|
+
* provider, or else pi-ai's provider of that name, if it has the model.
|
|
109
|
+
*/
|
|
110
|
+
function routeOf(model: string): Route {
|
|
111
|
+
const [provider, id] = providerOf(model);
|
|
112
|
+
if (provider === 'deepseek') return { provider: 'deepseek-official', model: id };
|
|
113
|
+
const from = process.env.MODEL === model ? ' (from MODEL)' : '';
|
|
114
|
+
const known = builtinProviders().find((p) => p.id === provider);
|
|
115
|
+
if (!known) {
|
|
116
|
+
throw new ModelError(`deepseek: the model "${model}"${from} is not provider/model-id of a provider pi-ai knows`);
|
|
117
|
+
}
|
|
118
|
+
if (!known.getModels().some((m) => m.id === id)) {
|
|
119
|
+
throw new ModelError(`deepseek: pi-ai knows no model "${id}" of ${provider} (the model "${model}"${from})`);
|
|
120
|
+
}
|
|
121
|
+
return { provider, model: id };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The harness, its session in `db`: the services
|
|
126
|
+
* an agent loop needs, the persistence and its checkpoints, and the provider
|
|
127
|
+
* of `route`.
|
|
128
|
+
*/
|
|
129
|
+
async function boot(db: restate.Database, route: Route, system?: string): Promise<Context> {
|
|
130
|
+
const harness = new Context();
|
|
131
|
+
await harness.plugin(LlmRuntime);
|
|
132
|
+
await harness.plugin(SessionStore);
|
|
133
|
+
await harness.plugin(SystemPrompt, system ? { personaPrefix: system } : {});
|
|
134
|
+
await harness.plugin(ToolRuntime, {});
|
|
135
|
+
await harness.plugin(AgentRegistry);
|
|
136
|
+
await harness.plugin(SessionProjectionRegistry);
|
|
137
|
+
await harness.plugin(SqlSessionPersistence, { db });
|
|
138
|
+
await harness.plugin(checkpoints);
|
|
139
|
+
// DeepSeek's with DEEPSEEK_API_KEY; another's with the key pi-ai finds for it (OPENAI_API_KEY...).
|
|
140
|
+
if (route.provider === 'deepseek-official') await harness.plugin(deepseek, {});
|
|
141
|
+
else await harness.plugin(piAi, { providers: { [route.provider]: {} } });
|
|
142
|
+
await harness.plugin(AgentLoop, { agents: [] });
|
|
143
|
+
return harness;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The text that asks the agent to finish an interrupted prompt. */
|
|
147
|
+
const CONTINUE = 'Continue: your last turn was interrupted. Finish the request.';
|
|
148
|
+
|
|
149
|
+
const promptId = (id: string) => MessageId(`prompt:${id}`);
|
|
150
|
+
const textOf = (message: Message) => message.content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('');
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The answer to prompt `id` in the session log: the last reply of the first
|
|
154
|
+
* turn completed after it, {@link CANCELLED} if a cancellation aborted its
|
|
155
|
+
* turn, or {@link UNANSWERED} if the model's provider refused it for good;
|
|
156
|
+
* undefined while it is absent or unfinished (a crash's interrupted turn, or
|
|
157
|
+
* one that failed otherwise, is continued).
|
|
158
|
+
*/
|
|
159
|
+
function answerOf(events: readonly SessionEvent[], id: MessageId): string | undefined {
|
|
160
|
+
const at = events.findIndex((e) => e.type === 'user/message' && e.data.id === id);
|
|
161
|
+
if (at < 0) return undefined;
|
|
162
|
+
let answer: string | undefined;
|
|
163
|
+
for (const e of events.slice(at)) {
|
|
164
|
+
if (e.type === 'assistant/message') answer = textOf(e.data.message);
|
|
165
|
+
if (e.type !== 'turn/end') continue;
|
|
166
|
+
const { reason } = e.data;
|
|
167
|
+
if (reason.kind === 'completed') return answer ?? '';
|
|
168
|
+
if (reason.kind === 'aborted' && reason.reason.kind === 'user') return CANCELLED;
|
|
169
|
+
if (reason.kind === 'error' && refusal(turnError(reason.error))) return UNANSWERED;
|
|
170
|
+
}
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The error a turn failed with, as the attempt fails with it (see {@link throwIfTurnFailed}). */
|
|
175
|
+
const turnError = (error: unknown) => new Error(`the agent's turn failed: ${JSON.stringify(error)}`);
|
|
176
|
+
|
|
177
|
+
/** The last prompt in the session log, by id. */
|
|
178
|
+
function lastPrompt(events: readonly SessionEvent[]): MessageId | undefined {
|
|
179
|
+
const prompt = events.findLast(
|
|
180
|
+
(e): e is SessionEvent<'user/message'> => e.type === 'user/message' && e.data.id.startsWith('prompt:'),
|
|
181
|
+
);
|
|
182
|
+
return prompt?.data.id;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const message = (id: string, text: string): UserMessage =>
|
|
186
|
+
freezeMessage({ id: MessageId(id), role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } });
|
|
187
|
+
|
|
188
|
+
/** A JSON schema node as the harness's value schema: what it cannot say, it takes as any JSON. */
|
|
189
|
+
function valueSpec(node: Record<string, unknown>): ValueSchemaSpec {
|
|
190
|
+
const annotations = typeof node.description === 'string' ? { description: node.description } : {};
|
|
191
|
+
const variants = (node.anyOf ?? node.oneOf) as Record<string, unknown>[] | undefined;
|
|
192
|
+
if (variants && variants.length >= 2) {
|
|
193
|
+
const [first, second, ...rest] = variants.map(valueSpec) as [
|
|
194
|
+
ValueSchemaSpec,
|
|
195
|
+
ValueSchemaSpec,
|
|
196
|
+
...ValueSchemaSpec[],
|
|
197
|
+
];
|
|
198
|
+
return { ...annotations, oneOf: [first, second, ...rest] };
|
|
199
|
+
}
|
|
200
|
+
switch (node.type) {
|
|
201
|
+
case 'string':
|
|
202
|
+
case 'number':
|
|
203
|
+
case 'integer':
|
|
204
|
+
case 'boolean':
|
|
205
|
+
case 'null':
|
|
206
|
+
return {
|
|
207
|
+
...annotations,
|
|
208
|
+
type: node.type,
|
|
209
|
+
...(Array.isArray(node.enum) ? { enum: node.enum } : {}),
|
|
210
|
+
};
|
|
211
|
+
case 'array':
|
|
212
|
+
return {
|
|
213
|
+
...annotations,
|
|
214
|
+
type: 'array',
|
|
215
|
+
...(node.items ? { items: valueSpec(node.items as Record<string, unknown>) } : {}),
|
|
216
|
+
};
|
|
217
|
+
case 'object':
|
|
218
|
+
return {
|
|
219
|
+
...annotations,
|
|
220
|
+
type: 'object',
|
|
221
|
+
properties: parameterSpec(node),
|
|
222
|
+
additionalProperties: node.additionalProperties !== false,
|
|
223
|
+
};
|
|
224
|
+
default:
|
|
225
|
+
return { ...annotations, type: 'json' };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** The properties of a JSON schema object as the harness's parameters. */
|
|
230
|
+
function parameterSpec(node: Record<string, unknown>): ParameterSchemaSpec {
|
|
231
|
+
const required = new Set((node.required as string[] | undefined) ?? []);
|
|
232
|
+
const properties = (node.properties ?? {}) as Record<string, Record<string, unknown>>;
|
|
233
|
+
return Object.fromEntries(
|
|
234
|
+
Object.entries(properties).map(([name, property]) => [
|
|
235
|
+
name,
|
|
236
|
+
{ ...valueSpec(property), ...(required.has(name) ? { required: true as const } : {}) },
|
|
237
|
+
]),
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** `t` as a harness tool. */
|
|
242
|
+
const native = (t: AnyTool, ctx: restate.SessionContext): ToolDefinition =>
|
|
243
|
+
textTool({
|
|
244
|
+
name: t.name,
|
|
245
|
+
description: t.description,
|
|
246
|
+
parameters: parameterSpec(jsonSchemaOf(t)),
|
|
247
|
+
// Aborted (the agent's turn, on a cancellation), it waits no more.
|
|
248
|
+
execute: (args, exec) => {
|
|
249
|
+
const run = t.run(args, { ctx, callId: exec.callId });
|
|
250
|
+
if (!exec.signal) return run;
|
|
251
|
+
const stopped = aborted(exec.signal).catch(() => {
|
|
252
|
+
throw new restate.CancelledError();
|
|
253
|
+
});
|
|
254
|
+
return Promise.race([run, stopped]);
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
/** An agent's options: `chat` and `prompt` take them. */
|
|
259
|
+
export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
|
|
260
|
+
/**
|
|
261
|
+
* The model, as `provider/model-id`: MODEL, or else deepseek/deepseek-flash.
|
|
262
|
+
* DeepSeek's, or any pi-ai knows, such as `openai/gpt-6-sol`.
|
|
263
|
+
*/
|
|
264
|
+
model?: string;
|
|
265
|
+
/** The system prompt: who the agent is, and how it answers. */
|
|
266
|
+
system?: string;
|
|
267
|
+
/** The agent's tools: `tool()`s, Restate's (`call`, `signal`...), or the harness's (`defineTool`). */
|
|
268
|
+
tools?: (AnyTool | ToolDefinition)[];
|
|
269
|
+
/**
|
|
270
|
+
* The answer as data: a zod object, whose JSON the agent replies with
|
|
271
|
+
* (checked), and `chat` and `prompt` answer with (see output.ts).
|
|
272
|
+
*/
|
|
273
|
+
output?: O;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** {@link prompt}, answering with the agent's text. */
|
|
277
|
+
const promptText = (ctx: restate.SessionContext, text: string, options: Options): Promise<string> =>
|
|
278
|
+
transcribing(
|
|
279
|
+
ctx,
|
|
280
|
+
() => transcribe(ctx.db, ctx.key),
|
|
281
|
+
() => answerOnce(ctx, text, options),
|
|
282
|
+
);
|
|
283
|
+
|
|
284
|
+
/** An agent of the harness, on a session. */
|
|
285
|
+
type Agent = Awaited<ReturnType<Context['agents']['create']>>['agent'];
|
|
286
|
+
|
|
287
|
+
const answerOnce = async (
|
|
288
|
+
ctx: restate.SessionContext,
|
|
289
|
+
text: string,
|
|
290
|
+
{ model: named, system, tools = [] }: Options,
|
|
291
|
+
): Promise<string> => {
|
|
292
|
+
const id = nextPromptId(ctx);
|
|
293
|
+
const route = routeOf(modelOf(named, DEEPSEEK_MODEL));
|
|
294
|
+
const harness = await boot(ctx.db, route, system);
|
|
295
|
+
// A tool's error fails the attempt, which Restate retries: the harness
|
|
296
|
+
// stores nothing more, so the retry finds the tool's call without a result.
|
|
297
|
+
// The turn's stop fails it too: a cancellation (below), or an attempt that
|
|
298
|
+
// ended first.
|
|
299
|
+
const { promise: failed, reject: fail } = Promise.withResolvers<never>();
|
|
300
|
+
failed.catch(() => {});
|
|
301
|
+
const turn = stopSignalOf(ctx);
|
|
302
|
+
const onStop = () => fail(turn!.reason);
|
|
303
|
+
turn?.addEventListener('abort', onStop, { once: true });
|
|
304
|
+
let agent: Agent | undefined;
|
|
305
|
+
try {
|
|
306
|
+
const sessionId = SessionId(ctx.key);
|
|
307
|
+
const options = {
|
|
308
|
+
agentOptions: route,
|
|
309
|
+
setup: (agentCtx: Context) => {
|
|
310
|
+
for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail));
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
// Resuming closes a turn a crash left open.
|
|
314
|
+
const started = (await harness.sessionPersistence.stat(sessionId))
|
|
315
|
+
? await harness.agents.resume({ resumeSessionId: sessionId, ...options })
|
|
316
|
+
: await harness.agents.create({ sessionId, ...options });
|
|
317
|
+
agent = started.agent;
|
|
318
|
+
const answer = await answered(harness, agent, id, text, failed);
|
|
319
|
+
return answer;
|
|
320
|
+
} catch (e) {
|
|
321
|
+
// A cancelled invocation cancels the agent's turn, which the log keeps.
|
|
322
|
+
if (e instanceof restate.CancelledError && agent) await cancelTurn(harness, agent);
|
|
323
|
+
else (harness.sessionPersistence as SqlSessionPersistence).abandon();
|
|
324
|
+
throw e;
|
|
325
|
+
} finally {
|
|
326
|
+
turn?.removeEventListener('abort', onStop);
|
|
327
|
+
await harness.fiber.dispose();
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* The answer of prompt `id`, `text`, asked once: a prompt left unfinished
|
|
333
|
+
* (this one's, after a crash) is finished first, then this one starts.
|
|
334
|
+
*/
|
|
335
|
+
async function answered(harness: Context, agent: Agent, id: string, text: string, failed: Promise<never>) {
|
|
336
|
+
// The log as this attempt found it: a turn that failed before is continued like an interrupted one.
|
|
337
|
+
const found = agent.session.snapshotEvents().length;
|
|
338
|
+
for (;;) {
|
|
339
|
+
const events = agent.session.snapshotEvents();
|
|
340
|
+
// First: a prompt refused in this attempt fails it, rather than answer.
|
|
341
|
+
throwIfTurnFailed(events.slice(found));
|
|
342
|
+
const answer = answerOf(events, promptId(id));
|
|
343
|
+
if (answer !== undefined) return storedAnswer(answer);
|
|
344
|
+
const last = lastPrompt(events);
|
|
345
|
+
const unfinished = last !== undefined && answerOf(events, last) === undefined;
|
|
346
|
+
agent.followup(unfinished ? message(`continue:${events.length}`, CONTINUE) : message(promptId(id), text));
|
|
347
|
+
await Promise.race([agent.whenIdle(), failed]);
|
|
348
|
+
await harness.sessions.flush(agent.session);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Fail the attempt if a turn of `events` (this attempt's) failed: its model
|
|
354
|
+
* request, or a checkpoint. Its end may be stored already, so only this
|
|
355
|
+
* attempt's turns count: the retry asks the model again.
|
|
356
|
+
*/
|
|
357
|
+
function throwIfTurnFailed(events: readonly SessionEvent[]) {
|
|
358
|
+
const end = events.findLast((e): e is SessionEvent<'turn/end'> => e.type === 'turn/end')?.data.reason;
|
|
359
|
+
if (end?.kind === 'error') throw turnError(end.error);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Cancel `agent`'s turn, and store it cancelled. */
|
|
363
|
+
async function cancelTurn(harness: Context, agent: Agent) {
|
|
364
|
+
agent.cancel({ kind: 'user' });
|
|
365
|
+
await agent.whenIdle();
|
|
366
|
+
await harness.sessions.flush(agent.session);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* `definition`, its calls published as they start and end (for the clients
|
|
371
|
+
* that follow the conversation), and its error failing the attempt.
|
|
372
|
+
*/
|
|
373
|
+
const tracked = (
|
|
374
|
+
definition: ToolDefinition,
|
|
375
|
+
ctx: restate.SessionContext,
|
|
376
|
+
fail: (error: unknown) => void,
|
|
377
|
+
): ToolDefinition => ({
|
|
378
|
+
...definition,
|
|
379
|
+
execute: async (args, exec) => {
|
|
380
|
+
try {
|
|
381
|
+
await toolCallStarted(ctx);
|
|
382
|
+
const result = await definition.execute(args, exec);
|
|
383
|
+
await toolCallEnded(ctx);
|
|
384
|
+
return result;
|
|
385
|
+
} catch (error) {
|
|
386
|
+
fromTool(error);
|
|
387
|
+
fail(error);
|
|
388
|
+
throw error;
|
|
389
|
+
}
|
|
390
|
+
},
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
|
|
395
|
+
* of an invocation is a prompt of its own. The session is the object's key.
|
|
396
|
+
* With `output`, it answers with the value the agent replies with (see
|
|
397
|
+
* output.ts), not its text.
|
|
398
|
+
*/
|
|
399
|
+
export const prompt = <O extends z.ZodObject | undefined = undefined>(
|
|
400
|
+
ctx: restate.SessionContext,
|
|
401
|
+
text: string,
|
|
402
|
+
options: Options<O> = {},
|
|
403
|
+
): Promise<Answer<O>> => withOutput(text, options, (t, o) => promptText(ctx, t, o)) as Promise<Answer<O>>;
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* A chat handler: each message an invocation, the session in the object's
|
|
407
|
+
* database, with `options`, or the options a function of the invocation's
|
|
408
|
+
* context gives. It takes the message as plain text (`curl -d 'Hi'`) or as
|
|
409
|
+
* a JSON string (`curl --json '"Hi"'`).
|
|
410
|
+
*/
|
|
411
|
+
export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
|
|
412
|
+
if (typeof options === 'object') {
|
|
413
|
+
checkModelName('deepseek', options.model);
|
|
414
|
+
routeOf(modelOf(options.model, DEEPSEEK_MODEL));
|
|
415
|
+
}
|
|
416
|
+
return chatHandler(async (ctx, text) => prompt(ctx, text, await configured(options, ctx)));
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
/** `json` parsed, or as it is if it is not JSON. */
|
|
420
|
+
const parsed = (json: string): unknown => {
|
|
421
|
+
try {
|
|
422
|
+
return JSON.parse(json);
|
|
423
|
+
} catch {
|
|
424
|
+
return json;
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* A handler of the conversation as clients read it: a page at a time, or
|
|
430
|
+
* what is new or changed since a cursor, from the log each change writes
|
|
431
|
+
* (log.ts). It answers while a message is answered.
|
|
432
|
+
*/
|
|
433
|
+
export const messages = () => messagesHandler();
|
|
434
|
+
|
|
435
|
+
/** The session `key` in `db`, from its log, as `messages` gives it. */
|
|
436
|
+
const transcribe = async (db: Database, key: string) => {
|
|
437
|
+
const transcript = new Transcript();
|
|
438
|
+
for (const e of await storedEvents(db, SessionId(key))) {
|
|
439
|
+
// The prompts, not the requests to continue an interrupted turn.
|
|
440
|
+
if (e.type === 'user/message' && e.data.id.startsWith('prompt:')) transcript.say('user', textOf(e.data));
|
|
441
|
+
if (e.type === 'assistant/message') transcript.say('assistant', textOf(e.data.message));
|
|
442
|
+
if (e.type === 'tool/call') transcript.call(e.data.callId, e.data.name, parsed(e.data.arguments));
|
|
443
|
+
if (e.type === 'tool/result')
|
|
444
|
+
transcript.result(e.data.message.toolCallId, textOf(e.data.message), e.data.message.isError);
|
|
445
|
+
}
|
|
446
|
+
return transcript;
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
/** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
|
|
450
|
+
export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
|
|
451
|
+
name,
|
|
452
|
+
description,
|
|
453
|
+
schema,
|
|
454
|
+
background,
|
|
455
|
+
...options
|
|
456
|
+
}: Options<O> & Definition<P>) =>
|
|
457
|
+
sessionObject({
|
|
458
|
+
name,
|
|
459
|
+
description,
|
|
460
|
+
schema,
|
|
461
|
+
background,
|
|
462
|
+
handlers: { chat: chat(options) },
|
|
463
|
+
views: { messages: messages() },
|
|
464
|
+
});
|