@restatedev/agents 0.2.0 → 0.4.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/README.md +89 -49
- package/dist/calls.d.ts +29 -8
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +79 -18
- package/dist/calls.js.map +1 -1
- package/dist/claude/index.d.ts +36 -7
- package/dist/claude/index.d.ts.map +1 -1
- package/dist/claude/index.js +238 -156
- package/dist/claude/index.js.map +1 -1
- package/dist/client.d.ts +12 -3
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js.map +1 -1
- package/dist/common.d.ts +161 -71
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +277 -226
- package/dist/common.js.map +1 -1
- package/dist/conversation.d.ts +466 -0
- package/dist/conversation.d.ts.map +1 -0
- package/dist/conversation.js +1247 -0
- package/dist/conversation.js.map +1 -0
- package/dist/deepseek/index.d.ts +38 -5
- package/dist/deepseek/index.d.ts.map +1 -1
- package/dist/deepseek/index.js +323 -107
- package/dist/deepseek/index.js.map +1 -1
- package/dist/deepseek/persistence.d.ts +9 -3
- package/dist/deepseek/persistence.d.ts.map +1 -1
- package/dist/deepseek/persistence.js +12 -6
- package/dist/deepseek/persistence.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -3
- package/dist/index.js.map +1 -1
- package/dist/langgraph/checkpointer.d.ts +16 -2
- package/dist/langgraph/checkpointer.d.ts.map +1 -1
- package/dist/langgraph/checkpointer.js +133 -26
- package/dist/langgraph/checkpointer.js.map +1 -1
- package/dist/langgraph/context.d.ts +10 -0
- package/dist/langgraph/context.d.ts.map +1 -0
- package/dist/langgraph/context.js +21 -0
- package/dist/langgraph/context.js.map +1 -0
- package/dist/langgraph/errors.d.ts +16 -0
- package/dist/langgraph/errors.d.ts.map +1 -0
- package/dist/langgraph/errors.js +30 -0
- package/dist/langgraph/errors.js.map +1 -0
- package/dist/langgraph/graph.d.ts +25 -0
- package/dist/langgraph/graph.d.ts.map +1 -0
- package/dist/langgraph/graph.js +346 -0
- package/dist/langgraph/graph.js.map +1 -0
- package/dist/langgraph/index.d.ts +65 -12
- package/dist/langgraph/index.d.ts.map +1 -1
- package/dist/langgraph/index.js +234 -180
- package/dist/langgraph/index.js.map +1 -1
- package/dist/langgraph/nodes.d.ts +70 -0
- package/dist/langgraph/nodes.d.ts.map +1 -0
- package/dist/langgraph/nodes.js +145 -0
- package/dist/langgraph/nodes.js.map +1 -0
- package/dist/messages.d.ts +18 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +182 -0
- package/dist/messages.js.map +1 -0
- package/dist/object.d.ts +65 -23
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +123 -40
- package/dist/object.js.map +1 -1
- package/dist/output.d.ts +15 -7
- package/dist/output.d.ts.map +1 -1
- package/dist/output.js +44 -26
- package/dist/output.js.map +1 -1
- package/dist/pi/index.d.ts +39 -11
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +281 -77
- package/dist/pi/index.js.map +1 -1
- package/dist/pi/storage.d.ts +29 -4
- package/dist/pi/storage.d.ts.map +1 -1
- package/dist/pi/storage.js +18 -6
- package/dist/pi/storage.js.map +1 -1
- package/dist/signals.d.ts +75 -7
- package/dist/signals.d.ts.map +1 -1
- package/dist/signals.js +154 -27
- package/dist/signals.js.map +1 -1
- package/dist/steering.d.ts +31 -0
- package/dist/steering.d.ts.map +1 -0
- package/dist/steering.js +45 -0
- package/dist/steering.js.map +1 -0
- package/dist/tools.d.ts +28 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +34 -5
- package/dist/tools.js.map +1 -1
- package/package.json +33 -37
- package/src/calls.ts +110 -24
- package/src/claude/README.md +41 -20
- package/src/claude/index.ts +271 -183
- package/src/client.ts +14 -3
- package/src/common.ts +354 -247
- package/src/conversation.ts +1527 -0
- package/src/deepseek/README.md +78 -11
- package/src/deepseek/index.ts +385 -138
- package/src/deepseek/persistence.ts +11 -8
- package/src/index.ts +13 -4
- package/src/langgraph/README.md +115 -25
- package/src/langgraph/checkpointer.ts +168 -28
- package/src/langgraph/context.ts +27 -0
- package/src/langgraph/errors.ts +26 -0
- package/src/langgraph/graph.ts +396 -0
- package/src/langgraph/index.ts +337 -193
- package/src/langgraph/nodes.ts +243 -0
- package/src/messages.ts +244 -0
- package/src/object.ts +178 -48
- package/src/output.ts +52 -31
- package/src/pi/README.md +18 -3
- package/src/pi/index.ts +346 -79
- package/src/pi/storage.ts +20 -7
- package/src/signals.ts +235 -31
- package/src/steering.ts +67 -0
- package/src/tools.ts +61 -8
- package/dist/claude/conversation.d.ts +0 -33
- package/dist/claude/conversation.d.ts.map +0 -1
- package/dist/claude/conversation.js +0 -95
- package/dist/claude/conversation.js.map +0 -1
- package/dist/log.d.ts +0 -29
- package/dist/log.d.ts.map +0 -1
- package/dist/log.js +0 -145
- package/dist/log.js.map +0 -1
- package/dist/opencode/db.d.ts +0 -40
- package/dist/opencode/db.d.ts.map +0 -1
- package/dist/opencode/db.js +0 -161
- package/dist/opencode/db.js.map +0 -1
- package/dist/opencode/index.d.ts +0 -100
- package/dist/opencode/index.d.ts.map +0 -1
- package/dist/opencode/index.js +0 -436
- package/dist/opencode/index.js.map +0 -1
- package/src/claude/conversation.ts +0 -114
- package/src/log.ts +0 -193
- package/src/opencode/README.md +0 -125
- package/src/opencode/db.ts +0 -223
- package/src/opencode/index.ts +0 -559
package/dist/deepseek/index.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
// DeepSeek Harness agents in Restate virtual objects: the session (the
|
|
2
|
-
// harness's event log) is in the object's database (persistence.ts)
|
|
2
|
+
// harness's event log) is in the object's database (persistence.ts), and
|
|
3
|
+
// each of its flushes copies the turn's new messages into the conversation of
|
|
4
|
+
// turns (../conversation.ts) in the same transaction: the harness keeps its
|
|
5
|
+
// own history, and the conversation is what clients read, and how turns end.
|
|
3
6
|
//
|
|
4
7
|
// const assistant = deepseek.agent({ name: 'assistant', tools: [weather] });
|
|
5
8
|
//
|
|
@@ -27,24 +30,36 @@
|
|
|
27
30
|
// - A message is answered once per invocation: its message carries the
|
|
28
31
|
// invocation id, and a retried attempt returns the answer of the turn that
|
|
29
32
|
// finished it.
|
|
33
|
+
// - A tool call that needs a person's approval (`approval`) waits for the
|
|
34
|
+
// signal `approval` before it runs: the harness asks its approval service
|
|
35
|
+
// (@deepseek-ai/dsh-user-approval), which this answers with a wait
|
|
36
|
+
// (`waitFor` of ../tools.ts). The wait is opened once: a crash, or a
|
|
37
|
+
// suspension, has the model make the call again, which joins it.
|
|
30
38
|
import * as restate from '@restatedev/sessions';
|
|
31
39
|
import { Context } from '@deepseek-ai/cordis';
|
|
32
40
|
import { AgentRegistry } from '@deepseek-ai/dsh-agent';
|
|
33
41
|
import { AgentLoop } from '@deepseek-ai/dsh-agent-loop';
|
|
34
42
|
import * as deepseek from '@deepseek-ai/dsh-llm-deepseek-api-key';
|
|
35
43
|
import * as piAi from '@deepseek-ai/dsh-llm-pi-ai';
|
|
36
|
-
import { LlmRuntime, MessageId, freezeMessage } from '@deepseek-ai/dsh-llm';
|
|
44
|
+
import { LlmRuntime, MessageId, ToolCallId, freezeMessage } from '@deepseek-ai/dsh-llm';
|
|
37
45
|
import { SessionId, SessionStore } from '@deepseek-ai/dsh-session';
|
|
38
46
|
import * as checkpoints from '@deepseek-ai/dsh-session-checkpoint-policy';
|
|
39
47
|
import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection';
|
|
40
48
|
import { SystemPrompt } from '@deepseek-ai/dsh-system-prompt';
|
|
49
|
+
import { TokenMeter } from '@deepseek-ai/dsh-token-meter';
|
|
50
|
+
import { ToolResultPruner } from '@deepseek-ai/dsh-compaction-tool-result-pruner';
|
|
51
|
+
import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
|
|
52
|
+
import { ApprovalService } from '@deepseek-ai/dsh-user-approval';
|
|
41
53
|
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
42
54
|
import { defineTool, ToolRuntime, } from '@deepseek-ai/dsh-tools';
|
|
43
|
-
import { aborted,
|
|
44
|
-
import {
|
|
55
|
+
import { aborted, chatHandler, checkModelName, configured, fromTool, inboxOf, ModelError, modelOf, providerOf, RETURNED_UNRECORDED, stopSignalOf, toolCallEnded, toolCallStarted, } from '../common.js';
|
|
56
|
+
import { answerOnce } from '../conversation.js';
|
|
57
|
+
import { tookSteers } from '../steering.js';
|
|
58
|
+
import { conversationView } from '../messages.js';
|
|
59
|
+
import { withChecked } from '../output.js';
|
|
45
60
|
import { sessionObject } from '../object.js';
|
|
46
|
-
import { isTool, jsonSchemaOf } from '../tools.js';
|
|
47
|
-
import { SqlSessionPersistence
|
|
61
|
+
import { isTool, jsonSchemaOf, waitFor } from '../tools.js';
|
|
62
|
+
import { SqlSessionPersistence } from './persistence.js';
|
|
48
63
|
export { SqlSessionPersistence };
|
|
49
64
|
/**
|
|
50
65
|
* A tool whose result is text: `defineTool` of @deepseek-ai/dsh-tools, with
|
|
@@ -76,19 +91,32 @@ function routeOf(model) {
|
|
|
76
91
|
}
|
|
77
92
|
/**
|
|
78
93
|
* The harness, its session in `db`: the services
|
|
79
|
-
* an agent loop needs, the persistence and its checkpoints,
|
|
80
|
-
* of `route
|
|
94
|
+
* an agent loop needs, the persistence and its checkpoints, compaction (with
|
|
95
|
+
* `compaction`'s settings), the provider of `route`, and with `approvals`
|
|
96
|
+
* the approval service, which asks before a tool call that needs a person's
|
|
97
|
+
* approval runs (see {@link approving}).
|
|
81
98
|
*/
|
|
82
|
-
async function boot(db, route, system) {
|
|
99
|
+
async function boot(db, route, system, compaction = {}, approvals = false) {
|
|
83
100
|
const harness = new Context();
|
|
84
101
|
await harness.plugin(LlmRuntime);
|
|
85
102
|
await harness.plugin(SessionStore);
|
|
86
103
|
await harness.plugin(SystemPrompt, system ? { personaPrefix: system } : {});
|
|
87
104
|
await harness.plugin(ToolRuntime, {});
|
|
105
|
+
// Without it, the harness denies a call that asks for an approval. With it,
|
|
106
|
+
// the model is also told that some calls may ask for one.
|
|
107
|
+
if (approvals)
|
|
108
|
+
await harness.plugin(ApprovalService, {});
|
|
88
109
|
await harness.plugin(AgentRegistry);
|
|
89
110
|
await harness.plugin(SessionProjectionRegistry);
|
|
90
111
|
await harness.plugin(SqlSessionPersistence, { db });
|
|
91
112
|
await harness.plugin(checkpoints);
|
|
113
|
+
// The model's input stays within its context window: as it nears the
|
|
114
|
+
// window (or overflows it), the oldest history is condensed into a summary,
|
|
115
|
+
// one more model request, after oversized tool results are trimmed. The
|
|
116
|
+
// log keeps every event, and the conversation of turns every message.
|
|
117
|
+
await harness.plugin(TokenMeter);
|
|
118
|
+
await harness.plugin(ToolResultPruner);
|
|
119
|
+
await harness.plugin(BasicCompactionEngine, compaction);
|
|
92
120
|
// DeepSeek's with DEEPSEEK_API_KEY; another's with the key pi-ai finds for it (OPENAI_API_KEY...).
|
|
93
121
|
if (route.provider === 'deepseek-official')
|
|
94
122
|
await harness.plugin(deepseek, {});
|
|
@@ -102,17 +130,17 @@ const CONTINUE = 'Continue: your last turn was interrupted. Finish the request.'
|
|
|
102
130
|
const promptId = (id) => MessageId(`prompt:${id}`);
|
|
103
131
|
const textOf = (message) => message.content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('');
|
|
104
132
|
/**
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
* one that failed otherwise, is continued).
|
|
133
|
+
* How the harness's turn of prompt `id` ended in the session log: the last
|
|
134
|
+
* reply of its first harness turn that completed (`answer`), or a failure
|
|
135
|
+
* (`error`); none while it is absent (`asked: false`) or was interrupted (a
|
|
136
|
+
* crash), when it is continued.
|
|
110
137
|
*/
|
|
111
|
-
function
|
|
138
|
+
function endOf(events, id) {
|
|
112
139
|
const at = events.findIndex((e) => e.type === 'user/message' && e.data.id === id);
|
|
113
140
|
if (at < 0)
|
|
114
|
-
return
|
|
141
|
+
return { asked: false };
|
|
115
142
|
let answer;
|
|
143
|
+
let error;
|
|
116
144
|
for (const e of events.slice(at)) {
|
|
117
145
|
if (e.type === 'assistant/message')
|
|
118
146
|
answer = textOf(e.data.message);
|
|
@@ -120,21 +148,19 @@ function answerOf(events, id) {
|
|
|
120
148
|
continue;
|
|
121
149
|
const { reason } = e.data;
|
|
122
150
|
if (reason.kind === 'completed')
|
|
123
|
-
return answer ?? '';
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
if (reason.kind === 'error' && refusal(turnError(reason.error)))
|
|
127
|
-
return UNANSWERED;
|
|
151
|
+
return { asked: true, answer: answer ?? '' };
|
|
152
|
+
// A failed harness turn, continued after (by a retry), or the last.
|
|
153
|
+
error = reason.kind === 'error' ? reason.error : undefined;
|
|
128
154
|
}
|
|
129
|
-
return
|
|
130
|
-
}
|
|
131
|
-
/** The error a turn failed with, as the attempt fails with it (see {@link throwIfTurnFailed}). */
|
|
132
|
-
const turnError = (error) => new Error(`the agent's turn failed: ${JSON.stringify(error)}`);
|
|
133
|
-
/** The last prompt in the session log, by id. */
|
|
134
|
-
function lastPrompt(events) {
|
|
135
|
-
const prompt = events.findLast((e) => e.type === 'user/message' && e.data.id.startsWith('prompt:'));
|
|
136
|
-
return prompt?.data.id;
|
|
155
|
+
return { asked: true, error };
|
|
137
156
|
}
|
|
157
|
+
/** The error a harness turn failed with: terminal for an overflow of the model's context, which a retry meets again. */
|
|
158
|
+
const turnError = (error) => {
|
|
159
|
+
const message = `the agent's turn failed: ${JSON.stringify(error)}`;
|
|
160
|
+
return /context.?length|context_length_exceeded|context window|maximum context/i.test(message)
|
|
161
|
+
? new restate.TerminalError(message)
|
|
162
|
+
: new Error(message);
|
|
163
|
+
};
|
|
138
164
|
const message = (id, text) => freezeMessage({ id: MessageId(id), role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } });
|
|
139
165
|
/** A JSON schema node as the harness's value schema: what it cannot say, it takes as any JSON. */
|
|
140
166
|
function valueSpec(node) {
|
|
@@ -197,83 +223,282 @@ const native = (t, ctx) => textTool({
|
|
|
197
223
|
return Promise.race([run, stopped]);
|
|
198
224
|
},
|
|
199
225
|
});
|
|
200
|
-
/**
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
226
|
+
/** The signal that a tool call waits for, to the agent, when it needs a person's approval (`approval`). */
|
|
227
|
+
export const APPROVAL = 'approval';
|
|
228
|
+
/** The texts that approve a tool call, whatever their case. */
|
|
229
|
+
const APPROVED = new Set(['approved', 'approve', 'yes', 'ok', 'allow', 'allowed']);
|
|
230
|
+
/**
|
|
231
|
+
* What the value of an {@link APPROVAL} signal decides about its tool call:
|
|
232
|
+
* `true`, `{ "approved": true }`, or a text such as "approved" or "yes"
|
|
233
|
+
* approves it once; anything else rejects it, so a value that does not say
|
|
234
|
+
* "approved" never runs the tool.
|
|
235
|
+
*/
|
|
236
|
+
const decided = (value) => value === true ||
|
|
237
|
+
(typeof value === 'string' && APPROVED.has(value.trim().toLowerCase())) ||
|
|
238
|
+
(typeof value === 'object' && value !== null && value.approved === true)
|
|
239
|
+
? 'allowed-once'
|
|
240
|
+
: 'rejected';
|
|
241
|
+
/**
|
|
242
|
+
* Have the harness of the agent of `agentCtx` ask for an approval before
|
|
243
|
+
* each tool call that `approval` names (`tools/pre-execute`, once the call
|
|
244
|
+
* is allowed otherwise), and answer each ask (`approval/request`) with a
|
|
245
|
+
* person's decision: a wait for the signal {@link APPROVAL} (`waitFor`),
|
|
246
|
+
* which `pending` shows with the call's tool and arguments, without holding
|
|
247
|
+
* a process.
|
|
248
|
+
*
|
|
249
|
+
* A crash, or a suspension, ends the attempt before the harness stored the
|
|
250
|
+
* call: the retry asks the model again, which makes the call again under a
|
|
251
|
+
* new id. Made with the same arguments, it joins the wait (`rejoin`): the
|
|
252
|
+
* person is asked once. The wait is an approval (`approval`): a stopped
|
|
253
|
+
* turn does not report its call as done because it was approved. An error
|
|
254
|
+
* of the wait fails the attempt (`fail`), and its ask never ends: the
|
|
255
|
+
* harness does not go on without a decision.
|
|
256
|
+
*/
|
|
257
|
+
function approving(agentCtx, ctx, approval, fail) {
|
|
258
|
+
const needs = typeof approval === 'function' ? approval : ({ name }) => approval.includes(name);
|
|
259
|
+
// The calls asked about, by id: what `pending` shows of each.
|
|
260
|
+
const asked = new Map();
|
|
261
|
+
agentCtx.on('tools/pre-execute', async (exec, next) => {
|
|
262
|
+
const decision = await next();
|
|
263
|
+
if (decision.kind !== 'allow' || !needs({ name: exec.name, args: exec.arguments }))
|
|
264
|
+
return decision;
|
|
265
|
+
asked.set(exec.callId, { tool: exec.name, args: exec.arguments });
|
|
266
|
+
return { kind: 'ask' };
|
|
267
|
+
});
|
|
268
|
+
agentCtx.on('approval/request', async ({ callId }, next) => {
|
|
269
|
+
const call = callId === undefined ? undefined : asked.get(callId);
|
|
270
|
+
// Asked by another (none is mounted): no one answers, and the harness denies it.
|
|
271
|
+
if (callId === undefined || call === undefined)
|
|
272
|
+
return next();
|
|
273
|
+
asked.delete(callId);
|
|
274
|
+
try {
|
|
275
|
+
// The calls whose results are stored are forgotten first: an earlier
|
|
276
|
+
// attempt's call with the same arguments, approved and done, is not this one.
|
|
277
|
+
await toolCallStarted(ctx);
|
|
278
|
+
return decided(await waitFor(ctx, callId, APPROVAL, call, { approval: true, rejoin: true }));
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
fromTool(ctx, error);
|
|
282
|
+
fail(error);
|
|
283
|
+
return new Promise(() => { });
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* DeepSeek's items, as the conversation of turns keeps them: the harness's
|
|
289
|
+
* messages. A user's text is said by the user; an assistant's by the
|
|
290
|
+
* assistant, with its tool calls; a tool message is a result.
|
|
291
|
+
*/
|
|
292
|
+
export const items = {
|
|
293
|
+
dump: (m) => JSON.stringify(m),
|
|
294
|
+
load: (stored) => {
|
|
295
|
+
// Only a harness's message (an id, a role, a list of content parts): another framework's row is not one.
|
|
296
|
+
const m = JSON.parse(stored);
|
|
297
|
+
if (typeof m.id !== 'string' || typeof m.role !== 'string' || !Array.isArray(m.content))
|
|
298
|
+
throw new Error("not a DeepSeek harness's message (an id, a role and a list of content parts)");
|
|
299
|
+
return freezeMessage(m);
|
|
300
|
+
},
|
|
301
|
+
prompt: (text) => message('prompt', text),
|
|
302
|
+
reply: (text) => freezeMessage({
|
|
303
|
+
id: MessageId('reply'),
|
|
304
|
+
role: 'assistant',
|
|
305
|
+
content: [{ type: 'text', text }],
|
|
306
|
+
source: { kind: 'model', provider: 'restate', model: 'note' },
|
|
307
|
+
}),
|
|
308
|
+
results: (results) => results.map(([call, output]) => freezeMessage({
|
|
309
|
+
id: MessageId(`result:${call.id}`),
|
|
310
|
+
role: 'tool',
|
|
311
|
+
toolCallId: ToolCallId(call.id),
|
|
312
|
+
content: [{ type: 'text', text: output }],
|
|
313
|
+
source: { kind: 'tool', callId: ToolCallId(call.id) },
|
|
314
|
+
isError: output !== RETURNED_UNRECORDED,
|
|
315
|
+
})),
|
|
316
|
+
read: (m) => {
|
|
317
|
+
if (m.role === 'user')
|
|
318
|
+
return { said: ['user', textOf(m)] };
|
|
319
|
+
if (m.role === 'assistant') {
|
|
320
|
+
const calls = m.content.flatMap((c) => c.type === 'tool-call' ? [{ id: c.id, name: c.name, input: parsedJson(c.arguments) }] : []);
|
|
321
|
+
// Each reply is a message of its own, its tool calls' too.
|
|
322
|
+
return { said: ['assistant', textOf(m)], calls };
|
|
323
|
+
}
|
|
324
|
+
if (m.role === 'tool')
|
|
325
|
+
return { results: [{ id: m.toolCallId, output: textOf(m), error: m.isError === true }] };
|
|
326
|
+
return {};
|
|
327
|
+
},
|
|
328
|
+
};
|
|
329
|
+
/**
|
|
330
|
+
* The harness's message of `turn`'s prompt: its text, after how the turn
|
|
331
|
+
* before it ended if its run did not answer it (stopped, refused, failed,
|
|
332
|
+
* or ended once its invocation was gone), which the harness's log does not
|
|
333
|
+
* say.
|
|
334
|
+
*/
|
|
335
|
+
function promptOf(turn, before) {
|
|
336
|
+
const text = textOf(turn.prompt.item);
|
|
337
|
+
const note = before && before.status !== 'answered' && before.answer ? `(${before.answer})\n\n` : '';
|
|
338
|
+
// The harness keeps the prompt as it is given, the turn's reminder too; the conversation as it was asked.
|
|
339
|
+
return message(promptId(turn.id), note + text + (turn.reminder ?? ''));
|
|
340
|
+
}
|
|
341
|
+
/** The id of the harness's message of the message `id` steered to a turn. */
|
|
342
|
+
const steerMessageId = (id) => `steer:${id}`;
|
|
343
|
+
/** The id of the steered message whose harness message has the id `messageId`, if it is one. */
|
|
344
|
+
const steeredId = (messageId) => (messageId.startsWith('steer:') ? messageId.slice(6) : undefined);
|
|
345
|
+
/**
|
|
346
|
+
* Copy the events of `batch` that are `turn`'s (after its latest ask, at seq
|
|
347
|
+
* `from()` of the log) into it, in `tx`: the model's replies, the tools'
|
|
348
|
+
* results, and the messages steered to the turn that the harness placed at
|
|
349
|
+
* a step (whose companion is told they are taken, in `tx`). Not the requests
|
|
350
|
+
* to continue (a step of the run's own), nor anything once the run stopped
|
|
351
|
+
* or `failed()` (the harness's result of a tool that failed the attempt, or
|
|
352
|
+
* was cancelled, is not the call's): the turn's close, or the retry, says
|
|
353
|
+
* how it ended. `resulted` gets the calls whose results it copied.
|
|
354
|
+
*/
|
|
355
|
+
const copying = (ctx, turn, from, failed, resulted) => async (tx, batch) => {
|
|
356
|
+
const start = from();
|
|
357
|
+
if (start === undefined || failed() || stopSignalOf(ctx)?.aborted || !turn.writable)
|
|
358
|
+
return;
|
|
359
|
+
const held = new Set(turn.steered().map((e) => e.steer));
|
|
360
|
+
const copied = batch.flatMap((e) => {
|
|
361
|
+
if (e.seq <= start)
|
|
362
|
+
return [];
|
|
363
|
+
if (e.type === 'assistant/message')
|
|
364
|
+
return [{ item: e.data.message, reply: true }];
|
|
365
|
+
if (e.type === 'tool/result')
|
|
366
|
+
return [{ item: e.data.message }];
|
|
367
|
+
if (e.type !== 'user/message')
|
|
368
|
+
return [];
|
|
369
|
+
const steer = steeredId(e.data.id);
|
|
370
|
+
return steer === undefined || held.has(steer) ? [] : [{ item: e.data, steer }];
|
|
371
|
+
});
|
|
372
|
+
if (copied.length === 0)
|
|
373
|
+
return;
|
|
374
|
+
await turn.copyIn(tx, copied);
|
|
375
|
+
tookSteers(ctx, tx, copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])));
|
|
376
|
+
resulted(batch.flatMap((e) => (e.seq > start && e.type === 'tool/result' ? [e.data.message.toolCallId] : [])));
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* The run of the harness of `options`, on the conversation: its turn's
|
|
380
|
+
* latest ask (its prompt, or the message that asked again) asked once, and
|
|
381
|
+
* continued after a crash.
|
|
382
|
+
*/
|
|
383
|
+
const runOf = (ctx, { model: named, system, tools = [], compaction, approval }) => async (conversation) => {
|
|
384
|
+
const turn = conversation.turn;
|
|
204
385
|
const route = routeOf(modelOf(named, DEEPSEEK_MODEL));
|
|
205
|
-
const harness = await boot(ctx.db, route, system);
|
|
386
|
+
const harness = await boot(ctx.db, route, system, compaction, approval !== undefined);
|
|
387
|
+
const persistence = harness.sessionPersistence;
|
|
206
388
|
// A tool's error fails the attempt, which Restate retries: the harness
|
|
207
389
|
// stores nothing more, so the retry finds the tool's call without a result.
|
|
208
|
-
// The turn's stop fails it too: a cancellation
|
|
209
|
-
|
|
210
|
-
const { promise: failed, reject: fail } = Promise.withResolvers();
|
|
390
|
+
// The turn's stop fails it too: a cancellation, or an attempt that ended first.
|
|
391
|
+
const { promise: failed, reject } = Promise.withResolvers();
|
|
211
392
|
failed.catch(() => { });
|
|
212
|
-
|
|
213
|
-
const
|
|
214
|
-
|
|
393
|
+
let broken = false;
|
|
394
|
+
const fail = (error) => {
|
|
395
|
+
broken = true;
|
|
396
|
+
reject(error);
|
|
397
|
+
};
|
|
398
|
+
const stop = stopSignalOf(ctx);
|
|
399
|
+
const onStop = () => fail(stop.reason);
|
|
400
|
+
stop?.addEventListener('abort', onStop, { once: true });
|
|
215
401
|
let agent;
|
|
402
|
+
let unlisten;
|
|
403
|
+
// The turn asked again (its output's check, say): the harness is asked that, and answers it.
|
|
404
|
+
const asked = turn.latestAsk();
|
|
405
|
+
const again = asked !== turn.prompt;
|
|
406
|
+
const id = again ? MessageId(`prompt:${turn.id}:again`) : promptId(turn.id);
|
|
407
|
+
// Where the turn's latest ask is in the log, once it is.
|
|
408
|
+
let from;
|
|
409
|
+
// The tool calls that returned, whose ends are published once a flush stored their results.
|
|
410
|
+
const returned = new Set();
|
|
216
411
|
try {
|
|
217
412
|
const sessionId = SessionId(ctx.key);
|
|
218
413
|
const options = {
|
|
219
414
|
agentOptions: route,
|
|
220
415
|
setup: (agentCtx) => {
|
|
221
416
|
for (const t of tools)
|
|
222
|
-
agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail));
|
|
417
|
+
agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail, returned));
|
|
418
|
+
if (approval !== undefined)
|
|
419
|
+
approving(agentCtx, ctx, approval, fail);
|
|
223
420
|
},
|
|
224
421
|
};
|
|
225
|
-
// Resuming closes a turn a crash left open.
|
|
226
|
-
const started = (await
|
|
422
|
+
// Resuming closes a harness turn a crash, or a killed invocation, left open.
|
|
423
|
+
const started = (await persistence.stat(sessionId))
|
|
227
424
|
? await harness.agents.resume({ resumeSessionId: sessionId, ...options })
|
|
228
425
|
: await harness.agents.create({ sessionId, ...options });
|
|
229
426
|
agent = started.agent;
|
|
230
|
-
const
|
|
231
|
-
|
|
427
|
+
const found = agent.session.snapshotEvents().length;
|
|
428
|
+
from = agent.session.snapshotEvents().find((e) => e.type === 'user/message' && e.data.id === id)?.seq;
|
|
429
|
+
// A tool call's end is published once a flush stored its result, for followers to read it there.
|
|
430
|
+
let ended = false;
|
|
431
|
+
// The harness messages of the steered messages in the log: those before this attempt, and each flush's.
|
|
432
|
+
const placed = new Set(agent.session
|
|
433
|
+
.snapshotEvents()
|
|
434
|
+
.flatMap((e) => (e.type === 'user/message' && steeredId(e.data.id) !== undefined ? [String(e.data.id)] : [])));
|
|
435
|
+
persistence.copy = async (tx, batch) => {
|
|
436
|
+
for (const e of batch)
|
|
437
|
+
if (e.type === 'user/message' && steeredId(e.data.id) !== undefined)
|
|
438
|
+
placed.add(e.data.id);
|
|
439
|
+
from ??= batch.find((e) => e.type === 'user/message' && e.data.id === id)?.seq;
|
|
440
|
+
await copying(ctx, turn, () => from, () => broken, (calls) => {
|
|
441
|
+
for (const call of calls)
|
|
442
|
+
if (returned.delete(call))
|
|
443
|
+
ended = true;
|
|
444
|
+
})(tx, batch);
|
|
445
|
+
};
|
|
446
|
+
persistence.flushed = async () => {
|
|
447
|
+
if (!ended)
|
|
448
|
+
return;
|
|
449
|
+
ended = false;
|
|
450
|
+
// Failing, it fails the attempt, as a tool's error does: never the flush, which is done.
|
|
451
|
+
await toolCallEnded(ctx).catch(fail);
|
|
452
|
+
};
|
|
453
|
+
// The messages steered to the turn, handed to the harness's step inbox as a publish lists them: only
|
|
454
|
+
// while a tool call runs or its result is stored, so that a step after them places them, in this turn.
|
|
455
|
+
const harnessAgent = agent;
|
|
456
|
+
const given = new Set();
|
|
457
|
+
unlisten = inboxOf(ctx)?.listen(() => {
|
|
458
|
+
if (stop?.aborted || broken)
|
|
459
|
+
return;
|
|
460
|
+
const pending = new Set(harnessAgent.inbox.nextStep.map((m) => String(m.id)));
|
|
461
|
+
for (const { id: steerId, text } of inboxOf(ctx).messages) {
|
|
462
|
+
const messageId = steerMessageId(steerId);
|
|
463
|
+
if (given.has(steerId) || pending.has(messageId) || placed.has(messageId))
|
|
464
|
+
continue;
|
|
465
|
+
given.add(steerId);
|
|
466
|
+
harnessAgent.steer(message(messageId, text));
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
// The turn before this one, as the conversation has it.
|
|
470
|
+
const before = conversation.transcript.at(-2);
|
|
471
|
+
for (;;) {
|
|
472
|
+
const events = agent.session.snapshotEvents();
|
|
473
|
+
const end = endOf(events, id);
|
|
474
|
+
// A turn of this attempt's that failed fails it (a refusal ends the turn); the retry asks the model again.
|
|
475
|
+
if ('error' in end && end.error !== undefined) {
|
|
476
|
+
const failedHere = events.slice(found).some((e) => e.type === 'turn/end' && e.data.reason.kind === 'error');
|
|
477
|
+
if (failedHere)
|
|
478
|
+
throw turnError(end.error);
|
|
479
|
+
}
|
|
480
|
+
if ('answer' in end && end.answer !== undefined)
|
|
481
|
+
return end.answer;
|
|
482
|
+
const ask = again ? message(id, textOf(asked.item)) : promptOf(turn, before);
|
|
483
|
+
agent.followup(end.asked ? message(`continue:${events.length}`, CONTINUE) : ask);
|
|
484
|
+
await Promise.race([agent.whenIdle(), failed]);
|
|
485
|
+
await harness.sessions.flush(agent.session);
|
|
486
|
+
}
|
|
232
487
|
}
|
|
233
488
|
catch (e) {
|
|
234
489
|
// A cancelled invocation cancels the agent's turn, which the log keeps.
|
|
235
490
|
if (e instanceof restate.CancelledError && agent)
|
|
236
491
|
await cancelTurn(harness, agent);
|
|
237
492
|
else
|
|
238
|
-
|
|
493
|
+
persistence.abandon();
|
|
239
494
|
throw e;
|
|
240
495
|
}
|
|
241
496
|
finally {
|
|
242
|
-
|
|
497
|
+
unlisten?.();
|
|
498
|
+
stop?.removeEventListener('abort', onStop);
|
|
243
499
|
await harness.fiber.dispose();
|
|
244
500
|
}
|
|
245
501
|
};
|
|
246
|
-
/**
|
|
247
|
-
* The answer of prompt `id`, `text`, asked once: a prompt left unfinished
|
|
248
|
-
* (this one's, after a crash) is finished first, then this one starts.
|
|
249
|
-
*/
|
|
250
|
-
async function answered(harness, agent, id, text, failed) {
|
|
251
|
-
// The log as this attempt found it: a turn that failed before is continued like an interrupted one.
|
|
252
|
-
const found = agent.session.snapshotEvents().length;
|
|
253
|
-
for (;;) {
|
|
254
|
-
const events = agent.session.snapshotEvents();
|
|
255
|
-
// First: a prompt refused in this attempt fails it, rather than answer.
|
|
256
|
-
throwIfTurnFailed(events.slice(found));
|
|
257
|
-
const answer = answerOf(events, promptId(id));
|
|
258
|
-
if (answer !== undefined)
|
|
259
|
-
return storedAnswer(answer);
|
|
260
|
-
const last = lastPrompt(events);
|
|
261
|
-
const unfinished = last !== undefined && answerOf(events, last) === undefined;
|
|
262
|
-
agent.followup(unfinished ? message(`continue:${events.length}`, CONTINUE) : message(promptId(id), text));
|
|
263
|
-
await Promise.race([agent.whenIdle(), failed]);
|
|
264
|
-
await harness.sessions.flush(agent.session);
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Fail the attempt if a turn of `events` (this attempt's) failed: its model
|
|
269
|
-
* request, or a checkpoint. Its end may be stored already, so only this
|
|
270
|
-
* attempt's turns count: the retry asks the model again.
|
|
271
|
-
*/
|
|
272
|
-
function throwIfTurnFailed(events) {
|
|
273
|
-
const end = events.findLast((e) => e.type === 'turn/end')?.data.reason;
|
|
274
|
-
if (end?.kind === 'error')
|
|
275
|
-
throw turnError(end.error);
|
|
276
|
-
}
|
|
277
502
|
/** Cancel `agent`'s turn, and store it cancelled. */
|
|
278
503
|
async function cancelTurn(harness, agent) {
|
|
279
504
|
agent.cancel({ kind: 'user' });
|
|
@@ -281,20 +506,23 @@ async function cancelTurn(harness, agent) {
|
|
|
281
506
|
await harness.sessions.flush(agent.session);
|
|
282
507
|
}
|
|
283
508
|
/**
|
|
284
|
-
* `definition`, its calls published as they start and
|
|
285
|
-
*
|
|
509
|
+
* `definition`, its calls published as they start, and as they end once
|
|
510
|
+
* their results are stored (each call that returned is put in `returned`),
|
|
511
|
+
* for the clients that follow the conversation; its error failing the
|
|
512
|
+
* attempt.
|
|
286
513
|
*/
|
|
287
|
-
const tracked = (definition, ctx, fail) => ({
|
|
514
|
+
const tracked = (definition, ctx, fail, returned) => ({
|
|
288
515
|
...definition,
|
|
289
516
|
execute: async (args, exec) => {
|
|
290
517
|
try {
|
|
291
518
|
await toolCallStarted(ctx);
|
|
292
519
|
const result = await definition.execute(args, exec);
|
|
293
|
-
|
|
520
|
+
// Its end is published once the harness stored its result (`runOf`).
|
|
521
|
+
returned.add(exec.callId);
|
|
294
522
|
return result;
|
|
295
523
|
}
|
|
296
524
|
catch (error) {
|
|
297
|
-
fromTool(error);
|
|
525
|
+
fromTool(ctx, error);
|
|
298
526
|
fail(error);
|
|
299
527
|
throw error;
|
|
300
528
|
}
|
|
@@ -306,7 +534,9 @@ const tracked = (definition, ctx, fail) => ({
|
|
|
306
534
|
* With `output`, it answers with the value the agent replies with (see
|
|
307
535
|
* output.ts), not its text.
|
|
308
536
|
*/
|
|
309
|
-
export const prompt = (ctx, text, options = {}) =>
|
|
537
|
+
export const prompt = (ctx, text, options = {}) => withChecked(text, options, (t, o, check, reminder) =>
|
|
538
|
+
// The harness keeps the model's history: the conversation reads only its latest turns.
|
|
539
|
+
answerOnce(ctx, t, items, runOf(ctx, o), { check, reminder, ownHistory: true }));
|
|
310
540
|
/**
|
|
311
541
|
* A chat handler: each message an invocation, the session in the object's
|
|
312
542
|
* database, with `options`, or the options a function of the invocation's
|
|
@@ -318,10 +548,10 @@ export const chat = (options = {}) => {
|
|
|
318
548
|
checkModelName('deepseek', options.model);
|
|
319
549
|
routeOf(modelOf(options.model, DEEPSEEK_MODEL));
|
|
320
550
|
}
|
|
321
|
-
return chatHandler(async (ctx, text) => prompt(ctx, text, await configured(options, ctx)));
|
|
551
|
+
return chatHandler(async (ctx, text) => prompt(ctx, text, await configured(options, ctx)), { steers: true });
|
|
322
552
|
};
|
|
323
553
|
/** `json` parsed, or as it is if it is not JSON. */
|
|
324
|
-
const
|
|
554
|
+
const parsedJson = (json) => {
|
|
325
555
|
try {
|
|
326
556
|
return JSON.parse(json);
|
|
327
557
|
}
|
|
@@ -330,33 +560,19 @@ const parsed = (json) => {
|
|
|
330
560
|
}
|
|
331
561
|
};
|
|
332
562
|
/**
|
|
333
|
-
* A
|
|
334
|
-
*
|
|
335
|
-
*
|
|
563
|
+
* A view of the conversation as clients read it: a page at a time, or what
|
|
564
|
+
* is new or changed since a cursor; `view: 'summary'` for each turn's
|
|
565
|
+
* message and answer. It answers while a message is answered.
|
|
336
566
|
*/
|
|
337
|
-
export const messages = () =>
|
|
338
|
-
/** The session `key` in `db`, from its log, as `messages` gives it. */
|
|
339
|
-
const transcribe = async (db, key) => {
|
|
340
|
-
const transcript = new Transcript();
|
|
341
|
-
for (const e of await storedEvents(db, SessionId(key))) {
|
|
342
|
-
// The prompts, not the requests to continue an interrupted turn.
|
|
343
|
-
if (e.type === 'user/message' && e.data.id.startsWith('prompt:'))
|
|
344
|
-
transcript.say('user', textOf(e.data));
|
|
345
|
-
if (e.type === 'assistant/message')
|
|
346
|
-
transcript.say('assistant', textOf(e.data.message));
|
|
347
|
-
if (e.type === 'tool/call')
|
|
348
|
-
transcript.call(e.data.callId, e.data.name, parsed(e.data.arguments));
|
|
349
|
-
if (e.type === 'tool/result')
|
|
350
|
-
transcript.result(e.data.message.toolCallId, textOf(e.data.message), e.data.message.isError);
|
|
351
|
-
}
|
|
352
|
-
return transcript;
|
|
353
|
-
};
|
|
567
|
+
export const messages = () => conversationView(items);
|
|
354
568
|
/** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
|
|
355
|
-
export const agent = ({ name, description, schema, background, ...options }) => sessionObject({
|
|
569
|
+
export const agent = ({ name, description, schema, background, window, budget, ...options }) => sessionObject({
|
|
356
570
|
name,
|
|
357
571
|
description,
|
|
358
572
|
schema,
|
|
359
573
|
background,
|
|
574
|
+
window,
|
|
575
|
+
budget,
|
|
360
576
|
handlers: { chat: chat(options) },
|
|
361
577
|
views: { messages: messages() },
|
|
362
578
|
});
|