@statelyai/agent 2.0.0-alpha.11 → 2.0.0-alpha.13
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/dist/ai-sdk.cjs +4 -5
- package/dist/ai-sdk.d.cts +7 -4
- package/dist/ai-sdk.d.mts +7 -4
- package/dist/ai-sdk.mjs +1 -2
- package/dist/{events-JiVPYrct.mjs → decision-BezSD_YC.mjs} +327 -20
- package/dist/{events-CRQj3VtP.cjs → decision-dWGhBh0P.cjs} +401 -28
- package/dist/errors-BQRk9eiZ.d.cts +19 -0
- package/dist/errors-C9rxnWbX.d.mts +19 -0
- package/dist/errors-CeSXQx0v.mjs +23 -0
- package/dist/errors-DUBBzRLP.cjs +28 -0
- package/dist/event-log-store-CNT_7F0V.cjs +452 -0
- package/dist/event-log-store-CriMgX1D.d.mts +144 -0
- package/dist/event-log-store-D7pWtIhb.mjs +411 -0
- package/dist/event-log-store-Ruq18mGp.d.cts +144 -0
- package/dist/index.cjs +1050 -705
- package/dist/index.d.cts +538 -565
- package/dist/index.d.mts +538 -565
- package/dist/index.mjs +950 -644
- package/dist/machines.cjs +752 -0
- package/dist/machines.d.cts +372 -0
- package/dist/machines.d.mts +372 -0
- package/dist/machines.mjs +741 -0
- package/dist/otel.cjs +268 -0
- package/dist/otel.d.cts +67 -0
- package/dist/otel.d.mts +67 -0
- package/dist/otel.mjs +267 -0
- package/dist/run-agent-C3mFDGTf.d.mts +1111 -0
- package/dist/run-agent-DnvtcnTZ.d.cts +1111 -0
- package/dist/setup-agent-DAZZSjDS.mjs +1711 -0
- package/dist/setup-agent-DP95MFrI.cjs +1836 -0
- package/dist/sqlite.cjs +135 -0
- package/dist/sqlite.d.cts +57 -0
- package/dist/sqlite.d.mts +57 -0
- package/dist/sqlite.mjs +133 -0
- package/dist/{text-logic-CaKqgX4Y.d.mts → text-logic-BDxwQNsD.d.cts} +155 -72
- package/dist/{text-logic-Ckhr2kKC.d.cts → text-logic-TkKPw8Aq.d.mts} +155 -72
- package/dist/{types-qm00QF91.d.mts → types-QbEfCVny.d.cts} +1 -1
- package/dist/{types-C9QiMjre.d.cts → types-_FXoFBGO.d.mts} +1 -1
- package/package.json +47 -39
- package/readme.md +49 -12
- package/schemas/agent-workflow.json +40 -21
- package/skills/generate-machine/SKILL.md +267 -0
- package/dist/adapter.cjs +0 -15
- package/dist/adapter.d.cts +0 -4
- package/dist/adapter.d.mts +0 -4
- package/dist/adapter.mjs +0 -2
- package/dist/decision-C3k4ve51.mjs +0 -227
- package/dist/decision-D8wJrM8W.cjs +0 -286
- package/dist/openai-compat.cjs +0 -309
- package/dist/openai-compat.d.cts +0 -59
- package/dist/openai-compat.d.mts +0 -59
- package/dist/openai-compat.mjs +0 -308
- package/dist/steps-BALp1eZo.d.mts +0 -198
- package/dist/steps-CVe54GPP.cjs +0 -420
- package/dist/steps-CkyyyuHd.mjs +0 -379
- package/dist/steps-MjnQI4aB.d.cts +0 -198
- package/dist/steps.cjs +0 -12
- package/dist/steps.d.cts +0 -3
- package/dist/steps.d.mts +0 -3
- package/dist/steps.mjs +0 -3
- package/dist/utils-BYqT_Dyv.d.cts +0 -108
- package/dist/utils-Do5wIJrh.d.mts +0 -108
- package/dist/zod.cjs +0 -31
- package/dist/zod.d.cts +0 -30
- package/dist/zod.d.mts +0 -30
- package/dist/zod.mjs +0 -30
package/dist/openai-compat.mjs
DELETED
|
@@ -1,308 +0,0 @@
|
|
|
1
|
-
import { L as isStandardSchema, N as getJsonSchema, P as getJsonSchemaSync, d as buildEnvelopeSchema, h as getAgentOutputMode } from "./events-JiVPYrct.mjs";
|
|
2
|
-
import { l as renderDecisionAttempts } from "./decision-C3k4ve51.mjs";
|
|
3
|
-
//#region src/openai-compat/mappers.ts
|
|
4
|
-
/** Maps `AgentTextRequest.messages`/`system`/`prompt` to Chat Completions messages. */
|
|
5
|
-
function toOpenAiMessages(request) {
|
|
6
|
-
if (request.messages) return request.messages.flatMap((message) => {
|
|
7
|
-
const content = typeof message.content === "string" ? message.content : "";
|
|
8
|
-
switch (message.role) {
|
|
9
|
-
case "system": return [{
|
|
10
|
-
role: "system",
|
|
11
|
-
content
|
|
12
|
-
}];
|
|
13
|
-
case "user": return [{
|
|
14
|
-
role: "user",
|
|
15
|
-
content
|
|
16
|
-
}];
|
|
17
|
-
case "assistant": return [{
|
|
18
|
-
role: "assistant",
|
|
19
|
-
content
|
|
20
|
-
}];
|
|
21
|
-
case "tool": return message.content.map((part) => ({
|
|
22
|
-
role: "tool",
|
|
23
|
-
content: part.output.type === "text" || part.output.type === "error-text" ? part.output.value : JSON.stringify(part.output.value),
|
|
24
|
-
tool_call_id: part.toolCallId
|
|
25
|
-
}));
|
|
26
|
-
}
|
|
27
|
-
});
|
|
28
|
-
const messages = [];
|
|
29
|
-
if (request.system) messages.push({
|
|
30
|
-
role: "system",
|
|
31
|
-
content: request.system
|
|
32
|
-
});
|
|
33
|
-
messages.push({
|
|
34
|
-
role: "user",
|
|
35
|
-
content: request.prompt ?? ""
|
|
36
|
-
});
|
|
37
|
-
return messages;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Maps sampling/stop settings. Targets `max_tokens` (not
|
|
41
|
-
* `max_completion_tokens`) — it's the field every OpenAI-compatible backend
|
|
42
|
-
* accepts (Ollama, vLLM, Groq, …), where `max_completion_tokens` is
|
|
43
|
-
* OpenAI-only. Undefined fields are pruned so they never hit the wire.
|
|
44
|
-
*/
|
|
45
|
-
function toOpenAiCallSettings(request) {
|
|
46
|
-
return pruneUndefined({
|
|
47
|
-
temperature: request.temperature,
|
|
48
|
-
max_tokens: request.maxOutputTokens,
|
|
49
|
-
top_p: request.topP,
|
|
50
|
-
seed: request.seed,
|
|
51
|
-
stop: request.stopSequences
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
/** One wire function tool per `AgentTools` entry. */
|
|
55
|
-
function toOpenAiTools(tools) {
|
|
56
|
-
return Object.entries(tools).flatMap(([name, descriptor]) => {
|
|
57
|
-
if (!descriptor) return [];
|
|
58
|
-
const inputSchema = typeof descriptor === "function" ? void 0 : descriptor.inputSchema;
|
|
59
|
-
return [{
|
|
60
|
-
type: "function",
|
|
61
|
-
function: {
|
|
62
|
-
name,
|
|
63
|
-
description: typeof descriptor === "function" ? void 0 : descriptor.description,
|
|
64
|
-
parameters: (isStandardSchema(inputSchema) ? getJsonSchemaSync(inputSchema) : void 0) ?? {}
|
|
65
|
-
}
|
|
66
|
-
}];
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
/** One wire function tool per candidate decision event — the
|
|
70
|
-
* "tool-per-event + tool_choice: 'required'" recipe. */
|
|
71
|
-
function toOpenAiEventTools(events) {
|
|
72
|
-
return events.map((event) => ({
|
|
73
|
-
type: "function",
|
|
74
|
-
function: {
|
|
75
|
-
name: event.toolName,
|
|
76
|
-
description: `Choose the '${event.type}' move.`,
|
|
77
|
-
parameters: getJsonSchemaSync(event.inputSchema) ?? {}
|
|
78
|
-
}
|
|
79
|
-
}));
|
|
80
|
-
}
|
|
81
|
-
/** Messages for a decision request, with prior failed `attempts` rendered as
|
|
82
|
-
* appended user messages (via core's {@link renderDecisionAttempts}) so
|
|
83
|
-
* retries converge. */
|
|
84
|
-
function toDecisionMessages(request) {
|
|
85
|
-
const messages = toOpenAiMessages(request);
|
|
86
|
-
for (const attempt of renderDecisionAttempts(request)) messages.push({
|
|
87
|
-
role: "user",
|
|
88
|
-
content: attempt.content
|
|
89
|
-
});
|
|
90
|
-
return messages;
|
|
91
|
-
}
|
|
92
|
-
function pruneUndefined(record) {
|
|
93
|
-
return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== void 0));
|
|
94
|
-
}
|
|
95
|
-
//#endregion
|
|
96
|
-
//#region src/openai-compat/index.ts
|
|
97
|
-
/**
|
|
98
|
-
* OpenAI-compatible Chat Completions adapter — a COMPLETE `{ generateText,
|
|
99
|
-
* streamText, decide }` executor set built on raw `fetch`, with zero runtime
|
|
100
|
-
* dependencies (no `openai` package, no Vercel AI SDK).
|
|
101
|
-
*
|
|
102
|
-
* The OpenAI Chat Completions wire format is the lingua franca of hosted and
|
|
103
|
-
* local inference: Groq, Together, Fireworks, OpenRouter, vLLM, Ollama, LM
|
|
104
|
-
* Studio, and OpenAI itself all speak it. Point `baseUrl` at any of them.
|
|
105
|
-
*
|
|
106
|
-
* Compare `createAiSdkExecutors` in `../ai-sdk/index.ts` (the AI-SDK-backed
|
|
107
|
-
* adapter) — same three-function contract, different transport. The request
|
|
108
|
-
* mapping is ported from `examples/openai-sdk-host/index.ts`, but wired
|
|
109
|
-
* against `POST {baseUrl}/chat/completions` instead of the `openai` package.
|
|
110
|
-
*/
|
|
111
|
-
/**
|
|
112
|
-
* Builds a complete `{ generateText, streamText, decide }` executor set over
|
|
113
|
-
* the OpenAI Chat Completions wire format via raw `fetch`.
|
|
114
|
-
*
|
|
115
|
-
* @example
|
|
116
|
-
* ```ts
|
|
117
|
-
* const executors = createOpenAiCompatExecutors({
|
|
118
|
-
* baseUrl: 'https://api.groq.com/openai/v1',
|
|
119
|
-
* apiKey: process.env.GROQ_API_KEY,
|
|
120
|
-
* models: { quick: 'llama-3.3-70b-versatile' },
|
|
121
|
-
* });
|
|
122
|
-
* const result = await runAgent(machine, { input, executors });
|
|
123
|
-
* ```
|
|
124
|
-
*/
|
|
125
|
-
function createOpenAiCompatExecutors(options) {
|
|
126
|
-
const doFetch = options.fetch ?? globalThis.fetch;
|
|
127
|
-
if (!doFetch) throw new Error("createOpenAiCompatExecutors: no `fetch` available — pass options.fetch for this runtime.");
|
|
128
|
-
const url = `${options.baseUrl.replace(/\/+$/, "")}/chat/completions`;
|
|
129
|
-
function resolveModel(modelRef) {
|
|
130
|
-
const resolved = options.models?.[modelRef] ?? modelRef ?? options.model;
|
|
131
|
-
if (!resolved) throw new Error("createOpenAiCompatExecutors: no model to send — set request.model, options.model, or options.models.");
|
|
132
|
-
return resolved;
|
|
133
|
-
}
|
|
134
|
-
function buildHeaders() {
|
|
135
|
-
return {
|
|
136
|
-
"content-type": "application/json",
|
|
137
|
-
...options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {},
|
|
138
|
-
...options.headers
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
async function post(body, signal) {
|
|
142
|
-
const response = await doFetch(url, {
|
|
143
|
-
method: "POST",
|
|
144
|
-
headers: buildHeaders(),
|
|
145
|
-
body: JSON.stringify(body),
|
|
146
|
-
signal
|
|
147
|
-
});
|
|
148
|
-
if (!response.ok) {
|
|
149
|
-
const snippet = await response.text().catch(() => "");
|
|
150
|
-
throw new Error(`createOpenAiCompatExecutors: ${url} responded ${response.status} ${response.statusText}: ` + snippet.slice(0, 500));
|
|
151
|
-
}
|
|
152
|
-
return response;
|
|
153
|
-
}
|
|
154
|
-
const generateText = async (request, info) => {
|
|
155
|
-
const tools = toOpenAiTools(request.tools);
|
|
156
|
-
const body = {
|
|
157
|
-
model: resolveModel(request.model),
|
|
158
|
-
messages: toOpenAiMessages(request),
|
|
159
|
-
...toOpenAiCallSettings(request),
|
|
160
|
-
...tools.length > 0 ? { tools } : {},
|
|
161
|
-
...request.toolChoice ? { tool_choice: toWireToolChoice(request.toolChoice) } : {}
|
|
162
|
-
};
|
|
163
|
-
const structured = getAgentOutputMode(request.outputSchema) === "structured";
|
|
164
|
-
if (structured) {
|
|
165
|
-
const jsonSchema = await getJsonSchema(buildEnvelopeSchema(request.outputSchema, { reasoning: request.reasoning }));
|
|
166
|
-
body.response_format = jsonSchema ? {
|
|
167
|
-
type: "json_schema",
|
|
168
|
-
json_schema: {
|
|
169
|
-
name: "output",
|
|
170
|
-
schema: jsonSchema,
|
|
171
|
-
strict: false
|
|
172
|
-
}
|
|
173
|
-
} : { type: "json_object" };
|
|
174
|
-
}
|
|
175
|
-
const json = await (await post(body, info?.signal)).json();
|
|
176
|
-
const choice = json.choices?.[0];
|
|
177
|
-
const content = choice?.message?.content ?? "";
|
|
178
|
-
if (structured) {
|
|
179
|
-
let parsed;
|
|
180
|
-
try {
|
|
181
|
-
parsed = content ? JSON.parse(content) : void 0;
|
|
182
|
-
} catch (error) {
|
|
183
|
-
throw new Error(`createOpenAiCompatExecutors: generateText${nameSuffix(request)} — structured request returned non-JSON content: ${errorMessage(error)}`);
|
|
184
|
-
}
|
|
185
|
-
let output = parsed;
|
|
186
|
-
let reasoning;
|
|
187
|
-
if (parsed && typeof parsed === "object" && "result" in parsed) {
|
|
188
|
-
output = parsed.result;
|
|
189
|
-
const rawReasoning = parsed.reasoning;
|
|
190
|
-
if (typeof rawReasoning === "string") reasoning = rawReasoning;
|
|
191
|
-
}
|
|
192
|
-
return {
|
|
193
|
-
output,
|
|
194
|
-
...reasoning !== void 0 ? { reasoning } : {},
|
|
195
|
-
usage: json.usage,
|
|
196
|
-
finishReason: choice?.finish_reason ?? void 0
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
return {
|
|
200
|
-
output: content,
|
|
201
|
-
usage: json.usage,
|
|
202
|
-
finishReason: choice?.finish_reason ?? void 0
|
|
203
|
-
};
|
|
204
|
-
};
|
|
205
|
-
const streamText = async (request, info) => {
|
|
206
|
-
const response = await post({
|
|
207
|
-
model: resolveModel(request.model),
|
|
208
|
-
messages: toOpenAiMessages(request),
|
|
209
|
-
...toOpenAiCallSettings(request),
|
|
210
|
-
stream: true
|
|
211
|
-
}, info?.signal);
|
|
212
|
-
let text = "";
|
|
213
|
-
for await (const data of iterateSse(response, request)) {
|
|
214
|
-
let chunk;
|
|
215
|
-
try {
|
|
216
|
-
chunk = JSON.parse(data);
|
|
217
|
-
} catch (error) {
|
|
218
|
-
throw new Error(`createOpenAiCompatExecutors: streamText${nameSuffix(request)} — malformed SSE JSON chunk: ${errorMessage(error)}`);
|
|
219
|
-
}
|
|
220
|
-
const delta = chunk.choices?.[0]?.delta?.content;
|
|
221
|
-
if (delta) {
|
|
222
|
-
text += delta;
|
|
223
|
-
info?.onChunk?.(delta);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
return { output: text };
|
|
227
|
-
};
|
|
228
|
-
const decide = async (request) => {
|
|
229
|
-
const tools = toOpenAiEventTools(request.events);
|
|
230
|
-
const json = await (await post({
|
|
231
|
-
model: resolveModel(request.model),
|
|
232
|
-
messages: toDecisionMessages(request),
|
|
233
|
-
tools,
|
|
234
|
-
tool_choice: "required",
|
|
235
|
-
...pruneUndefined({
|
|
236
|
-
temperature: request.temperature,
|
|
237
|
-
max_tokens: request.maxOutputTokens,
|
|
238
|
-
top_p: request.topP,
|
|
239
|
-
seed: request.seed,
|
|
240
|
-
stop: request.stopSequences
|
|
241
|
-
})
|
|
242
|
-
}, request.signal)).json();
|
|
243
|
-
const choice = json.choices?.[0];
|
|
244
|
-
const toolCall = choice?.message?.tool_calls?.[0];
|
|
245
|
-
if (!toolCall || toolCall.type && toolCall.type !== "function" || !toolCall.function?.name) throw new Error("createOpenAiCompatExecutors: decide — model did not call an event tool.");
|
|
246
|
-
const chosenEvent = request.events.find((event) => event.toolName === toolCall.function.name);
|
|
247
|
-
if (!chosenEvent) throw new Error(`createOpenAiCompatExecutors: decide — model called unknown tool '${toolCall.function.name}'.`);
|
|
248
|
-
let args = {};
|
|
249
|
-
if (toolCall.function.arguments) try {
|
|
250
|
-
args = JSON.parse(toolCall.function.arguments);
|
|
251
|
-
} catch (error) {
|
|
252
|
-
throw new Error(`createOpenAiCompatExecutors: decide — could not parse tool arguments for '${chosenEvent.type}': ${errorMessage(error)}`);
|
|
253
|
-
}
|
|
254
|
-
return {
|
|
255
|
-
event: {
|
|
256
|
-
...args && typeof args === "object" ? args : {},
|
|
257
|
-
type: chosenEvent.type
|
|
258
|
-
},
|
|
259
|
-
usage: json.usage,
|
|
260
|
-
finishReason: choice?.finish_reason ?? void 0
|
|
261
|
-
};
|
|
262
|
-
};
|
|
263
|
-
return {
|
|
264
|
-
generateText,
|
|
265
|
-
streamText,
|
|
266
|
-
decide
|
|
267
|
-
};
|
|
268
|
-
}
|
|
269
|
-
/** Maps an `AgentToolChoice` to the wire `tool_choice` shape. */
|
|
270
|
-
function toWireToolChoice(toolChoice) {
|
|
271
|
-
return typeof toolChoice === "object" ? {
|
|
272
|
-
type: "function",
|
|
273
|
-
function: { name: toolChoice.name }
|
|
274
|
-
} : toolChoice;
|
|
275
|
-
}
|
|
276
|
-
async function* iterateSse(response, request) {
|
|
277
|
-
const body = response.body;
|
|
278
|
-
if (!body) throw new Error(`createOpenAiCompatExecutors: streamText${nameSuffix(request)} — response has no body to read SSE from.`);
|
|
279
|
-
const reader = body.getReader();
|
|
280
|
-
const decoder = new TextDecoder();
|
|
281
|
-
let buffer = "";
|
|
282
|
-
const flushLine = function* (line) {
|
|
283
|
-
const trimmed = line.trim();
|
|
284
|
-
if (!trimmed || !trimmed.startsWith("data:")) return;
|
|
285
|
-
const data = trimmed.slice(5).trim();
|
|
286
|
-
if (data && data !== "[DONE]") yield data;
|
|
287
|
-
};
|
|
288
|
-
while (true) {
|
|
289
|
-
const { done, value } = await reader.read();
|
|
290
|
-
if (done) break;
|
|
291
|
-
buffer += decoder.decode(value, { stream: true });
|
|
292
|
-
let newlineIndex;
|
|
293
|
-
while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
|
|
294
|
-
const line = buffer.slice(0, newlineIndex);
|
|
295
|
-
buffer = buffer.slice(newlineIndex + 1);
|
|
296
|
-
yield* flushLine(line);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
yield* flushLine(buffer);
|
|
300
|
-
}
|
|
301
|
-
function nameSuffix(request) {
|
|
302
|
-
return request.name ? ` '${request.name}'` : "";
|
|
303
|
-
}
|
|
304
|
-
function errorMessage(error) {
|
|
305
|
-
return error instanceof Error ? error.message : String(error);
|
|
306
|
-
}
|
|
307
|
-
//#endregion
|
|
308
|
-
export { createOpenAiCompatExecutors };
|
|
@@ -1,198 +0,0 @@
|
|
|
1
|
-
import { m as ChosenEvent, u as AgentTools } from "./types-qm00QF91.mjs";
|
|
2
|
-
import { G as AgentRequestOptions, K as AgentRequestSource, M as AgentPlanInput, U as AgentEventDescriptor, c as AgentRequestMode, j as AgentDecisionRequest, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-CaKqgX4Y.mjs";
|
|
3
|
-
import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EventFromLogic, SnapshotFrom } from "xstate";
|
|
4
|
-
|
|
5
|
-
//#region src/internal/registry.d.ts
|
|
6
|
-
type AgentExecutionOptions = Pick<AgentRequestOptions, "schemas" | "actorSources"> & {
|
|
7
|
-
models?: object;
|
|
8
|
-
};
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region src/steps.d.ts
|
|
11
|
-
/**
|
|
12
|
-
* A pending text request surfaced by step discovery ({@link getAgentRequests}
|
|
13
|
-
* / {@link AgentStep.requests}): the machine has spawned a
|
|
14
|
-
* `TextLogic`-backed invoke and is waiting on its result. Resolve it with
|
|
15
|
-
* {@link executeAgentRequest} (or by hand, then feed the output into
|
|
16
|
-
* {@link resolveAgentStep} via `xstate.done.actor.<id>`).
|
|
17
|
-
*/
|
|
18
|
-
interface AgentRequest<TInput extends AgentTextRequest = AgentTextRequest> {
|
|
19
|
-
kind: "text";
|
|
20
|
-
id: string;
|
|
21
|
-
src: AgentRequestSource;
|
|
22
|
-
mode?: AgentRequestMode;
|
|
23
|
-
input: TInput;
|
|
24
|
-
tools: AgentTools;
|
|
25
|
-
events: AgentEventDescriptor[];
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* A pending **plan** request re-surfaced by step discovery: the machine
|
|
29
|
-
* invoked `agent.plan`, which applies an ordered sequence of legal events
|
|
30
|
-
* (each one a decision) rather than a single one. Unlike text/decision
|
|
31
|
-
* requests — surfaced once and resolved once — a plan request **re-surfaces on
|
|
32
|
-
* every step** while the plan is in flight, its `events`/`applied`/
|
|
33
|
-
* `stepsRemaining` updated each time, until it terminates.
|
|
34
|
-
*
|
|
35
|
-
* All fields are plain serializable data. Resolve ONE decision per step from
|
|
36
|
-
* `events` (via {@link resolveDecision}, wiring `canTake` to
|
|
37
|
-
* `snapshot.can` exactly like a single decision) then apply it: a real machine
|
|
38
|
-
* event advances the plan (the next step re-surfaces this request); the
|
|
39
|
-
* reserved `agent.plan.done` move, a `stopOn` event, an exhausted budget, or no
|
|
40
|
-
* legal events completes it (its invoke resolves with `{ steps, stopped }`).
|
|
41
|
-
* {@link resolveAgentRequests} does all of this natively — one decision (or one
|
|
42
|
-
* completion) per call.
|
|
43
|
-
*
|
|
44
|
-
* The in-progress plan state (`applied` trail + remaining budget) lives in the
|
|
45
|
-
* plan invoke child's own `createLogic` snapshot `context`
|
|
46
|
-
* (`children.<id>.snapshot.context`), so it survives a full JSON
|
|
47
|
-
* `getPersistedSnapshot` → restore round-trip: a host that persists the step
|
|
48
|
-
* after every event and reloads resumes the plan identically.
|
|
49
|
-
*/
|
|
50
|
-
interface AgentPlanRequest {
|
|
51
|
-
kind: "plan";
|
|
52
|
-
/** Durable invoke id of the `agent.plan` invoke. */
|
|
53
|
-
id: string;
|
|
54
|
-
/** Invoke src (`'agent.plan'` or a registered plan-logic source name). */
|
|
55
|
-
src: AgentRequestSource;
|
|
56
|
-
/** The resolved plan input (`model`/`system`/`prompt`/`allowedEvents`/`stopOn`/`maxSteps`/…). */
|
|
57
|
-
input: AgentPlanInput;
|
|
58
|
-
/**
|
|
59
|
-
* The legal candidates for the NEXT plan step: the currently
|
|
60
|
-
* snapshot-legal machine events (∩ declared `allowedEvents`) plus the
|
|
61
|
-
* reserved `agent.plan.done` move.
|
|
62
|
-
*/
|
|
63
|
-
events: AgentEventDescriptor[];
|
|
64
|
-
/** The events applied so far in this plan, in order (the trail). */
|
|
65
|
-
applied: ChosenEvent[];
|
|
66
|
-
/** How many more events the plan may apply (`maxSteps - applied.length`). */
|
|
67
|
-
stepsRemaining: number;
|
|
68
|
-
}
|
|
69
|
-
/** `AgentStep.requests` element: a text, decision, or plan request. */
|
|
70
|
-
type AgentStepRequest = AgentRequest | AgentDecisionRequest | AgentPlanRequest;
|
|
71
|
-
/**
|
|
72
|
-
* One durable checkpoint on the step path: the machine's current snapshot,
|
|
73
|
-
* the executable actions that produced it, the pending
|
|
74
|
-
* {@link AgentStepRequest}s (text/decision work still to resolve), and
|
|
75
|
-
* whether the machine has reached a final state. This is the
|
|
76
|
-
* per-model-call-checkpoint path for durable hosts (Workflows, Temporal,
|
|
77
|
-
* queues, …) — a peer of `runAgent`, not a lesser version of it. Produced by
|
|
78
|
-
* {@link initialAgentStep}/{@link transitionAgentStep}/{@link resolveAgentStep}.
|
|
79
|
-
*/
|
|
80
|
-
interface AgentStep<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
|
|
81
|
-
snapshot: TSnapshot;
|
|
82
|
-
actions: readonly {
|
|
83
|
-
type?: string;
|
|
84
|
-
params?: unknown;
|
|
85
|
-
}[];
|
|
86
|
-
requests: AgentStepRequest[];
|
|
87
|
-
done: boolean;
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Starts a machine and returns its first {@link AgentStep} — the step-path
|
|
91
|
-
* equivalent of `initialTransition` plus request discovery. Begins the
|
|
92
|
-
* durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
|
|
93
|
-
* (via {@link executeAgentRequest} for `kind: 'text'`, or
|
|
94
|
-
* {@link resolveDecision} for `kind: 'decision'`), then advance with
|
|
95
|
-
* {@link resolveAgentStep} or {@link transitionAgentStep}.
|
|
96
|
-
*/
|
|
97
|
-
declare function initialAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, input?: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
|
|
98
|
-
/**
|
|
99
|
-
* Applies an externally-sent event (e.g. a decision's chosen event, or a
|
|
100
|
-
* human's reply) and returns the next {@link AgentStep}. Accepts **either**
|
|
101
|
-
* a raw snapshot **or** a prior `AgentStep` as the second argument —
|
|
102
|
-
* `.snapshot` is unwrapped automatically, so callers can thread the whole
|
|
103
|
-
* step object through without manually plucking the snapshot out.
|
|
104
|
-
*/
|
|
105
|
-
declare function transitionAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, snapshotOrStep: SnapshotFrom<TMachine> | AgentStep<SnapshotFrom<TMachine>>, event: EventFromLogic<TMachine>, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
|
|
106
|
-
/**
|
|
107
|
-
* Applies a resolved text request's output (a `kind: 'text'`
|
|
108
|
-
* {@link AgentRequest} — not a decision) as a done event and returns the
|
|
109
|
-
* next {@link AgentStep}. For decisions, resolve with `resolveDecision`
|
|
110
|
-
* (which returns a {@link ChosenEvent}) and apply it with
|
|
111
|
-
* {@link transitionAgentStep} instead — a decision has no output value of
|
|
112
|
-
* its own to feed here.
|
|
113
|
-
*/
|
|
114
|
-
declare function resolveAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, request: Pick<AgentRequest, "id"> | string, output: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
|
|
115
|
-
/**
|
|
116
|
-
* Snapshot in, requests out: scans executable actions for spawned agent
|
|
117
|
-
* invokes and lowers each into an {@link AgentStepRequest}, pre-filled with
|
|
118
|
-
* the machine's registered `setupAgent` schemas/actorSources (so callers
|
|
119
|
-
* don't pass them by hand each call) — merged with any `options` passed here,
|
|
120
|
-
* which take precedence. The step path's public discovery primitive;
|
|
121
|
-
* `initialAgentStep`/`transitionAgentStep`/`resolveAgentStep` call it
|
|
122
|
-
* internally to populate `AgentStep.requests`.
|
|
123
|
-
*/
|
|
124
|
-
declare function getAgentRequests(machine: AnyActorLogic, actions: readonly {
|
|
125
|
-
type?: string;
|
|
126
|
-
params?: unknown;
|
|
127
|
-
}[], snapshot?: AnyMachineSnapshot, options?: Pick<AgentRequestOptions, "eventToolName"> & Partial<AgentExecutionOptions>): AgentStepRequest[];
|
|
128
|
-
/**
|
|
129
|
-
* Resolves one **text** {@link AgentRequest} against a host's
|
|
130
|
-
* {@link AgentRequestExecutors} — merges the request's tools, dispatches to
|
|
131
|
-
* `generateText`/`streamText` per `request.mode`, and validates the result
|
|
132
|
-
* against `request.input.outputSchema` if present. **Text-only**: passing a
|
|
133
|
-
* `kind: 'decision'` request throws, directing the caller to
|
|
134
|
-
* `resolveDecision(request, executors.decide, ...)` instead. By default
|
|
135
|
-
* returns the normalized output; pass `{ verbose: true }` to also get the
|
|
136
|
-
* raw executor result (tool calls, usage, finish reason — needed for
|
|
137
|
-
* observability and event-sourced replay).
|
|
138
|
-
*/
|
|
139
|
-
declare function executeAgentRequest(request: AgentRequest, executors: Partial<AgentRequestExecutors>): Promise<unknown>;
|
|
140
|
-
declare function executeAgentRequest(request: AgentRequest, executors: Partial<AgentRequestExecutors>, options: {
|
|
141
|
-
verbose: true;
|
|
142
|
-
}): Promise<{
|
|
143
|
-
output: unknown;
|
|
144
|
-
raw: unknown;
|
|
145
|
-
}>;
|
|
146
|
-
/**
|
|
147
|
-
* Options for {@link resolveAgentRequests}.
|
|
148
|
-
*/
|
|
149
|
-
interface ResolveAgentRequestsOptions extends Partial<AgentExecutionOptions> {
|
|
150
|
-
/** Retries per decision, passed to `resolveDecision`. Default `2`. */
|
|
151
|
-
maxRetries?: number;
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
154
|
-
* Resolves the current step's pending requests and returns the next
|
|
155
|
-
* {@link AgentStep} — one iteration of the durable step loop, collapsing the
|
|
156
|
-
* manual `request.kind` dispatch a host would otherwise write by hand.
|
|
157
|
-
*
|
|
158
|
-
* For each pending request, in order: a `kind: 'text'` request is run with
|
|
159
|
-
* {@link executeAgentRequest} then fed back via {@link resolveAgentStep}; a
|
|
160
|
-
* `kind: 'decision'` request is resolved with `resolveDecision` (wiring
|
|
161
|
-
* `canTake` to `step.snapshot.can` so guard-rejected choices retry) then
|
|
162
|
-
* applied with {@link transitionAgentStep}. The **current** step is re-read
|
|
163
|
-
* after each application — the machine may advance and its `requests` change —
|
|
164
|
-
* so this always resolves against the live step, never a stale list.
|
|
165
|
-
*
|
|
166
|
-
* A `kind: 'plan'` request (`agent.plan`) is resolved natively too: one plan
|
|
167
|
-
* step per call. It resolves a single decision from `request.events` (wiring
|
|
168
|
-
* `canTake` to `step.snapshot.can`, exempting the reserved `agent.plan.done`
|
|
169
|
-
* move and `stopOn` events), then either applies the chosen machine event and
|
|
170
|
-
* lets the next step re-surface the plan, or completes the plan (feeding its
|
|
171
|
-
* `{ steps, stopped }` output back) on the done move / a `stopOn` event / an
|
|
172
|
-
* exhausted budget / no legal events. The plan's applied trail is carried in
|
|
173
|
-
* the invoke child's snapshot, so persisting the step between calls resumes the
|
|
174
|
-
* plan identically.
|
|
175
|
-
*
|
|
176
|
-
* Missing the executor a request needs throws a clear error
|
|
177
|
-
* (`generateText`/`streamText` for text, `decide` for decisions and plans).
|
|
178
|
-
*
|
|
179
|
-
* A complete durable host is two lines:
|
|
180
|
-
*
|
|
181
|
-
* ```ts
|
|
182
|
-
* let step = initialAgentStep(machine, input);
|
|
183
|
-
* while (!step.done) step = await resolveAgentRequests(machine, step, executors);
|
|
184
|
-
* ```
|
|
185
|
-
*
|
|
186
|
-
* All pending **text** requests of a step are resolved in parallel
|
|
187
|
-
* (`Promise.all`) — parallel statechart regions are genuinely concurrent, so
|
|
188
|
-
* their model calls run concurrently — then their outputs apply in
|
|
189
|
-
* **request-array order** (deterministic for durable replay regardless of which
|
|
190
|
-
* call finishes first). Decisions and plans stay **one at a time**: applying
|
|
191
|
-
* either changes the set of legal candidates for what follows, so they cannot be
|
|
192
|
-
* resolved against a stale snapshot. A host that instead wants strictly
|
|
193
|
-
* sequential text resolution loops the manual per-request helpers
|
|
194
|
-
* ({@link executeAgentRequest} + {@link resolveAgentStep}) one at a time.
|
|
195
|
-
*/
|
|
196
|
-
declare function resolveAgentRequests<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, executors: Partial<AgentRequestExecutors>, options?: ResolveAgentRequestsOptions): Promise<AgentStep<SnapshotFrom<TMachine>>>;
|
|
197
|
-
//#endregion
|
|
198
|
-
export { ResolveAgentRequestsOptions as a, initialAgentStep as c, transitionAgentStep as d, AgentStepRequest as i, resolveAgentRequests as l, AgentRequest as n, executeAgentRequest as o, AgentStep as r, getAgentRequests as s, AgentPlanRequest as t, resolveAgentStep as u };
|