@statelyai/agent 2.0.0-alpha.6 → 2.0.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ai-sdk.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_decision = require("./decision-CX3YdwrO.cjs");
2
+ const require_decision = require("./decision-BnATHy0W.cjs");
3
3
  let ai = require("ai");
4
4
  //#region src/ai-sdk/index.ts
5
5
  /**
@@ -115,6 +115,56 @@ function isStructuredOutputRequest(request) {
115
115
  return require_decision.getAgentOutputMode(request.outputSchema) === "structured";
116
116
  }
117
117
  /**
118
+ * Extracts the first complete top-level JSON value from `text`, or returns
119
+ * `undefined` when there is nothing to repair (no complete value, or the value
120
+ * already spans the whole text). Models occasionally emit two structured-output
121
+ * envelopes back to back (`{"result":{…}}{"result":{…}}`), which fails JSON
122
+ * parsing wholesale; the balanced scan below recovers the first value and
123
+ * drops the rest.
124
+ */
125
+ function extractFirstJsonValue(text) {
126
+ const start = text.search(/[{[]/);
127
+ if (start === -1) return;
128
+ let depth = 0;
129
+ let inString = false;
130
+ let escaped = false;
131
+ for (let i = start; i < text.length; i++) {
132
+ const char = text[i];
133
+ if (inString) {
134
+ if (escaped) escaped = false;
135
+ else if (char === "\\") escaped = true;
136
+ else if (char === "\"") inString = false;
137
+ continue;
138
+ }
139
+ if (char === "\"") inString = true;
140
+ else if (char === "{" || char === "[") depth++;
141
+ else if (char === "}" || char === "]") {
142
+ depth--;
143
+ if (depth === 0) {
144
+ const value = text.slice(start, i + 1);
145
+ return value === text.trim() ? void 0 : value;
146
+ }
147
+ }
148
+ }
149
+ }
150
+ function withJsonRepair(output) {
151
+ return {
152
+ ...output,
153
+ parseCompleteOutput: async (options, context) => {
154
+ try {
155
+ return await output.parseCompleteOutput(options, context);
156
+ } catch (error) {
157
+ const repaired = extractFirstJsonValue(options.text);
158
+ if (repaired === void 0) throw error;
159
+ return await output.parseCompleteOutput({
160
+ ...options,
161
+ text: repaired
162
+ }, context);
163
+ }
164
+ }
165
+ };
166
+ }
167
+ /**
118
168
  * The canonical Vercel AI SDK adapter: builds the `{ generateText, streamText,
119
169
  * decide }` executor set consumed by `runAgent`/`executeAgentRequest`. `ai`
120
170
  * must not become a dependency of core `src/` files — this subpath is the one
@@ -138,10 +188,21 @@ function createAiSdkExecutors(options) {
138
188
  };
139
189
  if (isStructuredOutputRequest(request)) {
140
190
  const envelope = require_decision.buildEnvelopeSchema(request.outputSchema, { reasoning: request.reasoning });
141
- const result = await (0, ai.generateText)({
142
- ...common,
143
- output: ai.Output.object({ schema: envelope })
144
- });
191
+ const structuredOutput = withJsonRepair(ai.Output.object({ schema: envelope }));
192
+ const canRetry = !request.tools || Object.keys(request.tools).length === 0;
193
+ let result;
194
+ try {
195
+ result = await (0, ai.generateText)({
196
+ ...common,
197
+ output: structuredOutput
198
+ });
199
+ } catch (error) {
200
+ if (!canRetry || !ai.NoObjectGeneratedError.isInstance(error) || info?.signal?.aborted) throw error;
201
+ result = await (0, ai.generateText)({
202
+ ...common,
203
+ output: structuredOutput
204
+ });
205
+ }
145
206
  const { result: output, reasoning } = result.output;
146
207
  return {
147
208
  output,
@@ -241,6 +302,7 @@ function toDecisionMessages(request) {
241
302
  //#endregion
242
303
  exports.createAiSdkExecutors = createAiSdkExecutors;
243
304
  exports.defineModels = defineModels;
305
+ exports.extractFirstJsonValue = extractFirstJsonValue;
244
306
  exports.isStructuredOutputRequest = isStructuredOutputRequest;
245
307
  exports.toAiSdkCallSettings = toAiSdkCallSettings;
246
308
  exports.toAiSdkEventTools = toAiSdkEventTools;
package/dist/ai-sdk.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { c as AgentTools, f as ChosenEvent } from "./types-BHjeDdch.cjs";
2
- import { B as AgentEventDescriptor, D as AgentDecisionExecutor, i as AgentRequestExecutor, k as AgentDecisionRequest, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-1ZQkO3zr.cjs";
2
+ import { H as AgentEventDescriptor, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-4Q2F9kyr.cjs";
3
3
  import { FinishReason, LanguageModel, LanguageModelUsage, ModelMessage, Tool, ToolSet, TypedToolCall, TypedToolResult } from "ai";
4
4
 
5
5
  //#region src/ai-sdk/index.d.ts
@@ -99,6 +99,15 @@ declare function toAiSdkToolChoice(toolChoice: AgentTextRequest["toolChoice"]):
99
99
  } | undefined;
100
100
  /** `true` when the request should use AI SDK structured `Output.object`. */
101
101
  declare function isStructuredOutputRequest(request: Pick<AgentTextRequest, "outputSchema">): boolean;
102
+ /**
103
+ * Extracts the first complete top-level JSON value from `text`, or returns
104
+ * `undefined` when there is nothing to repair (no complete value, or the value
105
+ * already spans the whole text). Models occasionally emit two structured-output
106
+ * envelopes back to back (`{"result":{…}}{"result":{…}}`), which fails JSON
107
+ * parsing wholesale; the balanced scan below recovers the first value and
108
+ * drops the rest.
109
+ */
110
+ declare function extractFirstJsonValue(text: string): string | undefined;
102
111
  /**
103
112
  * Raw result shape from {@link AiSdkExecutors.generateText} — the `{ output }`
104
113
  * envelope (the validated structured object for structured-output requests,
@@ -165,4 +174,4 @@ declare function toAiSdkEventTools(events: AgentEventDescriptor[]): {
165
174
  */
166
175
  declare function toDecisionMessages(request: Pick<AgentDecisionRequest, "messages" | "prompt" | "events" | "attempts">): ModelMessage[] | undefined;
167
176
  //#endregion
168
- export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, createAiSdkExecutors, defineModels, isStructuredOutputRequest, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
177
+ export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, createAiSdkExecutors, defineModels, extractFirstJsonValue, isStructuredOutputRequest, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
package/dist/ai-sdk.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { c as AgentTools, f as ChosenEvent } from "./types-Cq1YlAQ6.mjs";
2
- import { B as AgentEventDescriptor, D as AgentDecisionExecutor, i as AgentRequestExecutor, k as AgentDecisionRequest, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-2EMJIS-n.mjs";
2
+ import { H as AgentEventDescriptor, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-2wFNEznm.mjs";
3
3
  import { FinishReason, LanguageModel, LanguageModelUsage, ModelMessage, Tool, ToolSet, TypedToolCall, TypedToolResult } from "ai";
4
4
 
5
5
  //#region src/ai-sdk/index.d.ts
@@ -99,6 +99,15 @@ declare function toAiSdkToolChoice(toolChoice: AgentTextRequest["toolChoice"]):
99
99
  } | undefined;
100
100
  /** `true` when the request should use AI SDK structured `Output.object`. */
101
101
  declare function isStructuredOutputRequest(request: Pick<AgentTextRequest, "outputSchema">): boolean;
102
+ /**
103
+ * Extracts the first complete top-level JSON value from `text`, or returns
104
+ * `undefined` when there is nothing to repair (no complete value, or the value
105
+ * already spans the whole text). Models occasionally emit two structured-output
106
+ * envelopes back to back (`{"result":{…}}{"result":{…}}`), which fails JSON
107
+ * parsing wholesale; the balanced scan below recovers the first value and
108
+ * drops the rest.
109
+ */
110
+ declare function extractFirstJsonValue(text: string): string | undefined;
102
111
  /**
103
112
  * Raw result shape from {@link AiSdkExecutors.generateText} — the `{ output }`
104
113
  * envelope (the validated structured object for structured-output requests,
@@ -165,4 +174,4 @@ declare function toAiSdkEventTools(events: AgentEventDescriptor[]): {
165
174
  */
166
175
  declare function toDecisionMessages(request: Pick<AgentDecisionRequest, "messages" | "prompt" | "events" | "attempts">): ModelMessage[] | undefined;
167
176
  //#endregion
168
- export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, createAiSdkExecutors, defineModels, isStructuredOutputRequest, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
177
+ export { AiSdkDecideResult, AiSdkExecutors, AiSdkGenerateResult, AiSdkModelMap, AiSdkStreamResult, CreateAiSdkExecutorsOptions, createAiSdkExecutors, defineModels, extractFirstJsonValue, isStructuredOutputRequest, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
package/dist/ai-sdk.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { G as isStandardSchema, T as getAgentOutputMode, l as renderDecisionAttempts, x as buildEnvelopeSchema } from "./decision-D1654JdD.mjs";
2
- import { Output, generateText, stepCountIs, streamText, tool } from "ai";
1
+ import { T as getAgentOutputMode, l as renderDecisionAttempts, q as isStandardSchema, x as buildEnvelopeSchema } from "./decision-mPR_YQd8.mjs";
2
+ import { NoObjectGeneratedError, Output, generateText, stepCountIs, streamText, tool } from "ai";
3
3
  //#region src/ai-sdk/index.ts
4
4
  /**
5
5
  * Maps an {@link AgentTools} map onto AI SDK `tool()` definitions. A tool that
@@ -114,6 +114,56 @@ function isStructuredOutputRequest(request) {
114
114
  return getAgentOutputMode(request.outputSchema) === "structured";
115
115
  }
116
116
  /**
117
+ * Extracts the first complete top-level JSON value from `text`, or returns
118
+ * `undefined` when there is nothing to repair (no complete value, or the value
119
+ * already spans the whole text). Models occasionally emit two structured-output
120
+ * envelopes back to back (`{"result":{…}}{"result":{…}}`), which fails JSON
121
+ * parsing wholesale; the balanced scan below recovers the first value and
122
+ * drops the rest.
123
+ */
124
+ function extractFirstJsonValue(text) {
125
+ const start = text.search(/[{[]/);
126
+ if (start === -1) return;
127
+ let depth = 0;
128
+ let inString = false;
129
+ let escaped = false;
130
+ for (let i = start; i < text.length; i++) {
131
+ const char = text[i];
132
+ if (inString) {
133
+ if (escaped) escaped = false;
134
+ else if (char === "\\") escaped = true;
135
+ else if (char === "\"") inString = false;
136
+ continue;
137
+ }
138
+ if (char === "\"") inString = true;
139
+ else if (char === "{" || char === "[") depth++;
140
+ else if (char === "}" || char === "]") {
141
+ depth--;
142
+ if (depth === 0) {
143
+ const value = text.slice(start, i + 1);
144
+ return value === text.trim() ? void 0 : value;
145
+ }
146
+ }
147
+ }
148
+ }
149
+ function withJsonRepair(output) {
150
+ return {
151
+ ...output,
152
+ parseCompleteOutput: async (options, context) => {
153
+ try {
154
+ return await output.parseCompleteOutput(options, context);
155
+ } catch (error) {
156
+ const repaired = extractFirstJsonValue(options.text);
157
+ if (repaired === void 0) throw error;
158
+ return await output.parseCompleteOutput({
159
+ ...options,
160
+ text: repaired
161
+ }, context);
162
+ }
163
+ }
164
+ };
165
+ }
166
+ /**
117
167
  * The canonical Vercel AI SDK adapter: builds the `{ generateText, streamText,
118
168
  * decide }` executor set consumed by `runAgent`/`executeAgentRequest`. `ai`
119
169
  * must not become a dependency of core `src/` files — this subpath is the one
@@ -137,10 +187,21 @@ function createAiSdkExecutors(options) {
137
187
  };
138
188
  if (isStructuredOutputRequest(request)) {
139
189
  const envelope = buildEnvelopeSchema(request.outputSchema, { reasoning: request.reasoning });
140
- const result = await generateText({
141
- ...common,
142
- output: Output.object({ schema: envelope })
143
- });
190
+ const structuredOutput = withJsonRepair(Output.object({ schema: envelope }));
191
+ const canRetry = !request.tools || Object.keys(request.tools).length === 0;
192
+ let result;
193
+ try {
194
+ result = await generateText({
195
+ ...common,
196
+ output: structuredOutput
197
+ });
198
+ } catch (error) {
199
+ if (!canRetry || !NoObjectGeneratedError.isInstance(error) || info?.signal?.aborted) throw error;
200
+ result = await generateText({
201
+ ...common,
202
+ output: structuredOutput
203
+ });
204
+ }
144
205
  const { result: output, reasoning } = result.output;
145
206
  return {
146
207
  output,
@@ -238,4 +299,4 @@ function toDecisionMessages(request) {
238
299
  return messages;
239
300
  }
240
301
  //#endregion
241
- export { createAiSdkExecutors, defineModels, isStructuredOutputRequest, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
302
+ export { createAiSdkExecutors, defineModels, extractFirstJsonValue, isStructuredOutputRequest, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
package/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- const require_src = require("./src-wBfi-kTA.cjs");
2
+ const require_src = require("./src-MysDmqwT.cjs");
3
3
  let node_fs = require("node:fs");
4
4
  //#region src/cli.ts
5
5
  /**
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { r as lintAgentMachine, v as setupAgent } from "./src-CEa947Dm.mjs";
2
+ import { r as lintAgentMachine, v as setupAgent } from "./src-BpQdxsKc.mjs";
3
3
  import { readFileSync } from "node:fs";
4
4
  //#region src/cli.ts
5
5
  /**
@@ -266,6 +266,27 @@ const DECIDE_ACTOR = "agent.decide";
266
266
  const PLAN_ACTOR = "agent.plan";
267
267
  /** Synthetic `src` stamped on trace requests produced by `getRequests` state interpretation — NOT a registered actor source (nothing is invoked; the pass makes the call directly). */
268
268
  const INTERPRET_SOURCE = "agent.interpret";
269
+ /**
270
+ * Splits a portable `"provider/model-id"` model ref (the convention JSON
271
+ * workflows and registry-less hosts use, e.g. `"openai/gpt-5.4-mini"`) into
272
+ * its parts. A ref with no `/` has no provider — `modelId` is the whole ref.
273
+ * The standard building block for a host's `resolveModel`:
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * const resolveModel = (ref: string) => openai(parseModelRef(ref).modelId);
278
+ * ```
279
+ */
280
+ function parseModelRef(modelRef) {
281
+ const slash = modelRef.indexOf("/");
282
+ return slash === -1 ? {
283
+ provider: void 0,
284
+ modelId: modelRef
285
+ } : {
286
+ provider: modelRef.slice(0, slash),
287
+ modelId: modelRef.slice(slash + 1)
288
+ };
289
+ }
269
290
  const agentTextInputSchema = { "~standard": {
270
291
  version: 1,
271
292
  vendor: "statelyai-agent",
@@ -336,7 +357,7 @@ const builtinTextActors = {
336
357
  [GENERATE_TEXT_ACTOR]: createBuiltinTextActor(GENERATE_TEXT_ACTOR, "generate", unknownOutputSchema),
337
358
  [STREAM_TEXT_ACTOR]: createBuiltinTextActor(STREAM_TEXT_ACTOR, "stream", stringOutputSchema)
338
359
  };
339
- /** The unbound `agent.userInput` builtin registered by setupAgent (an unbound-placeholder logic — see internal/registry.ts). @internal */
360
+ /** The unbound `agent.userInput` builtin registered by setupAgent (an unbound-placeholder logic — see internal/registry.ts). Output is `string` — what the human typed. @internal */
340
361
  const userInputActor = (0, xstate.createAsyncLogic)({ run: async () => {
341
362
  throw new Error(`'${USER_INPUT_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${USER_INPUT_ACTOR}': ... } }).`);
342
363
  } });
@@ -444,12 +465,15 @@ function createTextLogic(config, execute) {
444
465
  * });
445
466
  * ```
446
467
  */
447
- function bindRequestExecutor(logic, executor) {
468
+ function bindRequestExecutor(logic, executor, info) {
448
469
  return logic.withExecutor(async ({ request, signal }) => {
449
470
  const { output } = await executor({
450
471
  ...request,
451
472
  tools: request.tools ?? {}
452
- }, { signal });
473
+ }, {
474
+ signal,
475
+ onChunk: info?.onChunk
476
+ });
453
477
  return { output };
454
478
  });
455
479
  }
@@ -524,6 +548,17 @@ function buildEnvelopeSchema(inner, options = {}) {
524
548
  } }
525
549
  } };
526
550
  }
551
+ /**
552
+ * Validates a raw provider value against the structured-output envelope for
553
+ * `request` and returns the unwrapped `{ result, reasoning? }` — the checked
554
+ * replacement for `raw as StructuredOutputEnvelope` in hand-written hosts.
555
+ * Pair with {@link buildEnvelopeSchema} (which produced the schema the
556
+ * provider was asked to satisfy).
557
+ */
558
+ function parseStructuredEnvelope(request, value) {
559
+ if (!request.outputSchema) throw new Error("parseStructuredEnvelope: the request declares no outputSchema.");
560
+ return validateSchemaSync(buildEnvelopeSchema(request.outputSchema, { reasoning: request.reasoning }), value);
561
+ }
527
562
  function getStandardSchemaJson(schema) {
528
563
  const jsonSchema = (schema?.["~standard"])?.jsonSchema?.input?.();
529
564
  return jsonSchema && !(jsonSchema instanceof Promise) ? jsonSchema : void 0;
@@ -1177,12 +1212,24 @@ Object.defineProperty(exports, "parseAgentEvent", {
1177
1212
  return parseAgentEvent;
1178
1213
  }
1179
1214
  });
1215
+ Object.defineProperty(exports, "parseModelRef", {
1216
+ enumerable: true,
1217
+ get: function() {
1218
+ return parseModelRef;
1219
+ }
1220
+ });
1180
1221
  Object.defineProperty(exports, "parseOutput", {
1181
1222
  enumerable: true,
1182
1223
  get: function() {
1183
1224
  return parseOutput;
1184
1225
  }
1185
1226
  });
1227
+ Object.defineProperty(exports, "parseStructuredEnvelope", {
1228
+ enumerable: true,
1229
+ get: function() {
1230
+ return parseStructuredEnvelope;
1231
+ }
1232
+ });
1186
1233
  Object.defineProperty(exports, "persistSnapshot", {
1187
1234
  enumerable: true,
1188
1235
  get: function() {
@@ -266,6 +266,27 @@ const DECIDE_ACTOR = "agent.decide";
266
266
  const PLAN_ACTOR = "agent.plan";
267
267
  /** Synthetic `src` stamped on trace requests produced by `getRequests` state interpretation — NOT a registered actor source (nothing is invoked; the pass makes the call directly). */
268
268
  const INTERPRET_SOURCE = "agent.interpret";
269
+ /**
270
+ * Splits a portable `"provider/model-id"` model ref (the convention JSON
271
+ * workflows and registry-less hosts use, e.g. `"openai/gpt-5.4-mini"`) into
272
+ * its parts. A ref with no `/` has no provider — `modelId` is the whole ref.
273
+ * The standard building block for a host's `resolveModel`:
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * const resolveModel = (ref: string) => openai(parseModelRef(ref).modelId);
278
+ * ```
279
+ */
280
+ function parseModelRef(modelRef) {
281
+ const slash = modelRef.indexOf("/");
282
+ return slash === -1 ? {
283
+ provider: void 0,
284
+ modelId: modelRef
285
+ } : {
286
+ provider: modelRef.slice(0, slash),
287
+ modelId: modelRef.slice(slash + 1)
288
+ };
289
+ }
269
290
  const agentTextInputSchema = { "~standard": {
270
291
  version: 1,
271
292
  vendor: "statelyai-agent",
@@ -336,7 +357,7 @@ const builtinTextActors = {
336
357
  [GENERATE_TEXT_ACTOR]: createBuiltinTextActor(GENERATE_TEXT_ACTOR, "generate", unknownOutputSchema),
337
358
  [STREAM_TEXT_ACTOR]: createBuiltinTextActor(STREAM_TEXT_ACTOR, "stream", stringOutputSchema)
338
359
  };
339
- /** The unbound `agent.userInput` builtin registered by setupAgent (an unbound-placeholder logic — see internal/registry.ts). @internal */
360
+ /** The unbound `agent.userInput` builtin registered by setupAgent (an unbound-placeholder logic — see internal/registry.ts). Output is `string` — what the human typed. @internal */
340
361
  const userInputActor = createAsyncLogic({ run: async () => {
341
362
  throw new Error(`'${USER_INPUT_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${USER_INPUT_ACTOR}': ... } }).`);
342
363
  } });
@@ -444,12 +465,15 @@ function createTextLogic(config, execute) {
444
465
  * });
445
466
  * ```
446
467
  */
447
- function bindRequestExecutor(logic, executor) {
468
+ function bindRequestExecutor(logic, executor, info) {
448
469
  return logic.withExecutor(async ({ request, signal }) => {
449
470
  const { output } = await executor({
450
471
  ...request,
451
472
  tools: request.tools ?? {}
452
- }, { signal });
473
+ }, {
474
+ signal,
475
+ onChunk: info?.onChunk
476
+ });
453
477
  return { output };
454
478
  });
455
479
  }
@@ -524,6 +548,17 @@ function buildEnvelopeSchema(inner, options = {}) {
524
548
  } }
525
549
  } };
526
550
  }
551
+ /**
552
+ * Validates a raw provider value against the structured-output envelope for
553
+ * `request` and returns the unwrapped `{ result, reasoning? }` — the checked
554
+ * replacement for `raw as StructuredOutputEnvelope` in hand-written hosts.
555
+ * Pair with {@link buildEnvelopeSchema} (which produced the schema the
556
+ * provider was asked to satisfy).
557
+ */
558
+ function parseStructuredEnvelope(request, value) {
559
+ if (!request.outputSchema) throw new Error("parseStructuredEnvelope: the request declares no outputSchema.");
560
+ return validateSchemaSync(buildEnvelopeSchema(request.outputSchema, { reasoning: request.reasoning }), value);
561
+ }
527
562
  function getStandardSchemaJson(schema) {
528
563
  const jsonSchema = (schema?.["~standard"])?.jsonSchema?.input?.();
529
564
  return jsonSchema && !(jsonSchema instanceof Promise) ? jsonSchema : void 0;
@@ -937,4 +972,4 @@ async function resolveDecision(request, executor, options = {}) {
937
972
  throw new DecisionExhaustedError(attempts);
938
973
  }
939
974
  //#endregion
940
- export { userInputActor as A, getAgentMessages as B, createTextLogic as C, isTextLogic as D, isStructuredOutputSchema as E, isUnboundPlaceholder as F, isStandardSchema as G, getJsonSchemaSync as H, machineSuspensionPredicates as I, toolMessage as J, persistSnapshot as K, missingActor as L, executorBoundLogics as M, getMachineSuspensionPredicate as N, normalizeGeneratorResult as O, getRegisteredAgentExecutionOptions as P, assistantMessage as R, builtinTextActors as S, getAgentOutputMode as T, getMachineStructuralHash as U, getJsonSchema as V, getStateMeta as W, validateSchemaSync as X, userMessage as Y, INTERPRET_SOURCE as _, createPlanActor as a, bindRequestExecutor as b, isPlanLogic as c, EVENT_TOOL_PREFIX as d, getAcceptedEvents as f, DECIDE_ACTOR as g, sanitizeEventToolName as h, createDecideActor as i, agentExecutionOptions as j, parseOutput as k, renderDecisionAttempts as l, parseAgentEvent as m, PLAN_DONE_EVENT_TYPE as n, initialPlanLedger as o, matchesEventPattern as p, systemMessage as q, advancePlanLedger as r, isDecisionLogic as s, DecisionExhaustedError as t, resolveDecision as u, PLAN_ACTOR as v, executeAgentTextRequest as w, buildEnvelopeSchema as x, USER_INPUT_ACTOR as y, findNonSerializableContextPaths as z };
975
+ export { parseOutput as A, assistantMessage as B, createTextLogic as C, isTextLogic as D, isStructuredOutputSchema as E, getMachineSuspensionPredicate as F, getMachineStructuralHash as G, getAgentMessages as H, getRegisteredAgentExecutionOptions as I, persistSnapshot as J, getStateMeta as K, isUnboundPlaceholder as L, userInputActor as M, agentExecutionOptions as N, normalizeGeneratorResult as O, executorBoundLogics as P, validateSchemaSync as Q, machineSuspensionPredicates as R, builtinTextActors as S, getAgentOutputMode as T, getJsonSchema as U, findNonSerializableContextPaths as V, getJsonSchemaSync as W, toolMessage as X, systemMessage as Y, userMessage as Z, INTERPRET_SOURCE as _, createPlanActor as a, bindRequestExecutor as b, isPlanLogic as c, EVENT_TOOL_PREFIX as d, getAcceptedEvents as f, DECIDE_ACTOR as g, sanitizeEventToolName as h, createDecideActor as i, parseStructuredEnvelope as j, parseModelRef as k, renderDecisionAttempts as l, parseAgentEvent as m, PLAN_DONE_EVENT_TYPE as n, initialPlanLedger as o, matchesEventPattern as p, isStandardSchema as q, advancePlanLedger as r, isDecisionLogic as s, DecisionExhaustedError as t, resolveDecision as u, PLAN_ACTOR as v, executeAgentTextRequest as w, buildEnvelopeSchema as x, USER_INPUT_ACTOR as y, missingActor as z };
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("./src-wBfi-kTA.cjs");
3
- const require_decision = require("./decision-CX3YdwrO.cjs");
2
+ const require_src = require("./src-MysDmqwT.cjs");
3
+ const require_decision = require("./decision-BnATHy0W.cjs");
4
4
  exports.AgentIdleError = require_src.AgentIdleError;
5
5
  exports.DecisionExhaustedError = require_decision.DecisionExhaustedError;
6
6
  exports.EVENT_TOOL_PREFIX = require_decision.EVENT_TOOL_PREFIX;
@@ -32,7 +32,9 @@ exports.lintAgentMachine = require_src.lintAgentMachine;
32
32
  exports.matchesEventPattern = require_decision.matchesEventPattern;
33
33
  exports.messagesSchema = require_src.messagesSchema;
34
34
  exports.parseAgentEvent = require_decision.parseAgentEvent;
35
+ exports.parseModelRef = require_decision.parseModelRef;
35
36
  exports.parseOutput = require_decision.parseOutput;
37
+ exports.parseStructuredEnvelope = require_decision.parseStructuredEnvelope;
36
38
  exports.persistSnapshot = require_decision.persistSnapshot;
37
39
  exports.renderDecisionAttempts = require_decision.renderDecisionAttempts;
38
40
  exports.resolveAgentRequests = require_src.resolveAgentRequests;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { C as ToolCallPart, D as UserMessage, E as ToolResultPart, S as TextPart, T as ToolResultOutput, _ as ImagePart, a as AgentToolDescriptor, b as StandardSchemaV1, c as AgentTools, d as AssistantMessage, f as ChosenEvent, g as FilePart, h as EventUnion, i as AgentToolChoice, l as AllowedEventPattern, m as EventPayload, n as AgentSnapshotStore, o as AgentToolExecute, p as DataContent, r as AgentTool, s as AgentToolSchema, t as AgentMessage, u as AllowedEvents, v as InferOutput, w as ToolMessage, x as SystemMessage, y as ProviderOptions } from "./types-BHjeDdch.cjs";
2
- import { A as AgentPlanInput, B as AgentEventDescriptor, C as createTextLogic, D as AgentDecisionExecutor, E as parseOutput, F as DecisionLogicConfig, G as getAcceptedEvents, H as AgentRequestOptions, I as PLAN_DONE_EVENT_TYPE, K as matchesEventPattern, L as ResolveDecisionOptions, M as DecisionAttempt, N as DecisionExhaustedError, O as AgentDecisionInput, P as DecisionLogic, R as renderDecisionAttempts, S as buildEnvelopeSchema, T as isStructuredOutputSchema, U as AgentRequestSource, V as AgentEventToolNameResolver, W as EVENT_TOOL_PREFIX, _ as TextLogicExecuteArgs, a as AgentRequestExecutorInfo, b as TextLogicOutput, c as AgentRequestMode, d as AiSdkShapedStreamResult, f as AiSdkShapedTextResult, g as TextLogicConfig, h as TextLogic, i as AgentRequestExecutor, j as AgentPlanOutput, k as AgentDecisionRequest, l as AgentTextRequest, m as StructuredOutputEnvelope, n as AgentModelRef, o as AgentRequestExecutorResult, p as BuiltinAgentActors, q as parseAgentEvent, r as AgentOutputMode, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput, v as TextLogicExecutor, w as getAgentOutputMode, x as bindRequestExecutor, y as TextLogicInput, z as resolveDecision } from "./text-logic-1ZQkO3zr.cjs";
2
+ import { A as AgentDecisionInput, B as renderDecisionAttempts, C as createTextLogic, D as parseOutput, E as parseModelRef, F as DecisionExhaustedError, G as AgentRequestSource, H as AgentEventDescriptor, I as DecisionLogic, J as matchesEventPattern, K as EVENT_TOOL_PREFIX, L as DecisionLogicConfig, M as AgentPlanInput, N as AgentPlanOutput, O as parseStructuredEnvelope, P as DecisionAttempt, R as PLAN_DONE_EVENT_TYPE, S as buildEnvelopeSchema, T as isStructuredOutputSchema, U as AgentEventToolNameResolver, V as resolveDecision, W as AgentRequestOptions, Y as parseAgentEvent, _ as TextLogicExecuteArgs, a as AgentRequestExecutorInfo, b as TextLogicOutput, c as AgentRequestMode, d as AiSdkShapedStreamResult, f as AiSdkShapedTextResult, g as TextLogicConfig, h as TextLogic, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, m as StructuredOutputEnvelope, n as AgentModelRef, o as AgentRequestExecutorResult, p as BuiltinAgentActors, q as getAcceptedEvents, r as AgentOutputMode, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput, v as TextLogicExecutor, w as getAgentOutputMode, x as bindRequestExecutor, y as TextLogicInput, z as ResolveDecisionOptions } from "./text-logic-4Q2F9kyr.cjs";
3
3
  import { a as getMachineStructuralHash, c as persistSnapshot, d as userMessage, f as validateSchemaSync, i as getJsonSchemaSync, l as systemMessage, n as getAgentMessages, o as getStateMeta, r as getJsonSchema, s as isStandardSchema, t as assistantMessage, u as toolMessage } from "./utils-lK1wnL2i.cjs";
4
4
  import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, Snapshot, SnapshotFrom } from "xstate";
5
5
 
@@ -256,16 +256,49 @@ type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<strin
256
256
  guards?: NonNullable<AnySetupConfig["guards"]>;
257
257
  delays?: NonNullable<AnySetupConfig["delays"]>;
258
258
  };
259
- type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TRequestSchemas extends AgentRequestSchemaMap, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>> = ({
259
+ /**
260
+ * Field-level context-narrowing sugar for one `setupAgent({ states })` entry:
261
+ * each `context` entry overrides that field's schema inside the state; every
262
+ * other field keeps the base context schema. Sugar for the full xstate form —
263
+ * `{ context: { draft: z.string() } }` resolves to
264
+ * `{ schemas: { context: <base with draft: string> } }` — so only the fields
265
+ * that change are declared, not the whole context schema.
266
+ */
267
+ interface AgentStateNarrowing {
268
+ context: Record<string, StandardSchemaV1>;
269
+ states?: Record<string, AgentSetupStateSchema>;
270
+ }
271
+ /** One `setupAgent({ states })` entry: xstate's {@link SetupStateSchema} full form, or the {@link AgentStateNarrowing} field-level sugar. */
272
+ type AgentSetupStateSchema = SetupStateSchema | AgentStateNarrowing;
273
+ type NarrowedContext<TContextSchema extends StandardSchemaV1, TFields extends Record<string, StandardSchemaV1>> = Omit<InferOutput<TContextSchema>, keyof TFields> & { [K in keyof TFields]: InferOutput<TFields[K]> };
274
+ type ResolveAgentStateSchema<TContextSchema extends StandardSchemaV1, T> = T extends {
275
+ context: infer TFields extends Record<string, StandardSchemaV1>;
276
+ } ? {
277
+ schemas: {
278
+ context: StandardSchemaV1<NarrowedContext<TContextSchema, TFields>>;
279
+ };
280
+ } & (T extends {
281
+ states: infer TChildren extends Record<string, AgentSetupStateSchema>;
282
+ } ? {
283
+ states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
284
+ } : {}) : T extends {
285
+ states: infer TChildren extends Record<string, AgentSetupStateSchema>;
286
+ } ? Omit<T, "states"> & {
287
+ states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
288
+ } : T;
289
+ type ResolveAgentStateSchemas<TContextSchema extends StandardSchemaV1, TStates extends Record<string, AgentSetupStateSchema>> = Constrain<{ [K in keyof TStates]: ResolveAgentStateSchema<TContextSchema, TStates[K]> }, Record<string, SetupStateSchema>>;
290
+ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TRequestSchemas extends AgentRequestSchemaMap, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = ({
260
291
  schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
261
292
  } | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
262
293
  models?: TModels;
263
294
  actorSources?: TActors;
264
295
  /**
265
- * Per-state schemas, mirroring xstate's `setup({ states })`: declare a
266
- * `schemas.context` on a state to narrow `context` inside that state
267
- * (invoke `input`, transition fns, final `output`) — e.g. mark a field
268
- * non-null in states only reachable after it is set.
296
+ * Per-state schemas, mirroring xstate's `setup({ states })`: narrow
297
+ * `context` inside a state (invoke `input`, transition fns, final `output`)
298
+ * — e.g. mark a field non-null in states only reachable after it is set.
299
+ * Two forms per state: the {@link AgentStateNarrowing} sugar
300
+ * (`{ context: { draft: z.string() } }` — only the fields that change) or
301
+ * xstate's full `{ schemas: { context } }` with a complete context schema.
269
302
  */
270
303
  states?: TStateSchemas;
271
304
  requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
@@ -284,7 +317,7 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
284
317
  */
285
318
  isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
286
319
  };
287
- type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>>;
320
+ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, ResolveAgentStateSchemas<TContextSchema, TStateSchemas>>>;
288
321
  /**
289
322
  * The object returned by {@link setupAgent}: an xstate `setup(...)` result
290
323
  * (`createMachine`, `assign`, …) extended with `schemas` (the resolved
@@ -293,7 +326,7 @@ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<strin
293
326
  * `runAgent` and the free step helpers can resolve their schemas/actors
294
327
  * without re-passing them each call.
295
328
  */
296
- type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>> = Omit<SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>, "createMachine"> & {
329
+ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = Omit<SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>, "createMachine"> & {
297
330
  /**
298
331
  * Creates the agent machine — XState's own `createMachine`, plus: the
299
332
  * machine is registered so step helpers and {@link runAgent} can resolve
@@ -358,7 +391,7 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
358
391
  * });
359
392
  * ```
360
393
  */
361
- declare function setupAgent<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TModels extends AgentModelMap = {}, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, const TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>>(config: SetupAgentBaseConfig<TContextSchema, TEventSchemas, TActors, TInputSchema, TOutputSchema, TMetaSchema, TRequestSchemas, TModels, TEmittedSchemas, TStateSchemas>): SetupAgentResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>;
394
+ declare function setupAgent<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TModels extends AgentModelMap = {}, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, const TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>>(config: SetupAgentBaseConfig<TContextSchema, TEventSchemas, TActors, TInputSchema, TOutputSchema, TMetaSchema, TRequestSchemas, TModels, TEmittedSchemas, TStateSchemas>): SetupAgentResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>;
362
395
  declare namespace setupAgent {
363
396
  /**
364
397
  * Builds a state machine from a serializable {@link AgentWorkflowConfig}
@@ -658,9 +691,9 @@ declare class AgentIdleError extends Error {
658
691
  readonly acceptedTypes: string[];
659
692
  constructor(snapshot: AnyMachineSnapshot, acceptedTypes: string[]);
660
693
  }
661
- /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. */
694
+ /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. Resolves to what the human typed. */
662
695
  interface AgentUserInputExecutor {
663
- (input: AgentUserInput): PromiseLike<unknown>;
696
+ (input: AgentUserInput): PromiseLike<string>;
664
697
  }
665
698
  type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
666
699
  runId: string;
@@ -924,7 +957,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
924
957
  * actor is stopped on every settle path — there is no live actor to resume;
925
958
  * resume is always by snapshot.
926
959
  */
927
- /** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt, schema, …). Answer it by resuming with a `userInput` handler. */
960
+ /** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt, metadata). Answer it by resuming with a `userInput` handler. */
928
961
  interface PendingUserInput {
929
962
  id: string;
930
963
  input: AgentUserInput | undefined;
@@ -1214,4 +1247,4 @@ interface CanReachResult {
1214
1247
  */
1215
1248
  declare function canReach(machine: AnyStateMachine, statePath: string, options?: ExplorePathsOptions): Promise<CanReachResult>;
1216
1249
  //#endregion
1217
- export { type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, type AgentLintSeverity, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, type AgentRequest, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentSchemaPack, type AgentSnapshotStore, type AgentStateRequest, type AgentStep, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type DecisionLogicConfig, EVENT_TOOL_PREFIX, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type ProviderOptions, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseOutput, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
1250
+ export { type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, type AgentLintSeverity, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, type AgentRequest, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentSchemaPack, type AgentSetupStateSchema, type AgentSnapshotStore, type AgentStateNarrowing, type AgentStateRequest, type AgentStep, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type DecisionLogicConfig, EVENT_TOOL_PREFIX, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type ProviderOptions, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { C as ToolCallPart, D as UserMessage, E as ToolResultPart, S as TextPart, T as ToolResultOutput, _ as ImagePart, a as AgentToolDescriptor, b as StandardSchemaV1, c as AgentTools, d as AssistantMessage, f as ChosenEvent, g as FilePart, h as EventUnion, i as AgentToolChoice, l as AllowedEventPattern, m as EventPayload, n as AgentSnapshotStore, o as AgentToolExecute, p as DataContent, r as AgentTool, s as AgentToolSchema, t as AgentMessage, u as AllowedEvents, v as InferOutput, w as ToolMessage, x as SystemMessage, y as ProviderOptions } from "./types-Cq1YlAQ6.mjs";
2
- import { A as AgentPlanInput, B as AgentEventDescriptor, C as createTextLogic, D as AgentDecisionExecutor, E as parseOutput, F as DecisionLogicConfig, G as getAcceptedEvents, H as AgentRequestOptions, I as PLAN_DONE_EVENT_TYPE, K as matchesEventPattern, L as ResolveDecisionOptions, M as DecisionAttempt, N as DecisionExhaustedError, O as AgentDecisionInput, P as DecisionLogic, R as renderDecisionAttempts, S as buildEnvelopeSchema, T as isStructuredOutputSchema, U as AgentRequestSource, V as AgentEventToolNameResolver, W as EVENT_TOOL_PREFIX, _ as TextLogicExecuteArgs, a as AgentRequestExecutorInfo, b as TextLogicOutput, c as AgentRequestMode, d as AiSdkShapedStreamResult, f as AiSdkShapedTextResult, g as TextLogicConfig, h as TextLogic, i as AgentRequestExecutor, j as AgentPlanOutput, k as AgentDecisionRequest, l as AgentTextRequest, m as StructuredOutputEnvelope, n as AgentModelRef, o as AgentRequestExecutorResult, p as BuiltinAgentActors, q as parseAgentEvent, r as AgentOutputMode, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput, v as TextLogicExecutor, w as getAgentOutputMode, x as bindRequestExecutor, y as TextLogicInput, z as resolveDecision } from "./text-logic-2EMJIS-n.mjs";
2
+ import { A as AgentDecisionInput, B as renderDecisionAttempts, C as createTextLogic, D as parseOutput, E as parseModelRef, F as DecisionExhaustedError, G as AgentRequestSource, H as AgentEventDescriptor, I as DecisionLogic, J as matchesEventPattern, K as EVENT_TOOL_PREFIX, L as DecisionLogicConfig, M as AgentPlanInput, N as AgentPlanOutput, O as parseStructuredEnvelope, P as DecisionAttempt, R as PLAN_DONE_EVENT_TYPE, S as buildEnvelopeSchema, T as isStructuredOutputSchema, U as AgentEventToolNameResolver, V as resolveDecision, W as AgentRequestOptions, Y as parseAgentEvent, _ as TextLogicExecuteArgs, a as AgentRequestExecutorInfo, b as TextLogicOutput, c as AgentRequestMode, d as AiSdkShapedStreamResult, f as AiSdkShapedTextResult, g as TextLogicConfig, h as TextLogic, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, m as StructuredOutputEnvelope, n as AgentModelRef, o as AgentRequestExecutorResult, p as BuiltinAgentActors, q as getAcceptedEvents, r as AgentOutputMode, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput, v as TextLogicExecutor, w as getAgentOutputMode, x as bindRequestExecutor, y as TextLogicInput, z as ResolveDecisionOptions } from "./text-logic-2wFNEznm.mjs";
3
3
  import { a as getMachineStructuralHash, c as persistSnapshot, d as userMessage, f as validateSchemaSync, i as getJsonSchemaSync, l as systemMessage, n as getAgentMessages, o as getStateMeta, r as getJsonSchema, s as isStandardSchema, t as assistantMessage, u as toolMessage } from "./utils-CWUCa3pF.mjs";
4
4
  import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, Snapshot, SnapshotFrom } from "xstate";
5
5
 
@@ -256,16 +256,49 @@ type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<strin
256
256
  guards?: NonNullable<AnySetupConfig["guards"]>;
257
257
  delays?: NonNullable<AnySetupConfig["delays"]>;
258
258
  };
259
- type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TRequestSchemas extends AgentRequestSchemaMap, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>> = ({
259
+ /**
260
+ * Field-level context-narrowing sugar for one `setupAgent({ states })` entry:
261
+ * each `context` entry overrides that field's schema inside the state; every
262
+ * other field keeps the base context schema. Sugar for the full xstate form —
263
+ * `{ context: { draft: z.string() } }` resolves to
264
+ * `{ schemas: { context: <base with draft: string> } }` — so only the fields
265
+ * that change are declared, not the whole context schema.
266
+ */
267
+ interface AgentStateNarrowing {
268
+ context: Record<string, StandardSchemaV1>;
269
+ states?: Record<string, AgentSetupStateSchema>;
270
+ }
271
+ /** One `setupAgent({ states })` entry: xstate's {@link SetupStateSchema} full form, or the {@link AgentStateNarrowing} field-level sugar. */
272
+ type AgentSetupStateSchema = SetupStateSchema | AgentStateNarrowing;
273
+ type NarrowedContext<TContextSchema extends StandardSchemaV1, TFields extends Record<string, StandardSchemaV1>> = Omit<InferOutput<TContextSchema>, keyof TFields> & { [K in keyof TFields]: InferOutput<TFields[K]> };
274
+ type ResolveAgentStateSchema<TContextSchema extends StandardSchemaV1, T> = T extends {
275
+ context: infer TFields extends Record<string, StandardSchemaV1>;
276
+ } ? {
277
+ schemas: {
278
+ context: StandardSchemaV1<NarrowedContext<TContextSchema, TFields>>;
279
+ };
280
+ } & (T extends {
281
+ states: infer TChildren extends Record<string, AgentSetupStateSchema>;
282
+ } ? {
283
+ states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
284
+ } : {}) : T extends {
285
+ states: infer TChildren extends Record<string, AgentSetupStateSchema>;
286
+ } ? Omit<T, "states"> & {
287
+ states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
288
+ } : T;
289
+ type ResolveAgentStateSchemas<TContextSchema extends StandardSchemaV1, TStates extends Record<string, AgentSetupStateSchema>> = Constrain<{ [K in keyof TStates]: ResolveAgentStateSchema<TContextSchema, TStates[K]> }, Record<string, SetupStateSchema>>;
290
+ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TRequestSchemas extends AgentRequestSchemaMap, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = ({
260
291
  schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
261
292
  } | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
262
293
  models?: TModels;
263
294
  actorSources?: TActors;
264
295
  /**
265
- * Per-state schemas, mirroring xstate's `setup({ states })`: declare a
266
- * `schemas.context` on a state to narrow `context` inside that state
267
- * (invoke `input`, transition fns, final `output`) — e.g. mark a field
268
- * non-null in states only reachable after it is set.
296
+ * Per-state schemas, mirroring xstate's `setup({ states })`: narrow
297
+ * `context` inside a state (invoke `input`, transition fns, final `output`)
298
+ * — e.g. mark a field non-null in states only reachable after it is set.
299
+ * Two forms per state: the {@link AgentStateNarrowing} sugar
300
+ * (`{ context: { draft: z.string() } }` — only the fields that change) or
301
+ * xstate's full `{ schemas: { context } }` with a complete context schema.
269
302
  */
270
303
  states?: TStateSchemas;
271
304
  requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
@@ -284,7 +317,7 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
284
317
  */
285
318
  isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
286
319
  };
287
- type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>>;
320
+ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, ResolveAgentStateSchemas<TContextSchema, TStateSchemas>>>;
288
321
  /**
289
322
  * The object returned by {@link setupAgent}: an xstate `setup(...)` result
290
323
  * (`createMachine`, `assign`, …) extended with `schemas` (the resolved
@@ -293,7 +326,7 @@ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<strin
293
326
  * `runAgent` and the free step helpers can resolve their schemas/actors
294
327
  * without re-passing them each call.
295
328
  */
296
- type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>> = Omit<SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>, "createMachine"> & {
329
+ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = Omit<SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>, "createMachine"> & {
297
330
  /**
298
331
  * Creates the agent machine — XState's own `createMachine`, plus: the
299
332
  * machine is registered so step helpers and {@link runAgent} can resolve
@@ -358,7 +391,7 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
358
391
  * });
359
392
  * ```
360
393
  */
361
- declare function setupAgent<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TModels extends AgentModelMap = {}, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, const TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>>(config: SetupAgentBaseConfig<TContextSchema, TEventSchemas, TActors, TInputSchema, TOutputSchema, TMetaSchema, TRequestSchemas, TModels, TEmittedSchemas, TStateSchemas>): SetupAgentResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>;
394
+ declare function setupAgent<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TModels extends AgentModelMap = {}, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, const TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>>(config: SetupAgentBaseConfig<TContextSchema, TEventSchemas, TActors, TInputSchema, TOutputSchema, TMetaSchema, TRequestSchemas, TModels, TEmittedSchemas, TStateSchemas>): SetupAgentResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>;
362
395
  declare namespace setupAgent {
363
396
  /**
364
397
  * Builds a state machine from a serializable {@link AgentWorkflowConfig}
@@ -658,9 +691,9 @@ declare class AgentIdleError extends Error {
658
691
  readonly acceptedTypes: string[];
659
692
  constructor(snapshot: AnyMachineSnapshot, acceptedTypes: string[]);
660
693
  }
661
- /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. */
694
+ /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. Resolves to what the human typed. */
662
695
  interface AgentUserInputExecutor {
663
- (input: AgentUserInput): PromiseLike<unknown>;
696
+ (input: AgentUserInput): PromiseLike<string>;
664
697
  }
665
698
  type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
666
699
  runId: string;
@@ -924,7 +957,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
924
957
  * actor is stopped on every settle path — there is no live actor to resume;
925
958
  * resume is always by snapshot.
926
959
  */
927
- /** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt, schema, …). Answer it by resuming with a `userInput` handler. */
960
+ /** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt, metadata). Answer it by resuming with a `userInput` handler. */
928
961
  interface PendingUserInput {
929
962
  id: string;
930
963
  input: AgentUserInput | undefined;
@@ -1214,4 +1247,4 @@ interface CanReachResult {
1214
1247
  */
1215
1248
  declare function canReach(machine: AnyStateMachine, statePath: string, options?: ExplorePathsOptions): Promise<CanReachResult>;
1216
1249
  //#endregion
1217
- export { type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, type AgentLintSeverity, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, type AgentRequest, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentSchemaPack, type AgentSnapshotStore, type AgentStateRequest, type AgentStep, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type DecisionLogicConfig, EVENT_TOOL_PREFIX, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type ProviderOptions, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseOutput, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
1250
+ export { type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, type AgentLintSeverity, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, type AgentRequest, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentSchemaPack, type AgentSetupStateSchema, type AgentSnapshotStore, type AgentStateNarrowing, type AgentStateRequest, type AgentStep, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type DecisionLogicConfig, EVENT_TOOL_PREFIX, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type ProviderOptions, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { _ as createAgentSchemas, a as AgentIdleError, b as messagesSchema, c as inspectTransitions, d as executeAgentRequest, f as getAgentRequests, g as transitionAgentStep, h as resolveAgentStep, i as simulateAgent, l as runAgent, m as resolveAgentRequests, n as explorePaths, o as IllegalResumeEventError, p as initialAgentStep, r as lintAgentMachine, s as SnapshotVersionMismatchError, t as canReach, u as runAgentToCompletion, v as setupAgent, y as appendMessages } from "./src-CEa947Dm.mjs";
2
- import { B as getAgentMessages, C as createTextLogic, E as isStructuredOutputSchema, G as isStandardSchema, H as getJsonSchemaSync, J as toolMessage, K as persistSnapshot, R as assistantMessage, T as getAgentOutputMode, U as getMachineStructuralHash, V as getJsonSchema, W as getStateMeta, X as validateSchemaSync, Y as userMessage, b as bindRequestExecutor, d as EVENT_TOOL_PREFIX, f as getAcceptedEvents, k as parseOutput, l as renderDecisionAttempts, m as parseAgentEvent, n as PLAN_DONE_EVENT_TYPE, p as matchesEventPattern, q as systemMessage, t as DecisionExhaustedError, u as resolveDecision, x as buildEnvelopeSchema } from "./decision-D1654JdD.mjs";
3
- export { AgentIdleError, DecisionExhaustedError, EVENT_TOOL_PREFIX, IllegalResumeEventError, PLAN_DONE_EVENT_TYPE, SnapshotVersionMismatchError, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseOutput, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
1
+ import { _ as createAgentSchemas, a as AgentIdleError, b as messagesSchema, c as inspectTransitions, d as executeAgentRequest, f as getAgentRequests, g as transitionAgentStep, h as resolveAgentStep, i as simulateAgent, l as runAgent, m as resolveAgentRequests, n as explorePaths, o as IllegalResumeEventError, p as initialAgentStep, r as lintAgentMachine, s as SnapshotVersionMismatchError, t as canReach, u as runAgentToCompletion, v as setupAgent, y as appendMessages } from "./src-BpQdxsKc.mjs";
2
+ import { A as parseOutput, B as assistantMessage, C as createTextLogic, E as isStructuredOutputSchema, G as getMachineStructuralHash, H as getAgentMessages, J as persistSnapshot, K as getStateMeta, Q as validateSchemaSync, T as getAgentOutputMode, U as getJsonSchema, W as getJsonSchemaSync, X as toolMessage, Y as systemMessage, Z as userMessage, b as bindRequestExecutor, d as EVENT_TOOL_PREFIX, f as getAcceptedEvents, j as parseStructuredEnvelope, k as parseModelRef, l as renderDecisionAttempts, m as parseAgentEvent, n as PLAN_DONE_EVENT_TYPE, p as matchesEventPattern, q as isStandardSchema, t as DecisionExhaustedError, u as resolveDecision, x as buildEnvelopeSchema } from "./decision-mPR_YQd8.mjs";
3
+ export { AgentIdleError, DecisionExhaustedError, EVENT_TOOL_PREFIX, IllegalResumeEventError, PLAN_DONE_EVENT_TYPE, SnapshotVersionMismatchError, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_decision = require("./decision-CX3YdwrO.cjs");
2
+ const require_decision = require("./decision-BnATHy0W.cjs");
3
3
  //#region src/openai-compat/index.ts
4
4
  /**
5
5
  * OpenAI-compatible Chat Completions adapter — a COMPLETE `{ generateText,
@@ -1,5 +1,5 @@
1
1
  import { c as AgentTools } from "./types-BHjeDdch.cjs";
2
- import { B as AgentEventDescriptor, D as AgentDecisionExecutor, k as AgentDecisionRequest, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-1ZQkO3zr.cjs";
2
+ import { H as AgentEventDescriptor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-4Q2F9kyr.cjs";
3
3
  import { r as getJsonSchema } from "./utils-lK1wnL2i.cjs";
4
4
 
5
5
  //#region src/openai-compat/index.d.ts
@@ -1,5 +1,5 @@
1
1
  import { c as AgentTools } from "./types-Cq1YlAQ6.mjs";
2
- import { B as AgentEventDescriptor, D as AgentDecisionExecutor, k as AgentDecisionRequest, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-2EMJIS-n.mjs";
2
+ import { H as AgentEventDescriptor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-2wFNEznm.mjs";
3
3
  import { r as getJsonSchema } from "./utils-CWUCa3pF.mjs";
4
4
 
5
5
  //#region src/openai-compat/index.d.ts
@@ -1,4 +1,4 @@
1
- import { G as isStandardSchema, H as getJsonSchemaSync, T as getAgentOutputMode, V as getJsonSchema, l as renderDecisionAttempts, x as buildEnvelopeSchema } from "./decision-D1654JdD.mjs";
1
+ import { T as getAgentOutputMode, U as getJsonSchema, W as getJsonSchemaSync, l as renderDecisionAttempts, q as isStandardSchema, x as buildEnvelopeSchema } from "./decision-mPR_YQd8.mjs";
2
2
  //#region src/openai-compat/index.ts
3
3
  /**
4
4
  * OpenAI-compatible Chat Completions adapter — a COMPLETE `{ generateText,
@@ -1,4 +1,4 @@
1
- import { A as userInputActor, B as getAgentMessages, C as createTextLogic, D as isTextLogic, F as isUnboundPlaceholder, H as getJsonSchemaSync, I as machineSuspensionPredicates, L as missingActor, M as executorBoundLogics, N as getMachineSuspensionPredicate, O as normalizeGeneratorResult, P as getRegisteredAgentExecutionOptions, R as assistantMessage, S as builtinTextActors, U as getMachineStructuralHash, X as validateSchemaSync, Y as userMessage, _ as INTERPRET_SOURCE, a as createPlanActor, c as isPlanLogic, f as getAcceptedEvents, g as DECIDE_ACTOR, h as sanitizeEventToolName, i as createDecideActor, j as agentExecutionOptions, n as PLAN_DONE_EVENT_TYPE, o as initialPlanLedger, r as advancePlanLedger, s as isDecisionLogic, t as DecisionExhaustedError, u as resolveDecision, v as PLAN_ACTOR, w as executeAgentTextRequest, y as USER_INPUT_ACTOR, z as findNonSerializableContextPaths } from "./decision-D1654JdD.mjs";
1
+ import { B as assistantMessage, C as createTextLogic, D as isTextLogic, F as getMachineSuspensionPredicate, G as getMachineStructuralHash, H as getAgentMessages, I as getRegisteredAgentExecutionOptions, L as isUnboundPlaceholder, M as userInputActor, N as agentExecutionOptions, O as normalizeGeneratorResult, P as executorBoundLogics, Q as validateSchemaSync, R as machineSuspensionPredicates, S as builtinTextActors, V as findNonSerializableContextPaths, W as getJsonSchemaSync, Z as userMessage, _ as INTERPRET_SOURCE, a as createPlanActor, c as isPlanLogic, f as getAcceptedEvents, g as DECIDE_ACTOR, h as sanitizeEventToolName, i as createDecideActor, n as PLAN_DONE_EVENT_TYPE, o as initialPlanLedger, r as advancePlanLedger, s as isDecisionLogic, t as DecisionExhaustedError, u as resolveDecision, v as PLAN_ACTOR, w as executeAgentTextRequest, y as USER_INPUT_ACTOR, z as missingActor } from "./decision-mPR_YQd8.mjs";
2
2
  import { createActor, createAsyncLogic, getNextTransitions, initialTransition, setup, transition } from "xstate";
3
3
  //#region src/messages.ts
4
4
  function addMessages(resolve) {
@@ -278,6 +278,43 @@ function createAgentSchemas(schemas) {
278
278
  emitted: schemas.emitted
279
279
  };
280
280
  }
281
+ function mergeContextSchema(base, fields) {
282
+ return { "~standard": {
283
+ version: 1,
284
+ vendor: "statelyai-agent",
285
+ validate(value) {
286
+ const baseResult = base["~standard"].validate(value);
287
+ if (baseResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
288
+ if (baseResult.issues) return baseResult;
289
+ const merged = { ...baseResult.value };
290
+ const issues = [];
291
+ for (const [key, fieldSchema] of Object.entries(fields)) {
292
+ const fieldResult = fieldSchema["~standard"].validate(value[key]);
293
+ if (fieldResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
294
+ if (fieldResult.issues) issues.push(...fieldResult.issues.map((issue) => ({
295
+ ...issue,
296
+ path: [key, ...issue.path ?? []]
297
+ })));
298
+ else merged[key] = fieldResult.value;
299
+ }
300
+ return issues.length > 0 ? { issues } : { value: merged };
301
+ }
302
+ } };
303
+ }
304
+ function resolveAgentStateSchemas(contextSchema, states) {
305
+ return Object.fromEntries(Object.entries(states).map(([key, state]) => {
306
+ if (!state || typeof state !== "object") return [key, state];
307
+ const children = "states" in state && state.states ? resolveAgentStateSchemas(contextSchema, state.states) : void 0;
308
+ if ("context" in state && state.context) return [key, {
309
+ schemas: { context: mergeContextSchema(contextSchema, state.context) },
310
+ ...children ? { states: children } : {}
311
+ }];
312
+ return [key, children ? {
313
+ ...state,
314
+ states: children
315
+ } : state];
316
+ }));
317
+ }
281
318
  /**
282
319
  * Schema-first `setup(...)` for agent machines — the standard entry point
283
320
  * for authoring a machine (the blueprint) that this library then runs (via
@@ -418,7 +455,7 @@ function createAgentSetupConfig(schemas, actorSources, config) {
418
455
  meta: schemas.meta,
419
456
  ...schemas.emitted && Object.keys(schemas.emitted).length > 0 ? { emitted: schemas.emitted } : {}
420
457
  },
421
- ...config.states ? { states: config.states } : {},
458
+ ...config.states ? { states: resolveAgentStateSchemas(schemas.context, config.states) } : {},
422
459
  actorSources,
423
460
  actions: config.actions,
424
461
  guards: config.guards,
@@ -463,6 +500,18 @@ function createSetupAgent(config) {
463
500
  * `resolveAgentRequests`.
464
501
  * @module
465
502
  */
503
+ /** @internal Normalizes current and legacy XState invoke effect shapes. */
504
+ function getInvokeEffectMetadata(action) {
505
+ if (action.type === "@xstate.spawn") return action;
506
+ if (action.type === "xstate.spawnChild") {
507
+ const params = action.params;
508
+ return params ? {
509
+ ...params,
510
+ logic: action.logic
511
+ } : void 0;
512
+ }
513
+ if (action.type === "@xstate.start" && typeof action.src === "string") return action;
514
+ }
466
515
  /**
467
516
  * Scans a set of executable actions (as returned by xstate's `transition`/
468
517
  * `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
@@ -478,11 +527,10 @@ function createSetupAgent(config) {
478
527
  */
479
528
  function getAgentRequestsWith(actions, options = {}) {
480
529
  return [...actions.flatMap((action) => {
481
- if (action.type !== "xstate.spawnChild" && action.type !== "@xstate.start") return [];
482
- const params = action.type === "@xstate.start" ? action : action.params;
530
+ const params = getInvokeEffectMetadata(action);
483
531
  if (!params || typeof params.src !== "string") return [];
484
532
  if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
485
- const registeredLogic = isTextLogic(action.logic) || isDecisionLogic(action.logic) ? action.logic : options.actorSources?.[params.src];
533
+ const registeredLogic = isTextLogic(params.logic) || isDecisionLogic(params.logic) ? params.logic : options.actorSources?.[params.src];
486
534
  if (isDecisionLogic(registeredLogic)) {
487
535
  const decisionRequest = registeredLogic.request(params.input);
488
536
  const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
@@ -2143,12 +2191,10 @@ function lintAgentMachine(machine, options = {}) {
2143
2191
  function pendingInvokes(step) {
2144
2192
  const out = [];
2145
2193
  for (const action of step.actions) {
2146
- const type = action.type;
2147
- if (type !== "xstate.spawnChild" && type !== "@xstate.start") continue;
2148
- const params = type === "@xstate.start" ? action : action.params ?? {};
2149
- if (typeof params.src === "string" && typeof params.id === "string") out.push({
2150
- id: params.id,
2151
- src: params.src
2194
+ const metadata = getInvokeEffectMetadata(action);
2195
+ if (typeof metadata?.src === "string" && typeof metadata.id === "string") out.push({
2196
+ id: metadata.id,
2197
+ src: metadata.src
2152
2198
  });
2153
2199
  }
2154
2200
  return out;
@@ -1,4 +1,4 @@
1
- const require_decision = require("./decision-CX3YdwrO.cjs");
1
+ const require_decision = require("./decision-BnATHy0W.cjs");
2
2
  let xstate = require("xstate");
3
3
  //#region src/messages.ts
4
4
  function addMessages(resolve) {
@@ -278,6 +278,43 @@ function createAgentSchemas(schemas) {
278
278
  emitted: schemas.emitted
279
279
  };
280
280
  }
281
+ function mergeContextSchema(base, fields) {
282
+ return { "~standard": {
283
+ version: 1,
284
+ vendor: "statelyai-agent",
285
+ validate(value) {
286
+ const baseResult = base["~standard"].validate(value);
287
+ if (baseResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
288
+ if (baseResult.issues) return baseResult;
289
+ const merged = { ...baseResult.value };
290
+ const issues = [];
291
+ for (const [key, fieldSchema] of Object.entries(fields)) {
292
+ const fieldResult = fieldSchema["~standard"].validate(value[key]);
293
+ if (fieldResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
294
+ if (fieldResult.issues) issues.push(...fieldResult.issues.map((issue) => ({
295
+ ...issue,
296
+ path: [key, ...issue.path ?? []]
297
+ })));
298
+ else merged[key] = fieldResult.value;
299
+ }
300
+ return issues.length > 0 ? { issues } : { value: merged };
301
+ }
302
+ } };
303
+ }
304
+ function resolveAgentStateSchemas(contextSchema, states) {
305
+ return Object.fromEntries(Object.entries(states).map(([key, state]) => {
306
+ if (!state || typeof state !== "object") return [key, state];
307
+ const children = "states" in state && state.states ? resolveAgentStateSchemas(contextSchema, state.states) : void 0;
308
+ if ("context" in state && state.context) return [key, {
309
+ schemas: { context: mergeContextSchema(contextSchema, state.context) },
310
+ ...children ? { states: children } : {}
311
+ }];
312
+ return [key, children ? {
313
+ ...state,
314
+ states: children
315
+ } : state];
316
+ }));
317
+ }
281
318
  /**
282
319
  * Schema-first `setup(...)` for agent machines — the standard entry point
283
320
  * for authoring a machine (the blueprint) that this library then runs (via
@@ -418,7 +455,7 @@ function createAgentSetupConfig(schemas, actorSources, config) {
418
455
  meta: schemas.meta,
419
456
  ...schemas.emitted && Object.keys(schemas.emitted).length > 0 ? { emitted: schemas.emitted } : {}
420
457
  },
421
- ...config.states ? { states: config.states } : {},
458
+ ...config.states ? { states: resolveAgentStateSchemas(schemas.context, config.states) } : {},
422
459
  actorSources,
423
460
  actions: config.actions,
424
461
  guards: config.guards,
@@ -463,6 +500,18 @@ function createSetupAgent(config) {
463
500
  * `resolveAgentRequests`.
464
501
  * @module
465
502
  */
503
+ /** @internal Normalizes current and legacy XState invoke effect shapes. */
504
+ function getInvokeEffectMetadata(action) {
505
+ if (action.type === "@xstate.spawn") return action;
506
+ if (action.type === "xstate.spawnChild") {
507
+ const params = action.params;
508
+ return params ? {
509
+ ...params,
510
+ logic: action.logic
511
+ } : void 0;
512
+ }
513
+ if (action.type === "@xstate.start" && typeof action.src === "string") return action;
514
+ }
466
515
  /**
467
516
  * Scans a set of executable actions (as returned by xstate's `transition`/
468
517
  * `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
@@ -478,11 +527,10 @@ function createSetupAgent(config) {
478
527
  */
479
528
  function getAgentRequestsWith(actions, options = {}) {
480
529
  return [...actions.flatMap((action) => {
481
- if (action.type !== "xstate.spawnChild" && action.type !== "@xstate.start") return [];
482
- const params = action.type === "@xstate.start" ? action : action.params;
530
+ const params = getInvokeEffectMetadata(action);
483
531
  if (!params || typeof params.src !== "string") return [];
484
532
  if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
485
- const registeredLogic = require_decision.isTextLogic(action.logic) || require_decision.isDecisionLogic(action.logic) ? action.logic : options.actorSources?.[params.src];
533
+ const registeredLogic = require_decision.isTextLogic(params.logic) || require_decision.isDecisionLogic(params.logic) ? params.logic : options.actorSources?.[params.src];
486
534
  if (require_decision.isDecisionLogic(registeredLogic)) {
487
535
  const decisionRequest = registeredLogic.request(params.input);
488
536
  const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
@@ -2143,12 +2191,10 @@ function lintAgentMachine(machine, options = {}) {
2143
2191
  function pendingInvokes(step) {
2144
2192
  const out = [];
2145
2193
  for (const action of step.actions) {
2146
- const type = action.type;
2147
- if (type !== "xstate.spawnChild" && type !== "@xstate.start") continue;
2148
- const params = type === "@xstate.start" ? action : action.params ?? {};
2149
- if (typeof params.src === "string" && typeof params.id === "string") out.push({
2150
- id: params.id,
2151
- src: params.src
2194
+ const metadata = getInvokeEffectMetadata(action);
2195
+ if (typeof metadata?.src === "string" && typeof metadata.id === "string") out.push({
2196
+ id: metadata.id,
2197
+ src: metadata.src
2152
2198
  });
2153
2199
  }
2154
2200
  return out;
@@ -383,6 +383,21 @@ type AgentModelMap = Record<string, unknown>;
383
383
  * adapter's models map / `resolveModel`) resolves them to a real model.
384
384
  */
385
385
  type AgentModelRef<TModels extends AgentModelMap = {}> = [keyof TModels] extends [never] ? string : (keyof TModels & string) | (string & {});
386
+ /**
387
+ * Splits a portable `"provider/model-id"` model ref (the convention JSON
388
+ * workflows and registry-less hosts use, e.g. `"openai/gpt-5.4-mini"`) into
389
+ * its parts. A ref with no `/` has no provider — `modelId` is the whole ref.
390
+ * The standard building block for a host's `resolveModel`:
391
+ *
392
+ * @example
393
+ * ```ts
394
+ * const resolveModel = (ref: string) => openai(parseModelRef(ref).modelId);
395
+ * ```
396
+ */
397
+ declare function parseModelRef(modelRef: string): {
398
+ provider: string | undefined;
399
+ modelId: string;
400
+ };
386
401
  /**
387
402
  * Portable, provider-agnostic input a text request passes to a host
388
403
  * executor (`generateText`/`streamText` on {@link AgentRequestExecutors}).
@@ -437,17 +452,22 @@ interface AgentTextRequest<TMetadata = Record<string, unknown>> {
437
452
  */
438
453
  metadata?: TMetadata;
439
454
  }
440
- /** Inline input for the `agent.userInput` builtin actor — a human-input request (CLI prompt, form, chat reply, …). See {@link RunAgentOptions.userInput}. */
455
+ /**
456
+ * Inline input for the `agent.userInput` builtin actor — a human-input request
457
+ * (CLI prompt, chat reply, …) that resolves to the `string` the human typed.
458
+ * See {@link RunAgentOptions.userInput}. For structured input, parse/classify
459
+ * the string in a follow-up state, or register a custom actor source; host
460
+ * rendering hints (a form spec, say) belong in `metadata`.
461
+ */
441
462
  interface AgentUserInput<TMetadata = Record<string, unknown>> {
442
463
  prompt?: string;
443
- schema?: StandardSchemaV1;
444
464
  metadata?: TMetadata;
445
465
  }
446
466
  /** The five `agent.*` builtin actor logics every setupAgent-built machine registers. @internal */
447
467
  type BuiltinAgentActors<TEvent extends string = string, TModel extends string = string> = {
448
468
  [GENERATE_TEXT_ACTOR]: AsyncActorLogic<unknown, AgentTextRequest>;
449
469
  [STREAM_TEXT_ACTOR]: AsyncActorLogic<unknown, AgentTextRequest>;
450
- [USER_INPUT_ACTOR]: AsyncActorLogic<unknown, AgentUserInput>;
470
+ [USER_INPUT_ACTOR]: AsyncActorLogic<string, AgentUserInput>;
451
471
  [DECIDE_ACTOR]: AsyncActorLogic<ChosenEvent, AgentDecisionInput<TEvent, Record<string, unknown>, TModel>>;
452
472
  [PLAN_ACTOR]: PlanLogic<StandardSchemaV1<AgentPlanInput<TEvent, Record<string, unknown>, TModel>>>;
453
473
  };
@@ -564,7 +584,7 @@ declare function createTextLogic<TInputSchema extends StandardSchemaV1, TOutputS
564
584
  * });
565
585
  * ```
566
586
  */
567
- declare function bindRequestExecutor<TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetadata>(logic: TextLogic<TInputSchema, TOutputSchema, TMetadata>, executor: AgentRequestExecutor): TextLogic<TInputSchema, TOutputSchema, TMetadata>;
587
+ declare function bindRequestExecutor<TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetadata>(logic: TextLogic<TInputSchema, TOutputSchema, TMetadata>, executor: AgentRequestExecutor, info?: Pick<AgentRequestExecutorInfo, "onChunk">): TextLogic<TInputSchema, TOutputSchema, TMetadata>;
568
588
  /**
569
589
  * The envelope an {@link AgentRequestExecutor} must return: `{ output }` where
570
590
  * `output` is the request's value (a text string or a structured object).
@@ -678,5 +698,13 @@ interface StructuredOutputEnvelope {
678
698
  declare function buildEnvelopeSchema(inner: StandardSchemaV1, options?: {
679
699
  reasoning?: boolean;
680
700
  }): StandardSchemaV1<StructuredOutputEnvelope>;
701
+ /**
702
+ * Validates a raw provider value against the structured-output envelope for
703
+ * `request` and returns the unwrapped `{ result, reasoning? }` — the checked
704
+ * replacement for `raw as StructuredOutputEnvelope` in hand-written hosts.
705
+ * Pair with {@link buildEnvelopeSchema} (which produced the schema the
706
+ * provider was asked to satisfy).
707
+ */
708
+ declare function parseStructuredEnvelope(request: Pick<AgentTextRequest, "outputSchema" | "reasoning">, value: unknown): StructuredOutputEnvelope;
681
709
  //#endregion
682
- export { AgentPlanInput as A, AgentEventDescriptor as B, createTextLogic as C, AgentDecisionExecutor as D, parseOutput as E, DecisionLogicConfig as F, getAcceptedEvents as G, AgentRequestOptions as H, PLAN_DONE_EVENT_TYPE as I, matchesEventPattern as K, ResolveDecisionOptions as L, DecisionAttempt as M, DecisionExhaustedError as N, AgentDecisionInput as O, DecisionLogic as P, renderDecisionAttempts as R, buildEnvelopeSchema as S, isStructuredOutputSchema as T, AgentRequestSource as U, AgentEventToolNameResolver as V, EVENT_TOOL_PREFIX as W, TextLogicExecuteArgs as _, AgentRequestExecutorInfo as a, TextLogicOutput as b, AgentRequestMode as c, AiSdkShapedStreamResult as d, AiSdkShapedTextResult as f, TextLogicConfig as g, TextLogic as h, AgentRequestExecutor as i, AgentPlanOutput as j, AgentDecisionRequest as k, AgentTextRequest as l, StructuredOutputEnvelope as m, AgentModelRef as n, AgentRequestExecutorResult as o, BuiltinAgentActors as p, parseAgentEvent as q, AgentOutputMode as r, AgentRequestExecutors as s, AgentModelMap as t, AgentUserInput as u, TextLogicExecutor as v, getAgentOutputMode as w, bindRequestExecutor as x, TextLogicInput as y, resolveDecision as z };
710
+ export { AgentDecisionInput as A, renderDecisionAttempts as B, createTextLogic as C, parseOutput as D, parseModelRef as E, DecisionExhaustedError as F, AgentRequestSource as G, AgentEventDescriptor as H, DecisionLogic as I, matchesEventPattern as J, EVENT_TOOL_PREFIX as K, DecisionLogicConfig as L, AgentPlanInput as M, AgentPlanOutput as N, parseStructuredEnvelope as O, DecisionAttempt as P, PLAN_DONE_EVENT_TYPE as R, buildEnvelopeSchema as S, isStructuredOutputSchema as T, AgentEventToolNameResolver as U, resolveDecision as V, AgentRequestOptions as W, parseAgentEvent as Y, TextLogicExecuteArgs as _, AgentRequestExecutorInfo as a, TextLogicOutput as b, AgentRequestMode as c, AiSdkShapedStreamResult as d, AiSdkShapedTextResult as f, TextLogicConfig as g, TextLogic as h, AgentRequestExecutor as i, AgentDecisionRequest as j, AgentDecisionExecutor as k, AgentTextRequest as l, StructuredOutputEnvelope as m, AgentModelRef as n, AgentRequestExecutorResult as o, BuiltinAgentActors as p, getAcceptedEvents as q, AgentOutputMode as r, AgentRequestExecutors as s, AgentModelMap as t, AgentUserInput as u, TextLogicExecutor as v, getAgentOutputMode as w, bindRequestExecutor as x, TextLogicInput as y, ResolveDecisionOptions as z };
@@ -383,6 +383,21 @@ type AgentModelMap = Record<string, unknown>;
383
383
  * adapter's models map / `resolveModel`) resolves them to a real model.
384
384
  */
385
385
  type AgentModelRef<TModels extends AgentModelMap = {}> = [keyof TModels] extends [never] ? string : (keyof TModels & string) | (string & {});
386
+ /**
387
+ * Splits a portable `"provider/model-id"` model ref (the convention JSON
388
+ * workflows and registry-less hosts use, e.g. `"openai/gpt-5.4-mini"`) into
389
+ * its parts. A ref with no `/` has no provider — `modelId` is the whole ref.
390
+ * The standard building block for a host's `resolveModel`:
391
+ *
392
+ * @example
393
+ * ```ts
394
+ * const resolveModel = (ref: string) => openai(parseModelRef(ref).modelId);
395
+ * ```
396
+ */
397
+ declare function parseModelRef(modelRef: string): {
398
+ provider: string | undefined;
399
+ modelId: string;
400
+ };
386
401
  /**
387
402
  * Portable, provider-agnostic input a text request passes to a host
388
403
  * executor (`generateText`/`streamText` on {@link AgentRequestExecutors}).
@@ -437,17 +452,22 @@ interface AgentTextRequest<TMetadata = Record<string, unknown>> {
437
452
  */
438
453
  metadata?: TMetadata;
439
454
  }
440
- /** Inline input for the `agent.userInput` builtin actor — a human-input request (CLI prompt, form, chat reply, …). See {@link RunAgentOptions.userInput}. */
455
+ /**
456
+ * Inline input for the `agent.userInput` builtin actor — a human-input request
457
+ * (CLI prompt, chat reply, …) that resolves to the `string` the human typed.
458
+ * See {@link RunAgentOptions.userInput}. For structured input, parse/classify
459
+ * the string in a follow-up state, or register a custom actor source; host
460
+ * rendering hints (a form spec, say) belong in `metadata`.
461
+ */
441
462
  interface AgentUserInput<TMetadata = Record<string, unknown>> {
442
463
  prompt?: string;
443
- schema?: StandardSchemaV1;
444
464
  metadata?: TMetadata;
445
465
  }
446
466
  /** The five `agent.*` builtin actor logics every setupAgent-built machine registers. @internal */
447
467
  type BuiltinAgentActors<TEvent extends string = string, TModel extends string = string> = {
448
468
  [GENERATE_TEXT_ACTOR]: AsyncActorLogic<unknown, AgentTextRequest>;
449
469
  [STREAM_TEXT_ACTOR]: AsyncActorLogic<unknown, AgentTextRequest>;
450
- [USER_INPUT_ACTOR]: AsyncActorLogic<unknown, AgentUserInput>;
470
+ [USER_INPUT_ACTOR]: AsyncActorLogic<string, AgentUserInput>;
451
471
  [DECIDE_ACTOR]: AsyncActorLogic<ChosenEvent, AgentDecisionInput<TEvent, Record<string, unknown>, TModel>>;
452
472
  [PLAN_ACTOR]: PlanLogic<StandardSchemaV1<AgentPlanInput<TEvent, Record<string, unknown>, TModel>>>;
453
473
  };
@@ -564,7 +584,7 @@ declare function createTextLogic<TInputSchema extends StandardSchemaV1, TOutputS
564
584
  * });
565
585
  * ```
566
586
  */
567
- declare function bindRequestExecutor<TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetadata>(logic: TextLogic<TInputSchema, TOutputSchema, TMetadata>, executor: AgentRequestExecutor): TextLogic<TInputSchema, TOutputSchema, TMetadata>;
587
+ declare function bindRequestExecutor<TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetadata>(logic: TextLogic<TInputSchema, TOutputSchema, TMetadata>, executor: AgentRequestExecutor, info?: Pick<AgentRequestExecutorInfo, "onChunk">): TextLogic<TInputSchema, TOutputSchema, TMetadata>;
568
588
  /**
569
589
  * The envelope an {@link AgentRequestExecutor} must return: `{ output }` where
570
590
  * `output` is the request's value (a text string or a structured object).
@@ -678,5 +698,13 @@ interface StructuredOutputEnvelope {
678
698
  declare function buildEnvelopeSchema(inner: StandardSchemaV1, options?: {
679
699
  reasoning?: boolean;
680
700
  }): StandardSchemaV1<StructuredOutputEnvelope>;
701
+ /**
702
+ * Validates a raw provider value against the structured-output envelope for
703
+ * `request` and returns the unwrapped `{ result, reasoning? }` — the checked
704
+ * replacement for `raw as StructuredOutputEnvelope` in hand-written hosts.
705
+ * Pair with {@link buildEnvelopeSchema} (which produced the schema the
706
+ * provider was asked to satisfy).
707
+ */
708
+ declare function parseStructuredEnvelope(request: Pick<AgentTextRequest, "outputSchema" | "reasoning">, value: unknown): StructuredOutputEnvelope;
681
709
  //#endregion
682
- export { AgentPlanInput as A, AgentEventDescriptor as B, createTextLogic as C, AgentDecisionExecutor as D, parseOutput as E, DecisionLogicConfig as F, getAcceptedEvents as G, AgentRequestOptions as H, PLAN_DONE_EVENT_TYPE as I, matchesEventPattern as K, ResolveDecisionOptions as L, DecisionAttempt as M, DecisionExhaustedError as N, AgentDecisionInput as O, DecisionLogic as P, renderDecisionAttempts as R, buildEnvelopeSchema as S, isStructuredOutputSchema as T, AgentRequestSource as U, AgentEventToolNameResolver as V, EVENT_TOOL_PREFIX as W, TextLogicExecuteArgs as _, AgentRequestExecutorInfo as a, TextLogicOutput as b, AgentRequestMode as c, AiSdkShapedStreamResult as d, AiSdkShapedTextResult as f, TextLogicConfig as g, TextLogic as h, AgentRequestExecutor as i, AgentPlanOutput as j, AgentDecisionRequest as k, AgentTextRequest as l, StructuredOutputEnvelope as m, AgentModelRef as n, AgentRequestExecutorResult as o, BuiltinAgentActors as p, parseAgentEvent as q, AgentOutputMode as r, AgentRequestExecutors as s, AgentModelMap as t, AgentUserInput as u, TextLogicExecutor as v, getAgentOutputMode as w, bindRequestExecutor as x, TextLogicInput as y, resolveDecision as z };
710
+ export { AgentDecisionInput as A, renderDecisionAttempts as B, createTextLogic as C, parseOutput as D, parseModelRef as E, DecisionExhaustedError as F, AgentRequestSource as G, AgentEventDescriptor as H, DecisionLogic as I, matchesEventPattern as J, EVENT_TOOL_PREFIX as K, DecisionLogicConfig as L, AgentPlanInput as M, AgentPlanOutput as N, parseStructuredEnvelope as O, DecisionAttempt as P, PLAN_DONE_EVENT_TYPE as R, buildEnvelopeSchema as S, isStructuredOutputSchema as T, AgentEventToolNameResolver as U, resolveDecision as V, AgentRequestOptions as W, parseAgentEvent as Y, TextLogicExecuteArgs as _, AgentRequestExecutorInfo as a, TextLogicOutput as b, AgentRequestMode as c, AiSdkShapedStreamResult as d, AiSdkShapedTextResult as f, TextLogicConfig as g, TextLogic as h, AgentRequestExecutor as i, AgentDecisionRequest as j, AgentDecisionExecutor as k, AgentTextRequest as l, StructuredOutputEnvelope as m, AgentModelRef as n, AgentRequestExecutorResult as o, BuiltinAgentActors as p, getAcceptedEvents as q, AgentOutputMode as r, AgentRequestExecutors as s, AgentModelMap as t, AgentUserInput as u, TextLogicExecutor as v, getAgentOutputMode as w, bindRequestExecutor as x, TextLogicInput as y, ResolveDecisionOptions as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statelyai/agent",
3
- "version": "2.0.0-alpha.6",
3
+ "version": "2.0.0-alpha.7",
4
4
  "description": "State-machine authoring layer for AI agents",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -96,7 +96,7 @@
96
96
  "tsx": "^4.21.0",
97
97
  "typescript": "^5.6.2",
98
98
  "vitest": "^2.1.2",
99
- "xstate": "6.0.0-alpha.17",
99
+ "xstate": "6.0.0-alpha.21",
100
100
  "zod": "^4.3.6"
101
101
  },
102
102
  "publishConfig": {
package/readme.md CHANGED
@@ -132,6 +132,7 @@ The example has one model decision and two final outcomes. Real machines can add
132
132
  <!-- starter examples derived from examples/*/metadata.json and examples/index.ts -->
133
133
 
134
134
  - [Twenty Questions](examples/twenty-questions) shows a model choosing legal events in a loop.
135
+ - [Go Fish](examples/go-fish) pits a model against a human while the machine enforces hidden-information game rules.
135
136
  - [Human in the loop](examples/human-in-the-loop) pauses, stores a snapshot, and resumes after review.
136
137
  - [Ticket triage](examples/triage) returns structured data from a model request.
137
138
  - [JSON agent](examples/json-agent) runs a machine defined as data.