@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.
Files changed (66) hide show
  1. package/dist/ai-sdk.cjs +4 -5
  2. package/dist/ai-sdk.d.cts +7 -4
  3. package/dist/ai-sdk.d.mts +7 -4
  4. package/dist/ai-sdk.mjs +1 -2
  5. package/dist/{events-JiVPYrct.mjs → decision-BezSD_YC.mjs} +327 -20
  6. package/dist/{events-CRQj3VtP.cjs → decision-dWGhBh0P.cjs} +401 -28
  7. package/dist/errors-BQRk9eiZ.d.cts +19 -0
  8. package/dist/errors-C9rxnWbX.d.mts +19 -0
  9. package/dist/errors-CeSXQx0v.mjs +23 -0
  10. package/dist/errors-DUBBzRLP.cjs +28 -0
  11. package/dist/event-log-store-CNT_7F0V.cjs +452 -0
  12. package/dist/event-log-store-CriMgX1D.d.mts +144 -0
  13. package/dist/event-log-store-D7pWtIhb.mjs +411 -0
  14. package/dist/event-log-store-Ruq18mGp.d.cts +144 -0
  15. package/dist/index.cjs +1050 -705
  16. package/dist/index.d.cts +538 -565
  17. package/dist/index.d.mts +538 -565
  18. package/dist/index.mjs +950 -644
  19. package/dist/machines.cjs +752 -0
  20. package/dist/machines.d.cts +372 -0
  21. package/dist/machines.d.mts +372 -0
  22. package/dist/machines.mjs +741 -0
  23. package/dist/otel.cjs +268 -0
  24. package/dist/otel.d.cts +67 -0
  25. package/dist/otel.d.mts +67 -0
  26. package/dist/otel.mjs +267 -0
  27. package/dist/run-agent-C3mFDGTf.d.mts +1111 -0
  28. package/dist/run-agent-DnvtcnTZ.d.cts +1111 -0
  29. package/dist/setup-agent-DAZZSjDS.mjs +1711 -0
  30. package/dist/setup-agent-DP95MFrI.cjs +1836 -0
  31. package/dist/sqlite.cjs +135 -0
  32. package/dist/sqlite.d.cts +57 -0
  33. package/dist/sqlite.d.mts +57 -0
  34. package/dist/sqlite.mjs +133 -0
  35. package/dist/{text-logic-CaKqgX4Y.d.mts → text-logic-BDxwQNsD.d.cts} +155 -72
  36. package/dist/{text-logic-Ckhr2kKC.d.cts → text-logic-TkKPw8Aq.d.mts} +155 -72
  37. package/dist/{types-qm00QF91.d.mts → types-QbEfCVny.d.cts} +1 -1
  38. package/dist/{types-C9QiMjre.d.cts → types-_FXoFBGO.d.mts} +1 -1
  39. package/package.json +47 -39
  40. package/readme.md +49 -12
  41. package/schemas/agent-workflow.json +40 -21
  42. package/skills/generate-machine/SKILL.md +267 -0
  43. package/dist/adapter.cjs +0 -15
  44. package/dist/adapter.d.cts +0 -4
  45. package/dist/adapter.d.mts +0 -4
  46. package/dist/adapter.mjs +0 -2
  47. package/dist/decision-C3k4ve51.mjs +0 -227
  48. package/dist/decision-D8wJrM8W.cjs +0 -286
  49. package/dist/openai-compat.cjs +0 -309
  50. package/dist/openai-compat.d.cts +0 -59
  51. package/dist/openai-compat.d.mts +0 -59
  52. package/dist/openai-compat.mjs +0 -308
  53. package/dist/steps-BALp1eZo.d.mts +0 -198
  54. package/dist/steps-CVe54GPP.cjs +0 -420
  55. package/dist/steps-CkyyyuHd.mjs +0 -379
  56. package/dist/steps-MjnQI4aB.d.cts +0 -198
  57. package/dist/steps.cjs +0 -12
  58. package/dist/steps.d.cts +0 -3
  59. package/dist/steps.d.mts +0 -3
  60. package/dist/steps.mjs +0 -3
  61. package/dist/utils-BYqT_Dyv.d.cts +0 -108
  62. package/dist/utils-Do5wIJrh.d.mts +0 -108
  63. package/dist/zod.cjs +0 -31
  64. package/dist/zod.d.cts +0 -30
  65. package/dist/zod.d.mts +0 -30
  66. package/dist/zod.mjs +0 -30
