@statelyai/agent 2.0.0-alpha.11 → 2.0.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/ai-sdk.cjs +4 -5
  2. package/dist/ai-sdk.d.cts +7 -4
  3. package/dist/ai-sdk.d.mts +7 -4
  4. package/dist/ai-sdk.mjs +1 -2
  5. package/dist/{events-JiVPYrct.mjs → decision-BezSD_YC.mjs} +327 -20
  6. package/dist/{events-CRQj3VtP.cjs → decision-dWGhBh0P.cjs} +401 -28
  7. package/dist/errors-BQRk9eiZ.d.cts +19 -0
  8. package/dist/errors-C9rxnWbX.d.mts +19 -0
  9. package/dist/errors-CeSXQx0v.mjs +23 -0
  10. package/dist/errors-DUBBzRLP.cjs +28 -0
  11. package/dist/event-log-store-CNT_7F0V.cjs +452 -0
  12. package/dist/event-log-store-CriMgX1D.d.mts +144 -0
  13. package/dist/event-log-store-D7pWtIhb.mjs +411 -0
  14. package/dist/event-log-store-Ruq18mGp.d.cts +144 -0
  15. package/dist/index.cjs +1050 -705
  16. package/dist/index.d.cts +538 -565
  17. package/dist/index.d.mts +538 -565
  18. package/dist/index.mjs +950 -644
  19. package/dist/machines.cjs +752 -0
  20. package/dist/machines.d.cts +372 -0
  21. package/dist/machines.d.mts +372 -0
  22. package/dist/machines.mjs +741 -0
  23. package/dist/otel.cjs +268 -0
  24. package/dist/otel.d.cts +67 -0
  25. package/dist/otel.d.mts +67 -0
  26. package/dist/otel.mjs +267 -0
  27. package/dist/run-agent-C3mFDGTf.d.mts +1111 -0
  28. package/dist/run-agent-DnvtcnTZ.d.cts +1111 -0
  29. package/dist/setup-agent-DAZZSjDS.mjs +1711 -0
  30. package/dist/setup-agent-DP95MFrI.cjs +1836 -0
  31. package/dist/sqlite.cjs +135 -0
  32. package/dist/sqlite.d.cts +57 -0
  33. package/dist/sqlite.d.mts +57 -0
  34. package/dist/sqlite.mjs +133 -0
  35. package/dist/{text-logic-CaKqgX4Y.d.mts → text-logic-BDxwQNsD.d.cts} +155 -72
  36. package/dist/{text-logic-Ckhr2kKC.d.cts → text-logic-TkKPw8Aq.d.mts} +155 -72
  37. package/dist/{types-qm00QF91.d.mts → types-QbEfCVny.d.cts} +1 -1
  38. package/dist/{types-C9QiMjre.d.cts → types-_FXoFBGO.d.mts} +1 -1
  39. package/package.json +47 -39
  40. package/readme.md +49 -12
  41. package/schemas/agent-workflow.json +40 -21
  42. package/skills/generate-machine/SKILL.md +267 -0
  43. package/dist/adapter.cjs +0 -15
  44. package/dist/adapter.d.cts +0 -4
  45. package/dist/adapter.d.mts +0 -4
  46. package/dist/adapter.mjs +0 -2
  47. package/dist/decision-C3k4ve51.mjs +0 -227
  48. package/dist/decision-D8wJrM8W.cjs +0 -286
  49. package/dist/openai-compat.cjs +0 -309
  50. package/dist/openai-compat.d.cts +0 -59
  51. package/dist/openai-compat.d.mts +0 -59
  52. package/dist/openai-compat.mjs +0 -308
  53. package/dist/steps-BALp1eZo.d.mts +0 -198
  54. package/dist/steps-CVe54GPP.cjs +0 -420
  55. package/dist/steps-CkyyyuHd.mjs +0 -379
  56. package/dist/steps-MjnQI4aB.d.cts +0 -198
  57. package/dist/steps.cjs +0 -12
  58. package/dist/steps.d.cts +0 -3
  59. package/dist/steps.d.mts +0 -3
  60. package/dist/steps.mjs +0 -3
  61. package/dist/utils-BYqT_Dyv.d.cts +0 -108
  62. package/dist/utils-Do5wIJrh.d.mts +0 -108
  63. package/dist/zod.cjs +0 -31
  64. package/dist/zod.d.cts +0 -30
  65. package/dist/zod.d.mts +0 -30
  66. package/dist/zod.mjs +0 -30
