reactive-fsm 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alejandro Alvarado
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,324 @@
1
+ # reactive-fsm
2
+
3
+ Reactive Finite State Machine for AI agent orchestration. Zero-dependency core with conditional tool gating, loop shield, and adapters for Vercel AI SDK and OpenAI SDK.
4
+
5
+ ```bash
6
+ pnpm add reactive-fsm
7
+ # o npm install reactive-fsm
8
+ ```
9
+
10
+ ## Concepts
11
+
12
+ | Concept | Role |
13
+ |---------|------|
14
+ | **FSM** | Manages states and which tool names are allowed at each state |
15
+ | **Tool Gating** | Registry of tool entries with runtime conditions and builders, filtered by gate |
16
+ | **Loop Shield** | Detects consecutive tool-call loops and signals the adapter to force-stop |
17
+ | **Adapters** | Translate the FSM into SDK-native format (Vercel AI SDK, OpenAI) |
18
+
19
+ ---
20
+
21
+ ## Quick Start
22
+
23
+ ### 1. Define your FSM
24
+
25
+ ```typescript
26
+ import { createFSM } from 'reactive-fsm'
27
+
28
+ const fsm = createFSM({
29
+ initialState: 'IDENTITY',
30
+ states: ['IDENTITY', 'BOOKING', 'PAYMENT'],
31
+ tools: {
32
+ IDENTITY: ['validate_dni'],
33
+ BOOKING: ['check_availability', 'reserve_slot'],
34
+ PAYMENT: ['process_payment'],
35
+ },
36
+ loopShield: { enabled: true, maxConsecutiveTools: 3 },
37
+ })
38
+
39
+ fsm.currentState // 'IDENTITY'
40
+ fsm.allowedTools // ['validate_dni']
41
+ fsm.transitionTo('BOOKING')
42
+ fsm.allowedTools // ['check_availability', 'reserve_slot']
43
+ ```
44
+
45
+ ### 2. Build a tool registry
46
+
47
+ ```typescript
48
+ import type { ToolEntry } from 'reactive-fsm'
49
+
50
+ interface AppCtx { contactId: string; role: 'user' | 'admin' }
51
+
52
+ const registry: ToolEntry<AppCtx>[] = [
53
+ {
54
+ name: 'validate_dni',
55
+ gates: ['IDENTITY'],
56
+ build: (ctx) => ({
57
+ description: `Validate DNI for ${ctx.contactId}`,
58
+ parameters: {},
59
+ execute: async () => ({ valid: true }),
60
+ }),
61
+ },
62
+ {
63
+ name: 'check_availability',
64
+ gates: ['BOOKING'],
65
+ build: () => ({
66
+ description: 'Check slot availability',
67
+ parameters: {},
68
+ execute: async () => ({ slots: ['10:00', '11:00'] }),
69
+ }),
70
+ },
71
+ {
72
+ name: 'reserve_slot',
73
+ gates: ['BOOKING'],
74
+ condition: (ctx) => ctx.contactId !== '',
75
+ build: () => ({
76
+ description: 'Reserve a time slot',
77
+ parameters: {},
78
+ execute: async () => ({ booked: true }),
79
+ }),
80
+ },
81
+ {
82
+ name: 'admin_panel',
83
+ gates: ['IDENTITY', 'BOOKING', 'PAYMENT'],
84
+ condition: (ctx) => ctx.role === 'admin',
85
+ build: () => ({
86
+ description: 'Access admin controls',
87
+ parameters: {},
88
+ execute: async () => ({ panel: 'open' }),
89
+ }),
90
+ },
91
+ ]
92
+ ```
93
+
94
+ ### 3. Use an adapter
95
+
96
+ #### Vercel AI SDK
97
+
98
+ ```typescript
99
+ import { createVercelAdapter } from 'reactive-fsm/adapters/vercel-ai'
100
+ import { generateText } from 'ai'
101
+ import { openai } from '@ai-sdk/openai'
102
+
103
+ const adapter = createVercelAdapter(fsm, registry, appCtx)
104
+
105
+ const response = await generateText({
106
+ model: openai('gpt-4o'),
107
+ messages: [{ role: 'user', content: 'Quiero agendar una cita' }],
108
+ ...adapter.inject(), // → { tools, prepareStep }
109
+ })
110
+ ```
111
+
112
+ #### OpenAI SDK
113
+
114
+ ```typescript
115
+ import { createOpenAIAdapter } from 'reactive-fsm/adapters/openai'
116
+ import OpenAI from 'openai'
117
+
118
+ const openai = new OpenAI()
119
+ const adapter = createOpenAIAdapter(fsm, registry, appCtx)
120
+
121
+ const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
122
+ { role: 'user', content: 'Quiero agendar una cita' },
123
+ ]
124
+
125
+ while (true) {
126
+ const { tools } = adapter.inject()
127
+
128
+ const response = await openai.chat.completions.create({
129
+ model: 'gpt-4o',
130
+ messages,
131
+ tools,
132
+ tool_choice: adapter.isLooping() ? 'none' : 'auto',
133
+ })
134
+
135
+ const msg = response.choices[0].message
136
+ messages.push(msg)
137
+
138
+ if (msg.tool_calls?.length) {
139
+ adapter.registerToolCall()
140
+
141
+ // Execute tools, push results to messages
142
+ for (const tc of msg.tool_calls) {
143
+ const result = await executeTool(tc.function.name, tc.function.arguments)
144
+ messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result) })
145
+ }
146
+
147
+ // If a tool mutated the DB state, refresh the gate
148
+ // adapter.refreshGate('BOOKING')
149
+ continue
150
+ }
151
+
152
+ console.log(msg.content) // final response
153
+ break
154
+ }
155
+ ```
156
+
157
+ ---
158
+
159
+ ## Real-World Patterns
160
+
161
+ ### Booking Funnel (3 gates)
162
+
163
+ ```typescript
164
+ const bookingFSM = createFSM({
165
+ initialState: 'GREETING',
166
+ states: ['GREETING', 'IDENTITY', 'SCHEDULING', 'CONFIRMED'],
167
+ tools: {
168
+ GREETING: ['greet', 'show_catalog'],
169
+ IDENTITY: ['collect_name', 'collect_dni', 'show_catalog'],
170
+ SCHEDULING: ['check_slots', 'book_appointment'],
171
+ CONFIRMED: ['send_confirmation'],
172
+ },
173
+ loopShield: { enabled: true, maxConsecutiveTools: 3 },
174
+ })
175
+
176
+ // Flow: GREETING → user shows interest → IDENTITY → collects data → SCHEDULING → booked → CONFIRMED
177
+ ```
178
+
179
+ ### Payment Gate (block everything except payment)
180
+
181
+ ```typescript
182
+ const paymentFSM = createFSM({
183
+ initialState: 'SHOPPING',
184
+ states: ['SHOPPING', 'PAYMENT', 'CONFIRMED'],
185
+ tools: {
186
+ SHOPPING: ['browse', 'add_to_cart', 'checkout'],
187
+ PAYMENT: ['process_payment', 'cancel_order'], // only these two
188
+ CONFIRMED: ['send_receipt'],
189
+ },
190
+ })
191
+
192
+ // When entering PAYMENT, the adapter removes all shopping tools.
193
+ // The LLM can ONLY call process_payment or cancel_order.
194
+ ```
195
+
196
+ ### Conditional Tool: Admin vs User
197
+
198
+ ```typescript
199
+ const registry: ToolEntry<{ role: 'user' | 'admin' }>[] = [
200
+ { name: 'view_profile', gates: ['DASHBOARD'], build: () => ({ /* ... */ }) },
201
+ {
202
+ name: 'delete_user',
203
+ gates: ['DASHBOARD'],
204
+ condition: (ctx) => ctx.role === 'admin',
205
+ build: () => ({ /* ... */ }),
206
+ },
207
+ ]
208
+
209
+ // Regular user → only view_profile
210
+ // Admin → view_profile + delete_user
211
+ ```
212
+
213
+ ---
214
+
215
+ ## API Reference
216
+
217
+ ### `createFSM(config)`
218
+
219
+ ```typescript
220
+ interface FSMConfig {
221
+ initialState: string
222
+ states: string[]
223
+ tools: Record<string, string[]> // state → tool names
224
+ loopShield?: LoopShieldConfig
225
+ }
226
+
227
+ interface FSMInstance {
228
+ readonly currentState: string
229
+ readonly allowedTools: string[]
230
+ readonly isLooping: boolean
231
+ transitionTo(state: string): void
232
+ }
233
+ ```
234
+
235
+ ### `buildToolsForGate(gate, ctx, registry)`
236
+
237
+ ```typescript
238
+ interface ToolEntry<TContext = any> {
239
+ name: string
240
+ gates: string[]
241
+ condition?: (ctx: TContext) => boolean // optional runtime filter
242
+ build: (ctx: TContext) => unknown // returns the tool definition
243
+ }
244
+
245
+ function buildToolsForGate<TContext>(
246
+ gate: string,
247
+ ctx: TContext,
248
+ registry: ToolEntry<TContext>[]
249
+ ): Record<string, unknown>
250
+ ```
251
+
252
+ ### `createVercelAdapter(fsm, registry, context)`
253
+
254
+ ```typescript
255
+ const adapter = createVercelAdapter(fsm, registry, context)
256
+
257
+ const { tools, prepareStep } = adapter.inject()
258
+ adapter.refreshGate('PAYMENT') // external gate change (e.g., after DB mutation)
259
+ ```
260
+
261
+ `prepareStep` automatically handles loop shield detection by counting consecutive tool steps from the history. When `maxConsecutiveTools` is exceeded, it returns `{ toolChoice: 'none' }`.
262
+
263
+ ### `createOpenAIAdapter(fsm, registry, context)`
264
+
265
+ ```typescript
266
+ const adapter = createOpenAIAdapter(fsm, registry, context)
267
+
268
+ const { tools } = adapter.inject() // → { tools: OpenAI-formatted array }
269
+ adapter.isLooping() // → boolean (check before each API call)
270
+ adapter.registerToolCall() // → track tool call for loop shield
271
+ adapter.resetLoopShield() // → reset counter
272
+ adapter.refreshGate('PAYMENT') // → external gate change
273
+ ```
274
+
275
+ Since the OpenAI SDK is stateless, the consumer controls the orchestration loop. Use `isLooping()` to decide `tool_choice` and `registerToolCall()` after each API call that invoked tools.
276
+
277
+ ### `createLoopShield(config)`
278
+
279
+ ```typescript
280
+ interface LoopShieldConfig {
281
+ enabled: boolean
282
+ maxConsecutiveTools: number
283
+ }
284
+
285
+ const shield = createLoopShield({ enabled: true, maxConsecutiveTools: 3 })
286
+ shield.registerToolCall()
287
+ shield.isLooping() // boolean
288
+ shield.reset()
289
+ ```
290
+
291
+ ---
292
+
293
+ ## Architecture
294
+
295
+ ```
296
+ src/
297
+ ├── core/
298
+ │ ├── machine.ts # createFSM() — state management
299
+ │ ├── tool-gating.ts # buildToolsForGate() — conditional tool injection
300
+ │ └── loop-shield.ts # createLoopShield() — cognitive loop detection
301
+ ├── adapters/
302
+ │ ├── vercel-ai.ts # createVercelAdapter() — Vercel AI SDK
303
+ │ └── openai.ts # createOpenAIAdapter() — OpenAI SDK
304
+ └── index.ts
305
+ ```
306
+
307
+ - **Core has zero npm dependencies.** Only TypeScript types.
308
+ - **Adapters are optional.** `ai` and `openai` are optional peerDependencies.
309
+ - **`ToolEntry<TContext>`** is fully generic — you define your own context shape.
310
+
311
+ ---
312
+
313
+ ## Loop Shield
314
+
315
+ The loop shield prevents LLMs from entering infinite tool-calling loops.
316
+
317
+ - **Vercel adapter**: `prepareStep` counts consecutive tool steps from history and forces `toolChoice: 'none'` when `maxConsecutiveTools` is exceeded.
318
+ - **OpenAI adapter**: the consumer checks `isLooping()` before each API call and sets `tool_choice: 'none'` when it returns `true`. Calls `registerToolCall()` after each tool-invoking response.
319
+
320
+ ---
321
+
322
+ ## License
323
+
324
+ MIT
@@ -0,0 +1,14 @@
1
+ import type { FSMInstance } from '../core/machine';
2
+ import { type ToolEntry } from '../core/tool-gating';
3
+ export interface OpenAIInjectResult {
4
+ tools: unknown[];
5
+ }
6
+ export interface OpenAIAdapter<TContext = any> {
7
+ inject(): OpenAIInjectResult;
8
+ isLooping(): boolean;
9
+ registerToolCall(): void;
10
+ resetLoopShield(): void;
11
+ refreshGate(state: string): void;
12
+ }
13
+ export declare function createOpenAIAdapter<TContext = any>(fsm: FSMInstance, registry: ToolEntry<TContext>[], context: TContext): OpenAIAdapter<TContext>;
14
+ //# sourceMappingURL=openai.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../src/adapters/openai.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAqB,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAExE,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,OAAO,EAAE,CAAC;CAClB;AAED,MAAM,WAAW,aAAa,CAAC,QAAQ,GAAG,GAAG;IAC3C,MAAM,IAAI,kBAAkB,CAAC;IAC7B,SAAS,IAAI,OAAO,CAAC;IACrB,gBAAgB,IAAI,IAAI,CAAC;IACzB,eAAe,IAAI,IAAI,CAAC;IACxB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC;AAED,wBAAgB,mBAAmB,CAAC,QAAQ,GAAG,GAAG,EAChD,GAAG,EAAE,WAAW,EAChB,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAC,EAAE,EAC/B,OAAO,EAAE,QAAQ,GAChB,aAAa,CAAC,QAAQ,CAAC,CAuBzB"}
@@ -0,0 +1,22 @@
1
+ import { buildToolsForGate } from '../core/tool-gating';
2
+ export function createOpenAIAdapter(fsm, registry, context) {
3
+ return {
4
+ inject() {
5
+ const toolMap = buildToolsForGate(fsm.currentState, context, registry);
6
+ return { tools: Object.values(toolMap) };
7
+ },
8
+ isLooping() {
9
+ return fsm.isLooping;
10
+ },
11
+ registerToolCall() {
12
+ fsm._registerToolCall();
13
+ },
14
+ resetLoopShield() {
15
+ fsm._resetLoopShield();
16
+ },
17
+ refreshGate(state) {
18
+ fsm._setState(state);
19
+ },
20
+ };
21
+ }
22
+ //# sourceMappingURL=openai.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai.js","sourceRoot":"","sources":["../../src/adapters/openai.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAkB,MAAM,qBAAqB,CAAC;AAcxE,MAAM,UAAU,mBAAmB,CACjC,GAAgB,EAChB,QAA+B,EAC/B,OAAiB;IAEjB,OAAO;QACL,MAAM;YACJ,MAAM,OAAO,GAAG,iBAAiB,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;YACvE,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;QAC3C,CAAC;QAED,SAAS;YACP,OAAO,GAAG,CAAC,SAAS,CAAC;QACvB,CAAC;QAED,gBAAgB;YACd,GAAG,CAAC,iBAAiB,EAAE,CAAC;QAC1B,CAAC;QAED,eAAe;YACb,GAAG,CAAC,gBAAgB,EAAE,CAAC;QACzB,CAAC;QAED,WAAW,CAAC,KAAa;YACvB,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,28 @@
1
+ import type { FSMInstance } from '../core/machine';
2
+ import { type ToolEntry } from '../core/tool-gating';
3
+ export interface VercelStepInfo {
4
+ toolCalls?: Array<{
5
+ toolName: string;
6
+ args?: unknown;
7
+ }>;
8
+ toolResults?: Array<{
9
+ toolName: string;
10
+ result?: unknown;
11
+ }>;
12
+ }
13
+ export interface VercelPrepareStepParams {
14
+ steps: VercelStepInfo[];
15
+ stepNumber: number;
16
+ }
17
+ export interface VercelInjectResult {
18
+ tools: Record<string, unknown>;
19
+ prepareStep?: (params: VercelPrepareStepParams) => Promise<{
20
+ toolChoice?: 'none';
21
+ } | Record<string, never>>;
22
+ }
23
+ export interface VercelAdapter<TContext = any> {
24
+ inject(): VercelInjectResult;
25
+ refreshGate(state: string): void;
26
+ }
27
+ export declare function createVercelAdapter<TContext = any>(fsm: FSMInstance, registry: ToolEntry<TContext>[], context: TContext): VercelAdapter<TContext>;
28
+ //# sourceMappingURL=vercel-ai.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercel-ai.d.ts","sourceRoot":"","sources":["../../src/adapters/vercel-ai.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAqB,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAExE,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IACxD,WAAW,CAAC,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAC7D;AAED,MAAM,WAAW,uBAAuB;IACtC,KAAK,EAAE,cAAc,EAAE,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,uBAAuB,KAAK,OAAO,CAAC;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;CAC7G;AAED,MAAM,WAAW,aAAa,CAAC,QAAQ,GAAG,GAAG;IAC3C,MAAM,IAAI,kBAAkB,CAAC;IAC7B,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC;AAiBD,wBAAgB,mBAAmB,CAAC,QAAQ,GAAG,GAAG,EAChD,GAAG,EAAE,WAAW,EAChB,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAC,EAAE,EAC/B,OAAO,EAAE,QAAQ,GAChB,aAAa,CAAC,QAAQ,CAAC,CA4CzB"}
@@ -0,0 +1,50 @@
1
+ import { buildToolsForGate } from '../core/tool-gating';
2
+ function syncTools(target, gate, ctx, registry) {
3
+ const fresh = buildToolsForGate(gate, ctx, registry);
4
+ for (const key of Object.keys(target)) {
5
+ delete target[key];
6
+ }
7
+ for (const [key, value] of Object.entries(fresh)) {
8
+ target[key] = value;
9
+ }
10
+ }
11
+ export function createVercelAdapter(fsm, registry, context) {
12
+ const tools = {};
13
+ let currentGate = null;
14
+ return {
15
+ inject() {
16
+ currentGate = fsm.currentState;
17
+ syncTools(tools, currentGate, context, registry);
18
+ return {
19
+ tools,
20
+ prepareStep: async ({ steps }) => {
21
+ let consecutiveToolSteps = 0;
22
+ for (let i = steps.length - 1; i >= 0; i--) {
23
+ if ((steps[i].toolCalls?.length ?? 0) > 0) {
24
+ consecutiveToolSteps++;
25
+ }
26
+ else {
27
+ break;
28
+ }
29
+ }
30
+ fsm._resetLoopShield();
31
+ for (let i = 0; i < consecutiveToolSteps; i++) {
32
+ fsm._registerToolCall();
33
+ }
34
+ if (fsm.isLooping) {
35
+ return { toolChoice: 'none' };
36
+ }
37
+ if (fsm.currentState !== currentGate) {
38
+ currentGate = fsm.currentState;
39
+ syncTools(tools, currentGate, context, registry);
40
+ }
41
+ return {};
42
+ },
43
+ };
44
+ },
45
+ refreshGate(state) {
46
+ fsm._setState(state);
47
+ },
48
+ };
49
+ }
50
+ //# sourceMappingURL=vercel-ai.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercel-ai.js","sourceRoot":"","sources":["../../src/adapters/vercel-ai.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAkB,MAAM,qBAAqB,CAAC;AAsBxE,SAAS,SAAS,CAChB,MAA+B,EAC/B,IAAY,EACZ,GAAY,EACZ,QAAqB;IAErB,MAAM,KAAK,GAAG,iBAAiB,CAAC,IAAI,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;IACrD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QACtC,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAA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AAE,OAAO,EAAE,QAAQ,CAAC,CAAC;oBACnD,CAAC;oBAED,OAAO,EAAE,CAAC;gBACZ,CAAC;aACF,CAAC;QACJ,CAAC;QAED,WAAW,CAAC,KAAa;YACvB,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ export interface LoopShieldConfig {
2
+ enabled: boolean;
3
+ maxConsecutiveTools: number;
4
+ }
5
+ export interface LoopShieldInstance {
6
+ registerToolCall(): void;
7
+ isLooping(): boolean;
8
+ reset(): void;
9
+ }
10
+ export declare function createLoopShield(config: LoopShieldConfig): LoopShieldInstance;
11
+ //# sourceMappingURL=loop-shield.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop-shield.d.ts","sourceRoot":"","sources":["../../src/core/loop-shield.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,kBAAkB;IACjC,gBAAgB,IAAI,IAAI,CAAC;IACzB,SAAS,IAAI,OAAO,CAAC;IACrB,KAAK,IAAI,IAAI,CAAC;CACf;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,kBAAkB,CAkB7E"}
@@ -0,0 +1,19 @@
1
+ export function createLoopShield(config) {
2
+ let consecutiveToolCalls = 0;
3
+ return {
4
+ registerToolCall() {
5
+ if (!config.enabled)
6
+ return;
7
+ consecutiveToolCalls++;
8
+ },
9
+ isLooping() {
10
+ if (!config.enabled)
11
+ return false;
12
+ return consecutiveToolCalls >= config.maxConsecutiveTools;
13
+ },
14
+ reset() {
15
+ consecutiveToolCalls = 0;
16
+ },
17
+ };
18
+ }
19
+ //# sourceMappingURL=loop-shield.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop-shield.js","sourceRoot":"","sources":["../../src/core/loop-shield.ts"],"names":[],"mappings":"AAWA,MAAM,UAAU,gBAAgB,CAAC,MAAwB;IACvD,IAAI,oBAAoB,GAAG,CAAC,CAAC;IAE7B,OAAO;QACL,gBAAgB;YACd,IAAI,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO;YAC5B,oBAAoB,EAAE,CAAC;QACzB,CAAC;QAED,SAAS;YACP,IAAI,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO,KAAK,CAAC;YAClC,OAAO,oBAAoB,IAAI,MAAM,CAAC,mBAAmB,CAAC;QAC5D,CAAC;QAED,KAAK;YACH,oBAAoB,GAAG,CAAC,CAAC;QAC3B,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { type LoopShieldConfig } from './loop-shield';
2
+ export interface FSMConfig {
3
+ initialState: string;
4
+ states: string[];
5
+ tools: Record<string, string[]>;
6
+ loopShield?: LoopShieldConfig;
7
+ }
8
+ export interface FSMInstance {
9
+ readonly currentState: string;
10
+ readonly allowedTools: string[];
11
+ readonly isLooping: boolean;
12
+ transitionTo(state: string): void;
13
+ _registerToolCall(): void;
14
+ _resetLoopShield(): void;
15
+ _setState(state: string): void;
16
+ }
17
+ export declare function createFSM(config: FSMConfig): FSMInstance;
18
+ //# sourceMappingURL=machine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machine.d.ts","sourceRoot":"","sources":["../../src/core/machine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAExE,MAAM,WAAW,SAAS;IACxB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAChC,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC/B;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,YAAY,EAAE,MAAM,EAAE,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,iBAAiB,IAAI,IAAI,CAAC;IAC1B,gBAAgB,IAAI,IAAI,CAAC;IACzB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS,GAAG,WAAW,CAoDxD"}
@@ -0,0 +1,42 @@
1
+ import { createLoopShield } from './loop-shield';
2
+ export function createFSM(config) {
3
+ const validStates = new Set(config.states);
4
+ if (!validStates.has(config.initialState)) {
5
+ throw new Error(`Initial state "${config.initialState}" is not in the states list`);
6
+ }
7
+ let _currentState = config.initialState;
8
+ const shield = createLoopShield(config.loopShield ?? { enabled: false, maxConsecutiveTools: 3 });
9
+ function getAllowedTools() {
10
+ return config.tools[_currentState] ?? [];
11
+ }
12
+ return {
13
+ get currentState() {
14
+ return _currentState;
15
+ },
16
+ get allowedTools() {
17
+ return getAllowedTools();
18
+ },
19
+ get isLooping() {
20
+ return shield.isLooping();
21
+ },
22
+ transitionTo(state) {
23
+ if (!validStates.has(state)) {
24
+ throw new Error(`Invalid state "${state}". Valid states: ${config.states.join(', ')}`);
25
+ }
26
+ _currentState = state;
27
+ },
28
+ _registerToolCall() {
29
+ shield.registerToolCall();
30
+ },
31
+ _resetLoopShield() {
32
+ shield.reset();
33
+ },
34
+ _setState(state) {
35
+ if (!validStates.has(state)) {
36
+ throw new Error(`Invalid state "${state}". Valid states: ${config.states.join(', ')}`);
37
+ }
38
+ _currentState = state;
39
+ },
40
+ };
41
+ }
42
+ //# sourceMappingURL=machine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machine.js","sourceRoot":"","sources":["../../src/core/machine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAyB,MAAM,eAAe,CAAC;AAmBxE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M,IAAI,KAAK,CAAC,kBAAkB,KAAK,oBAAoB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzF,CAAC;YACD,aAAa,GAAG,KAAK,CAAC;QACxB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,8 @@
1
+ export interface ToolEntry<TContext = any> {
2
+ name: string;
3
+ gates: string[];
4
+ condition?: (ctx: TContext) => boolean;
5
+ build: (ctx: TContext) => unknown;
6
+ }
7
+ export declare function buildToolsForGate<TContext = any>(gate: string, ctx: TContext, registry: ToolEntry<TContext>[]): Record<string, unknown>;
8
+ //# sourceMappingURL=tool-gating.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-gating.d.ts","sourceRoot":"","sources":["../../src/core/tool-gating.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,SAAS,CAAC,QAAQ,GAAG,GAAG;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,QAAQ,KAAK,OAAO,CAAC;IACvC,KAAK,EAAE,CAAC,GAAG,EAAE,QAAQ,KAAK,OAAO,CAAC;CACnC;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,GAAG,GAAG,EAC9C,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,QAAQ,EACb,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAC,EAAE,GAC9B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAOzB"}
@@ -0,0 +1,7 @@
1
+ export function buildToolsForGate(gate, ctx, registry) {
2
+ return Object.fromEntries(registry
3
+ .filter((entry) => entry.gates.includes(gate))
4
+ .filter((entry) => entry.condition === undefined || entry.condition(ctx))
5
+ .map((entry) => [entry.name, entry.build(ctx)]));
6
+ }
7
+ //# sourceMappingURL=tool-gating.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-gating.js","sourceRoot":"","sources":["../../src/core/tool-gating.ts"],"names":[],"mappings":"AAOA,MAAM,UAAU,iBAAiB,CAC/B,IAAY,EACZ,GAAa,EACb,QAA+B;IAE/B,OAAO,MAAM,CAAC,WAAW,CACvB,QAAQ;SACL,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;SAC7C,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,KAAK,SAAS,IAAI,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;SACxE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAClD,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ export { createFSM } from './core/machine';
2
+ export type { FSMConfig, FSMInstance } from './core/machine';
3
+ export { buildToolsForGate } from './core/tool-gating';
4
+ export type { ToolEntry } from './core/tool-gating';
5
+ export { createLoopShield } from './core/loop-shield';
6
+ export type { LoopShieldConfig, LoopShieldInstance } from './core/loop-shield';
7
+ export { createVercelAdapter } from './adapters/vercel-ai';
8
+ export type { VercelAdapter, VercelInjectResult, VercelStepInfo, VercelPrepareStepParams, } from './adapters/vercel-ai';
9
+ export { createOpenAIAdapter } from './adapters/openai';
10
+ export type { OpenAIAdapter, OpenAIInjectResult, } from './adapters/openai';
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,YAAY,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE/E,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,YAAY,EACV,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,uBAAuB,GACxB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,YAAY,EACV,aAAa,EACb,kBAAkB,GACnB,MAAM,mBAAmB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { createFSM } from './core/machine';
2
+ export { buildToolsForGate } from './core/tool-gating';
3
+ export { createLoopShield } from './core/loop-shield';
4
+ export { createVercelAdapter } from './adapters/vercel-ai';
5
+ export { createOpenAIAdapter } from './adapters/openai';
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAG3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAGvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAQ3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "reactive-fsm",
3
+ "version": "1.0.0",
4
+ "description": "Reactive Finite State Machine for AI agent orchestration — zero dependencies core, conditional tool gating, loop shield, adapters for Vercel AI SDK and OpenAI SDK",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./adapters/vercel-ai": {
14
+ "types": "./dist/adapters/vercel-ai.d.ts",
15
+ "import": "./dist/adapters/vercel-ai.js"
16
+ },
17
+ "./adapters/openai": {
18
+ "types": "./dist/adapters/openai.d.ts",
19
+ "import": "./dist/adapters/openai.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "keywords": [
28
+ "fsm",
29
+ "finite-state-machine",
30
+ "ai-agents",
31
+ "vercel-ai-sdk",
32
+ "openai",
33
+ "tool-gating"
34
+ ],
35
+ "author": "Alejandro Alvarado <roddcode.dev@gmail.com>",
36
+ "license": "MIT",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/roddcode/reactive-fsm"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/roddcode/reactive-fsm/issues"
43
+ },
44
+ "homepage": "https://github.com/roddcode/reactive-fsm#readme",
45
+ "engines": {
46
+ "node": ">=18"
47
+ },
48
+ "devDependencies": {
49
+ "tsx": "^4.22.4",
50
+ "typescript": "^5.7.0",
51
+ "vitest": "^4.1.0"
52
+ },
53
+ "peerDependencies": {
54
+ "ai": "^4.0.0",
55
+ "openai": "^4.0.0"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "ai": {
59
+ "optional": true
60
+ },
61
+ "openai": {
62
+ "optional": true
63
+ }
64
+ },
65
+ "scripts": {
66
+ "build": "tsc",
67
+ "test": "vitest run",
68
+ "test:watch": "vitest"
69
+ }
70
+ }