@statelyai/agent 1.1.6 → 2.0.0-alpha.11

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 (92) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapter.cjs +15 -0
  3. package/dist/adapter.d.cts +4 -0
  4. package/dist/adapter.d.mts +4 -0
  5. package/dist/adapter.mjs +2 -0
  6. package/dist/ai-sdk.cjs +306 -0
  7. package/dist/ai-sdk.d.cts +96 -0
  8. package/dist/ai-sdk.d.mts +96 -0
  9. package/dist/ai-sdk.mjs +304 -0
  10. package/dist/decision-C3k4ve51.mjs +227 -0
  11. package/dist/decision-D8wJrM8W.cjs +286 -0
  12. package/dist/events-CRQj3VtP.cjs +1010 -0
  13. package/dist/events-JiVPYrct.mjs +759 -0
  14. package/dist/index.cjs +2528 -0
  15. package/dist/index.d.cts +1232 -0
  16. package/dist/index.d.mts +1217 -413
  17. package/dist/index.mjs +2489 -584
  18. package/dist/openai-compat.cjs +309 -0
  19. package/dist/openai-compat.d.cts +59 -0
  20. package/dist/openai-compat.d.mts +59 -0
  21. package/dist/openai-compat.mjs +308 -0
  22. package/dist/steps-BALp1eZo.d.mts +198 -0
  23. package/dist/steps-CVe54GPP.cjs +420 -0
  24. package/dist/steps-CkyyyuHd.mjs +379 -0
  25. package/dist/steps-MjnQI4aB.d.cts +198 -0
  26. package/dist/steps.cjs +12 -0
  27. package/dist/steps.d.cts +3 -0
  28. package/dist/steps.d.mts +3 -0
  29. package/dist/steps.mjs +3 -0
  30. package/dist/text-logic-CaKqgX4Y.d.mts +710 -0
  31. package/dist/text-logic-Ckhr2kKC.d.cts +710 -0
  32. package/dist/types-C9QiMjre.d.cts +219 -0
  33. package/dist/types-qm00QF91.d.mts +219 -0
  34. package/dist/utils-BYqT_Dyv.d.cts +108 -0
  35. package/dist/utils-Do5wIJrh.d.mts +108 -0
  36. package/dist/zod.cjs +31 -0
  37. package/dist/zod.d.cts +30 -0
  38. package/dist/zod.d.mts +30 -0
  39. package/dist/zod.mjs +30 -0
  40. package/package.json +132 -28
  41. package/readme.md +153 -6
  42. package/schemas/agent-workflow.json +526 -0
  43. package/.changeset/README.md +0 -8
  44. package/.changeset/config.json +0 -11
  45. package/.env.template +0 -3
  46. package/.github/actions/ci-setup/action.yml +0 -24
  47. package/.github/workflows/release.yml +0 -46
  48. package/.vscode/launch.json +0 -28
  49. package/CHANGELOG.md +0 -222
  50. package/dist/index.d.ts +0 -428
  51. package/dist/index.js +0 -621
  52. package/examples/chatbot.ts +0 -71
  53. package/examples/cot.ts +0 -89
  54. package/examples/email.ts +0 -118
  55. package/examples/example.ts +0 -81
  56. package/examples/goal.ts +0 -94
  57. package/examples/helpers/helpers.ts +0 -17
  58. package/examples/helpers/loader.ts +0 -32
  59. package/examples/helpers/runner.ts +0 -27
  60. package/examples/joke.ts +0 -225
  61. package/examples/multi.ts +0 -103
  62. package/examples/newspaper.ts +0 -324
  63. package/examples/number.ts +0 -102
  64. package/examples/raffle.ts +0 -105
  65. package/examples/sandbox.ts +0 -28
  66. package/examples/simple.ts +0 -39
  67. package/examples/support.ts +0 -147
  68. package/examples/ticTacToe.ts +0 -224
  69. package/examples/todo.ts +0 -137
  70. package/examples/tutor.ts +0 -100
  71. package/examples/verify.ts +0 -120
  72. package/examples/weather.ts +0 -178
  73. package/examples/wiki.ts +0 -30
  74. package/examples/word.ts +0 -171
  75. package/src/adapters/vercel.ts +0 -7
  76. package/src/agent-experimental.ts +0 -221
  77. package/src/agent.test.ts +0 -506
  78. package/src/agent.ts +0 -300
  79. package/src/decision.test.ts +0 -179
  80. package/src/decision.ts +0 -84
  81. package/src/index.ts +0 -4
  82. package/src/memory.ts +0 -25
  83. package/src/planners/shortestPathPlanner.ts +0 -22
  84. package/src/planners/simplePlanner.ts +0 -139
  85. package/src/schemas.ts +0 -11
  86. package/src/strategies/chain-of-note.ts +0 -155
  87. package/src/templates/defaultText.ts +0 -18
  88. package/src/text.ts +0 -241
  89. package/src/types.ts +0 -499
  90. package/src/utils.ts +0 -72
  91. package/tsconfig.json +0 -109
  92. package/vitest.config.ts +0 -9