@@ -1,309 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_events = require("./events-CRQj3VtP.cjs");
3
- const require_decision = require("./decision-D8wJrM8W.cjs");
4
- //#region src/openai-compat/mappers.ts
5
- /** Maps `AgentTextRequest.messages`/`system`/`prompt` to Chat Completions messages. */
6
- function toOpenAiMessages(request) {
7
- if (request.messages) return request.messages.flatMap((message) => {
8
- const content = typeof message.content === "string" ? message.content : "";
9
- switch (message.role) {
10
- case "system": return [{
11
- role: "system",
12
- content
13
- }];
14
- case "user": return [{
15
- role: "user",
16
- content
17
- }];
18
- case "assistant": return [{
19
- role: "assistant",
20
- content
21
- }];
22
- case "tool": return message.content.map((part) => ({
23
- role: "tool",
24
- content: part.output.type === "text" || part.output.type === "error-text" ? part.output.value : JSON.stringify(part.output.value),
25
- tool_call_id: part.toolCallId
26
- }));
27
- }
28
- });
29
- const messages = [];
30
- if (request.system) messages.push({
31
- role: "system",
32
- content: request.system
33
- });
34
- messages.push({
35
- role: "user",
36
- content: request.prompt ?? ""
37
- });
38
- return messages;
39
- }
40
- /**
41
- * Maps sampling/stop settings. Targets `max_tokens` (not
42
- * `max_completion_tokens`) — it's the field every OpenAI-compatible backend
43
- * accepts (Ollama, vLLM, Groq, …), where `max_completion_tokens` is
44
- * OpenAI-only. Undefined fields are pruned so they never hit the wire.
45
- */
46
- function toOpenAiCallSettings(request) {
47
- return pruneUndefined({
48
- temperature: request.temperature,
49
- max_tokens: request.maxOutputTokens,
50
- top_p: request.topP,
51
- seed: request.seed,
52
- stop: request.stopSequences
53
- });
54
- }
55
- /** One wire function tool per `AgentTools` entry. */
56
- function toOpenAiTools(tools) {
57
- return Object.entries(tools).flatMap(([name, descriptor]) => {
58
- if (!descriptor) return [];
59
- const inputSchema = typeof descriptor === "function" ? void 0 : descriptor.inputSchema;
60
- return [{
61
- type: "function",
62
- function: {
63
- name,
64
- description: typeof descriptor === "function" ? void 0 : descriptor.description,
65
- parameters: (require_events.isStandardSchema(inputSchema) ? require_events.getJsonSchemaSync(inputSchema) : void 0) ?? {}
66
- }
67
- }];
68
- });
69
- }
70
- /** One wire function tool per candidate decision event — the
71
- * "tool-per-event + tool_choice: 'required'" recipe. */
72
- function toOpenAiEventTools(events) {
73
- return events.map((event) => ({
74
- type: "function",
75
- function: {
76
- name: event.toolName,
77
- description: `Choose the '${event.type}' move.`,
78
- parameters: require_events.getJsonSchemaSync(event.inputSchema) ?? {}
79
- }
80
- }));
81
- }
82
- /** Messages for a decision request, with prior failed `attempts` rendered as
83
- * appended user messages (via core's {@link renderDecisionAttempts}) so
84
- * retries converge. */
85
- function toDecisionMessages(request) {
86
- const messages = toOpenAiMessages(request);
87
- for (const attempt of require_decision.renderDecisionAttempts(request)) messages.push({
88
- role: "user",
89
- content: attempt.content
90
- });
91
- return messages;
92
- }
93
- function pruneUndefined(record) {
94
- return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== void 0));
95
- }
96
- //#endregion
97
- //#region src/openai-compat/index.ts
98
- /**
99
- * OpenAI-compatible Chat Completions adapter — a COMPLETE `{ generateText,
100
- * streamText, decide }` executor set built on raw `fetch`, with zero runtime
101
- * dependencies (no `openai` package, no Vercel AI SDK).
102
- *
103
- * The OpenAI Chat Completions wire format is the lingua franca of hosted and
104
- * local inference: Groq, Together, Fireworks, OpenRouter, vLLM, Ollama, LM
105
- * Studio, and OpenAI itself all speak it. Point `baseUrl` at any of them.
106
- *
107
- * Compare `createAiSdkExecutors` in `../ai-sdk/index.ts` (the AI-SDK-backed
108
- * adapter) — same three-function contract, different transport. The request
109
- * mapping is ported from `examples/openai-sdk-host/index.ts`, but wired
110
- * against `POST {baseUrl}/chat/completions` instead of the `openai` package.
111
- */
112
- /**
113
- * Builds a complete `{ generateText, streamText, decide }` executor set over
114
- * the OpenAI Chat Completions wire format via raw `fetch`.
115
- *
116
- * @example
117
- * ```ts
118
- * const executors = createOpenAiCompatExecutors({
119
- * baseUrl: 'https://api.groq.com/openai/v1',
120
- * apiKey: process.env.GROQ_API_KEY,
121
- * models: { quick: 'llama-3.3-70b-versatile' },
122
- * });
123
- * const result = await runAgent(machine, { input, executors });
124
- * ```
125
- */
126
- function createOpenAiCompatExecutors(options) {
127
- const doFetch = options.fetch ?? globalThis.fetch;
128
- if (!doFetch) throw new Error("createOpenAiCompatExecutors: no `fetch` available — pass options.fetch for this runtime.");
129
- const url = `${options.baseUrl.replace(/\/+$/, "")}/chat/completions`;
130
- function resolveModel(modelRef) {
131
- const resolved = options.models?.[modelRef] ?? modelRef ?? options.model;
132
- if (!resolved) throw new Error("createOpenAiCompatExecutors: no model to send — set request.model, options.model, or options.models.");
133
- return resolved;
134
- }
135
- function buildHeaders() {
136
- return {
137
- "content-type": "application/json",
138
- ...options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {},
139
- ...options.headers
140
- };
141
- }
142
- async function post(body, signal) {
143
- const response = await doFetch(url, {
144
- method: "POST",
145
- headers: buildHeaders(),
146
- body: JSON.stringify(body),
147
- signal
148
- });
149
- if (!response.ok) {
150
- const snippet = await response.text().catch(() => "");
151
- throw new Error(`createOpenAiCompatExecutors: ${url} responded ${response.status} ${response.statusText}: ` + snippet.slice(0, 500));
152
- }
153
- return response;
154
- }
155
- const generateText = async (request, info) => {
156
- const tools = toOpenAiTools(request.tools);
157
- const body = {
158
- model: resolveModel(request.model),
159
- messages: toOpenAiMessages(request),
160
- ...toOpenAiCallSettings(request),
161
- ...tools.length > 0 ? { tools } : {},
162
- ...request.toolChoice ? { tool_choice: toWireToolChoice(request.toolChoice) } : {}
163
- };
164
- const structured = require_events.getAgentOutputMode(request.outputSchema) === "structured";
165
- if (structured) {
166
- const jsonSchema = await require_events.getJsonSchema(require_events.buildEnvelopeSchema(request.outputSchema, { reasoning: request.reasoning }));
167
- body.response_format = jsonSchema ? {
168
- type: "json_schema",
169
- json_schema: {
170
- name: "output",
171
- schema: jsonSchema,
172
- strict: false
173
- }
174
- } : { type: "json_object" };
175
- }
176
- const json = await (await post(body, info?.signal)).json();
177
- const choice = json.choices?.[0];
178
- const content = choice?.message?.content ?? "";
179
- if (structured) {
180
- let parsed;
181
- try {
182
- parsed = content ? JSON.parse(content) : void 0;
183
- } catch (error) {
184
- throw new Error(`createOpenAiCompatExecutors: generateText${nameSuffix(request)} — structured request returned non-JSON content: ${errorMessage(error)}`);
185
- }
186
- let output = parsed;
187
- let reasoning;
188
- if (parsed && typeof parsed === "object" && "result" in parsed) {
189
- output = parsed.result;
190
- const rawReasoning = parsed.reasoning;
191
- if (typeof rawReasoning === "string") reasoning = rawReasoning;
192
- }
193
- return {
194
- output,
195
- ...reasoning !== void 0 ? { reasoning } : {},
196
- usage: json.usage,
197
- finishReason: choice?.finish_reason ?? void 0
198
- };
199
- }
200
- return {
201
- output: content,
202
- usage: json.usage,
203
- finishReason: choice?.finish_reason ?? void 0
204
- };
205
- };
206
- const streamText = async (request, info) => {
207
- const response = await post({
208
- model: resolveModel(request.model),
209
- messages: toOpenAiMessages(request),
210
- ...toOpenAiCallSettings(request),
211
- stream: true
212
- }, info?.signal);
213
- let text = "";
214
- for await (const data of iterateSse(response, request)) {
215
- let chunk;
216
- try {
217
- chunk = JSON.parse(data);
218
- } catch (error) {
219
- throw new Error(`createOpenAiCompatExecutors: streamText${nameSuffix(request)} — malformed SSE JSON chunk: ${errorMessage(error)}`);
220
- }
221
- const delta = chunk.choices?.[0]?.delta?.content;
222
- if (delta) {
223
- text += delta;
224
- info?.onChunk?.(delta);
225
- }
226
- }
227
- return { output: text };
228
- };
229
- const decide = async (request) => {
230
- const tools = toOpenAiEventTools(request.events);
231
- const json = await (await post({
232
- model: resolveModel(request.model),
233
- messages: toDecisionMessages(request),
234
- tools,
235
- tool_choice: "required",
236
- ...pruneUndefined({
237
- temperature: request.temperature,
238
- max_tokens: request.maxOutputTokens,
239
- top_p: request.topP,
240
- seed: request.seed,
241
- stop: request.stopSequences
242
- })
243
- }, request.signal)).json();
244
- const choice = json.choices?.[0];
245
- const toolCall = choice?.message?.tool_calls?.[0];
246
- if (!toolCall || toolCall.type && toolCall.type !== "function" || !toolCall.function?.name) throw new Error("createOpenAiCompatExecutors: decide — model did not call an event tool.");
247
- const chosenEvent = request.events.find((event) => event.toolName === toolCall.function.name);
248
- if (!chosenEvent) throw new Error(`createOpenAiCompatExecutors: decide — model called unknown tool '${toolCall.function.name}'.`);
249
- let args = {};
250
- if (toolCall.function.arguments) try {
251
- args = JSON.parse(toolCall.function.arguments);
252
- } catch (error) {
253
- throw new Error(`createOpenAiCompatExecutors: decide — could not parse tool arguments for '${chosenEvent.type}': ${errorMessage(error)}`);
254
- }
255
- return {
256
- event: {
257
- ...args && typeof args === "object" ? args : {},
258
- type: chosenEvent.type
259
- },
260
- usage: json.usage,
261
- finishReason: choice?.finish_reason ?? void 0
262
- };
263
- };
264
- return {
265
- generateText,
266
- streamText,
267
- decide
268
- };
269
- }
270
- /** Maps an `AgentToolChoice` to the wire `tool_choice` shape. */
271
- function toWireToolChoice(toolChoice) {
272
- return typeof toolChoice === "object" ? {
273
- type: "function",
274
- function: { name: toolChoice.name }
275
- } : toolChoice;
276
- }
277
- async function* iterateSse(response, request) {
278
- const body = response.body;
279
- if (!body) throw new Error(`createOpenAiCompatExecutors: streamText${nameSuffix(request)} — response has no body to read SSE from.`);
280
- const reader = body.getReader();
281
- const decoder = new TextDecoder();
282
- let buffer = "";
283
- const flushLine = function* (line) {
284
- const trimmed = line.trim();
285
- if (!trimmed || !trimmed.startsWith("data:")) return;
286
- const data = trimmed.slice(5).trim();
287
- if (data && data !== "[DONE]") yield data;
288
- };
289
- while (true) {
290
- const { done, value } = await reader.read();
291
- if (done) break;
292
- buffer += decoder.decode(value, { stream: true });
293
- let newlineIndex;
294
- while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
295
- const line = buffer.slice(0, newlineIndex);
296
- buffer = buffer.slice(newlineIndex + 1);
297
- yield* flushLine(line);
298
- }
299
- }
300
- yield* flushLine(buffer);
301
- }
302
- function nameSuffix(request) {
303
- return request.name ? ` '${request.name}'` : "";
304
- }
305
- function errorMessage(error) {
306
- return error instanceof Error ? error.message : String(error);
307
- }
308
- //#endregion
309
- exports.createOpenAiCompatExecutors = createOpenAiCompatExecutors;
@@ -1,59 +0,0 @@
1
- import { k as AgentDecisionExecutor, s as AgentRequestExecutors } from "./text-logic-Ckhr2kKC.cjs";
2
-
3
- //#region src/openai-compat/index.d.ts
4
- /** Minimal `fetch` shape the adapter needs — matches the global `fetch` and
5
- * Cloudflare Workers' `fetch`, so a custom transport is drop-in. */
6
- type FetchLike = (input: string, init: {
7
- method: string;
8
- headers: Record<string, string>;
9
- body: string;
10
- signal?: AbortSignal;
11
- }) => Promise<{
12
- ok: boolean;
13
- status: number;
14
- statusText: string;
15
- text(): Promise<string>;
16
- json(): Promise<unknown>;
17
- body: ReadableStream<Uint8Array> | null;
18
- }>;
19
- /** Options for {@link createOpenAiCompatExecutors}. */
20
- interface CreateOpenAiCompatExecutorsOptions {
21
- /** Base URL of the Chat Completions API, e.g. `"https://api.groq.com/openai/v1"`
22
- * or `"http://localhost:11434/v1"`. `/chat/completions` is appended. */
23
- baseUrl: string;
24
- /** Bearer token sent as `Authorization: Bearer <apiKey>`. Omit for keyless
25
- * local servers (Ollama, LM Studio). */
26
- apiKey?: string;
27
- /** Extra headers merged onto every request (e.g. `HTTP-Referer` for OpenRouter). */
28
- headers?: Record<string, string>;
29
- /** `fetch` override for Workers/tests. Defaults to the global `fetch`. */
30
- fetch?: FetchLike;
31
- /** Default wire model id, used when a request's model ref is empty. */
32
- model?: string;
33
- /** Model ref → wire model id map. A `request.model` present here resolves
34
- * to its mapped id; otherwise it passes through as the wire id. */
35
- models?: Record<string, string>;
36
- }
37
- /** `createOpenAiCompatExecutors` always populates all three executor slots. */
38
- interface OpenAiCompatExecutors extends AgentRequestExecutors {
39
- generateText: NonNullable<AgentRequestExecutors["generateText"]>;
40
- streamText: NonNullable<AgentRequestExecutors["streamText"]>;
41
- decide: AgentDecisionExecutor;
42
- }
43
- /**
44
- * Builds a complete `{ generateText, streamText, decide }` executor set over
45
- * the OpenAI Chat Completions wire format via raw `fetch`.
46
- *
47
- * @example
48
- * ```ts
49
- * const executors = createOpenAiCompatExecutors({
50
- * baseUrl: 'https://api.groq.com/openai/v1',
51
- * apiKey: process.env.GROQ_API_KEY,
52
- * models: { quick: 'llama-3.3-70b-versatile' },
53
- * });
54
- * const result = await runAgent(machine, { input, executors });
55
- * ```
56
- */
57
- declare function createOpenAiCompatExecutors(options: CreateOpenAiCompatExecutorsOptions): OpenAiCompatExecutors;
58
- //#endregion
59
- export { CreateOpenAiCompatExecutorsOptions, FetchLike, OpenAiCompatExecutors, createOpenAiCompatExecutors };
@@ -1,59 +0,0 @@
1
- import { k as AgentDecisionExecutor, s as AgentRequestExecutors } from "./text-logic-CaKqgX4Y.mjs";
2
-
3
- //#region src/openai-compat/index.d.ts
4
- /** Minimal `fetch` shape the adapter needs — matches the global `fetch` and
5
- * Cloudflare Workers' `fetch`, so a custom transport is drop-in. */
6
- type FetchLike = (input: string, init: {
7
- method: string;
8
- headers: Record<string, string>;
9
- body: string;
10
- signal?: AbortSignal;
11
- }) => Promise<{
12
- ok: boolean;
13
- status: number;
14
- statusText: string;
15
- text(): Promise<string>;
16
- json(): Promise<unknown>;
17
- body: ReadableStream<Uint8Array> | null;
18
- }>;
19
- /** Options for {@link createOpenAiCompatExecutors}. */
20
- interface CreateOpenAiCompatExecutorsOptions {
21
- /** Base URL of the Chat Completions API, e.g. `"https://api.groq.com/openai/v1"`
22
- * or `"http://localhost:11434/v1"`. `/chat/completions` is appended. */
23
- baseUrl: string;
24
- /** Bearer token sent as `Authorization: Bearer <apiKey>`. Omit for keyless
25
- * local servers (Ollama, LM Studio). */
26
- apiKey?: string;
27
- /** Extra headers merged onto every request (e.g. `HTTP-Referer` for OpenRouter). */
28
- headers?: Record<string, string>;
29
- /** `fetch` override for Workers/tests. Defaults to the global `fetch`. */
30
- fetch?: FetchLike;
31
- /** Default wire model id, used when a request's model ref is empty. */
32
- model?: string;
33
- /** Model ref → wire model id map. A `request.model` present here resolves
34
- * to its mapped id; otherwise it passes through as the wire id. */
35
- models?: Record<string, string>;
36
- }
37
- /** `createOpenAiCompatExecutors` always populates all three executor slots. */
38
- interface OpenAiCompatExecutors extends AgentRequestExecutors {
39
- generateText: NonNullable<AgentRequestExecutors["generateText"]>;
40
- streamText: NonNullable<AgentRequestExecutors["streamText"]>;
41
- decide: AgentDecisionExecutor;
42
- }
43
- /**
44
- * Builds a complete `{ generateText, streamText, decide }` executor set over
45
- * the OpenAI Chat Completions wire format via raw `fetch`.
46
- *
47
- * @example
48
- * ```ts
49
- * const executors = createOpenAiCompatExecutors({
50
- * baseUrl: 'https://api.groq.com/openai/v1',
51
- * apiKey: process.env.GROQ_API_KEY,
52
- * models: { quick: 'llama-3.3-70b-versatile' },
53
- * });
54
- * const result = await runAgent(machine, { input, executors });
55
- * ```
56
- */
57
- declare function createOpenAiCompatExecutors(options: CreateOpenAiCompatExecutorsOptions): OpenAiCompatExecutors;
58
- //#endregion
59
- export { CreateOpenAiCompatExecutorsOptions, FetchLike, OpenAiCompatExecutors, createOpenAiCompatExecutors };