@@ -1,227 +0,0 @@
1
- import { H as validateSchemaSync, V as userMessage, a as sanitizeEventToolName, n as isEventPattern, o as DECIDE_ACTOR } from "./events-JiVPYrct.mjs";
2
- import { createAsyncLogic, createLogic } from "xstate";
3
- //#region src/decision.ts
4
- function decideRequestFromInput(input) {
5
- const allowedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input) ?? [];
6
- return {
7
- kind: "decision",
8
- id: "",
9
- model: input.model,
10
- system: input.system,
11
- prompt: input.prompt,
12
- messages: input.messages,
13
- events: allowedEventTypes.filter((type) => !isEventPattern(type)).map((type) => ({
14
- type,
15
- toolName: sanitizeEventToolName(type)
16
- })),
17
- attempts: [],
18
- temperature: input.temperature,
19
- maxOutputTokens: input.maxOutputTokens,
20
- topP: input.topP,
21
- topK: input.topK,
22
- seed: input.seed,
23
- stopSequences: input.stopSequences,
24
- metadata: input.metadata
25
- };
26
- }
27
- function decideActorWithExecutor(execute) {
28
- const logic = createAsyncLogic({ run: async ({ input, signal }) => {
29
- if (!execute) throw new Error(`'${DECIDE_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${DECIDE_ACTOR}': ... } }) or resolve the returned agent request with resolveDecision(...).`);
30
- const resolvedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input);
31
- if (resolvedEventTypes === void 0) throw new Error(`'${DECIDE_ACTOR}' input has omitted \`allowedEvents\`, which means "all currently-legal events" — but that requires a snapshot-aware host (runAgent or the step path) to resolve. Under a bare createActor(...), declare \`allowedEvents\` explicitly to use this actor here.`);
32
- if (resolvedEventTypes.some(isEventPattern)) throw new Error(`'${DECIDE_ACTOR}' input uses wildcard \`allowedEvents\` patterns, which expand against the live snapshot — that requires a snapshot-aware host (runAgent or the step path). Under a bare createActor(...), list event types explicitly.`);
33
- return resolveDecision(decideRequestFromInput(input), execute, {
34
- maxRetries: input.maxRetries ?? 2,
35
- signal
36
- });
37
- } });
38
- return Object.assign(logic, {
39
- kind: "statelyai.decisionLogic",
40
- maxRetries: 2,
41
- request: decideRequestFromInput,
42
- allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input),
43
- withExecutor: (nextExecute) => decideActorWithExecutor(nextExecute)
44
- });
45
- }
46
- function createDecideActor() {
47
- return decideActorWithExecutor();
48
- }
49
- /**
50
- * Reserved event type the `agent.plan` builtin adds to every step's
51
- * candidates as the explicit "no further action needed" move. Choosing it
52
- * ends the plan (`stopped: 'done'`); it is never sent to the machine, so
53
- * machines need no no-op sentinel event of their own.
54
- */
55
- const PLAN_DONE_EVENT_TYPE = "agent.plan.done";
56
- function createPlanActor() {
57
- const logic = createLogic({
58
- context: ({ input }) => ({
59
- applied: [],
60
- stepsRemaining: input.maxSteps ?? 8,
61
- stopped: null
62
- }),
63
- run: ({ context, event }) => event.type === "plan.applied" ? { context: {
64
- ...context,
65
- applied: [...context.applied, event.event],
66
- stepsRemaining: context.stepsRemaining - 1
67
- } } : event.type === "plan.ended" ? {
68
- context: {
69
- ...context,
70
- stopped: event.stopped
71
- },
72
- status: "done",
73
- output: {
74
- steps: context.applied,
75
- stopped: event.stopped
76
- }
77
- } : void 0
78
- });
79
- return Object.assign(logic, {
80
- kind: "statelyai.planLogic",
81
- maxRetries: 2,
82
- request: decideRequestFromInput,
83
- allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input)
84
- });
85
- }
86
- const PLAN_LEDGER_SCOPE = { emit: () => {} };
87
- /**
88
- * Builds a fresh plan ledger snapshot from resolved plan input — the shared
89
- * starting point for BOTH hosts (the step path reads the invoke child's own
90
- * initial snapshot; runAgent seeds a local ledger with this). @internal
91
- */
92
- function initialPlanLedger(logic, input) {
93
- return logic.getInitialSnapshot(PLAN_LEDGER_SCOPE, input);
94
- }
95
- /**
96
- * Advances a plan ledger by one {@link PlanLedgerEvent}, returning the next
97
- * snapshot (unwrapping `createLogic`'s `[snapshot, effects]` tuple). Pure — no
98
- * mutation of the input snapshot. @internal
99
- */
100
- function advancePlanLedger(logic, snapshot, event) {
101
- const result = logic.transition(snapshot, event, PLAN_LEDGER_SCOPE);
102
- return Array.isArray(result) ? result[0] : result;
103
- }
104
- /** Type guard: true for the `agent.plan` builtin logic (checks the `kind` marker). @internal */
105
- function isPlanLogic(logic) {
106
- return !!logic && logic.kind === "statelyai.planLogic";
107
- }
108
- function resolveAllowedEventTypes(allowedEvents, input) {
109
- if (allowedEvents === void 0) return;
110
- const resolved = typeof allowedEvents === "function" ? allowedEvents({ input }) : allowedEvents;
111
- return typeof resolved === "string" ? [resolved] : resolved;
112
- }
113
- /** Type guard: true for any actor logic built by createDecisionLogic/createDecideActor (checks the `kind` marker). @internal */
114
- function isDecisionLogic(value) {
115
- return !!value && typeof value === "object" && value.kind === "statelyai.decisionLogic" && typeof value.request === "function";
116
- }
117
- /**
118
- * Thrown by {@link resolveDecision} when every attempt (up to
119
- * `maxRetries + 1` of them) fails one of the three checks recorded in
120
- * {@link DecisionAttempt.failure}. Carries the full `attempts` list for
121
- * diagnostics; a machine typically routes this via the decision invoke's
122
- * `onError`.
123
- */
124
- var DecisionExhaustedError = class extends Error {
125
- attempts;
126
- constructor(attempts) {
127
- super(`Decision exhausted after ${attempts.length} attempt${attempts.length === 1 ? "" : "s"}: ` + attempts.map((attempt) => attempt.reason).join("; "));
128
- this.name = "DecisionExhaustedError";
129
- this.attempts = attempts;
130
- }
131
- };
132
- /**
133
- * Renders a decision request's prior failed `attempts` into feedback messages
134
- * a host appends to the model call so retries converge — the transport-agnostic
135
- * "your last choice failed because X, choose again from Y" logic every adapter
136
- * and raw-SDK host repeats. Returns one `user`-role {@link AgentMessage} per
137
- * attempt (empty when there are none); adapters map each onto their wire
138
- * message shape (`attempt.content` is always a string). Core never rewrites the
139
- * request itself — this only turns the recorded attempts into messages.
140
- *
141
- * @example
142
- * ```ts
143
- * const messages = [...baseMessages, ...renderDecisionAttempts(request)];
144
- * ```
145
- */
146
- function renderDecisionAttempts(request) {
147
- const types = request.events.map((event) => event.type).join(", ") || "(none)";
148
- return request.attempts.map((attempt) => userMessage(`Your previous choice failed: ${attempt.reason}. Choose again from: ${types}`));
149
- }
150
- /**
151
- * Validation + retry core for decisions. No provider mechanics — the
152
- * `executor` is responsible for making the model choose an event; this
153
- * function only validates the choice and retries on failure, up to
154
- * `options.maxRetries` (default 2, i.e. up to 3 attempts total).
155
- *
156
- * Each attempt is checked in order and can fail one of three ways (recorded
157
- * as a {@link DecisionAttempt}): `'unknown-event'` (the chosen `type` is not
158
- * among `request.events`), `'invalid-payload'` (the payload fails that
159
- * event's schema), or `'rejected-by-guard'` (passes both checks but
160
- * `options.canTake` returns `false` — a type/payload-legal event the
161
- * machine's guard rejects right now; omit `canTake` to skip this check).
162
- * Every prior failed attempt for this call is fed back to the executor on
163
- * the next attempt via `request.attempts`, so an adapter can render "your
164
- * last choice failed because X — try again" into the next model call; core
165
- * never rewrites the request itself. Exhausting all attempts throws
166
- * {@link DecisionExhaustedError} with the full attempts list.
167
- *
168
- * @example
169
- * ```ts
170
- * const event = await resolveDecision(request, decide, {
171
- * canTake: (e) => snapshot.can(e),
172
- * });
173
- * ```
174
- */
175
- async function resolveDecision(request, executor, options = {}) {
176
- const maxRetries = options.maxRetries ?? 2;
177
- const attempts = [];
178
- const eventsByType = new Map(request.events.map((event) => [event.type, event]));
179
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
180
- options.signal?.throwIfAborted();
181
- const result = await executor({
182
- ...request,
183
- attempts: [...attempts],
184
- signal: options.signal
185
- });
186
- if (!result || typeof result !== "object" || typeof result.event !== "object" || result.event === null || typeof result.event.type !== "string") throw new Error(`decide executor must return { event: { type: string, ... } }; got ${JSON.stringify(result)}. Wrap the chosen event: return { event: { type: 'SAFE' } }.`);
187
- const { event } = result;
188
- const descriptor = eventsByType.get(event.type);
189
- if (!descriptor) {
190
- attempts.push({
191
- event,
192
- failure: "unknown-event",
193
- reason: `'${event.type}' is not among the currently allowed events: ${request.events.map((candidate) => candidate.type).join(", ") || "(none)"}.`
194
- });
195
- continue;
196
- }
197
- let validatedEvent = event;
198
- if (descriptor.inputSchema) {
199
- const { type, ...payload } = event;
200
- try {
201
- validatedEvent = {
202
- ...validateSchemaSync(descriptor.inputSchema, payload),
203
- type
204
- };
205
- } catch (error) {
206
- attempts.push({
207
- event,
208
- failure: "invalid-payload",
209
- reason: `'${event.type}' payload failed validation: ${error instanceof Error ? error.message : String(error)}`
210
- });
211
- continue;
212
- }
213
- }
214
- if (options.canTake?.(validatedEvent) === false) {
215
- attempts.push({
216
- event: validatedEvent,
217
- failure: "rejected-by-guard",
218
- reason: `'${validatedEvent.type}' is not currently takeable (guard rejected it).`
219
- });
220
- continue;
221
- }
222
- return validatedEvent;
223
- }
224
- throw new DecisionExhaustedError(attempts);
225
- }
226
- //#endregion
227
- export { createPlanActor as a, isPlanLogic as c, createDecideActor as i, renderDecisionAttempts as l, PLAN_DONE_EVENT_TYPE as n, initialPlanLedger as o, advancePlanLedger as r, isDecisionLogic as s, DecisionExhaustedError as t, resolveDecision as u };
@@ -1,286 +0,0 @@
1
- const require_events = require("./events-CRQj3VtP.cjs");
2
- let xstate = require("xstate");
3
- //#region src/decision.ts
4
- function decideRequestFromInput(input) {
5
- const allowedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input) ?? [];
6
- return {
7
- kind: "decision",
8
- id: "",
9
- model: input.model,
10
- system: input.system,
11
- prompt: input.prompt,
12
- messages: input.messages,
13
- events: allowedEventTypes.filter((type) => !require_events.isEventPattern(type)).map((type) => ({
14
- type,
15
- toolName: require_events.sanitizeEventToolName(type)
16
- })),
17
- attempts: [],
18
- temperature: input.temperature,
19
- maxOutputTokens: input.maxOutputTokens,
20
- topP: input.topP,
21
- topK: input.topK,
22
- seed: input.seed,
23
- stopSequences: input.stopSequences,
24
- metadata: input.metadata
25
- };
26
- }
27
- function decideActorWithExecutor(execute) {
28
- const logic = (0, xstate.createAsyncLogic)({ run: async ({ input, signal }) => {
29
- if (!execute) throw new Error(`'${require_events.DECIDE_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${require_events.DECIDE_ACTOR}': ... } }) or resolve the returned agent request with resolveDecision(...).`);
30
- const resolvedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input);
31
- if (resolvedEventTypes === void 0) throw new Error(`'${require_events.DECIDE_ACTOR}' input has omitted \`allowedEvents\`, which means "all currently-legal events" — but that requires a snapshot-aware host (runAgent or the step path) to resolve. Under a bare createActor(...), declare \`allowedEvents\` explicitly to use this actor here.`);
32
- if (resolvedEventTypes.some(require_events.isEventPattern)) throw new Error(`'${require_events.DECIDE_ACTOR}' input uses wildcard \`allowedEvents\` patterns, which expand against the live snapshot — that requires a snapshot-aware host (runAgent or the step path). Under a bare createActor(...), list event types explicitly.`);
33
- return resolveDecision(decideRequestFromInput(input), execute, {
34
- maxRetries: input.maxRetries ?? 2,
35
- signal
36
- });
37
- } });
38
- return Object.assign(logic, {
39
- kind: "statelyai.decisionLogic",
40
- maxRetries: 2,
41
- request: decideRequestFromInput,
42
- allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input),
43
- withExecutor: (nextExecute) => decideActorWithExecutor(nextExecute)
44
- });
45
- }
46
- function createDecideActor() {
47
- return decideActorWithExecutor();
48
- }
49
- /**
50
- * Reserved event type the `agent.plan` builtin adds to every step's
51
- * candidates as the explicit "no further action needed" move. Choosing it
52
- * ends the plan (`stopped: 'done'`); it is never sent to the machine, so
53
- * machines need no no-op sentinel event of their own.
54
- */
55
- const PLAN_DONE_EVENT_TYPE = "agent.plan.done";
56
- function createPlanActor() {
57
- const logic = (0, xstate.createLogic)({
58
- context: ({ input }) => ({
59
- applied: [],
60
- stepsRemaining: input.maxSteps ?? 8,
61
- stopped: null
62
- }),
63
- run: ({ context, event }) => event.type === "plan.applied" ? { context: {
64
- ...context,
65
- applied: [...context.applied, event.event],
66
- stepsRemaining: context.stepsRemaining - 1
67
- } } : event.type === "plan.ended" ? {
68
- context: {
69
- ...context,
70
- stopped: event.stopped
71
- },
72
- status: "done",
73
- output: {
74
- steps: context.applied,
75
- stopped: event.stopped
76
- }
77
- } : void 0
78
- });
79
- return Object.assign(logic, {
80
- kind: "statelyai.planLogic",
81
- maxRetries: 2,
82
- request: decideRequestFromInput,
83
- allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input)
84
- });
85
- }
86
- const PLAN_LEDGER_SCOPE = { emit: () => {} };
87
- /**
88
- * Builds a fresh plan ledger snapshot from resolved plan input — the shared
89
- * starting point for BOTH hosts (the step path reads the invoke child's own
90
- * initial snapshot; runAgent seeds a local ledger with this). @internal
91
- */
92
- function initialPlanLedger(logic, input) {
93
- return logic.getInitialSnapshot(PLAN_LEDGER_SCOPE, input);
94
- }
95
- /**
96
- * Advances a plan ledger by one {@link PlanLedgerEvent}, returning the next
97
- * snapshot (unwrapping `createLogic`'s `[snapshot, effects]` tuple). Pure — no
98
- * mutation of the input snapshot. @internal
99
- */
100
- function advancePlanLedger(logic, snapshot, event) {
101
- const result = logic.transition(snapshot, event, PLAN_LEDGER_SCOPE);
102
- return Array.isArray(result) ? result[0] : result;
103
- }
104
- /** Type guard: true for the `agent.plan` builtin logic (checks the `kind` marker). @internal */
105
- function isPlanLogic(logic) {
106
- return !!logic && logic.kind === "statelyai.planLogic";
107
- }
108
- function resolveAllowedEventTypes(allowedEvents, input) {
109
- if (allowedEvents === void 0) return;
110
- const resolved = typeof allowedEvents === "function" ? allowedEvents({ input }) : allowedEvents;
111
- return typeof resolved === "string" ? [resolved] : resolved;
112
- }
113
- /** Type guard: true for any actor logic built by createDecisionLogic/createDecideActor (checks the `kind` marker). @internal */
114
- function isDecisionLogic(value) {
115
- return !!value && typeof value === "object" && value.kind === "statelyai.decisionLogic" && typeof value.request === "function";
116
- }
117
- /**
118
- * Thrown by {@link resolveDecision} when every attempt (up to
119
- * `maxRetries + 1` of them) fails one of the three checks recorded in
120
- * {@link DecisionAttempt.failure}. Carries the full `attempts` list for
121
- * diagnostics; a machine typically routes this via the decision invoke's
122
- * `onError`.
123
- */
124
- var DecisionExhaustedError = class extends Error {
125
- attempts;
126
- constructor(attempts) {
127
- super(`Decision exhausted after ${attempts.length} attempt${attempts.length === 1 ? "" : "s"}: ` + attempts.map((attempt) => attempt.reason).join("; "));
128
- this.name = "DecisionExhaustedError";
129
- this.attempts = attempts;
130
- }
131
- };
132
- /**
133
- * Renders a decision request's prior failed `attempts` into feedback messages
134
- * a host appends to the model call so retries converge — the transport-agnostic
135
- * "your last choice failed because X, choose again from Y" logic every adapter
136
- * and raw-SDK host repeats. Returns one `user`-role {@link AgentMessage} per
137
- * attempt (empty when there are none); adapters map each onto their wire
138
- * message shape (`attempt.content` is always a string). Core never rewrites the
139
- * request itself — this only turns the recorded attempts into messages.
140
- *
141
- * @example
142
- * ```ts
143
- * const messages = [...baseMessages, ...renderDecisionAttempts(request)];
144
- * ```
145
- */
146
- function renderDecisionAttempts(request) {
147
- const types = request.events.map((event) => event.type).join(", ") || "(none)";
148
- return request.attempts.map((attempt) => require_events.userMessage(`Your previous choice failed: ${attempt.reason}. Choose again from: ${types}`));
149
- }
150
- /**
151
- * Validation + retry core for decisions. No provider mechanics — the
152
- * `executor` is responsible for making the model choose an event; this
153
- * function only validates the choice and retries on failure, up to
154
- * `options.maxRetries` (default 2, i.e. up to 3 attempts total).
155
- *
156
- * Each attempt is checked in order and can fail one of three ways (recorded
157
- * as a {@link DecisionAttempt}): `'unknown-event'` (the chosen `type` is not
158
- * among `request.events`), `'invalid-payload'` (the payload fails that
159
- * event's schema), or `'rejected-by-guard'` (passes both checks but
160
- * `options.canTake` returns `false` — a type/payload-legal event the
161
- * machine's guard rejects right now; omit `canTake` to skip this check).
162
- * Every prior failed attempt for this call is fed back to the executor on
163
- * the next attempt via `request.attempts`, so an adapter can render "your
164
- * last choice failed because X — try again" into the next model call; core
165
- * never rewrites the request itself. Exhausting all attempts throws
166
- * {@link DecisionExhaustedError} with the full attempts list.
167
- *
168
- * @example
169
- * ```ts
170
- * const event = await resolveDecision(request, decide, {
171
- * canTake: (e) => snapshot.can(e),
172
- * });
173
- * ```
174
- */
175
- async function resolveDecision(request, executor, options = {}) {
176
- const maxRetries = options.maxRetries ?? 2;
177
- const attempts = [];
178
- const eventsByType = new Map(request.events.map((event) => [event.type, event]));
179
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
180
- options.signal?.throwIfAborted();
181
- const result = await executor({
182
- ...request,
183
- attempts: [...attempts],
184
- signal: options.signal
185
- });
186
- if (!result || typeof result !== "object" || typeof result.event !== "object" || result.event === null || typeof result.event.type !== "string") throw new Error(`decide executor must return { event: { type: string, ... } }; got ${JSON.stringify(result)}. Wrap the chosen event: return { event: { type: 'SAFE' } }.`);
187
- const { event } = result;
188
- const descriptor = eventsByType.get(event.type);
189
- if (!descriptor) {
190
- attempts.push({
191
- event,
192
- failure: "unknown-event",
193
- reason: `'${event.type}' is not among the currently allowed events: ${request.events.map((candidate) => candidate.type).join(", ") || "(none)"}.`
194
- });
195
- continue;
196
- }
197
- let validatedEvent = event;
198
- if (descriptor.inputSchema) {
199
- const { type, ...payload } = event;
200
- try {
201
- validatedEvent = {
202
- ...require_events.validateSchemaSync(descriptor.inputSchema, payload),
203
- type
204
- };
205
- } catch (error) {
206
- attempts.push({
207
- event,
208
- failure: "invalid-payload",
209
- reason: `'${event.type}' payload failed validation: ${error instanceof Error ? error.message : String(error)}`
210
- });
211
- continue;
212
- }
213
- }
214
- if (options.canTake?.(validatedEvent) === false) {
215
- attempts.push({
216
- event: validatedEvent,
217
- failure: "rejected-by-guard",
218
- reason: `'${validatedEvent.type}' is not currently takeable (guard rejected it).`
219
- });
220
- continue;
221
- }
222
- return validatedEvent;
223
- }
224
- throw new DecisionExhaustedError(attempts);
225
- }
226
- //#endregion
227
- Object.defineProperty(exports, "DecisionExhaustedError", {
228
- enumerable: true,
229
- get: function() {
230
- return DecisionExhaustedError;
231
- }
232
- });
233
- Object.defineProperty(exports, "PLAN_DONE_EVENT_TYPE", {
234
- enumerable: true,
235
- get: function() {
236
- return PLAN_DONE_EVENT_TYPE;
237
- }
238
- });
239
- Object.defineProperty(exports, "advancePlanLedger", {
240
- enumerable: true,
241
- get: function() {
242
- return advancePlanLedger;
243
- }
244
- });
245
- Object.defineProperty(exports, "createDecideActor", {
246
- enumerable: true,
247
- get: function() {
248
- return createDecideActor;
249
- }
250
- });
251
- Object.defineProperty(exports, "createPlanActor", {
252
- enumerable: true,
253
- get: function() {
254
- return createPlanActor;
255
- }
256
- });
257
- Object.defineProperty(exports, "initialPlanLedger", {
258
- enumerable: true,
259
- get: function() {
260
- return initialPlanLedger;
261
- }
262
- });
263
- Object.defineProperty(exports, "isDecisionLogic", {
264
- enumerable: true,
265
- get: function() {
266
- return isDecisionLogic;
267
- }
268
- });
269
- Object.defineProperty(exports, "isPlanLogic", {
270
- enumerable: true,
271
- get: function() {
272
- return isPlanLogic;
273
- }
274
- });
275
- Object.defineProperty(exports, "renderDecisionAttempts", {
276
- enumerable: true,
277
- get: function() {
278
- return renderDecisionAttempts;
279
- }
280
- });
281
- Object.defineProperty(exports, "resolveDecision", {
282
- enumerable: true,
283
- get: function() {
284
- return resolveDecision;
285
- }
286
- });