@statelyai/agent 1.1.6 → 2.0.0-alpha.5

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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/dist/ai-sdk.cjs +249 -0
  3. package/dist/ai-sdk.d.cts +168 -0
  4. package/dist/ai-sdk.d.mts +168 -0
  5. package/dist/ai-sdk.mjs +241 -0
  6. package/dist/cli.cjs +63 -0
  7. package/dist/cli.d.cts +1 -0
  8. package/dist/cli.d.mts +1 -0
  9. package/dist/cli.mjs +64 -0
  10. package/dist/decision-FTmbqSEe.mjs +938 -0
  11. package/dist/decision-pC-bY2DE.cjs +1231 -0
  12. package/dist/index.cjs +54 -0
  13. package/dist/index.d.cts +1217 -0
  14. package/dist/index.d.mts +1194 -405
  15. package/dist/index.mjs +3 -588
  16. package/dist/openai-compat.cjs +319 -0
  17. package/dist/openai-compat.d.cts +98 -0
  18. package/dist/openai-compat.d.mts +98 -0
  19. package/dist/openai-compat.mjs +312 -0
  20. package/dist/src-CjpHDU8F.mjs +2445 -0
  21. package/dist/src-DcRsWPfV.cjs +2564 -0
  22. package/dist/text-logic-1ZQkO3zr.d.cts +682 -0
  23. package/dist/text-logic-2EMJIS-n.d.mts +682 -0
  24. package/dist/types-BHjeDdch.d.cts +208 -0
  25. package/dist/types-Cq1YlAQ6.d.mts +208 -0
  26. package/dist/utils-CWUCa3pF.d.mts +108 -0
  27. package/dist/utils-lK1wnL2i.d.cts +108 -0
  28. package/dist/zod.cjs +31 -0
  29. package/dist/zod.d.cts +30 -0
  30. package/dist/zod.d.mts +30 -0
  31. package/dist/zod.mjs +30 -0
  32. package/package.json +109 -28
  33. package/readme.md +144 -6
  34. package/schemas/agent-workflow.json +527 -0
  35. package/.changeset/README.md +0 -8
  36. package/.changeset/config.json +0 -11
  37. package/.env.template +0 -3
  38. package/.github/actions/ci-setup/action.yml +0 -24
  39. package/.github/workflows/release.yml +0 -46
  40. package/.vscode/launch.json +0 -28
  41. package/CHANGELOG.md +0 -222
  42. package/dist/index.d.ts +0 -428
  43. package/dist/index.js +0 -621
  44. package/examples/chatbot.ts +0 -71
  45. package/examples/cot.ts +0 -89
  46. package/examples/email.ts +0 -118
  47. package/examples/example.ts +0 -81
  48. package/examples/goal.ts +0 -94
  49. package/examples/helpers/helpers.ts +0 -17
  50. package/examples/helpers/loader.ts +0 -32
  51. package/examples/helpers/runner.ts +0 -27
  52. package/examples/joke.ts +0 -225
  53. package/examples/multi.ts +0 -103
  54. package/examples/newspaper.ts +0 -324
  55. package/examples/number.ts +0 -102
  56. package/examples/raffle.ts +0 -105
  57. package/examples/sandbox.ts +0 -28
  58. package/examples/simple.ts +0 -39
  59. package/examples/support.ts +0 -147
  60. package/examples/ticTacToe.ts +0 -224
  61. package/examples/todo.ts +0 -137
  62. package/examples/tutor.ts +0 -100
  63. package/examples/verify.ts +0 -120
  64. package/examples/weather.ts +0 -178
  65. package/examples/wiki.ts +0 -30
  66. package/examples/word.ts +0 -171
  67. package/src/adapters/vercel.ts +0 -7
  68. package/src/agent-experimental.ts +0 -221
  69. package/src/agent.test.ts +0 -506
  70. package/src/agent.ts +0 -300
  71. package/src/decision.test.ts +0 -179
  72. package/src/decision.ts +0 -84
  73. package/src/index.ts +0 -4
  74. package/src/memory.ts +0 -25
  75. package/src/planners/shortestPathPlanner.ts +0 -22
  76. package/src/planners/simplePlanner.ts +0 -139
  77. package/src/schemas.ts +0 -11
  78. package/src/strategies/chain-of-note.ts +0 -155
  79. package/src/templates/defaultText.ts +0 -18
  80. package/src/text.ts +0 -241
  81. package/src/types.ts +0 -499
  82. package/src/utils.ts +0 -72
  83. package/tsconfig.json +0 -109
  84. package/vitest.config.ts +0 -9
