@restatedev/agents 0.11.1 → 0.12.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 +189 -808
- package/dist/pi/factory.d.ts +73 -0
- package/dist/pi/factory.d.ts.map +1 -0
- package/dist/pi/factory.js +145 -0
- package/dist/pi/factory.js.map +1 -0
- package/dist/pi/index.d.ts +5 -129
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +31 -571
- package/dist/pi/index.js.map +1 -1
- package/dist/pi/keepalive.d.ts +3 -16
- package/dist/pi/keepalive.d.ts.map +1 -1
- package/dist/pi/keepalive.js +38 -41
- package/dist/pi/keepalive.js.map +1 -1
- package/dist/pi/left.d.ts +16 -0
- package/dist/pi/left.d.ts.map +1 -0
- package/dist/pi/left.js +23 -0
- package/dist/pi/left.js.map +1 -0
- package/dist/pi/storage.d.ts +19 -76
- package/dist/pi/storage.d.ts.map +1 -1
- package/dist/pi/storage.js +50 -368
- package/dist/pi/storage.js.map +1 -1
- package/dist/pi/tools.d.ts +12 -0
- package/dist/pi/tools.d.ts.map +1 -0
- package/dist/pi/tools.js +70 -0
- package/dist/pi/tools.js.map +1 -0
- package/package.json +11 -254
- package/src/pi/factory.ts +231 -0
- package/src/pi/index.ts +31 -759
- package/src/pi/keepalive.ts +46 -56
- package/src/pi/left.ts +52 -0
- package/src/pi/storage.ts +75 -409
- package/src/pi/tools.ts +78 -0
- package/dist/agentlib/agent.d.ts +0 -32
- package/dist/agentlib/agent.d.ts.map +0 -1
- package/dist/agentlib/agent.js +0 -174
- package/dist/agentlib/agent.js.map +0 -1
- package/dist/agentlib/index.d.ts +0 -5
- package/dist/agentlib/index.d.ts.map +0 -1
- package/dist/agentlib/index.js +0 -15
- package/dist/agentlib/index.js.map +0 -1
- package/dist/agentlib/messages.d.ts +0 -39
- package/dist/agentlib/messages.d.ts.map +0 -1
- package/dist/agentlib/messages.js +0 -177
- package/dist/agentlib/messages.js.map +0 -1
- package/dist/agentlib/model.d.ts +0 -31
- package/dist/agentlib/model.d.ts.map +0 -1
- package/dist/agentlib/model.js +0 -140
- package/dist/agentlib/model.js.map +0 -1
- package/dist/agentlib/options.d.ts +0 -58
- package/dist/agentlib/options.d.ts.map +0 -1
- package/dist/agentlib/options.js +0 -2
- package/dist/agentlib/options.js.map +0 -1
- package/dist/agentlib/runtime.d.ts +0 -37
- package/dist/agentlib/runtime.d.ts.map +0 -1
- package/dist/agentlib/runtime.js +0 -216
- package/dist/agentlib/runtime.js.map +0 -1
- package/dist/agentlib/state.d.ts +0 -114
- package/dist/agentlib/state.d.ts.map +0 -1
- package/dist/agentlib/state.js +0 -52
- package/dist/agentlib/state.js.map +0 -1
- package/dist/agentlib/steering.d.ts +0 -23
- package/dist/agentlib/steering.d.ts.map +0 -1
- package/dist/agentlib/steering.js +0 -48
- package/dist/agentlib/steering.js.map +0 -1
- package/dist/agentlib/tools.d.ts +0 -33
- package/dist/agentlib/tools.d.ts.map +0 -1
- package/dist/agentlib/tools.js +0 -245
- package/dist/agentlib/tools.js.map +0 -1
- package/dist/agentlib/turn.d.ts +0 -82
- package/dist/agentlib/turn.d.ts.map +0 -1
- package/dist/agentlib/turn.js +0 -253
- package/dist/agentlib/turn.js.map +0 -1
- package/dist/calls.d.ts +0 -90
- package/dist/calls.d.ts.map +0 -1
- package/dist/calls.js +0 -235
- package/dist/calls.js.map +0 -1
- package/dist/claude/index.d.ts +0 -106
- package/dist/claude/index.d.ts.map +0 -1
- package/dist/claude/index.js +0 -386
- package/dist/claude/index.js.map +0 -1
- package/dist/client.d.ts +0 -90
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js +0 -88
- package/dist/client.js.map +0 -1
- package/dist/common.d.ts +0 -410
- package/dist/common.d.ts.map +0 -1
- package/dist/common.js +0 -563
- package/dist/common.js.map +0 -1
- package/dist/companion.d.ts +0 -286
- package/dist/companion.d.ts.map +0 -1
- package/dist/companion.js +0 -463
- package/dist/companion.js.map +0 -1
- package/dist/conversation.d.ts +0 -576
- package/dist/conversation.d.ts.map +0 -1
- package/dist/conversation.js +0 -1476
- package/dist/conversation.js.map +0 -1
- package/dist/deepseek/barriers.d.ts +0 -11
- package/dist/deepseek/barriers.d.ts.map +0 -1
- package/dist/deepseek/barriers.js +0 -36
- package/dist/deepseek/barriers.js.map +0 -1
- package/dist/deepseek/index.d.ts +0 -97
- package/dist/deepseek/index.d.ts.map +0 -1
- package/dist/deepseek/index.js +0 -603
- package/dist/deepseek/index.js.map +0 -1
- package/dist/deepseek/persistence.d.ts +0 -83
- package/dist/deepseek/persistence.d.ts.map +0 -1
- package/dist/deepseek/persistence.js +0 -262
- package/dist/deepseek/persistence.js.map +0 -1
- package/dist/index.d.ts +0 -14
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -17
- package/dist/index.js.map +0 -1
- package/dist/langgraph/checkpointer.d.ts +0 -52
- package/dist/langgraph/checkpointer.d.ts.map +0 -1
- package/dist/langgraph/checkpointer.js +0 -477
- package/dist/langgraph/checkpointer.js.map +0 -1
- package/dist/langgraph/context.d.ts +0 -10
- package/dist/langgraph/context.d.ts.map +0 -1
- package/dist/langgraph/context.js +0 -21
- package/dist/langgraph/context.js.map +0 -1
- package/dist/langgraph/errors.d.ts +0 -16
- package/dist/langgraph/errors.d.ts.map +0 -1
- package/dist/langgraph/errors.js +0 -30
- package/dist/langgraph/errors.js.map +0 -1
- package/dist/langgraph/graph.d.ts +0 -25
- package/dist/langgraph/graph.d.ts.map +0 -1
- package/dist/langgraph/graph.js +0 -378
- package/dist/langgraph/graph.js.map +0 -1
- package/dist/langgraph/index.d.ts +0 -119
- package/dist/langgraph/index.d.ts.map +0 -1
- package/dist/langgraph/index.js +0 -325
- package/dist/langgraph/index.js.map +0 -1
- package/dist/langgraph/keepalive.d.ts +0 -16
- package/dist/langgraph/keepalive.d.ts.map +0 -1
- package/dist/langgraph/keepalive.js +0 -51
- package/dist/langgraph/keepalive.js.map +0 -1
- package/dist/langgraph/nodes.d.ts +0 -71
- package/dist/langgraph/nodes.d.ts.map +0 -1
- package/dist/langgraph/nodes.js +0 -148
- package/dist/langgraph/nodes.js.map +0 -1
- package/dist/messages.d.ts +0 -18
- package/dist/messages.d.ts.map +0 -1
- package/dist/messages.js +0 -182
- package/dist/messages.js.map +0 -1
- package/dist/object.d.ts +0 -213
- package/dist/object.d.ts.map +0 -1
- package/dist/object.js +0 -309
- package/dist/object.js.map +0 -1
- package/dist/opencode/db.d.ts +0 -81
- package/dist/opencode/db.d.ts.map +0 -1
- package/dist/opencode/db.js +0 -249
- package/dist/opencode/db.js.map +0 -1
- package/dist/opencode/index.d.ts +0 -184
- package/dist/opencode/index.d.ts.map +0 -1
- package/dist/opencode/index.js +0 -1079
- package/dist/opencode/index.js.map +0 -1
- package/dist/output.d.ts +0 -25
- package/dist/output.d.ts.map +0 -1
- package/dist/output.js +0 -99
- package/dist/output.js.map +0 -1
- package/dist/pi/commits.d.ts +0 -6
- package/dist/pi/commits.d.ts.map +0 -1
- package/dist/pi/commits.js +0 -3
- package/dist/pi/commits.js.map +0 -1
- package/dist/steering.d.ts +0 -32
- package/dist/steering.d.ts.map +0 -1
- package/dist/steering.js +0 -45
- package/dist/steering.js.map +0 -1
- package/dist/tools.d.ts +0 -267
- package/dist/tools.d.ts.map +0 -1
- package/dist/tools.js +0 -305
- package/dist/tools.js.map +0 -1
- package/dist/webhook.d.ts +0 -71
- package/dist/webhook.d.ts.map +0 -1
- package/dist/webhook.js +0 -102
- package/dist/webhook.js.map +0 -1
- package/src/agentlib/README.md +0 -229
- package/src/agentlib/agent.ts +0 -216
- package/src/agentlib/index.ts +0 -16
- package/src/agentlib/messages.ts +0 -207
- package/src/agentlib/model.ts +0 -156
- package/src/agentlib/options.ts +0 -62
- package/src/agentlib/runtime.ts +0 -252
- package/src/agentlib/state.ts +0 -93
- package/src/agentlib/steering.ts +0 -53
- package/src/agentlib/tools.ts +0 -355
- package/src/agentlib/turn.ts +0 -302
- package/src/calls.ts +0 -330
- package/src/claude/README.md +0 -107
- package/src/claude/index.ts +0 -487
- package/src/client.ts +0 -187
- package/src/common.ts +0 -766
- package/src/companion.ts +0 -675
- package/src/conversation.ts +0 -1799
- package/src/deepseek/README.md +0 -202
- package/src/deepseek/barriers.ts +0 -63
- package/src/deepseek/index.ts +0 -740
- package/src/deepseek/persistence.ts +0 -337
- package/src/index.ts +0 -41
- package/src/langgraph/README.md +0 -199
- package/src/langgraph/checkpointer.ts +0 -614
- package/src/langgraph/context.ts +0 -27
- package/src/langgraph/errors.ts +0 -26
- package/src/langgraph/graph.ts +0 -422
- package/src/langgraph/index.ts +0 -500
- package/src/langgraph/keepalive.ts +0 -58
- package/src/langgraph/nodes.ts +0 -247
- package/src/messages.ts +0 -244
- package/src/object.ts +0 -454
- package/src/opencode/README.md +0 -249
- package/src/opencode/db.ts +0 -387
- package/src/opencode/index.ts +0 -1339
- package/src/output.ts +0 -116
- package/src/pi/README.md +0 -174
- package/src/pi/commits.ts +0 -7
- package/src/steering.ts +0 -68
- package/src/tools.ts +0 -515
- package/src/webhook.ts +0 -161
package/src/claude/index.ts
DELETED
|
@@ -1,487 +0,0 @@
|
|
|
1
|
-
// Claude agents in Restate virtual objects, on the tool runner of the
|
|
2
|
-
// Anthropic SDK (`client.beta.messages.toolRunner`): the conversation is the
|
|
3
|
-
// object's conversation of turns (../conversation.ts), whose items are the
|
|
4
|
-
// SDK's messages (`BetaMessageParam`).
|
|
5
|
-
//
|
|
6
|
-
// const assistant = claude.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
|
|
7
|
-
//
|
|
8
|
-
// or a handler of an object of your own: `handlers: { chat: claude.chat() }`,
|
|
9
|
-
// with options for each invocation: `claude.chat(async (ctx) => ({ system }))`,
|
|
10
|
-
// or a prompt of your own handler: `claude.prompt(ctx, text, options)`
|
|
11
|
-
//
|
|
12
|
-
// The model is `model`, or else MODEL, or else anthropic/claude-sonnet-5-5,
|
|
13
|
-
// with ANTHROPIC_API_KEY.
|
|
14
|
-
//
|
|
15
|
-
// The handler is not replayed: a retried attempt (a crash, a lost connection)
|
|
16
|
-
// runs again from the start, and starts the runner with what the model sees
|
|
17
|
-
// of the conversation (`history()`: the earlier turns as their prompts and
|
|
18
|
-
// answers, the latest whole):
|
|
19
|
-
// - Each reply of the model is stored before its tools run, and their results
|
|
20
|
-
// before the next request. So a crash during the tools resumes them with the
|
|
21
|
-
// same tool call ids (`callId(context)`), without asking the model again,
|
|
22
|
-
// and a tool passes the id on to stay idempotent. A stored final reply is
|
|
23
|
-
// the answer: the model is not asked for it again.
|
|
24
|
-
// - A tool's error fails the attempt, which Restate retries; but the SDK's
|
|
25
|
-
// `ToolError`, which is meant for the model, is the tool's result.
|
|
26
|
-
// - A message is answered once per invocation (`answerOnce`).
|
|
27
|
-
// - A reply cut off at `maxTokens`, declined, or past the model's context
|
|
28
|
-
// window ends the turn: its tool calls do not run, and the handler fails
|
|
29
|
-
// with a terminal error.
|
|
30
|
-
// - With `output`, a model with structured outputs is asked for it natively:
|
|
31
|
-
// each request of the run has its JSON schema (`output_config.format`),
|
|
32
|
-
// which holds the final reply to it, and tool calls go on as before. The
|
|
33
|
-
// reply is checked all the same (output.ts).
|
|
34
|
-
import * as restate from '@restatedev/sessions';
|
|
35
|
-
import { ScopeKey } from '@restatedev/sessions/internal';
|
|
36
|
-
import Anthropic from '@anthropic-ai/sdk';
|
|
37
|
-
import { betaZodOutputFormat } from '@anthropic-ai/sdk/helpers/beta/zod';
|
|
38
|
-
import type { BetaRunnableTool, BetaToolRunContext } from '@anthropic-ai/sdk/lib/tools/BetaRunnableTool';
|
|
39
|
-
import { ToolError } from '@anthropic-ai/sdk/lib/tools/ToolError';
|
|
40
|
-
import {
|
|
41
|
-
chatHandler,
|
|
42
|
-
CLAUDE_MODEL,
|
|
43
|
-
type Configure,
|
|
44
|
-
configured,
|
|
45
|
-
fromTool,
|
|
46
|
-
keepAlive,
|
|
47
|
-
modelIdOf,
|
|
48
|
-
modelOf,
|
|
49
|
-
RETURNED_UNRECORDED,
|
|
50
|
-
toolCallStarted,
|
|
51
|
-
stopSignalOf,
|
|
52
|
-
type Summarize,
|
|
53
|
-
NO_ANSWER,
|
|
54
|
-
} from '../common.ts';
|
|
55
|
-
import { answerOnce, type Items, type Parsed, type Run } from '../conversation.ts';
|
|
56
|
-
import { takeSteers } from '../steering.ts';
|
|
57
|
-
import { conversationView } from '../messages.ts';
|
|
58
|
-
import { type Answer, withChecked } from '../output.ts';
|
|
59
|
-
import type { z } from 'zod';
|
|
60
|
-
import { type Definition, sessionObject } from '../object.ts';
|
|
61
|
-
import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
|
|
62
|
-
|
|
63
|
-
type MessageParam = Anthropic.Beta.Messages.BetaMessageParam;
|
|
64
|
-
|
|
65
|
-
/** The id of the tool call a tool runs for: the runner always passes it. */
|
|
66
|
-
export const callId = (context?: BetaToolRunContext) => {
|
|
67
|
-
if (!context) throw new Error('a tool call without its context');
|
|
68
|
-
return context.toolUse.id;
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* `messages` as the API takes them: it refuses an empty text, and an
|
|
73
|
-
* assistant's message with no content but the last. The model may reply
|
|
74
|
-
* with nothing (stored as it came): sent back, such a reply says so.
|
|
75
|
-
*/
|
|
76
|
-
const sendable = (messages: MessageParam[]): MessageParam[] =>
|
|
77
|
-
messages.map((m) => {
|
|
78
|
-
if (m.role !== 'assistant') return m;
|
|
79
|
-
if (typeof m.content === 'string') return m.content.trim() ? m : { ...m, content: NO_ANSWER };
|
|
80
|
-
const content = m.content.filter((b) => b.type !== 'text' || b.text.trim() !== '');
|
|
81
|
-
if (content.length === 0) return { ...m, content: NO_ANSWER };
|
|
82
|
-
return content.length === m.content.length ? m : { ...m, content };
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
/** The text of stored content, without its tool calls and results. */
|
|
86
|
-
const storedText = (content: string | readonly { type: string; text?: string }[] | undefined) =>
|
|
87
|
-
typeof content === 'string' ? content : (content ?? []).flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('');
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Claude's items: the SDK's messages, as JSON. A user's text is said by the
|
|
91
|
-
* user, an assistant's by the assistant, and its `tool_use` blocks are its
|
|
92
|
-
* calls; a `tool_result` is a result. A server tool's blocks (and a
|
|
93
|
-
* `system` message) say nothing: they leave no open call the API would
|
|
94
|
-
* refuse a result for.
|
|
95
|
-
*/
|
|
96
|
-
export const items: Items<MessageParam> = {
|
|
97
|
-
dump: (message) => JSON.stringify(message),
|
|
98
|
-
load: (stored) => {
|
|
99
|
-
// Only a message of the API's (a role and its content): another framework's row is not one.
|
|
100
|
-
const message = JSON.parse(stored) as MessageParam;
|
|
101
|
-
const { role, content, ...rest } = message;
|
|
102
|
-
if ((role !== 'user' && role !== 'assistant') || (typeof content !== 'string' && !Array.isArray(content)))
|
|
103
|
-
throw new Error('not a message of the Claude API (a role and its content)');
|
|
104
|
-
if (Object.keys(rest).length > 0)
|
|
105
|
-
throw new Error(`not a message of the Claude API: ${Object.keys(rest).join(', ')}`);
|
|
106
|
-
return message;
|
|
107
|
-
},
|
|
108
|
-
prompt: (text) => ({ role: 'user', content: text }),
|
|
109
|
-
// The API refuses an empty text: an empty answer, as the model sees it later, says so.
|
|
110
|
-
reply: (text) => ({ role: 'assistant', content: text.trim() ? text : NO_ANSWER }),
|
|
111
|
-
// Every result of a reply in one message, as the API wants them.
|
|
112
|
-
results: (results) =>
|
|
113
|
-
results.length === 0
|
|
114
|
-
? []
|
|
115
|
-
: [
|
|
116
|
-
{
|
|
117
|
-
role: 'user',
|
|
118
|
-
content: results.map(([call, output]) => ({
|
|
119
|
-
type: 'tool_result' as const,
|
|
120
|
-
tool_use_id: call.id,
|
|
121
|
-
content: output,
|
|
122
|
-
...(output === RETURNED_UNRECORDED ? {} : { is_error: true }),
|
|
123
|
-
})),
|
|
124
|
-
},
|
|
125
|
-
],
|
|
126
|
-
read: (message): Parsed => {
|
|
127
|
-
if (message.role !== 'user' && message.role !== 'assistant') return {};
|
|
128
|
-
const { role, content } = message;
|
|
129
|
-
if (typeof content === 'string') return { said: [role, content] };
|
|
130
|
-
const texts = content.filter((b) => b.type === 'text');
|
|
131
|
-
const calls = content.flatMap((b) => (b.type === 'tool_use' ? [{ id: b.id, name: b.name, input: b.input }] : []));
|
|
132
|
-
const results = content.flatMap((b) =>
|
|
133
|
-
b.type === 'tool_result'
|
|
134
|
-
? [{ id: b.tool_use_id, output: storedText(b.content as never), error: b.is_error === true }]
|
|
135
|
-
: [],
|
|
136
|
-
);
|
|
137
|
-
// Each reply of the model is a message of its own, its tool calls' too (as
|
|
138
|
-
// the views gave them before); a message of results only says nothing.
|
|
139
|
-
const said = role === 'assistant' || texts.length > 0;
|
|
140
|
-
return {
|
|
141
|
-
...(said ? { said: [role, texts.map((b) => b.text).join('')] as ['user' | 'assistant', string] } : {}),
|
|
142
|
-
calls,
|
|
143
|
-
results,
|
|
144
|
-
};
|
|
145
|
-
},
|
|
146
|
-
};
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* `tools`, whose errors fail the attempt: the runner would hand a thrown error
|
|
150
|
-
* to the model as the tool's result, so each one is kept, for `check()` to
|
|
151
|
-
* throw once the tools ran. The SDK's `ToolError` is for the model: the
|
|
152
|
-
* runner hands it over as the tool's result.
|
|
153
|
-
*/
|
|
154
|
-
function failing(ctx: restate.SessionContext, tools: BetaRunnableTool[]) {
|
|
155
|
-
let failure: unknown;
|
|
156
|
-
return {
|
|
157
|
-
tools: tools.map((tool): BetaRunnableTool => ({
|
|
158
|
-
...tool,
|
|
159
|
-
run: async (args, context) => {
|
|
160
|
-
try {
|
|
161
|
-
return await tool.run(args, context);
|
|
162
|
-
} catch (e) {
|
|
163
|
-
if (e instanceof ToolError) throw e;
|
|
164
|
-
fromTool(ctx, e);
|
|
165
|
-
failure ??= e;
|
|
166
|
-
throw e;
|
|
167
|
-
}
|
|
168
|
-
},
|
|
169
|
-
})),
|
|
170
|
-
check: () => {
|
|
171
|
-
if (failure !== undefined) throw failure;
|
|
172
|
-
},
|
|
173
|
-
};
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
const textOf = (content: Anthropic.Beta.Messages.BetaContentBlock[]) =>
|
|
177
|
-
content
|
|
178
|
-
.filter((c) => c.type === 'text')
|
|
179
|
-
.map((c) => c.text)
|
|
180
|
-
.join('');
|
|
181
|
-
|
|
182
|
-
interface Agent {
|
|
183
|
-
client: Anthropic;
|
|
184
|
-
model: string;
|
|
185
|
-
maxTokens: number;
|
|
186
|
-
effort?: Effort;
|
|
187
|
-
system?: string;
|
|
188
|
-
tools: BetaRunnableTool[];
|
|
189
|
-
/** The JSON schema of `output`, asked for natively: the API holds the final reply to it. */
|
|
190
|
-
format?: Anthropic.Beta.Messages.BetaJSONOutputFormat;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/**
|
|
194
|
-
* The run of `agent` on the conversation: from the stored turn on, each
|
|
195
|
-
* reply with tool calls stored before its tools run, and their results
|
|
196
|
-
* after; each such write published as it commits, by the conversation (for
|
|
197
|
-
* the clients that follow it), and the final reply stored with the answer. At each step (before a request that follows the
|
|
198
|
-
* prompt or the tools' results), it takes the messages steered to the turn
|
|
199
|
-
* (`takeSteers`): the request then goes out from the conversation's
|
|
200
|
-
* history, which has them after the tools' results.
|
|
201
|
-
*/
|
|
202
|
-
const runOf =
|
|
203
|
-
(ctx: restate.SessionContext, agent: Agent): Run<MessageParam> =>
|
|
204
|
-
async (conversation) => {
|
|
205
|
-
const { client, model, maxTokens, effort, system, format } = agent;
|
|
206
|
-
const turn = conversation.turn;
|
|
207
|
-
for (;;) {
|
|
208
|
-
// A stored final reply is the answer: the model is not asked for it again.
|
|
209
|
-
const final = turn.finalReply();
|
|
210
|
-
if (final !== undefined) return final;
|
|
211
|
-
// A paused reply goes back as the last message, which a steered one would not leave it.
|
|
212
|
-
if (turn.entries.at(-1)!.parsed?.said?.[0] !== 'assistant') await takeSteers(ctx, conversation);
|
|
213
|
-
const { tools, check } = failing(ctx, agent.tools);
|
|
214
|
-
const runner = client.beta.messages.toolRunner(
|
|
215
|
-
{
|
|
216
|
-
model,
|
|
217
|
-
max_tokens: maxTokens,
|
|
218
|
-
...(effort === undefined && format === undefined ? {} : { output_config: { effort, format } }),
|
|
219
|
-
...(system === undefined ? {} : { system }),
|
|
220
|
-
tools,
|
|
221
|
-
messages: sendable(conversation.history()),
|
|
222
|
-
// The conversation is the session's: each request carries all of it, as stored, and no message thread
|
|
223
|
-
// of the API's holds a copy that a crash or a steered message would leave behind.
|
|
224
|
-
thread: false,
|
|
225
|
-
},
|
|
226
|
-
{ signal: stopSignalOf(ctx) },
|
|
227
|
-
);
|
|
228
|
-
/** A step: the messages steered to the turn go into the next request, after the tools' results. */
|
|
229
|
-
const step = async () => {
|
|
230
|
-
if ((await takeSteers(ctx, conversation)).length === 0) return;
|
|
231
|
-
// The runner leaves the history to its caller, who changed it: the reply, its results and the messages.
|
|
232
|
-
runner.setMessagesParams((params) => ({ ...params, messages: sendable(conversation.history()) }));
|
|
233
|
-
};
|
|
234
|
-
// A reply whose tools did not finish (a crash): run them, with the same
|
|
235
|
-
// ids, once the calls whose results are stored are settled, as for any
|
|
236
|
-
// reply: else one of its calls could take the id of an identical call
|
|
237
|
-
// answered before.
|
|
238
|
-
if (turn.openCalls().length > 0) {
|
|
239
|
-
await toolCallStarted(ctx);
|
|
240
|
-
const results = await runner.generateToolResponse();
|
|
241
|
-
check();
|
|
242
|
-
if (results) {
|
|
243
|
-
await turn.append(results);
|
|
244
|
-
runner.pushMessages(results);
|
|
245
|
-
}
|
|
246
|
-
await step();
|
|
247
|
-
}
|
|
248
|
-
let paused = false;
|
|
249
|
-
for await (const message of requests(ctx, runner)) {
|
|
250
|
-
// A reply that cannot go on ends the turn, whose tool calls do not run.
|
|
251
|
-
const stopped = stoppedShort(message, maxTokens);
|
|
252
|
-
if (stopped) throw new restate.TerminalError(stopped);
|
|
253
|
-
const said: MessageParam = { role: 'assistant', content: message.content };
|
|
254
|
-
// Paused (a server tool's long turn): a step of the turn, not a reply to
|
|
255
|
-
// end it with, and the model goes on from it.
|
|
256
|
-
if (message.stop_reason === 'pause_turn') {
|
|
257
|
-
// Stored before the model goes on: a crash in a server tool's long turn goes on from it, rather than
|
|
258
|
-
// ask the whole of it again.
|
|
259
|
-
await turn.append(said);
|
|
260
|
-
await conversation.flush();
|
|
261
|
-
paused = true;
|
|
262
|
-
break;
|
|
263
|
-
}
|
|
264
|
-
// A reply with tool calls commits, and is published, before its tools run; the final reply commits with
|
|
265
|
-
// the turn's answer.
|
|
266
|
-
await turn.appendReply([said]);
|
|
267
|
-
if (!message.content.some((c) => c.type === 'tool_use')) return textOf(message.content);
|
|
268
|
-
await toolCallStarted(ctx);
|
|
269
|
-
const results = await runner.generateToolResponse();
|
|
270
|
-
check();
|
|
271
|
-
if (results) await turn.append(results);
|
|
272
|
-
await step();
|
|
273
|
-
}
|
|
274
|
-
if (!paused) throw new Error('the tool runner ended without a reply');
|
|
275
|
-
}
|
|
276
|
-
};
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* `runner`'s replies, each model request kept alive: from the moment the
|
|
280
|
-
* loop asks for the next reply until it arrives (the runner does not stream,
|
|
281
|
-
* so the reply is the whole response), however it ends: an error, or the turn
|
|
282
|
-
* stopped. The tools run outside it: the loop runs them (`generateToolResponse`)
|
|
283
|
-
* before it asks again, and the runner then finds their results done.
|
|
284
|
-
*/
|
|
285
|
-
async function* requests<T>(ctx: restate.SessionContext, runner: AsyncIterable<T>): AsyncGenerator<T> {
|
|
286
|
-
const replies = runner[Symbol.asyncIterator]();
|
|
287
|
-
try {
|
|
288
|
-
for (;;) {
|
|
289
|
-
const release = keepAlive(ctx);
|
|
290
|
-
let next: IteratorResult<T>;
|
|
291
|
-
try {
|
|
292
|
-
next = await replies.next();
|
|
293
|
-
} finally {
|
|
294
|
-
release();
|
|
295
|
-
}
|
|
296
|
-
if (next.done) return;
|
|
297
|
-
yield next.value;
|
|
298
|
-
}
|
|
299
|
-
} finally {
|
|
300
|
-
// Ends the runner's loop (its span and its stream) when the caller leaves it early, as a final reply does.
|
|
301
|
-
await replies.return?.();
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
/**
|
|
306
|
-
* Why the model's `message` stopped short of a reply to go on from: cut off
|
|
307
|
-
* at `maxTokens` (its text, or a tool call's input, unfinished), declined, or
|
|
308
|
-
* past the model's context window: a terminal error's message.
|
|
309
|
-
*/
|
|
310
|
-
function stoppedShort(message: Anthropic.Beta.Messages.BetaMessage, maxTokens: number) {
|
|
311
|
-
if (message.stop_reason === 'max_tokens') {
|
|
312
|
-
return `the model's reply reached maxTokens (${maxTokens}) before it ended: raise the agent's maxTokens`;
|
|
313
|
-
}
|
|
314
|
-
if (message.stop_reason === 'refusal') {
|
|
315
|
-
const category = message.stop_details?.category;
|
|
316
|
-
return `the model declined to answer${category ? ` (${category})` : ''}`;
|
|
317
|
-
}
|
|
318
|
-
if (message.stop_reason === 'model_context_window_exceeded') {
|
|
319
|
-
return "the conversation outgrew the model's context window: lower the agent's window or budget";
|
|
320
|
-
}
|
|
321
|
-
return undefined;
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/** `t` as a tool of the Anthropic SDK's tool runner: `t.run` checks the model's arguments itself. */
|
|
325
|
-
const native = (t: AnyTool, ctx: restate.SessionContext): BetaRunnableTool => ({
|
|
326
|
-
type: 'custom',
|
|
327
|
-
name: t.name,
|
|
328
|
-
description: t.description,
|
|
329
|
-
input_schema: jsonSchemaOf(t) as Anthropic.Beta.Messages.BetaTool.InputSchema,
|
|
330
|
-
parse: (args) => args,
|
|
331
|
-
run: (args, context) => t.run(args, { ctx, callId: callId(context) }),
|
|
332
|
-
});
|
|
333
|
-
|
|
334
|
-
/** How much effort the model puts into a reply (Anthropic's `output_config.effort`). */
|
|
335
|
-
export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
336
|
-
|
|
337
|
-
/** An agent's options: `chat` and `prompt` take them. */
|
|
338
|
-
export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
|
|
339
|
-
/** The model, as `anthropic/model-id`: MODEL, or else anthropic/claude-sonnet-5-5. */
|
|
340
|
-
model?: string;
|
|
341
|
-
/** The system prompt. */
|
|
342
|
-
system?: string;
|
|
343
|
-
/** The agent's tools: `tool()`s, Restate's (`call`, `signal`...), or the SDK's (such as `betaZodTool`s). */
|
|
344
|
-
tools?: (AnyTool | BetaRunnableTool)[];
|
|
345
|
-
/** The client of the Anthropic API: by default one with ANTHROPIC_API_KEY. */
|
|
346
|
-
client?: Anthropic;
|
|
347
|
-
/**
|
|
348
|
-
* The most tokens of each of the model's replies (default 16000). A reply
|
|
349
|
-
* cut off there ends its prompt, which fails (a terminal error).
|
|
350
|
-
*/
|
|
351
|
-
maxTokens?: number;
|
|
352
|
-
/** How much effort the model puts into each reply: more is more thorough, and slower (default: the model's). */
|
|
353
|
-
effort?: Effort;
|
|
354
|
-
/**
|
|
355
|
-
* The answer as data: a zod object, whose JSON the agent replies with
|
|
356
|
-
* (checked), and `chat` and `prompt` answer with (see output.ts).
|
|
357
|
-
*/
|
|
358
|
-
output?: O;
|
|
359
|
-
/**
|
|
360
|
-
* Whether the model is asked for `output` natively, with the API's
|
|
361
|
-
* structured outputs (`output_config.format`: the JSON schema the API
|
|
362
|
-
* holds the final reply to), rather than in the prompt (default: if the
|
|
363
|
-
* model has them, as Claude's have since the 4.5 models). A schema the API
|
|
364
|
-
* cannot take (too complex, say) refuses the message: `false` asks in the
|
|
365
|
-
* prompt instead.
|
|
366
|
-
*/
|
|
367
|
-
nativeOutput?: boolean;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
/**
|
|
371
|
-
* The Claude models with structured outputs: of each family, the 4.5 models
|
|
372
|
-
* and later (and Mythos Preview); not Claude 3, Opus 4 and 4.1, or Sonnet 4.
|
|
373
|
-
*/
|
|
374
|
-
const STRUCTURED_OUTPUTS =
|
|
375
|
-
/claude-(?:(?:opus|sonnet|haiku)-4-[5-9](?!\d)|(?:opus|sonnet|haiku|fable|mythos)-(?:[5-9]|[1-9]\d)|mythos-preview)/;
|
|
376
|
-
|
|
377
|
-
/** Whether an agent of `options` asks the model for its `output` natively (see `nativeOutput`). */
|
|
378
|
-
const asksNatively = ({ model, output, nativeOutput }: Options) =>
|
|
379
|
-
output !== undefined &&
|
|
380
|
-
(nativeOutput ?? STRUCTURED_OUTPUTS.test(modelIdOf(modelOf(model, CLAUDE_MODEL), 'anthropic')));
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* `output`'s JSON schema, as the API takes it (the SDK's helper's): what the
|
|
384
|
-
* API does not take (a string's `minLength`, say) goes to a description, and
|
|
385
|
-
* is left to the check of the reply.
|
|
386
|
-
*/
|
|
387
|
-
const formatOf = (output: z.ZodObject): Anthropic.Beta.Messages.BetaJSONOutputFormat => {
|
|
388
|
-
const { type, schema } = betaZodOutputFormat(output);
|
|
389
|
-
return { type, schema };
|
|
390
|
-
};
|
|
391
|
-
|
|
392
|
-
/** The client of an agent without one of its own, on the context of the turn it answers. */
|
|
393
|
-
const CLIENT = new ScopeKey<Anthropic>('the Anthropic client');
|
|
394
|
-
|
|
395
|
-
/** The agent of `options`, for the turn of `ctx`. */
|
|
396
|
-
const agentOf = (ctx: restate.SessionContext, options: Options): Agent => {
|
|
397
|
-
const { model, system, tools = [], client, maxTokens = 16_000, effort, output } = options;
|
|
398
|
-
return {
|
|
399
|
-
client: client ?? CLIENT.of(ctx, () => new Anthropic()),
|
|
400
|
-
model: modelIdOf(modelOf(model, CLAUDE_MODEL), 'anthropic'),
|
|
401
|
-
maxTokens,
|
|
402
|
-
effort,
|
|
403
|
-
system,
|
|
404
|
-
tools: tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
|
|
405
|
-
...(output !== undefined && asksNatively(options) ? { format: formatOf(output) } : {}),
|
|
406
|
-
};
|
|
407
|
-
};
|
|
408
|
-
|
|
409
|
-
/**
|
|
410
|
-
* Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
|
|
411
|
-
* of an invocation is a prompt of its own.
|
|
412
|
-
* With `output`, it answers with the value the agent replies with (see
|
|
413
|
-
* output.ts), not its text: a reply that is not one is asked again within
|
|
414
|
-
* its turn, once. A model with structured outputs is asked for it natively
|
|
415
|
-
* (`nativeOutput`), else in the prompt.
|
|
416
|
-
*/
|
|
417
|
-
export const prompt = async <O extends z.ZodObject | undefined = undefined>(
|
|
418
|
-
ctx: restate.SessionContext,
|
|
419
|
-
text: string,
|
|
420
|
-
options: Options<O> = {},
|
|
421
|
-
): Promise<Answer<O>> =>
|
|
422
|
-
withChecked(
|
|
423
|
-
text,
|
|
424
|
-
options,
|
|
425
|
-
(t, o, check, reminder) => answerOnce(ctx, t, items, runOf(ctx, agentOf(ctx, o)), { check, reminder }),
|
|
426
|
-
asksNatively(options),
|
|
427
|
-
) as Promise<Answer<O>>;
|
|
428
|
-
|
|
429
|
-
/**
|
|
430
|
-
* A chat handler: each message an invocation, the conversation in the
|
|
431
|
-
* object's database, with `options`, or the options a function of the
|
|
432
|
-
* invocation's context gives. It takes the message as plain text
|
|
433
|
-
* (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
|
|
434
|
-
*/
|
|
435
|
-
export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
|
|
436
|
-
if (typeof options === 'object') modelIdOf(modelOf(options.model, CLAUDE_MODEL), 'anthropic');
|
|
437
|
-
return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)), { steers: true });
|
|
438
|
-
};
|
|
439
|
-
|
|
440
|
-
/**
|
|
441
|
-
* A view of the conversation as clients read it: a page at a time, or what
|
|
442
|
-
* is new or changed since a cursor; `view: 'summary'` for each turn's
|
|
443
|
-
* message and answer. It answers while a message is answered.
|
|
444
|
-
*/
|
|
445
|
-
export const messages = () => conversationView(items);
|
|
446
|
-
|
|
447
|
-
/**
|
|
448
|
-
* How an agent of `options` summarizes the earliest turns, past its budget:
|
|
449
|
-
* with its own client and model (`agent()` gives it; for an object of your
|
|
450
|
-
* own, `sessionObject`'s `summarize`).
|
|
451
|
-
*/
|
|
452
|
-
export const summarizer =
|
|
453
|
-
(options: Options = {}): Summarize =>
|
|
454
|
-
async (ctx, request) => {
|
|
455
|
-
const { client, model, maxTokens } = agentOf(ctx, { ...options, tools: [] });
|
|
456
|
-
const message = await ctx.working(() =>
|
|
457
|
-
client.beta.messages.create({
|
|
458
|
-
model,
|
|
459
|
-
max_tokens: maxTokens,
|
|
460
|
-
messages: [{ role: 'user', content: request }],
|
|
461
|
-
}),
|
|
462
|
-
);
|
|
463
|
-
return textOf(message.content);
|
|
464
|
-
};
|
|
465
|
-
|
|
466
|
-
/** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
|
|
467
|
-
export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
|
|
468
|
-
name,
|
|
469
|
-
description,
|
|
470
|
-
schema,
|
|
471
|
-
background,
|
|
472
|
-
window,
|
|
473
|
-
budget,
|
|
474
|
-
summarize,
|
|
475
|
-
...options
|
|
476
|
-
}: Options<O> & Definition<P>) =>
|
|
477
|
-
sessionObject({
|
|
478
|
-
name,
|
|
479
|
-
description,
|
|
480
|
-
schema,
|
|
481
|
-
background,
|
|
482
|
-
window,
|
|
483
|
-
budget,
|
|
484
|
-
summarize: summarize ?? summarizer(options),
|
|
485
|
-
handlers: { chat: chat(options) },
|
|
486
|
-
views: { messages: messages() },
|
|
487
|
-
});
|
package/src/client.ts
DELETED
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
// An agent for Restate's client (@restatedev/restate-sdk-clients), from a
|
|
2
|
-
// chat UI or any other code: the agent's definition as the client takes it,
|
|
3
|
-
// its name and the types of its handlers, and the types of what they answer;
|
|
4
|
-
// and `follow`, which follows its conversation as it changes. It imports
|
|
5
|
-
// Restate's client, and nothing of the agent's code or the SDK, so a web app
|
|
6
|
-
// bundles it as it is.
|
|
7
|
-
//
|
|
8
|
-
// import * as clients from '@restatedev/restate-sdk-clients';
|
|
9
|
-
// import { agent, follow } from '@restatedev/agents/client';
|
|
10
|
-
//
|
|
11
|
-
// const restate = clients.connect({ url: 'http://localhost:8080' });
|
|
12
|
-
// const alice = restate.objectClient(agent('assistant'), 'alice');
|
|
13
|
-
// const { messages } = await alice.messages({ limit: 20 });
|
|
14
|
-
// for await (const { status, messages } of follow(restate, agent('assistant'), 'alice')) { ... }
|
|
15
|
-
import * as clients from '@restatedev/restate-sdk-clients';
|
|
16
|
-
import type { VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
|
|
17
|
-
import type { Answering, ChatMessage, Messages, MessagesRequest, Part } from './common.ts';
|
|
18
|
-
import type { Status, Stopped, Synced, SyncRequest } from './object.ts';
|
|
19
|
-
import type { Notifications, Resolved, Signal, Steered, Steering, Waiting, Watch } from './companion.ts';
|
|
20
|
-
|
|
21
|
-
export type {
|
|
22
|
-
Answering,
|
|
23
|
-
ChatMessage,
|
|
24
|
-
Messages,
|
|
25
|
-
MessagesRequest,
|
|
26
|
-
Notifications,
|
|
27
|
-
Part,
|
|
28
|
-
Resolved,
|
|
29
|
-
Signal,
|
|
30
|
-
Status,
|
|
31
|
-
Steered,
|
|
32
|
-
Steering,
|
|
33
|
-
Stopped,
|
|
34
|
-
Synced,
|
|
35
|
-
SyncRequest,
|
|
36
|
-
Waiting,
|
|
37
|
-
Watch,
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
/** The handlers of an agent (`agent()` of any framework), as Restate's client calls them. */
|
|
41
|
-
export interface Agent {
|
|
42
|
-
/** Answer `message`. */
|
|
43
|
-
chat(ctx: unknown, message: string): Promise<string>;
|
|
44
|
-
/**
|
|
45
|
-
* Send `message` while the agent answers another: the turn being answered
|
|
46
|
-
* takes it at its next step (once its model's tool calls have their
|
|
47
|
-
* results), and its answer covers it; else it is answered as a turn of its
|
|
48
|
-
* own, after the messages before it. Either way it is answered once: send
|
|
49
|
-
* it with an idempotency key, made once per message, so that sending it
|
|
50
|
-
* again is the same message.
|
|
51
|
-
*/
|
|
52
|
-
steer(ctx: unknown, message: string): Promise<Steered>;
|
|
53
|
-
/** The conversation, a page at a time, or what is new or changed since a cursor, also while a message is answered. */
|
|
54
|
-
messages(ctx: unknown, request?: MessagesRequest): Promise<Messages>;
|
|
55
|
-
/** The conversation since a cursor, the status and the revision; with `revision`, once there is a newer one. */
|
|
56
|
-
sync(ctx: unknown, request?: SyncRequest): Promise<Synced>;
|
|
57
|
-
/** What the agent is doing: the message it answers, and what its tools wait for. */
|
|
58
|
-
status(ctx: unknown): Promise<Status>;
|
|
59
|
-
/** Stop the message it answers: cancel its invocation. */
|
|
60
|
-
stop(ctx: unknown): Promise<Stopped>;
|
|
61
|
-
/** Forget the conversation (stopping the message it answers): its database and state too. */
|
|
62
|
-
clear(ctx: unknown): Promise<Stopped>;
|
|
63
|
-
/** What its tools wait for. */
|
|
64
|
-
pending(ctx: unknown): Promise<Waiting[]>;
|
|
65
|
-
/** Resolve a wait: by its id, or the oldest for a name. */
|
|
66
|
-
signal(ctx: unknown, signal: Signal): Promise<Resolved>;
|
|
67
|
-
/** The revision of its conversation, which each change increases. */
|
|
68
|
-
notifications(ctx: unknown): Promise<Notifications>;
|
|
69
|
-
/** The revision, once there is one newer than `revision`, or at the timeout. */
|
|
70
|
-
watch(ctx: unknown, watch: Watch): Promise<Notifications>;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* The agent `name`, as Restate's client takes it: its name, typed with the
|
|
75
|
-
* handlers of an agent (or `H`, an object of your own's).
|
|
76
|
-
*/
|
|
77
|
-
export const agent = <H = Agent, P extends string = string>(name: P) => ({ name }) as VirtualObjectDefinition<P, H>;
|
|
78
|
-
|
|
79
|
-
/** What {@link follow} gives each time the conversation changes. */
|
|
80
|
-
export interface Followed {
|
|
81
|
-
/** What the agent is doing now. */
|
|
82
|
-
status: Status;
|
|
83
|
-
/**
|
|
84
|
-
* The messages new or changed since the last time, by when they changed: a
|
|
85
|
-
* message may come again, changed (a tool call with its output, say), with
|
|
86
|
-
* its `id`, which a UI keeps them by, and orders them by.
|
|
87
|
-
*/
|
|
88
|
-
messages: ChatMessage[];
|
|
89
|
-
/**
|
|
90
|
-
* The id of the conversation's first message: one kept from before is
|
|
91
|
-
* gone (`clear` forgot it), and a UI drops it.
|
|
92
|
-
*/
|
|
93
|
-
first: number;
|
|
94
|
-
/** Where this leaves off: `follow(..., { cursor })` carries on from here, later or elsewhere. */
|
|
95
|
-
cursor: number;
|
|
96
|
-
/** What the agent's tools wait for now (`status.waiting`). */
|
|
97
|
-
waiting: Waiting[];
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* `message` to read, such as in a terminal: its text after its role, and
|
|
102
|
-
* each tool call on a line of its own, with its output (`…` until it has one).
|
|
103
|
-
*/
|
|
104
|
-
export const asText = ({ role, parts }: ChatMessage) =>
|
|
105
|
-
parts
|
|
106
|
-
.map((part) =>
|
|
107
|
-
part.type === 'text'
|
|
108
|
-
? `${role}: ${part.text}`
|
|
109
|
-
: ` ${part.name}(${JSON.stringify(part.input)}) -> ${part.output ?? '…'}`,
|
|
110
|
-
)
|
|
111
|
-
.join('\n');
|
|
112
|
-
|
|
113
|
-
/** Where {@link follow} starts, and what stops it. */
|
|
114
|
-
export interface FollowOptions {
|
|
115
|
-
/** The messages new or changed since this cursor (a page's, or a `Followed`'s); by default, all of them. */
|
|
116
|
-
cursor?: number;
|
|
117
|
-
/** Following ends once it aborts. */
|
|
118
|
-
signal?: AbortSignal;
|
|
119
|
-
/** How long one wait for a change lasts at most, in seconds (default 50). */
|
|
120
|
-
timeoutSeconds?: number;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/** Whether a retry may answer: a network failure, Restate's (5xx) or too many requests (429); not a 4xx. */
|
|
124
|
-
const transient = (error: unknown) =>
|
|
125
|
-
!(error instanceof clients.HttpCallError) || error.status >= 500 || error.status === 429;
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* One `sync` of `followed`, tried again a second later with the same
|
|
129
|
-
* idempotency key until it answers, unless its error would last; undefined
|
|
130
|
-
* once `signal` aborts.
|
|
131
|
-
*/
|
|
132
|
-
async function syncRetried(
|
|
133
|
-
followed: clients.IngressClient<Agent>,
|
|
134
|
-
request: SyncRequest,
|
|
135
|
-
signal: AbortSignal | undefined,
|
|
136
|
-
): Promise<Synced | undefined> {
|
|
137
|
-
const opts = clients.rpc.opts<SyncRequest, Synced>({ signal, idempotencyKey: crypto.randomUUID() });
|
|
138
|
-
for (;;) {
|
|
139
|
-
if (signal?.aborted) return undefined;
|
|
140
|
-
try {
|
|
141
|
-
return await followed.sync(request, opts);
|
|
142
|
-
} catch (error) {
|
|
143
|
-
if (signal?.aborted) return undefined;
|
|
144
|
-
if (!transient(error)) throw error;
|
|
145
|
-
console.warn('follow: retrying', error);
|
|
146
|
-
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* The conversation of the agent `definition` (such as `agent('assistant')`)
|
|
153
|
-
* with key `key`, as it changes, through `ingress` (Restate's client): what
|
|
154
|
-
* the agent is doing and the messages so far, then each change, until
|
|
155
|
-
* `signal` aborts.
|
|
156
|
-
*
|
|
157
|
-
* Each change is one `sync`, which waits in Restate for the next. A network
|
|
158
|
-
* failure (or Restate's, restarting) does not end it: it tries again, and a
|
|
159
|
-
* sync it retries keeps its idempotency key, so it joins the one already
|
|
160
|
-
* waiting.
|
|
161
|
-
*/
|
|
162
|
-
export async function* follow(
|
|
163
|
-
ingress: clients.Ingress,
|
|
164
|
-
definition: VirtualObjectDefinition<string, Agent>,
|
|
165
|
-
key: string,
|
|
166
|
-
{ cursor = 0, signal, timeoutSeconds = 50 }: FollowOptions = {},
|
|
167
|
-
): AsyncGenerator<Followed, void, void> {
|
|
168
|
-
const followed = ingress.objectClient(definition, key);
|
|
169
|
-
let revision: number | undefined;
|
|
170
|
-
for (;;) {
|
|
171
|
-
const synced = await syncRetried(followed, { cursor, revision, timeoutSeconds }, signal);
|
|
172
|
-
if (!synced) return;
|
|
173
|
-
// Nothing changed (the wait timed out): wait again.
|
|
174
|
-
if (synced.revision !== revision || synced.messages.length > 0) {
|
|
175
|
-
yield {
|
|
176
|
-
status: synced.status,
|
|
177
|
-
messages: synced.messages,
|
|
178
|
-
first: synced.first ?? 0,
|
|
179
|
-
cursor: synced.cursor,
|
|
180
|
-
waiting: synced.status.waiting,
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
cursor = synced.cursor;
|
|
184
|
-
// With more to read, at once; else once something changes.
|
|
185
|
-
revision = synced.more ? undefined : synced.revision;
|
|
186
|
-
}
|
|
187
|
-
}
|