@@ -0,0 +1,219 @@
1
+ import { Snapshot } from "xstate";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * A minimal, type-only contract for a snapshot store: persist a `runAgent`
6
+ * idle/settled snapshot under an id and load it back. It exists purely so
7
+ * userland stores (a file, a SQLite table, a KV row, …) share one shape and
8
+ * interoperate — there is **zero runtime** behind it; the library ships no
9
+ * implementation. See `examples/file-snapshot-store` for a `node:fs` store.
10
+ */
11
+ interface AgentSnapshotStore {
12
+ load(id: string): Promise<Snapshot<unknown> | undefined>;
13
+ save(id: string, snapshot: Snapshot<unknown>): Promise<void>;
14
+ }
15
+ /**
16
+ * The [Standard Schema](https://standardschema.dev) interface. Every schema
17
+ * this library accepts (context, events, input/output, tool schemas, …) is a
18
+ * `StandardSchemaV1` — Zod, Valibot, ArkType, and hand-written validators all
19
+ * implement it, so the library never depends on a specific validation
20
+ * library. JSON workflow configs use a caller-provided {@link SchemaCompiler}.
21
+ */
22
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
23
+ readonly "~standard": {
24
+ readonly version: 1;
25
+ readonly vendor: string;
26
+ readonly validate: (value: unknown) => any;
27
+ readonly types?: {
28
+ readonly input: Input;
29
+ readonly output: Output;
30
+ };
31
+ readonly jsonSchema?: {
32
+ readonly input?: (...args: any[]) => unknown;
33
+ readonly output?: (...args: any[]) => unknown;
34
+ };
35
+ };
36
+ }
37
+ /** The validated output type of a {@link StandardSchemaV1}. */
38
+ type InferOutput<T> = T extends StandardSchemaV1<any, infer O> ? O : never;
39
+ /** An event schema's output, widened to `unknown` when it validates an empty object (no payload fields). */
40
+ type EventPayload<T> = T extends Record<string, never> ? unknown : T;
41
+ /**
42
+ * One entry in an event schema map: a Standard Schema for the event's
43
+ * payload, or the `{}` shorthand for a payload-less event
44
+ * (`events: { CONFIRM: {} }` ≡ `events: { CONFIRM: z.object({}) }`).
45
+ */
46
+ type AgentEventSchemaInput = StandardSchemaV1 | Record<string, never>;
47
+ /** An event schema map as authored: payload schemas and/or `{}` payload-less shorthands, keyed by event type. */
48
+ type AgentEventSchemaInputMap = Record<string, AgentEventSchemaInput>;
49
+ /** Resolves an authored event schema map's `{}` shorthands to real (empty-payload) schemas — the type-level counterpart of the runtime normalization in `createAgentSchemas`. */
50
+ type NormalizedEventSchemas<T extends AgentEventSchemaInputMap> = { [K in keyof T]: T[K] extends StandardSchemaV1 ? T[K] : StandardSchemaV1<{}> };
51
+ /**
52
+ * The discriminated event union derived from a machine's event schema map
53
+ * (e.g. `{ ASK: z.object({ question: z.string() }) }` → `{ type: 'ASK';
54
+ * question: string }`; a `{}` shorthand entry yields its bare `{ type: K }`).
55
+ * Used internally by {@link createAgentSchemas} and `setupAgent` to type a
56
+ * machine's `TEvent`.
57
+ */
58
+ type EventUnion<T extends AgentEventSchemaInputMap> = { [K in keyof T & string]: {
59
+ type: K;
60
+ } & (T[K] extends StandardSchemaV1 ? EventPayload<InferOutput<T[K]>> : unknown) }[keyof T & string];
61
+ /** Raw binary or string content for an {@link ImagePart}/{@link FilePart}. */
62
+ type DataContent = string | Uint8Array | ArrayBuffer;
63
+ /** Provider-specific passthrough options, keyed by provider name (e.g. `{ anthropic: { cacheControl: ... } }`). */
64
+ type ProviderOptions = Record<string, Record<string, unknown>>;
65
+ /** A plain-text segment of a multi-part {@link AgentMessage} content array. */
66
+ interface TextPart {
67
+ type: "text";
68
+ text: string;
69
+ providerOptions?: ProviderOptions;
70
+ }
71
+ /**
72
+ * Binary (`Uint8Array`/`ArrayBuffer`) and `URL` values are not
73
+ * JSON-serializable. Machines that persist snapshots/event logs should use
74
+ * URL strings or base64-encoded strings in `image` instead.
75
+ */
76
+ interface ImagePart {
77
+ type: "image";
78
+ image: DataContent | URL;
79
+ mediaType?: string;
80
+ providerOptions?: ProviderOptions;
81
+ }
82
+ /**
83
+ * Binary (`Uint8Array`/`ArrayBuffer`) and `URL` values are not
84
+ * JSON-serializable. Machines that persist snapshots/event logs should use
85
+ * URL strings or base64-encoded strings in `data` instead.
86
+ */
87
+ interface FilePart {
88
+ type: "file";
89
+ data: DataContent | URL;
90
+ mediaType: string;
91
+ filename?: string;
92
+ providerOptions?: ProviderOptions;
93
+ }
94
+ /** A model-issued tool call, as an {@link AssistantMessage} content part. */
95
+ interface ToolCallPart {
96
+ type: "tool-call";
97
+ toolCallId: string;
98
+ toolName: string;
99
+ input: unknown;
100
+ providerOptions?: ProviderOptions;
101
+ }
102
+ /** The result payload of a {@link ToolResultPart}, discriminated by shape (plain text/JSON, or an error variant of either). */
103
+ type ToolResultOutput = {
104
+ type: "text";
105
+ value: string;
106
+ } | {
107
+ type: "json";
108
+ value: unknown;
109
+ } | {
110
+ type: "error-text";
111
+ value: string;
112
+ } | {
113
+ type: "error-json";
114
+ value: unknown;
115
+ } | {
116
+ type: "content";
117
+ value: Array<TextPart | ImagePart>;
118
+ };
119
+ /** A tool's result, as a {@link ToolMessage} content part. */
120
+ interface ToolResultPart {
121
+ type: "tool-result";
122
+ toolCallId: string;
123
+ toolName: string;
124
+ output: ToolResultOutput;
125
+ providerOptions?: ProviderOptions;
126
+ }
127
+ /** A system-role {@link AgentMessage}. Create with {@link systemMessage}. */
128
+ type SystemMessage = {
129
+ role: "system";
130
+ content: string;
131
+ providerOptions?: ProviderOptions;
132
+ };
133
+ /** A user-role {@link AgentMessage}, optionally multimodal. Create with {@link userMessage}. */
134
+ type UserMessage = {
135
+ role: "user";
136
+ content: string | Array<TextPart | ImagePart | FilePart>;
137
+ providerOptions?: ProviderOptions;
138
+ };
139
+ /** An assistant-role {@link AgentMessage}, which may carry tool calls/results inline. Create with {@link assistantMessage}. */
140
+ type AssistantMessage = {
141
+ role: "assistant";
142
+ content: string | Array<TextPart | FilePart | ToolCallPart | ToolResultPart>;
143
+ providerOptions?: ProviderOptions;
144
+ };
145
+ /** A tool-role {@link AgentMessage} carrying one or more tool results. Create with {@link toolMessage}. */
146
+ type ToolMessage = {
147
+ role: "tool";
148
+ content: Array<ToolResultPart>;
149
+ providerOptions?: ProviderOptions;
150
+ };
151
+ /**
152
+ * A single conversation turn, in this library's portable message model
153
+ * (structurally compatible with the AI SDK's `ModelMessage`). Stored as
154
+ * plain context state — see {@link appendMessages} — and passed to text/
155
+ * decision requests via `messages`. Validate a context field with
156
+ * {@link messagesSchema}.
157
+ */
158
+ type AgentMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;
159
+ /**
160
+ * A schema value on an {@link AgentToolDescriptor}. Core reads it as a
161
+ * {@link StandardSchemaV1} (via `getJsonSchema`/`isStandardSchema`) when it can,
162
+ * but the type is deliberately widened with `object` so an SDK-native tool —
163
+ * whose `inputSchema` is the SDK's own union type (a Zod schema, the SDK's
164
+ * `Schema`, a lazy thunk, …) — assigns structurally with no cast.
165
+ */
166
+ type AgentToolSchema = StandardSchemaV1 | object;
167
+ /**
168
+ * A tool exposed to a text request, described for both the model and
169
+ * (optionally) host execution. This is a **minimal structural contract**: any
170
+ * object matching it — an AI SDK `tool({...})`, an MCP-style descriptor, or a
171
+ * hand-written `{ description, inputSchema, execute }` — is a valid entry, and
172
+ * extra properties (`providerOptions`, `toModelOutput`, …) pass through
173
+ * untouched via the index signature. `execute` is typed permissively so a
174
+ * native tool's `(input, options)` executor is structurally assignable; the
175
+ * SDK you built the tool with owns its precise input typing.
176
+ */
177
+ interface AgentToolDescriptor {
178
+ description?: string;
179
+ inputSchema?: AgentToolSchema;
180
+ outputSchema?: AgentToolSchema;
181
+ execute?: (...args: any[]) => unknown;
182
+ [key: string]: unknown;
183
+ }
184
+ /** A bare tool implementation (no description/schema) — shorthand for {@link AgentToolDescriptor.execute}. */
185
+ type AgentToolExecute = (input?: unknown) => unknown | Promise<unknown>;
186
+ /** A tool entry in {@link AgentTools}: either a full descriptor or a bare execute function. */
187
+ type AgentTool = AgentToolDescriptor | AgentToolExecute;
188
+ /** The `tools` map passed on an {@link AgentTextRequest}, keyed by tool name. */
189
+ type AgentTools = Record<string, AgentTool | undefined>;
190
+ /** How a text request's model should select among its `tools`; `{ type: 'tool', name }` forces one specific tool. */
191
+ type AgentToolChoice = "auto" | "none" | "required" | {
192
+ type: "tool";
193
+ name: string;
194
+ };
195
+ /** The event chosen and raised by a decision. */
196
+ type ChosenEvent = {
197
+ type: string;
198
+ [key: string]: unknown;
199
+ };
200
+ type EventWildcardsOf<TEvent extends string> = TEvent extends `${infer Head}.${infer Rest}` ? `${Head}.*` | `${Head}.${EventWildcardsOf<Rest>}` : never;
201
+ /** One `allowedEvents` entry: an exact declared event type, `'*'` (every event), or a `'prefix.*'` wildcard derived from the declared dotted event types. */
202
+ type AllowedEventPattern<TEvent extends string = string> = TEvent | "*" | EventWildcardsOf<TEvent>;
203
+ /**
204
+ * Candidate event types for a decision or plan (declared on the
205
+ * `agent.decide`/`agent.plan` builtins' `allowedEvents` input). A single
206
+ * entry or an array; entries are exact event types or wildcard patterns
207
+ * (`'*'` for every event, `'todo.*'` for a dotted namespace). The effective
208
+ * candidate set offered to the model is this declaration **intersected with
209
+ * the snapshot's currently-legal events** (via `getAcceptedEvents`) —
210
+ * omitting `allowedEvents` means "all currently-legal events." A resolver
211
+ * function can therefore only ever narrow, never widen, the real surface.
212
+ * Wildcards expand against the live snapshot, so they need a snapshot-aware
213
+ * host (`runAgent` or the step path).
214
+ */
215
+ type AllowedEvents<TEvent extends string = string, TInput = unknown> = AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[] | ((args: {
216
+ input: TInput;
217
+ }) => AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[]);
218
+ //#endregion
219
+ export { UserMessage as A, StandardSchemaV1 as C, ToolMessage as D, ToolCallPart as E, ToolResultOutput as O, ProviderOptions as S, TextPart as T, EventUnion as _, AgentTool as a, InferOutput as b, AgentToolExecute as c, AllowedEventPattern as d, AllowedEvents as f, EventPayload as g, DataContent as h, AgentSnapshotStore as i, ToolResultPart as k, AgentToolSchema as l, ChosenEvent as m, AgentEventSchemaInputMap as n, AgentToolChoice as o, AssistantMessage as p, AgentMessage as r, AgentToolDescriptor as s, AgentEventSchemaInput as t, AgentTools as u, FilePart as v, SystemMessage as w, NormalizedEventSchemas as x, ImagePart as y };
@@ -0,0 +1,219 @@
1
+ import { Snapshot } from "xstate";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * A minimal, type-only contract for a snapshot store: persist a `runAgent`
6
+ * idle/settled snapshot under an id and load it back. It exists purely so
7
+ * userland stores (a file, a SQLite table, a KV row, …) share one shape and
8
+ * interoperate — there is **zero runtime** behind it; the library ships no
9
+ * implementation. See `examples/file-snapshot-store` for a `node:fs` store.
10
+ */
11
+ interface AgentSnapshotStore {
12
+ load(id: string): Promise<Snapshot<unknown> | undefined>;
13
+ save(id: string, snapshot: Snapshot<unknown>): Promise<void>;
14
+ }
15
+ /**
16
+ * The [Standard Schema](https://standardschema.dev) interface. Every schema
17
+ * this library accepts (context, events, input/output, tool schemas, …) is a
18
+ * `StandardSchemaV1` — Zod, Valibot, ArkType, and hand-written validators all
19
+ * implement it, so the library never depends on a specific validation
20
+ * library. JSON workflow configs use a caller-provided {@link SchemaCompiler}.
21
+ */
22
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
23
+ readonly "~standard": {
24
+ readonly version: 1;
25
+ readonly vendor: string;
26
+ readonly validate: (value: unknown) => any;
27
+ readonly types?: {
28
+ readonly input: Input;
29
+ readonly output: Output;
30
+ };
31
+ readonly jsonSchema?: {
32
+ readonly input?: (...args: any[]) => unknown;
33
+ readonly output?: (...args: any[]) => unknown;
34
+ };
35
+ };
36
+ }
37
+ /** The validated output type of a {@link StandardSchemaV1}. */
38
+ type InferOutput<T> = T extends StandardSchemaV1<any, infer O> ? O : never;
39
+ /** An event schema's output, widened to `unknown` when it validates an empty object (no payload fields). */
40
+ type EventPayload<T> = T extends Record<string, never> ? unknown : T;
41
+ /**
42
+ * One entry in an event schema map: a Standard Schema for the event's
43
+ * payload, or the `{}` shorthand for a payload-less event
44
+ * (`events: { CONFIRM: {} }` ≡ `events: { CONFIRM: z.object({}) }`).
45
+ */
46
+ type AgentEventSchemaInput = StandardSchemaV1 | Record<string, never>;
47
+ /** An event schema map as authored: payload schemas and/or `{}` payload-less shorthands, keyed by event type. */
48
+ type AgentEventSchemaInputMap = Record<string, AgentEventSchemaInput>;
49
+ /** Resolves an authored event schema map's `{}` shorthands to real (empty-payload) schemas — the type-level counterpart of the runtime normalization in `createAgentSchemas`. */
50
+ type NormalizedEventSchemas<T extends AgentEventSchemaInputMap> = { [K in keyof T]: T[K] extends StandardSchemaV1 ? T[K] : StandardSchemaV1<{}> };
51
+ /**
52
+ * The discriminated event union derived from a machine's event schema map
53
+ * (e.g. `{ ASK: z.object({ question: z.string() }) }` → `{ type: 'ASK';
54
+ * question: string }`; a `{}` shorthand entry yields its bare `{ type: K }`).
55
+ * Used internally by {@link createAgentSchemas} and `setupAgent` to type a
56
+ * machine's `TEvent`.
57
+ */
58
+ type EventUnion<T extends AgentEventSchemaInputMap> = { [K in keyof T & string]: {
59
+ type: K;
60
+ } & (T[K] extends StandardSchemaV1 ? EventPayload<InferOutput<T[K]>> : unknown) }[keyof T & string];
61
+ /** Raw binary or string content for an {@link ImagePart}/{@link FilePart}. */
62
+ type DataContent = string | Uint8Array | ArrayBuffer;
63
+ /** Provider-specific passthrough options, keyed by provider name (e.g. `{ anthropic: { cacheControl: ... } }`). */
64
+ type ProviderOptions = Record<string, Record<string, unknown>>;
65
+ /** A plain-text segment of a multi-part {@link AgentMessage} content array. */
66
+ interface TextPart {
67
+ type: "text";
68
+ text: string;
69
+ providerOptions?: ProviderOptions;
70
+ }
71
+ /**
72
+ * Binary (`Uint8Array`/`ArrayBuffer`) and `URL` values are not
73
+ * JSON-serializable. Machines that persist snapshots/event logs should use
74
+ * URL strings or base64-encoded strings in `image` instead.
75
+ */
76
+ interface ImagePart {
77
+ type: "image";
78
+ image: DataContent | URL;
79
+ mediaType?: string;
80
+ providerOptions?: ProviderOptions;
81
+ }
82
+ /**
83
+ * Binary (`Uint8Array`/`ArrayBuffer`) and `URL` values are not
84
+ * JSON-serializable. Machines that persist snapshots/event logs should use
85
+ * URL strings or base64-encoded strings in `data` instead.
86
+ */
87
+ interface FilePart {
88
+ type: "file";
89
+ data: DataContent | URL;
90
+ mediaType: string;
91
+ filename?: string;
92
+ providerOptions?: ProviderOptions;
93
+ }
94
+ /** A model-issued tool call, as an {@link AssistantMessage} content part. */
95
+ interface ToolCallPart {
96
+ type: "tool-call";
97
+ toolCallId: string;
98
+ toolName: string;
99
+ input: unknown;
100
+ providerOptions?: ProviderOptions;
101
+ }
102
+ /** The result payload of a {@link ToolResultPart}, discriminated by shape (plain text/JSON, or an error variant of either). */
103
+ type ToolResultOutput = {
104
+ type: "text";
105
+ value: string;
106
+ } | {
107
+ type: "json";
108
+ value: unknown;
109
+ } | {
110
+ type: "error-text";
111
+ value: string;
112
+ } | {
113
+ type: "error-json";
114
+ value: unknown;
115
+ } | {
116
+ type: "content";
117
+ value: Array<TextPart | ImagePart>;
118
+ };
119
+ /** A tool's result, as a {@link ToolMessage} content part. */
120
+ interface ToolResultPart {
121
+ type: "tool-result";
122
+ toolCallId: string;
123
+ toolName: string;
124
+ output: ToolResultOutput;
125
+ providerOptions?: ProviderOptions;
126
+ }
127
+ /** A system-role {@link AgentMessage}. Create with {@link systemMessage}. */
128
+ type SystemMessage = {
129
+ role: "system";
130
+ content: string;
131
+ providerOptions?: ProviderOptions;
132
+ };
133
+ /** A user-role {@link AgentMessage}, optionally multimodal. Create with {@link userMessage}. */
134
+ type UserMessage = {
135
+ role: "user";
136
+ content: string | Array<TextPart | ImagePart | FilePart>;
137
+ providerOptions?: ProviderOptions;
138
+ };
139
+ /** An assistant-role {@link AgentMessage}, which may carry tool calls/results inline. Create with {@link assistantMessage}. */
140
+ type AssistantMessage = {
141
+ role: "assistant";
142
+ content: string | Array<TextPart | FilePart | ToolCallPart | ToolResultPart>;
143
+ providerOptions?: ProviderOptions;
144
+ };
145
+ /** A tool-role {@link AgentMessage} carrying one or more tool results. Create with {@link toolMessage}. */
146
+ type ToolMessage = {
147
+ role: "tool";
148
+ content: Array<ToolResultPart>;
149
+ providerOptions?: ProviderOptions;
150
+ };
151
+ /**
152
+ * A single conversation turn, in this library's portable message model
153
+ * (structurally compatible with the AI SDK's `ModelMessage`). Stored as
154
+ * plain context state — see {@link appendMessages} — and passed to text/
155
+ * decision requests via `messages`. Validate a context field with
156
+ * {@link messagesSchema}.
157
+ */
158
+ type AgentMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;
159
+ /**
160
+ * A schema value on an {@link AgentToolDescriptor}. Core reads it as a
161
+ * {@link StandardSchemaV1} (via `getJsonSchema`/`isStandardSchema`) when it can,
162
+ * but the type is deliberately widened with `object` so an SDK-native tool —
163
+ * whose `inputSchema` is the SDK's own union type (a Zod schema, the SDK's
164
+ * `Schema`, a lazy thunk, …) — assigns structurally with no cast.
165
+ */
166
+ type AgentToolSchema = StandardSchemaV1 | object;
167
+ /**
168
+ * A tool exposed to a text request, described for both the model and
169
+ * (optionally) host execution. This is a **minimal structural contract**: any
170
+ * object matching it — an AI SDK `tool({...})`, an MCP-style descriptor, or a
171
+ * hand-written `{ description, inputSchema, execute }` — is a valid entry, and
172
+ * extra properties (`providerOptions`, `toModelOutput`, …) pass through
173
+ * untouched via the index signature. `execute` is typed permissively so a
174
+ * native tool's `(input, options)` executor is structurally assignable; the
175
+ * SDK you built the tool with owns its precise input typing.
176
+ */
177
+ interface AgentToolDescriptor {
178
+ description?: string;
179
+ inputSchema?: AgentToolSchema;
180
+ outputSchema?: AgentToolSchema;
181
+ execute?: (...args: any[]) => unknown;
182
+ [key: string]: unknown;
183
+ }
184
+ /** A bare tool implementation (no description/schema) — shorthand for {@link AgentToolDescriptor.execute}. */
185
+ type AgentToolExecute = (input?: unknown) => unknown | Promise<unknown>;
186
+ /** A tool entry in {@link AgentTools}: either a full descriptor or a bare execute function. */
187
+ type AgentTool = AgentToolDescriptor | AgentToolExecute;
188
+ /** The `tools` map passed on an {@link AgentTextRequest}, keyed by tool name. */
189
+ type AgentTools = Record<string, AgentTool | undefined>;
190
+ /** How a text request's model should select among its `tools`; `{ type: 'tool', name }` forces one specific tool. */
191
+ type AgentToolChoice = "auto" | "none" | "required" | {
192
+ type: "tool";
193
+ name: string;
194
+ };
195
+ /** The event chosen and raised by a decision. */
196
+ type ChosenEvent = {
197
+ type: string;
198
+ [key: string]: unknown;
199
+ };
200
+ type EventWildcardsOf<TEvent extends string> = TEvent extends `${infer Head}.${infer Rest}` ? `${Head}.*` | `${Head}.${EventWildcardsOf<Rest>}` : never;
201
+ /** One `allowedEvents` entry: an exact declared event type, `'*'` (every event), or a `'prefix.*'` wildcard derived from the declared dotted event types. */
202
+ type AllowedEventPattern<TEvent extends string = string> = TEvent | "*" | EventWildcardsOf<TEvent>;
203
+ /**
204
+ * Candidate event types for a decision or plan (declared on the
205
+ * `agent.decide`/`agent.plan` builtins' `allowedEvents` input). A single
206
+ * entry or an array; entries are exact event types or wildcard patterns
207
+ * (`'*'` for every event, `'todo.*'` for a dotted namespace). The effective
208
+ * candidate set offered to the model is this declaration **intersected with
209
+ * the snapshot's currently-legal events** (via `getAcceptedEvents`) —
210
+ * omitting `allowedEvents` means "all currently-legal events." A resolver
211
+ * function can therefore only ever narrow, never widen, the real surface.
212
+ * Wildcards expand against the live snapshot, so they need a snapshot-aware
213
+ * host (`runAgent` or the step path).
214
+ */
215
+ type AllowedEvents<TEvent extends string = string, TInput = unknown> = AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[] | ((args: {
216
+ input: TInput;
217
+ }) => AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[]);
218
+ //#endregion
219
+ export { UserMessage as A, StandardSchemaV1 as C, ToolMessage as D, ToolCallPart as E, ToolResultOutput as O, ProviderOptions as S, TextPart as T, EventUnion as _, AgentTool as a, InferOutput as b, AgentToolExecute as c, AllowedEventPattern as d, AllowedEvents as f, EventPayload as g, DataContent as h, AgentSnapshotStore as i, ToolResultPart as k, AgentToolSchema as l, ChosenEvent as m, AgentEventSchemaInputMap as n, AgentToolChoice as o, AssistantMessage as p, AgentMessage as r, AgentToolDescriptor as s, AgentEventSchemaInput as t, AgentTools as u, FilePart as v, SystemMessage as w, NormalizedEventSchemas as x, ImagePart as y };
@@ -0,0 +1,108 @@
1
+ import { A as UserMessage, C as StandardSchemaV1, D as ToolMessage, E as ToolCallPart, T as TextPart, k as ToolResultPart, p as AssistantMessage, r as AgentMessage, v as FilePart, w as SystemMessage, y as ImagePart } from "./types-C9QiMjre.cjs";
2
+ import { AnyMachineSnapshot, AnyStateMachine } from "xstate";
3
+
4
+ //#region src/utils.d.ts
5
+ /**
6
+ * Deep-clones a snapshot to a plain-JSON value via a `JSON` round-trip, the
7
+ * shape you persist and later feed back to `runAgent({ snapshot })`. Asserts
8
+ * JSON-serializability: functions, `undefined`, and other non-JSON values are
9
+ * dropped or throw exactly as `JSON.stringify`/`JSON.parse` would. Returns a
10
+ * plain-JSON deep clone, not a live snapshot.
11
+ */
12
+ declare function persistSnapshot<TSnapshot>(snapshot: TSnapshot): TSnapshot;
13
+ /**
14
+ * A stable, dependency-free structural fingerprint of a machine — a short hex
15
+ * `djb2` hash over its **structural** config only: state ids/nesting, transition
16
+ * event types and targets, invoke `src`s, `initial`, and any other serializable
17
+ * config fields. Function values (context/output builders, prompts, inline
18
+ * guards/actions) are excluded entirely, so two machines that differ only in
19
+ * their prompts or executors hash identically; adding/removing/retargeting a
20
+ * state or transition changes the hash.
21
+ *
22
+ * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
23
+ * detect a structurally-edited machine on resume. It is a change detector, not
24
+ * a cryptographic digest — collisions are possible but unlikely for real
25
+ * configs. Pass an explicit `machineVersion` to `runAgent` to override it.
26
+ */
27
+ declare function getMachineStructuralHash(machine: AnyStateMachine): string;
28
+ /** Builds a {@link UserMessage} from a string or multimodal content parts. */
29
+ declare function userMessage(content: string | Array<TextPart | ImagePart | FilePart>): UserMessage;
30
+ /** Builds an {@link AssistantMessage} from a string or content parts (text, files, tool calls/results). */
31
+ declare function assistantMessage(content: string | Array<TextPart | FilePart | ToolCallPart | ToolResultPart>): AssistantMessage;
32
+ /** Builds a {@link SystemMessage}. */
33
+ declare function systemMessage(content: string): SystemMessage;
34
+ /** Builds a {@link ToolMessage} from one or more tool-result parts. */
35
+ declare function toolMessage(content: Array<ToolResultPart>): ToolMessage;
36
+ type MetaOfSnapshot<TSnapshot extends {
37
+ getMeta(): Record<string, unknown>;
38
+ }> = NonNullable<ReturnType<TSnapshot["getMeta"]>[keyof ReturnType<TSnapshot["getMeta"]>]>;
39
+ /**
40
+ * Returns the merged `meta` of a snapshot's active state(s) — the typed
41
+ * replacement for the `Object.values(snapshot.getMeta())[0]` dance.
42
+ *
43
+ * `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
44
+ * state, but parallel/nested machines can have several. This shallow-merges
45
+ * every active state's meta into one object (later/deeper entries win) and
46
+ * returns `{}` when no active state declares meta.
47
+ *
48
+ * The return type is recovered from the snapshot's own `getMeta()` type, so a
49
+ * schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
50
+ * output type. Pass an explicit `TMeta` to override when the snapshot is
51
+ * untyped (e.g. `AnyMachineSnapshot`).
52
+ *
53
+ * @example HITL: read the current state's interaction protocol off an idle
54
+ * snapshot to render for a human.
55
+ * ```ts
56
+ * const { interaction } = getStateMeta(result.snapshot);
57
+ * ```
58
+ */
59
+ declare function getStateMeta<TSnapshot extends {
60
+ getMeta(): Record<string, unknown>;
61
+ } = AnyMachineSnapshot, TMeta = MetaOfSnapshot<TSnapshot>>(snapshot: TSnapshot): Partial<TMeta>;
62
+ /**
63
+ * Reads the run-owned message log off a snapshot settled by a `runAgent` call
64
+ * that used `getRequests` (or `options.messages`) — the typed replacement for
65
+ * the `(snapshot as { messages?: AgentMessage[] }).messages` cast. runAgent
66
+ * stamps the log as a plain enumerable `messages` property (like `agentMeta`),
67
+ * so it survives a JSON persist/resume round-trip; this accessor works on the
68
+ * live settled snapshot and on a JSON-parsed persisted one alike. Returns `[]`
69
+ * when no log was stamped (e.g. a default invoke-driven run).
70
+ *
71
+ * The write path is `runAgent(..., { messages })`: an explicit seed that
72
+ * overrides the resume snapshot's stamped log (fold in a user reply on
73
+ * resume, or start a run with prior history).
74
+ */
75
+ declare function getAgentMessages(snapshot: unknown): AgentMessage[];
76
+ /**
77
+ * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
78
+ * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
79
+ * (a Zod/Valibot/… schema) apart from an SDK-specific schema wrapper that core
80
+ * can't read directly — see the `ai-sdk` tool pass-through and `openai-compat`
81
+ * tool serialization.
82
+ */
83
+ declare function isStandardSchema(value: unknown): value is StandardSchemaV1;
84
+ /**
85
+ * Pulls the JSON Schema off a {@link StandardSchemaV1} via its optional
86
+ * `~standard.jsonSchema.input()` extension (implemented by e.g. Zod v4's
87
+ * `z.toJSONSchema`), awaiting it when the producer is async. Returns
88
+ * `undefined` when the schema doesn't expose the extension. Use this to build
89
+ * a provider request's `response_format`/tool `parameters` from a schema.
90
+ */
91
+ declare function getJsonSchema(schema?: StandardSchemaV1): Promise<Record<string, unknown> | undefined>;
92
+ /**
93
+ * Synchronous variant of {@link getJsonSchema}, for call sites that can't
94
+ * await (building tool/event descriptors inline). An async JSON Schema
95
+ * producer is treated as absent (returns `undefined`) — in practice Zod's
96
+ * `z.toJSONSchema` resolves synchronously.
97
+ */
98
+ declare function getJsonSchemaSync(schema?: StandardSchemaV1): Record<string, unknown> | undefined;
99
+ /**
100
+ * Validates `value` against a {@link StandardSchemaV1}, synchronously.
101
+ * Throws if the schema's `validate` returns a `Promise` (async validation is
102
+ * not supported anywhere in this library) or if validation reports issues —
103
+ * in which case the thrown `Error.message` joins every issue message with
104
+ * `', '`.
105
+ */
106
+ declare function validateSchemaSync<T>(schema: StandardSchemaV1<T>, value: unknown): T;
107
+ //#endregion
108
+ export { getMachineStructuralHash as a, persistSnapshot as c, userMessage as d, validateSchemaSync as f, getJsonSchemaSync as i, systemMessage as l, getAgentMessages as n, getStateMeta as o, getJsonSchema as r, isStandardSchema as s, assistantMessage as t, toolMessage as u };
@@ -0,0 +1,108 @@
1
+ import { A as UserMessage, C as StandardSchemaV1, D as ToolMessage, E as ToolCallPart, T as TextPart, k as ToolResultPart, p as AssistantMessage, r as AgentMessage, v as FilePart, w as SystemMessage, y as ImagePart } from "./types-qm00QF91.mjs";
2
+ import { AnyMachineSnapshot, AnyStateMachine } from "xstate";
3
+
4
+ //#region src/utils.d.ts
5
+ /**
6
+ * Deep-clones a snapshot to a plain-JSON value via a `JSON` round-trip, the
7
+ * shape you persist and later feed back to `runAgent({ snapshot })`. Asserts
8
+ * JSON-serializability: functions, `undefined`, and other non-JSON values are
9
+ * dropped or throw exactly as `JSON.stringify`/`JSON.parse` would. Returns a
10
+ * plain-JSON deep clone, not a live snapshot.
11
+ */
12
+ declare function persistSnapshot<TSnapshot>(snapshot: TSnapshot): TSnapshot;
13
+ /**
14
+ * A stable, dependency-free structural fingerprint of a machine — a short hex
15
+ * `djb2` hash over its **structural** config only: state ids/nesting, transition
16
+ * event types and targets, invoke `src`s, `initial`, and any other serializable
17
+ * config fields. Function values (context/output builders, prompts, inline
18
+ * guards/actions) are excluded entirely, so two machines that differ only in
19
+ * their prompts or executors hash identically; adding/removing/retargeting a
20
+ * state or transition changes the hash.
21
+ *
22
+ * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
23
+ * detect a structurally-edited machine on resume. It is a change detector, not
24
+ * a cryptographic digest — collisions are possible but unlikely for real
25
+ * configs. Pass an explicit `machineVersion` to `runAgent` to override it.
26
+ */
27
+ declare function getMachineStructuralHash(machine: AnyStateMachine): string;
28
+ /** Builds a {@link UserMessage} from a string or multimodal content parts. */
29
+ declare function userMessage(content: string | Array<TextPart | ImagePart | FilePart>): UserMessage;
30
+ /** Builds an {@link AssistantMessage} from a string or content parts (text, files, tool calls/results). */
31
+ declare function assistantMessage(content: string | Array<TextPart | FilePart | ToolCallPart | ToolResultPart>): AssistantMessage;
32
+ /** Builds a {@link SystemMessage}. */
33
+ declare function systemMessage(content: string): SystemMessage;
34
+ /** Builds a {@link ToolMessage} from one or more tool-result parts. */
35
+ declare function toolMessage(content: Array<ToolResultPart>): ToolMessage;
36
+ type MetaOfSnapshot<TSnapshot extends {
37
+ getMeta(): Record<string, unknown>;
38
+ }> = NonNullable<ReturnType<TSnapshot["getMeta"]>[keyof ReturnType<TSnapshot["getMeta"]>]>;
39
+ /**
40
+ * Returns the merged `meta` of a snapshot's active state(s) — the typed
41
+ * replacement for the `Object.values(snapshot.getMeta())[0]` dance.
42
+ *
43
+ * `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
44
+ * state, but parallel/nested machines can have several. This shallow-merges
45
+ * every active state's meta into one object (later/deeper entries win) and
46
+ * returns `{}` when no active state declares meta.
47
+ *
48
+ * The return type is recovered from the snapshot's own `getMeta()` type, so a
49
+ * schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
50
+ * output type. Pass an explicit `TMeta` to override when the snapshot is
51
+ * untyped (e.g. `AnyMachineSnapshot`).
52
+ *
53
+ * @example HITL: read the current state's interaction protocol off an idle
54
+ * snapshot to render for a human.
55
+ * ```ts
56
+ * const { interaction } = getStateMeta(result.snapshot);
57
+ * ```
58
+ */
59
+ declare function getStateMeta<TSnapshot extends {
60
+ getMeta(): Record<string, unknown>;
61
+ } = AnyMachineSnapshot, TMeta = MetaOfSnapshot<TSnapshot>>(snapshot: TSnapshot): Partial<TMeta>;
62
+ /**
63
+ * Reads the run-owned message log off a snapshot settled by a `runAgent` call
64
+ * that used `getRequests` (or `options.messages`) — the typed replacement for
65
+ * the `(snapshot as { messages?: AgentMessage[] }).messages` cast. runAgent
66
+ * stamps the log as a plain enumerable `messages` property (like `agentMeta`),
67
+ * so it survives a JSON persist/resume round-trip; this accessor works on the
68
+ * live settled snapshot and on a JSON-parsed persisted one alike. Returns `[]`
69
+ * when no log was stamped (e.g. a default invoke-driven run).
70
+ *
71
+ * The write path is `runAgent(..., { messages })`: an explicit seed that
72
+ * overrides the resume snapshot's stamped log (fold in a user reply on
73
+ * resume, or start a run with prior history).
74
+ */
75
+ declare function getAgentMessages(snapshot: unknown): AgentMessage[];
76
+ /**
77
+ * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
78
+ * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
79
+ * (a Zod/Valibot/… schema) apart from an SDK-specific schema wrapper that core
80
+ * can't read directly — see the `ai-sdk` tool pass-through and `openai-compat`
81
+ * tool serialization.
82
+ */
83
+ declare function isStandardSchema(value: unknown): value is StandardSchemaV1;
84
+ /**
85
+ * Pulls the JSON Schema off a {@link StandardSchemaV1} via its optional
86
+ * `~standard.jsonSchema.input()` extension (implemented by e.g. Zod v4's
87
+ * `z.toJSONSchema`), awaiting it when the producer is async. Returns
88
+ * `undefined` when the schema doesn't expose the extension. Use this to build
89
+ * a provider request's `response_format`/tool `parameters` from a schema.
90
+ */
91
+ declare function getJsonSchema(schema?: StandardSchemaV1): Promise<Record<string, unknown> | undefined>;
92
+ /**
93
+ * Synchronous variant of {@link getJsonSchema}, for call sites that can't
94
+ * await (building tool/event descriptors inline). An async JSON Schema
95
+ * producer is treated as absent (returns `undefined`) — in practice Zod's
96
+ * `z.toJSONSchema` resolves synchronously.
97
+ */
98
+ declare function getJsonSchemaSync(schema?: StandardSchemaV1): Record<string, unknown> | undefined;
99
+ /**
100
+ * Validates `value` against a {@link StandardSchemaV1}, synchronously.
101
+ * Throws if the schema's `validate` returns a `Promise` (async validation is
102
+ * not supported anywhere in this library) or if validation reports issues —
103
+ * in which case the thrown `Error.message` joins every issue message with
104
+ * `', '`.
105
+ */
106
+ declare function validateSchemaSync<T>(schema: StandardSchemaV1<T>, value: unknown): T;
107
+ //#endregion
108
+ export { getMachineStructuralHash as a, persistSnapshot as c, userMessage as d, validateSchemaSync as f, getJsonSchemaSync as i, systemMessage as l, getAgentMessages as n, getStateMeta as o, getJsonSchema as r, isStandardSchema as s, assistantMessage as t, toolMessage as u };