@@ -0,0 +1,208 @@
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
+ * The discriminated event union derived from a machine's event schema map
43
+ * (e.g. `{ ASK: z.object({ question: z.string() }) }` → `{ type: 'ASK';
44
+ * question: string }`). Used internally by {@link createAgentSchemas} and
45
+ * `setupAgent` to type a machine's `TEvent`.
46
+ */
47
+ type EventUnion<T extends Record<string, StandardSchemaV1>> = { [K in keyof T & string]: {
48
+ type: K;
49
+ } & EventPayload<InferOutput<T[K]>> }[keyof T & string];
50
+ /** Raw binary or string content for an {@link ImagePart}/{@link FilePart}. */
51
+ type DataContent = string | Uint8Array | ArrayBuffer;
52
+ /** Provider-specific passthrough options, keyed by provider name (e.g. `{ anthropic: { cacheControl: ... } }`). */
53
+ type ProviderOptions = Record<string, Record<string, unknown>>;
54
+ /** A plain-text segment of a multi-part {@link AgentMessage} content array. */
55
+ interface TextPart {
56
+ type: "text";
57
+ text: string;
58
+ providerOptions?: ProviderOptions;
59
+ }
60
+ /**
61
+ * Binary (`Uint8Array`/`ArrayBuffer`) and `URL` values are not
62
+ * JSON-serializable. Machines that persist snapshots/event logs should use
63
+ * URL strings or base64-encoded strings in `image` instead.
64
+ */
65
+ interface ImagePart {
66
+ type: "image";
67
+ image: DataContent | URL;
68
+ mediaType?: 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 `data` instead.
75
+ */
76
+ interface FilePart {
77
+ type: "file";
78
+ data: DataContent | URL;
79
+ mediaType: string;
80
+ filename?: string;
81
+ providerOptions?: ProviderOptions;
82
+ }
83
+ /** A model-issued tool call, as an {@link AssistantMessage} content part. */
84
+ interface ToolCallPart {
85
+ type: "tool-call";
86
+ toolCallId: string;
87
+ toolName: string;
88
+ input: unknown;
89
+ providerOptions?: ProviderOptions;
90
+ }
91
+ /** The result payload of a {@link ToolResultPart}, discriminated by shape (plain text/JSON, or an error variant of either). */
92
+ type ToolResultOutput = {
93
+ type: "text";
94
+ value: string;
95
+ } | {
96
+ type: "json";
97
+ value: unknown;
98
+ } | {
99
+ type: "error-text";
100
+ value: string;
101
+ } | {
102
+ type: "error-json";
103
+ value: unknown;
104
+ } | {
105
+ type: "content";
106
+ value: Array<TextPart | ImagePart>;
107
+ };
108
+ /** A tool's result, as a {@link ToolMessage} content part. */
109
+ interface ToolResultPart {
110
+ type: "tool-result";
111
+ toolCallId: string;
112
+ toolName: string;
113
+ output: ToolResultOutput;
114
+ providerOptions?: ProviderOptions;
115
+ }
116
+ /** A system-role {@link AgentMessage}. Create with {@link systemMessage}. */
117
+ type SystemMessage = {
118
+ role: "system";
119
+ content: string;
120
+ providerOptions?: ProviderOptions;
121
+ };
122
+ /** A user-role {@link AgentMessage}, optionally multimodal. Create with {@link userMessage}. */
123
+ type UserMessage = {
124
+ role: "user";
125
+ content: string | Array<TextPart | ImagePart | FilePart>;
126
+ providerOptions?: ProviderOptions;
127
+ };
128
+ /** An assistant-role {@link AgentMessage}, which may carry tool calls/results inline. Create with {@link assistantMessage}. */
129
+ type AssistantMessage = {
130
+ role: "assistant";
131
+ content: string | Array<TextPart | FilePart | ToolCallPart | ToolResultPart>;
132
+ providerOptions?: ProviderOptions;
133
+ };
134
+ /** A tool-role {@link AgentMessage} carrying one or more tool results. Create with {@link toolMessage}. */
135
+ type ToolMessage = {
136
+ role: "tool";
137
+ content: Array<ToolResultPart>;
138
+ providerOptions?: ProviderOptions;
139
+ };
140
+ /**
141
+ * A single conversation turn, in this library's portable message model
142
+ * (structurally compatible with the AI SDK's `ModelMessage`). Stored as
143
+ * plain context state — see {@link appendMessages} — and passed to text/
144
+ * decision requests via `messages`. Validate a context field with
145
+ * {@link messagesSchema}.
146
+ */
147
+ type AgentMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;
148
+ /**
149
+ * A schema value on an {@link AgentToolDescriptor}. Core reads it as a
150
+ * {@link StandardSchemaV1} (via `getJsonSchema`/`isStandardSchema`) when it can,
151
+ * but the type is deliberately widened with `object` so an SDK-native tool —
152
+ * whose `inputSchema` is the SDK's own union type (a Zod schema, the SDK's
153
+ * `Schema`, a lazy thunk, …) — assigns structurally with no cast.
154
+ */
155
+ type AgentToolSchema = StandardSchemaV1 | object;
156
+ /**
157
+ * A tool exposed to a text request, described for both the model and
158
+ * (optionally) host execution. This is a **minimal structural contract**: any
159
+ * object matching it — an AI SDK `tool({...})`, an MCP-style descriptor, or a
160
+ * hand-written `{ description, inputSchema, execute }` — is a valid entry, and
161
+ * extra properties (`providerOptions`, `toModelOutput`, …) pass through
162
+ * untouched via the index signature. `execute` is typed permissively so a
163
+ * native tool's `(input, options)` executor is structurally assignable; the
164
+ * SDK you built the tool with owns its precise input typing.
165
+ */
166
+ interface AgentToolDescriptor {
167
+ description?: string;
168
+ inputSchema?: AgentToolSchema;
169
+ outputSchema?: AgentToolSchema;
170
+ execute?: (...args: any[]) => unknown;
171
+ [key: string]: unknown;
172
+ }
173
+ /** A bare tool implementation (no description/schema) — shorthand for {@link AgentToolDescriptor.execute}. */
174
+ type AgentToolExecute = (input?: unknown) => unknown | Promise<unknown>;
175
+ /** A tool entry in {@link AgentTools}: either a full descriptor or a bare execute function. */
176
+ type AgentTool = AgentToolDescriptor | AgentToolExecute;
177
+ /** The `tools` map passed on an {@link AgentTextRequest}, keyed by tool name. */
178
+ type AgentTools = Record<string, AgentTool | undefined>;
179
+ /** How a text request's model should select among its `tools`; `{ type: 'tool', name }` forces one specific tool. */
180
+ type AgentToolChoice = "auto" | "none" | "required" | {
181
+ type: "tool";
182
+ name: string;
183
+ };
184
+ /** The event chosen and raised by a decision. */
185
+ type ChosenEvent = {
186
+ type: string;
187
+ [key: string]: unknown;
188
+ };
189
+ type EventWildcardsOf<TEvent extends string> = TEvent extends `${infer Head}.${infer Rest}` ? `${Head}.*` | `${Head}.${EventWildcardsOf<Rest>}` : never;
190
+ /** One `allowedEvents` entry: an exact declared event type, `'*'` (every event), or a `'prefix.*'` wildcard derived from the declared dotted event types. */
191
+ type AllowedEventPattern<TEvent extends string = string> = TEvent | "*" | EventWildcardsOf<TEvent>;
192
+ /**
193
+ * Candidate event types for a decision or plan (declared on the
194
+ * `agent.decide`/`agent.plan` builtins' `allowedEvents` input). A single
195
+ * entry or an array; entries are exact event types or wildcard patterns
196
+ * (`'*'` for every event, `'todo.*'` for a dotted namespace). The effective
197
+ * candidate set offered to the model is this declaration **intersected with
198
+ * the snapshot's currently-legal events** (via `getAcceptedEvents`) —
199
+ * omitting `allowedEvents` means "all currently-legal events." A resolver
200
+ * function can therefore only ever narrow, never widen, the real surface.
201
+ * Wildcards expand against the live snapshot, so they need a snapshot-aware
202
+ * host (`runAgent` or the step path).
203
+ */
204
+ type AllowedEvents<TEvent extends string = string, TInput = unknown> = AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[] | ((args: {
205
+ input: TInput;
206
+ }) => AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[]);
207
+ //#endregion
208
+ export { ToolCallPart as C, UserMessage as D, ToolResultPart as E, TextPart as S, ToolResultOutput as T, ImagePart as _, AgentToolDescriptor as a, StandardSchemaV1 as b, AgentTools as c, AssistantMessage as d, ChosenEvent as f, FilePart as g, EventUnion as h, AgentToolChoice as i, AllowedEventPattern as l, EventPayload as m, AgentSnapshotStore as n, AgentToolExecute as o, DataContent as p, AgentTool as r, AgentToolSchema as s, AgentMessage as t, AllowedEvents as u, InferOutput as v, ToolMessage as w, SystemMessage as x, ProviderOptions as y };
@@ -0,0 +1,208 @@
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
+ * The discriminated event union derived from a machine's event schema map
43
+ * (e.g. `{ ASK: z.object({ question: z.string() }) }` → `{ type: 'ASK';
44
+ * question: string }`). Used internally by {@link createAgentSchemas} and
45
+ * `setupAgent` to type a machine's `TEvent`.
46
+ */
47
+ type EventUnion<T extends Record<string, StandardSchemaV1>> = { [K in keyof T & string]: {
48
+ type: K;
49
+ } & EventPayload<InferOutput<T[K]>> }[keyof T & string];
50
+ /** Raw binary or string content for an {@link ImagePart}/{@link FilePart}. */
51
+ type DataContent = string | Uint8Array | ArrayBuffer;
52
+ /** Provider-specific passthrough options, keyed by provider name (e.g. `{ anthropic: { cacheControl: ... } }`). */
53
+ type ProviderOptions = Record<string, Record<string, unknown>>;
54
+ /** A plain-text segment of a multi-part {@link AgentMessage} content array. */
55
+ interface TextPart {
56
+ type: "text";
57
+ text: string;
58
+ providerOptions?: ProviderOptions;
59
+ }
60
+ /**
61
+ * Binary (`Uint8Array`/`ArrayBuffer`) and `URL` values are not
62
+ * JSON-serializable. Machines that persist snapshots/event logs should use
63
+ * URL strings or base64-encoded strings in `image` instead.
64
+ */
65
+ interface ImagePart {
66
+ type: "image";
67
+ image: DataContent | URL;
68
+ mediaType?: 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 `data` instead.
75
+ */
76
+ interface FilePart {
77
+ type: "file";
78
+ data: DataContent | URL;
79
+ mediaType: string;
80
+ filename?: string;
81
+ providerOptions?: ProviderOptions;
82
+ }
83
+ /** A model-issued tool call, as an {@link AssistantMessage} content part. */
84
+ interface ToolCallPart {
85
+ type: "tool-call";
86
+ toolCallId: string;
87
+ toolName: string;
88
+ input: unknown;
89
+ providerOptions?: ProviderOptions;
90
+ }
91
+ /** The result payload of a {@link ToolResultPart}, discriminated by shape (plain text/JSON, or an error variant of either). */
92
+ type ToolResultOutput = {
93
+ type: "text";
94
+ value: string;
95
+ } | {
96
+ type: "json";
97
+ value: unknown;
98
+ } | {
99
+ type: "error-text";
100
+ value: string;
101
+ } | {
102
+ type: "error-json";
103
+ value: unknown;
104
+ } | {
105
+ type: "content";
106
+ value: Array<TextPart | ImagePart>;
107
+ };
108
+ /** A tool's result, as a {@link ToolMessage} content part. */
109
+ interface ToolResultPart {
110
+ type: "tool-result";
111
+ toolCallId: string;
112
+ toolName: string;
113
+ output: ToolResultOutput;
114
+ providerOptions?: ProviderOptions;
115
+ }
116
+ /** A system-role {@link AgentMessage}. Create with {@link systemMessage}. */
117
+ type SystemMessage = {
118
+ role: "system";
119
+ content: string;
120
+ providerOptions?: ProviderOptions;
121
+ };
122
+ /** A user-role {@link AgentMessage}, optionally multimodal. Create with {@link userMessage}. */
123
+ type UserMessage = {
124
+ role: "user";
125
+ content: string | Array<TextPart | ImagePart | FilePart>;
126
+ providerOptions?: ProviderOptions;
127
+ };
128
+ /** An assistant-role {@link AgentMessage}, which may carry tool calls/results inline. Create with {@link assistantMessage}. */
129
+ type AssistantMessage = {
130
+ role: "assistant";
131
+ content: string | Array<TextPart | FilePart | ToolCallPart | ToolResultPart>;
132
+ providerOptions?: ProviderOptions;
133
+ };
134
+ /** A tool-role {@link AgentMessage} carrying one or more tool results. Create with {@link toolMessage}. */
135
+ type ToolMessage = {
136
+ role: "tool";
137
+ content: Array<ToolResultPart>;
138
+ providerOptions?: ProviderOptions;
139
+ };
140
+ /**
141
+ * A single conversation turn, in this library's portable message model
142
+ * (structurally compatible with the AI SDK's `ModelMessage`). Stored as
143
+ * plain context state — see {@link appendMessages} — and passed to text/
144
+ * decision requests via `messages`. Validate a context field with
145
+ * {@link messagesSchema}.
146
+ */
147
+ type AgentMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;
148
+ /**
149
+ * A schema value on an {@link AgentToolDescriptor}. Core reads it as a
150
+ * {@link StandardSchemaV1} (via `getJsonSchema`/`isStandardSchema`) when it can,
151
+ * but the type is deliberately widened with `object` so an SDK-native tool —
152
+ * whose `inputSchema` is the SDK's own union type (a Zod schema, the SDK's
153
+ * `Schema`, a lazy thunk, …) — assigns structurally with no cast.
154
+ */
155
+ type AgentToolSchema = StandardSchemaV1 | object;
156
+ /**
157
+ * A tool exposed to a text request, described for both the model and
158
+ * (optionally) host execution. This is a **minimal structural contract**: any
159
+ * object matching it — an AI SDK `tool({...})`, an MCP-style descriptor, or a
160
+ * hand-written `{ description, inputSchema, execute }` — is a valid entry, and
161
+ * extra properties (`providerOptions`, `toModelOutput`, …) pass through
162
+ * untouched via the index signature. `execute` is typed permissively so a
163
+ * native tool's `(input, options)` executor is structurally assignable; the
164
+ * SDK you built the tool with owns its precise input typing.
165
+ */
166
+ interface AgentToolDescriptor {
167
+ description?: string;
168
+ inputSchema?: AgentToolSchema;
169
+ outputSchema?: AgentToolSchema;
170
+ execute?: (...args: any[]) => unknown;
171
+ [key: string]: unknown;
172
+ }
173
+ /** A bare tool implementation (no description/schema) — shorthand for {@link AgentToolDescriptor.execute}. */
174
+ type AgentToolExecute = (input?: unknown) => unknown | Promise<unknown>;
175
+ /** A tool entry in {@link AgentTools}: either a full descriptor or a bare execute function. */
176
+ type AgentTool = AgentToolDescriptor | AgentToolExecute;
177
+ /** The `tools` map passed on an {@link AgentTextRequest}, keyed by tool name. */
178
+ type AgentTools = Record<string, AgentTool | undefined>;
179
+ /** How a text request's model should select among its `tools`; `{ type: 'tool', name }` forces one specific tool. */
180
+ type AgentToolChoice = "auto" | "none" | "required" | {
181
+ type: "tool";
182
+ name: string;
183
+ };
184
+ /** The event chosen and raised by a decision. */
185
+ type ChosenEvent = {
186
+ type: string;
187
+ [key: string]: unknown;
188
+ };
189
+ type EventWildcardsOf<TEvent extends string> = TEvent extends `${infer Head}.${infer Rest}` ? `${Head}.*` | `${Head}.${EventWildcardsOf<Rest>}` : never;
190
+ /** One `allowedEvents` entry: an exact declared event type, `'*'` (every event), or a `'prefix.*'` wildcard derived from the declared dotted event types. */
191
+ type AllowedEventPattern<TEvent extends string = string> = TEvent | "*" | EventWildcardsOf<TEvent>;
192
+ /**
193
+ * Candidate event types for a decision or plan (declared on the
194
+ * `agent.decide`/`agent.plan` builtins' `allowedEvents` input). A single
195
+ * entry or an array; entries are exact event types or wildcard patterns
196
+ * (`'*'` for every event, `'todo.*'` for a dotted namespace). The effective
197
+ * candidate set offered to the model is this declaration **intersected with
198
+ * the snapshot's currently-legal events** (via `getAcceptedEvents`) —
199
+ * omitting `allowedEvents` means "all currently-legal events." A resolver
200
+ * function can therefore only ever narrow, never widen, the real surface.
201
+ * Wildcards expand against the live snapshot, so they need a snapshot-aware
202
+ * host (`runAgent` or the step path).
203
+ */
204
+ type AllowedEvents<TEvent extends string = string, TInput = unknown> = AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[] | ((args: {
205
+ input: TInput;
206
+ }) => AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[]);
207
+ //#endregion
208
+ export { ToolCallPart as C, UserMessage as D, ToolResultPart as E, TextPart as S, ToolResultOutput as T, ImagePart as _, AgentToolDescriptor as a, StandardSchemaV1 as b, AgentTools as c, AssistantMessage as d, ChosenEvent as f, FilePart as g, EventUnion as h, AgentToolChoice as i, AllowedEventPattern as l, EventPayload as m, AgentSnapshotStore as n, AgentToolExecute as o, DataContent as p, AgentTool as r, AgentToolSchema as s, AgentMessage as t, AllowedEvents as u, InferOutput as v, ToolMessage as w, SystemMessage as x, ProviderOptions as y };
@@ -0,0 +1,108 @@
1
+ import { C as ToolCallPart, D as UserMessage, E as ToolResultPart, S as TextPart, _ as ImagePart, b as StandardSchemaV1, d as AssistantMessage, g as FilePart, t as AgentMessage, w as ToolMessage, x as SystemMessage } from "./types-Cq1YlAQ6.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 };
@@ -0,0 +1,108 @@
1
+ import { C as ToolCallPart, D as UserMessage, E as ToolResultPart, S as TextPart, _ as ImagePart, b as StandardSchemaV1, d as AssistantMessage, g as FilePart, t as AgentMessage, w as ToolMessage, x as SystemMessage } from "./types-BHjeDdch.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 };
package/dist/zod.cjs ADDED
@@ -0,0 +1,31 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let zod = require("zod");
3
+ //#region src/zod/index.ts
4
+ /**
5
+ * A zod schema for an `AgentMessage[]` context/input field — the typed,
6
+ * dependency-light replacement for the hand-rolled
7
+ * `z.custom<AgentMessage[]>((value) => Array.isArray(value))` recipe repeated
8
+ * across machines that carry a message transcript in context.
9
+ *
10
+ * `AgentMessage` is a structural union (see `src/types.ts`), not something to
11
+ * re-declare as a zod object, so this stays a `z.custom` under the hood while
12
+ * exposing the precise `z.ZodType<AgentMessage[]>` type. Validation checks that
13
+ * the value is an array; element shape is trusted (the library's own message
14
+ * builders and adapters produce well-formed `AgentMessage`s).
15
+ *
16
+ * `zod` is an optional peer of `@statelyai/agent` — this subpath is the only
17
+ * place it's imported, mirroring how `./ai-sdk` gates on `ai`.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { z } from 'zod';
22
+ * import { zodAgentMessages } from '@statelyai/agent/zod';
23
+ *
24
+ * const context = z.object({ messages: zodAgentMessages() });
25
+ * ```
26
+ */
27
+ function zodAgentMessages() {
28
+ return zod.z.custom((value) => Array.isArray(value));
29
+ }
30
+ //#endregion
31
+ exports.zodAgentMessages = zodAgentMessages;