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