@falai/agent 0.4.0 → 0.5.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.
Files changed (285) hide show
  1. package/README.md +21 -74
  2. package/dist/cjs/core/Agent.d.ts +22 -29
  3. package/dist/cjs/core/Agent.d.ts.map +1 -1
  4. package/dist/cjs/core/Agent.js +465 -275
  5. package/dist/cjs/core/Agent.js.map +1 -1
  6. package/dist/cjs/core/Events.d.ts +10 -1
  7. package/dist/cjs/core/Events.d.ts.map +1 -1
  8. package/dist/cjs/core/Events.js +3 -2
  9. package/dist/cjs/core/Events.js.map +1 -1
  10. package/dist/cjs/core/PersistenceManager.d.ts +19 -0
  11. package/dist/cjs/core/PersistenceManager.d.ts.map +1 -1
  12. package/dist/cjs/core/PersistenceManager.js +57 -0
  13. package/dist/cjs/core/PersistenceManager.js.map +1 -1
  14. package/dist/cjs/core/PromptComposer.d.ts +24 -0
  15. package/dist/cjs/core/PromptComposer.d.ts.map +1 -0
  16. package/dist/cjs/core/PromptComposer.js +127 -0
  17. package/dist/cjs/core/PromptComposer.js.map +1 -0
  18. package/dist/cjs/core/ResponseEngine.d.ts +19 -0
  19. package/dist/cjs/core/ResponseEngine.d.ts.map +1 -0
  20. package/dist/cjs/core/ResponseEngine.js +51 -0
  21. package/dist/cjs/core/ResponseEngine.js.map +1 -0
  22. package/dist/cjs/core/Route.d.ts +18 -12
  23. package/dist/cjs/core/Route.d.ts.map +1 -1
  24. package/dist/cjs/core/Route.js +15 -9
  25. package/dist/cjs/core/Route.js.map +1 -1
  26. package/dist/cjs/core/RoutingEngine.d.ts +38 -0
  27. package/dist/cjs/core/RoutingEngine.d.ts.map +1 -0
  28. package/dist/cjs/core/RoutingEngine.js +110 -0
  29. package/dist/cjs/core/RoutingEngine.js.map +1 -0
  30. package/dist/cjs/core/State.d.ts +15 -4
  31. package/dist/cjs/core/State.d.ts.map +1 -1
  32. package/dist/cjs/core/State.js +21 -2
  33. package/dist/cjs/core/State.js.map +1 -1
  34. package/dist/cjs/core/ToolExecutor.d.ts +29 -0
  35. package/dist/cjs/core/ToolExecutor.d.ts.map +1 -0
  36. package/dist/cjs/core/ToolExecutor.js +73 -0
  37. package/dist/cjs/core/ToolExecutor.js.map +1 -0
  38. package/dist/cjs/core/Transition.d.ts +5 -5
  39. package/dist/cjs/core/Transition.d.ts.map +1 -1
  40. package/dist/cjs/core/Transition.js.map +1 -1
  41. package/dist/cjs/index.d.ts +6 -8
  42. package/dist/cjs/index.d.ts.map +1 -1
  43. package/dist/cjs/index.js +8 -10
  44. package/dist/cjs/index.js.map +1 -1
  45. package/dist/cjs/providers/AnthropicProvider.d.ts.map +1 -1
  46. package/dist/cjs/providers/AnthropicProvider.js +10 -13
  47. package/dist/cjs/providers/AnthropicProvider.js.map +1 -1
  48. package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
  49. package/dist/cjs/providers/GeminiProvider.js +12 -8
  50. package/dist/cjs/providers/GeminiProvider.js.map +1 -1
  51. package/dist/cjs/providers/OpenAIProvider.d.ts.map +1 -1
  52. package/dist/cjs/providers/OpenAIProvider.js +10 -53
  53. package/dist/cjs/providers/OpenAIProvider.js.map +1 -1
  54. package/dist/cjs/providers/OpenRouterProvider.d.ts.map +1 -1
  55. package/dist/cjs/providers/OpenRouterProvider.js +10 -53
  56. package/dist/cjs/providers/OpenRouterProvider.js.map +1 -1
  57. package/dist/cjs/types/agent.d.ts +13 -9
  58. package/dist/cjs/types/agent.d.ts.map +1 -1
  59. package/dist/cjs/types/ai.d.ts +8 -2
  60. package/dist/cjs/types/ai.d.ts.map +1 -1
  61. package/dist/cjs/types/history.d.ts +8 -0
  62. package/dist/cjs/types/history.d.ts.map +1 -1
  63. package/dist/cjs/types/index.d.ts +0 -3
  64. package/dist/cjs/types/index.d.ts.map +1 -1
  65. package/dist/cjs/types/index.js +1 -3
  66. package/dist/cjs/types/index.js.map +1 -1
  67. package/dist/cjs/types/route.d.ts +39 -4
  68. package/dist/cjs/types/route.d.ts.map +1 -1
  69. package/dist/cjs/types/routing.d.ts +16 -0
  70. package/dist/cjs/types/routing.d.ts.map +1 -0
  71. package/dist/cjs/types/routing.js +3 -0
  72. package/dist/cjs/types/routing.js.map +1 -0
  73. package/dist/cjs/types/schema.d.ts +22 -0
  74. package/dist/cjs/types/schema.d.ts.map +1 -0
  75. package/dist/cjs/types/schema.js +3 -0
  76. package/dist/cjs/types/schema.js.map +1 -0
  77. package/dist/cjs/types/session.d.ts +72 -0
  78. package/dist/cjs/types/session.d.ts.map +1 -0
  79. package/dist/cjs/types/session.js +140 -0
  80. package/dist/cjs/types/session.js.map +1 -0
  81. package/dist/cjs/types/tool.d.ts +11 -5
  82. package/dist/cjs/types/tool.d.ts.map +1 -1
  83. package/dist/cjs/utils/id.d.ts +0 -5
  84. package/dist/cjs/utils/id.d.ts.map +1 -1
  85. package/dist/cjs/utils/id.js +0 -10
  86. package/dist/cjs/utils/id.js.map +1 -1
  87. package/dist/cjs/utils/schema.d.ts +17 -0
  88. package/dist/cjs/utils/schema.d.ts.map +1 -0
  89. package/dist/cjs/utils/schema.js +32 -0
  90. package/dist/cjs/utils/schema.js.map +1 -0
  91. package/dist/core/Agent.d.ts +22 -29
  92. package/dist/core/Agent.d.ts.map +1 -1
  93. package/dist/core/Agent.js +465 -275
  94. package/dist/core/Agent.js.map +1 -1
  95. package/dist/core/Events.d.ts +10 -1
  96. package/dist/core/Events.d.ts.map +1 -1
  97. package/dist/core/Events.js +3 -2
  98. package/dist/core/Events.js.map +1 -1
  99. package/dist/core/PersistenceManager.d.ts +19 -0
  100. package/dist/core/PersistenceManager.d.ts.map +1 -1
  101. package/dist/core/PersistenceManager.js +57 -0
  102. package/dist/core/PersistenceManager.js.map +1 -1
  103. package/dist/core/PromptComposer.d.ts +24 -0
  104. package/dist/core/PromptComposer.d.ts.map +1 -0
  105. package/dist/core/PromptComposer.js +123 -0
  106. package/dist/core/PromptComposer.js.map +1 -0
  107. package/dist/core/ResponseEngine.d.ts +19 -0
  108. package/dist/core/ResponseEngine.d.ts.map +1 -0
  109. package/dist/core/ResponseEngine.js +47 -0
  110. package/dist/core/ResponseEngine.js.map +1 -0
  111. package/dist/core/Route.d.ts +18 -12
  112. package/dist/core/Route.d.ts.map +1 -1
  113. package/dist/core/Route.js +15 -9
  114. package/dist/core/Route.js.map +1 -1
  115. package/dist/core/RoutingEngine.d.ts +38 -0
  116. package/dist/core/RoutingEngine.d.ts.map +1 -0
  117. package/dist/core/RoutingEngine.js +106 -0
  118. package/dist/core/RoutingEngine.js.map +1 -0
  119. package/dist/core/State.d.ts +15 -4
  120. package/dist/core/State.d.ts.map +1 -1
  121. package/dist/core/State.js +21 -2
  122. package/dist/core/State.js.map +1 -1
  123. package/dist/core/ToolExecutor.d.ts +29 -0
  124. package/dist/core/ToolExecutor.d.ts.map +1 -0
  125. package/dist/core/ToolExecutor.js +69 -0
  126. package/dist/core/ToolExecutor.js.map +1 -0
  127. package/dist/core/Transition.d.ts +5 -5
  128. package/dist/core/Transition.d.ts.map +1 -1
  129. package/dist/core/Transition.js.map +1 -1
  130. package/dist/index.d.ts +6 -8
  131. package/dist/index.d.ts.map +1 -1
  132. package/dist/index.js +3 -5
  133. package/dist/index.js.map +1 -1
  134. package/dist/providers/AnthropicProvider.d.ts.map +1 -1
  135. package/dist/providers/AnthropicProvider.js +10 -13
  136. package/dist/providers/AnthropicProvider.js.map +1 -1
  137. package/dist/providers/GeminiProvider.d.ts.map +1 -1
  138. package/dist/providers/GeminiProvider.js +12 -8
  139. package/dist/providers/GeminiProvider.js.map +1 -1
  140. package/dist/providers/OpenAIProvider.d.ts.map +1 -1
  141. package/dist/providers/OpenAIProvider.js +10 -53
  142. package/dist/providers/OpenAIProvider.js.map +1 -1
  143. package/dist/providers/OpenRouterProvider.d.ts.map +1 -1
  144. package/dist/providers/OpenRouterProvider.js +10 -53
  145. package/dist/providers/OpenRouterProvider.js.map +1 -1
  146. package/dist/types/agent.d.ts +13 -9
  147. package/dist/types/agent.d.ts.map +1 -1
  148. package/dist/types/ai.d.ts +8 -2
  149. package/dist/types/ai.d.ts.map +1 -1
  150. package/dist/types/history.d.ts +8 -0
  151. package/dist/types/history.d.ts.map +1 -1
  152. package/dist/types/index.d.ts +0 -3
  153. package/dist/types/index.d.ts.map +1 -1
  154. package/dist/types/index.js +0 -1
  155. package/dist/types/index.js.map +1 -1
  156. package/dist/types/route.d.ts +39 -4
  157. package/dist/types/route.d.ts.map +1 -1
  158. package/dist/types/routing.d.ts +16 -0
  159. package/dist/types/routing.d.ts.map +1 -0
  160. package/dist/types/routing.js +2 -0
  161. package/dist/types/routing.js.map +1 -0
  162. package/dist/types/schema.d.ts +22 -0
  163. package/dist/types/schema.d.ts.map +1 -0
  164. package/dist/types/schema.js +2 -0
  165. package/dist/types/schema.js.map +1 -0
  166. package/dist/types/session.d.ts +72 -0
  167. package/dist/types/session.d.ts.map +1 -0
  168. package/dist/types/session.js +132 -0
  169. package/dist/types/session.js.map +1 -0
  170. package/dist/types/tool.d.ts +11 -5
  171. package/dist/types/tool.d.ts.map +1 -1
  172. package/dist/utils/id.d.ts +0 -5
  173. package/dist/utils/id.d.ts.map +1 -1
  174. package/dist/utils/id.js +0 -9
  175. package/dist/utils/id.js.map +1 -1
  176. package/dist/utils/schema.d.ts +17 -0
  177. package/dist/utils/schema.d.ts.map +1 -0
  178. package/dist/utils/schema.js +27 -0
  179. package/dist/utils/schema.js.map +1 -0
  180. package/docs/ADAPTERS.md +83 -3
  181. package/docs/API_REFERENCE.md +95 -104
  182. package/docs/ARCHITECTURE.md +284 -286
  183. package/docs/CONSTRUCTOR_OPTIONS.md +192 -135
  184. package/docs/CONTEXT_MANAGEMENT.md +311 -28
  185. package/docs/CONTRIBUTING.md +1 -1
  186. package/docs/DOMAINS.md +61 -0
  187. package/docs/GETTING_STARTED.md +177 -88
  188. package/docs/PERSISTENCE.md +170 -23
  189. package/docs/README.md +7 -10
  190. package/examples/business-onboarding.ts +21 -9
  191. package/examples/company-qna-agent.ts +508 -0
  192. package/examples/declarative-agent.ts +143 -26
  193. package/examples/domain-scoping.ts +31 -10
  194. package/examples/extracted-data-modification.ts +415 -0
  195. package/examples/healthcare-agent.ts +194 -90
  196. package/examples/openai-agent.ts +67 -25
  197. package/examples/opensearch-persistence.ts +455 -151
  198. package/examples/persistent-onboarding.ts +162 -96
  199. package/examples/prisma-persistence.ts +371 -125
  200. package/examples/redis-persistence.ts +393 -23
  201. package/examples/rules-prohibitions.ts +32 -11
  202. package/examples/streaming-agent.ts +61 -13
  203. package/examples/travel-agent.ts +266 -133
  204. package/package.json +1 -1
  205. package/src/core/Agent.ts +679 -332
  206. package/src/core/Events.ts +12 -2
  207. package/src/core/PersistenceManager.ts +83 -0
  208. package/src/core/PromptComposer.ts +143 -0
  209. package/src/core/ResponseEngine.ts +82 -0
  210. package/src/core/Route.ts +32 -17
  211. package/src/core/RoutingEngine.ts +165 -0
  212. package/src/core/State.ts +55 -15
  213. package/src/core/ToolExecutor.ts +117 -0
  214. package/src/core/Transition.ts +5 -5
  215. package/src/index.ts +12 -21
  216. package/src/providers/AnthropicProvider.ts +10 -13
  217. package/src/providers/GeminiProvider.ts +12 -8
  218. package/src/providers/OpenAIProvider.ts +10 -56
  219. package/src/providers/OpenRouterProvider.ts +10 -56
  220. package/src/types/agent.ts +16 -10
  221. package/src/types/ai.ts +6 -2
  222. package/src/types/history.ts +8 -0
  223. package/src/types/index.ts +0 -11
  224. package/src/types/route.ts +41 -5
  225. package/src/types/routing.ts +18 -0
  226. package/src/types/schema.ts +23 -0
  227. package/src/types/session.ts +207 -0
  228. package/src/types/tool.ts +29 -7
  229. package/src/utils/id.ts +0 -10
  230. package/src/utils/schema.ts +32 -0
  231. package/dist/cjs/core/ConditionEvaluator.d.ts +0 -72
  232. package/dist/cjs/core/ConditionEvaluator.d.ts.map +0 -1
  233. package/dist/cjs/core/ConditionEvaluator.js +0 -272
  234. package/dist/cjs/core/ConditionEvaluator.js.map +0 -1
  235. package/dist/cjs/core/Observation.d.ts +0 -24
  236. package/dist/cjs/core/Observation.d.ts.map +0 -1
  237. package/dist/cjs/core/Observation.js +0 -39
  238. package/dist/cjs/core/Observation.js.map +0 -1
  239. package/dist/cjs/core/PreparationEngine.d.ts +0 -105
  240. package/dist/cjs/core/PreparationEngine.d.ts.map +0 -1
  241. package/dist/cjs/core/PreparationEngine.js +0 -320
  242. package/dist/cjs/core/PreparationEngine.js.map +0 -1
  243. package/dist/cjs/core/PromptBuilder.d.ts +0 -136
  244. package/dist/cjs/core/PromptBuilder.d.ts.map +0 -1
  245. package/dist/cjs/core/PromptBuilder.js +0 -421
  246. package/dist/cjs/core/PromptBuilder.js.map +0 -1
  247. package/dist/cjs/types/observation.d.ts +0 -27
  248. package/dist/cjs/types/observation.d.ts.map +0 -1
  249. package/dist/cjs/types/observation.js +0 -6
  250. package/dist/cjs/types/observation.js.map +0 -1
  251. package/dist/cjs/types/prompt.d.ts +0 -46
  252. package/dist/cjs/types/prompt.d.ts.map +0 -1
  253. package/dist/cjs/types/prompt.js +0 -19
  254. package/dist/cjs/types/prompt.js.map +0 -1
  255. package/dist/core/ConditionEvaluator.d.ts +0 -72
  256. package/dist/core/ConditionEvaluator.d.ts.map +0 -1
  257. package/dist/core/ConditionEvaluator.js +0 -268
  258. package/dist/core/ConditionEvaluator.js.map +0 -1
  259. package/dist/core/Observation.d.ts +0 -24
  260. package/dist/core/Observation.d.ts.map +0 -1
  261. package/dist/core/Observation.js +0 -35
  262. package/dist/core/Observation.js.map +0 -1
  263. package/dist/core/PreparationEngine.d.ts +0 -105
  264. package/dist/core/PreparationEngine.d.ts.map +0 -1
  265. package/dist/core/PreparationEngine.js +0 -316
  266. package/dist/core/PreparationEngine.js.map +0 -1
  267. package/dist/core/PromptBuilder.d.ts +0 -136
  268. package/dist/core/PromptBuilder.d.ts.map +0 -1
  269. package/dist/core/PromptBuilder.js +0 -417
  270. package/dist/core/PromptBuilder.js.map +0 -1
  271. package/dist/types/observation.d.ts +0 -27
  272. package/dist/types/observation.d.ts.map +0 -1
  273. package/dist/types/observation.js +0 -5
  274. package/dist/types/observation.js.map +0 -1
  275. package/dist/types/prompt.d.ts +0 -46
  276. package/dist/types/prompt.d.ts.map +0 -1
  277. package/dist/types/prompt.js +0 -16
  278. package/dist/types/prompt.js.map +0 -1
  279. package/docs/STRUCTURE.md +0 -58
  280. package/src/core/ConditionEvaluator.ts +0 -381
  281. package/src/core/Observation.ts +0 -47
  282. package/src/core/PreparationEngine.ts +0 -500
  283. package/src/core/PromptBuilder.ts +0 -617
  284. package/src/types/observation.ts +0 -29
  285. package/src/types/prompt.ts +0 -49
@@ -21,11 +21,6 @@ export enum CompositionMode {
21
21
  CANNED_STRICT = "strict_canned",
22
22
  }
23
23
 
24
- /**
25
- * Forward declare observation types
26
- */
27
- import type { ObservationOptions } from "./observation";
28
-
29
24
  /**
30
25
  * Context lifecycle hooks for managing state persistence
31
26
  */
@@ -44,6 +39,19 @@ export interface ContextLifecycleHooks<TContext = unknown> {
44
39
  newContext: TContext,
45
40
  previousContext: TContext
46
41
  ) => Promise<void> | void;
42
+
43
+ /**
44
+ * Called after extracted data is updated (from AI response or tool execution)
45
+ * Useful for validation, enrichment, or persistence of gathered data
46
+ * Return modified extracted data or the same data to keep it unchanged
47
+ *
48
+ * Note: This hook works with ANY route's extracted data (since an agent can have
49
+ * multiple routes with different extraction schemas). Use type guards or runtime
50
+ * checks if you need type-specific logic.
51
+ */
52
+
53
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
+ onExtractedUpdate?: (extracted: any, previousExtracted: any) => any;
47
55
  }
48
56
 
49
57
  /**
@@ -64,6 +72,8 @@ export interface AgentOptions<TContext = unknown> {
64
72
  description?: string;
65
73
  /** The agent's primary goal or objective */
66
74
  goal?: string;
75
+ /** Optional personality/tone instructions used in prompts */
76
+ personality?: string;
67
77
  /** Default context data available to the agent */
68
78
  context?: TContext;
69
79
  /** Context provider function for always-fresh context (alternative to static context) */
@@ -72,8 +82,6 @@ export interface AgentOptions<TContext = unknown> {
72
82
  hooks?: ContextLifecycleHooks<TContext>;
73
83
  /** AI provider strategy for generating responses */
74
84
  ai: AiProvider;
75
- /** Maximum number of processing iterations per request */
76
- maxEngineIterations?: number;
77
85
  /** Composition mode for response generation */
78
86
  compositionMode?: CompositionMode;
79
87
  /** Initial terms for domain glossary */
@@ -83,9 +91,7 @@ export interface AgentOptions<TContext = unknown> {
83
91
  /** Initial capabilities */
84
92
  capabilities?: Capability[];
85
93
  /** Initial routes (will be instantiated as Route objects) */
86
- routes?: RouteOptions[];
87
- /** Initial observations for disambiguation */
88
- observations?: ObservationOptions[];
94
+ routes?: RouteOptions<unknown>[];
89
95
  /** Optional persistence configuration for auto-saving sessions and messages */
90
96
  persistence?: PersistenceConfig;
91
97
  }
package/src/types/ai.ts CHANGED
@@ -45,8 +45,12 @@ export interface GenerateMessageInput<TContext = unknown> {
45
45
  maxOutputTokens?: number;
46
46
  /** Reasoning/thinking configuration */
47
47
  reasoning?: ReasoningConfig;
48
- /** Enable structured JSON output mode */
49
- jsonMode?: boolean;
48
+ /**
49
+ * Required: Structured JSON schema the provider must enforce for output
50
+ */
51
+ jsonSchema: { [key: string]: unknown };
52
+ /** Optional schema name (used by providers that require one) */
53
+ schemaName?: string;
50
54
  };
51
55
  /** Abort signal for cancellation */
52
56
  signal?: AbortSignal;
@@ -54,6 +54,14 @@ export interface MessageEventData {
54
54
  flagged?: boolean;
55
55
  /** Tags/reasons if flagged */
56
56
  tags?: string[];
57
+ /** Session metadata attached to this message */
58
+ session?: {
59
+ routeId?: string;
60
+ routeTitle?: string;
61
+ stateId?: string;
62
+ stateDescription?: string;
63
+ extracted?: Record<string, unknown>;
64
+ };
57
65
  }
58
66
 
59
67
  /**
@@ -44,17 +44,6 @@ export type {
44
44
  GenerateMessageOutput,
45
45
  } from "./ai";
46
46
 
47
- // Prompt types
48
- export type {
49
- PromptSection,
50
- ContextVariable,
51
- ContextVariableValue,
52
- } from "./prompt";
53
- export { SectionStatus } from "./prompt";
54
-
55
- // Observation types
56
- export type { Observation, ObservationOptions } from "./observation";
57
-
58
47
  // Persistence types
59
48
  export type {
60
49
  SessionData,
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import type { ToolRef } from "./tool";
6
+ import type { StructuredSchema } from "./schema";
6
7
 
7
8
  /**
8
9
  * Reference to a route
@@ -29,8 +30,9 @@ import type { Guideline } from "./agent";
29
30
 
30
31
  /**
31
32
  * Options for creating a route
33
+ * @template TExtracted - Type of data extracted throughout the route (inferred from gatherSchema)
32
34
  */
33
- export interface RouteOptions {
35
+ export interface RouteOptions<TExtracted = unknown> {
34
36
  /** Custom ID for the route (optional - will generate deterministic ID from title if not provided) */
35
37
  id?: string;
36
38
  /** Title of the route */
@@ -47,12 +49,27 @@ export interface RouteOptions {
47
49
  rules?: string[];
48
50
  /** Absolute prohibitions the agent must never do in this route */
49
51
  prohibitions?: string[];
52
+ /** Optional: extractions the router may return (added to routing schema) */
53
+ routingExtrasSchema?: StructuredSchema;
54
+ /** Optional: structured response data for this route's message generation */
55
+ responseOutputSchema?: StructuredSchema;
56
+ /**
57
+ * NEW: Schema defining data to extract throughout this route
58
+ * This creates a type-safe contract for what data the route collects
59
+ */
60
+ gatherSchema?: StructuredSchema;
61
+ /**
62
+ * NEW: Initial data to pre-populate when entering this route
63
+ * Useful for restoring sessions or pre-filling known information
64
+ * States with skipIf conditions will be automatically bypassed if data is present
65
+ */
66
+ initialData?: Partial<TExtracted>;
50
67
  }
51
68
 
52
69
  /**
53
70
  * Specification for a state transition
54
71
  */
55
- export interface TransitionSpec<TContext = unknown> {
72
+ export interface TransitionSpec<TContext = unknown, TExtracted = unknown> {
56
73
  /** Transition to a chat state with this description */
57
74
  chatState?: string;
58
75
  /** Transition to execute a tool */
@@ -60,16 +77,35 @@ export interface TransitionSpec<TContext = unknown> {
60
77
  toolState?: ToolRef<TContext, any[], any>;
61
78
  /** Transition to a specific state or end marker */
62
79
  state?: StateRef | symbol;
80
+ /**
81
+ * NEW: Fields to gather from the conversation in this state
82
+ * These should match keys in the route's gatherSchema
83
+ */
84
+ gather?: string[];
85
+ /**
86
+ * NEW: Function to determine if this state should be skipped
87
+ * If returns true, the state will be bypassed
88
+ * @param extracted - Currently extracted data
89
+ * @returns true if state should be skipped, false otherwise
90
+ */
91
+ skipIf?: (extracted: Partial<TExtracted>) => boolean;
92
+ /**
93
+ * NEW: Required data fields that must be present before entering this state
94
+ * If any required field is missing, state cannot be entered
95
+ * Uses string[] for developer-friendly usage (same as gather)
96
+ */
97
+ requiredData?: string[];
63
98
  }
64
99
 
65
100
  /**
66
101
  * Result of a transition operation
67
102
  * Combines state reference with the ability to chain transitions
68
103
  */
69
- export interface TransitionResult<TContext = unknown> extends StateRef {
104
+ export interface TransitionResult<TContext = unknown, TExtracted = unknown>
105
+ extends StateRef {
70
106
  /** Allow chaining transitions */
71
107
  transitionTo: (
72
- spec: TransitionSpec<TContext>,
108
+ spec: TransitionSpec<TContext, TExtracted>,
73
109
  condition?: string
74
- ) => TransitionResult<TContext>;
110
+ ) => TransitionResult<TContext, TExtracted>;
75
111
  }
@@ -0,0 +1,18 @@
1
+ import type { StructuredSchema } from "./schema";
2
+
3
+ export interface RoutingDecision {
4
+ context: string;
5
+ routes: Record<string, number>;
6
+ responseDirectives?: string[];
7
+ extractions?: unknown;
8
+ contextUpdate?: Record<string, unknown>;
9
+ }
10
+
11
+ export interface RoutingDecisionWithRoute extends RoutingDecision {
12
+ selectedRouteId: string;
13
+ maxScore: number;
14
+ }
15
+
16
+ export interface RoutingSchemaOptions {
17
+ extrasSchema?: StructuredSchema;
18
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * StructuredSchema - minimal JSON Schema subset used across providers
3
+ */
4
+ export interface StructuredSchema {
5
+ type?: string | string[];
6
+ description?: string;
7
+ enum?: Array<string | number | boolean | null>;
8
+ nullable?: boolean;
9
+ properties?: Record<string, StructuredSchema>;
10
+ required?: string[];
11
+ items?: StructuredSchema;
12
+ additionalProperties?: boolean | StructuredSchema;
13
+ // Allow provider-specific passthroughs without breaking types
14
+ [key: string]: unknown;
15
+ }
16
+
17
+ /**
18
+ * A small helper describing a named schema (for providers that require a name)
19
+ */
20
+ export interface NamedSchema {
21
+ name?: string;
22
+ schema: StructuredSchema;
23
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Session state types for tracking conversation progress
3
+ */
4
+
5
+ /**
6
+ * Session state tracks the current position in the conversation flow
7
+ * and data extracted during the route progression
8
+ */
9
+ export interface SessionState<TExtracted = Record<string, unknown>> {
10
+ /** Current route the conversation is in */
11
+ currentRoute?: {
12
+ id: string;
13
+ title: string;
14
+ enteredAt: Date;
15
+ };
16
+
17
+ /** Current state within the route */
18
+ currentState?: {
19
+ id: string;
20
+ description?: string;
21
+ enteredAt: Date;
22
+ };
23
+
24
+ /** Data extracted during the current route */
25
+ extracted: Partial<TExtracted>;
26
+
27
+ /** History of routes visited in this session */
28
+ routeHistory: Array<{
29
+ routeId: string;
30
+ enteredAt: Date;
31
+ exitedAt?: Date;
32
+ completed: boolean;
33
+ }>;
34
+
35
+ /** Session metadata */
36
+ metadata?: {
37
+ sessionId?: string;
38
+ createdAt?: Date;
39
+ lastUpdatedAt?: Date;
40
+ [key: string]: unknown;
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Helper to create a new session
46
+ */
47
+ export function createSession<TExtracted = Record<string, unknown>>(
48
+ metadata?: SessionState<TExtracted>["metadata"]
49
+ ): SessionState<TExtracted> {
50
+ return {
51
+ extracted: {},
52
+ routeHistory: [],
53
+ metadata: {
54
+ ...metadata,
55
+ createdAt: new Date(),
56
+ lastUpdatedAt: new Date(),
57
+ },
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Helper to update session with new route
63
+ */
64
+ export function enterRoute<TExtracted = Record<string, unknown>>(
65
+ session: SessionState<TExtracted>,
66
+ routeId: string,
67
+ routeTitle: string
68
+ ): SessionState<TExtracted> {
69
+ // Exit current route if exists
70
+ const routeHistory = [...session.routeHistory];
71
+ if (session.currentRoute) {
72
+ const lastRouteIndex = routeHistory.findIndex(
73
+ (r) => r.routeId === session.currentRoute?.id && !r.exitedAt
74
+ );
75
+ if (lastRouteIndex >= 0) {
76
+ routeHistory[lastRouteIndex].exitedAt = new Date();
77
+ }
78
+ }
79
+
80
+ // Enter new route
81
+ const now = new Date();
82
+ return {
83
+ ...session,
84
+ currentRoute: {
85
+ id: routeId,
86
+ title: routeTitle,
87
+ enteredAt: now,
88
+ },
89
+ currentState: undefined,
90
+ extracted: {}, // Reset extracted data for new route
91
+ routeHistory: [
92
+ ...routeHistory,
93
+ {
94
+ routeId,
95
+ enteredAt: now,
96
+ completed: false,
97
+ },
98
+ ],
99
+ metadata: {
100
+ ...session.metadata,
101
+ lastUpdatedAt: now,
102
+ },
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Helper to update session with new state
108
+ */
109
+ export function enterState<TExtracted = Record<string, unknown>>(
110
+ session: SessionState<TExtracted>,
111
+ stateId: string,
112
+ stateDescription?: string
113
+ ): SessionState<TExtracted> {
114
+ return {
115
+ ...session,
116
+ currentState: {
117
+ id: stateId,
118
+ description: stateDescription,
119
+ enteredAt: new Date(),
120
+ },
121
+ metadata: {
122
+ ...session.metadata,
123
+ lastUpdatedAt: new Date(),
124
+ },
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Helper to merge extracted data into session
130
+ */
131
+ export function mergeExtracted<TExtracted = Record<string, unknown>>(
132
+ session: SessionState<TExtracted>,
133
+ extracted: Partial<TExtracted>
134
+ ): SessionState<TExtracted> {
135
+ return {
136
+ ...session,
137
+ extracted: {
138
+ ...session.extracted,
139
+ ...extracted,
140
+ },
141
+ metadata: {
142
+ ...session.metadata,
143
+ lastUpdatedAt: new Date(),
144
+ },
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Helper to convert SessionState to persistence-friendly format
150
+ * Used when saving to database
151
+ */
152
+ export function sessionStateToData<TExtracted = Record<string, unknown>>(
153
+ session: SessionState<TExtracted>
154
+ ): {
155
+ currentRoute?: string;
156
+ currentState?: string;
157
+ collectedData: Record<string, unknown>;
158
+ } {
159
+ return {
160
+ currentRoute: session.currentRoute?.id,
161
+ currentState: session.currentState?.id,
162
+ collectedData: {
163
+ extracted: session.extracted,
164
+ routeHistory: session.routeHistory,
165
+ currentRouteTitle: session.currentRoute?.title,
166
+ currentStateDescription: session.currentState?.description,
167
+ metadata: session.metadata,
168
+ },
169
+ };
170
+ }
171
+
172
+ /**
173
+ * Helper to convert database SessionData back to SessionState
174
+ * Used when loading from database
175
+ */
176
+ export function sessionDataToState<TExtracted = Record<string, unknown>>(data: {
177
+ currentRoute?: string;
178
+ currentState?: string;
179
+ collectedData?: Record<string, unknown>;
180
+ }): Partial<SessionState<TExtracted>> {
181
+ const collectedData = data.collectedData || {};
182
+
183
+ return {
184
+ currentRoute: data.currentRoute
185
+ ? {
186
+ id: data.currentRoute,
187
+ title:
188
+ (collectedData.currentRouteTitle as string) || data.currentRoute,
189
+ enteredAt: new Date(),
190
+ }
191
+ : undefined,
192
+ currentState: data.currentState
193
+ ? {
194
+ id: data.currentState,
195
+ description:
196
+ (collectedData.currentStateDescription as string) || undefined,
197
+ enteredAt: new Date(),
198
+ }
199
+ : undefined,
200
+ extracted: (collectedData.extracted as Partial<TExtracted>) || {},
201
+ routeHistory:
202
+ (collectedData.routeHistory as SessionState<TExtracted>["routeHistory"]) ||
203
+ [],
204
+ metadata:
205
+ (collectedData.metadata as SessionState<TExtracted>["metadata"]) || {},
206
+ };
207
+ }
package/src/types/tool.ts CHANGED
@@ -7,7 +7,7 @@ import type { Event, StateRef } from "./index";
7
7
  /**
8
8
  * Context provided to tool handlers
9
9
  */
10
- export interface ToolContext<TContext = unknown> {
10
+ export interface ToolContext<TContext = unknown, TExtracted = unknown> {
11
11
  /** The agent's context data */
12
12
  context: TContext;
13
13
  /** Update the agent's context (triggers lifecycle hooks if configured) */
@@ -16,6 +16,8 @@ export interface ToolContext<TContext = unknown> {
16
16
  state?: StateRef;
17
17
  /** Interaction history */
18
18
  history: Event[];
19
+ /** Data extracted so far in the current route */
20
+ extracted?: Partial<TExtracted>;
19
21
  /** Additional metadata */
20
22
  metadata?: Record<string, unknown>;
21
23
  }
@@ -23,11 +25,17 @@ export interface ToolContext<TContext = unknown> {
23
25
  /**
24
26
  * Result returned by a tool
25
27
  */
26
- export interface ToolResult<TData = unknown, TContext = unknown> {
28
+ export interface ToolResult<
29
+ TData = unknown,
30
+ TContext = unknown,
31
+ TExtracted = unknown
32
+ > {
27
33
  /** The result data */
28
34
  data: TData;
29
35
  /** Optional context update to be merged with current context */
30
36
  contextUpdate?: Partial<TContext>;
37
+ /** Optional extracted data update to be merged with session state */
38
+ extractedUpdate?: Partial<TExtracted>;
31
39
  /** Optional metadata about the execution */
32
40
  meta?: Record<string, unknown>;
33
41
  }
@@ -35,23 +43,37 @@ export interface ToolResult<TData = unknown, TContext = unknown> {
35
43
  /**
36
44
  * Handler function for a tool
37
45
  */
38
- export type ToolHandler<TContext, TArgs extends unknown[], TResult> = (
39
- context: ToolContext<TContext>,
46
+ export type ToolHandler<
47
+ TContext,
48
+ TArgs extends unknown[],
49
+ TResult,
50
+ TExtracted = unknown
51
+ > = (
52
+ context: ToolContext<TContext, TExtracted>,
40
53
  ...args: TArgs
41
- ) => Promise<ToolResult<TResult, TContext>> | ToolResult<TResult, TContext>;
54
+ ) =>
55
+ | Promise<ToolResult<TResult, TContext, TExtracted>>
56
+ | ToolResult<TResult, TContext, TExtracted>;
42
57
 
43
58
  /**
44
59
  * Reference to a defined tool
45
60
  */
46
- export interface ToolRef<TContext, TArgs extends unknown[], TResult> {
61
+ export interface ToolRef<
62
+ TContext,
63
+ TArgs extends unknown[],
64
+ TResult,
65
+ TExtracted = unknown
66
+ > {
47
67
  /** Tool identifier */
48
68
  id: string;
49
69
  /** Tool name */
50
70
  name: string;
51
71
  /** Tool handler function */
52
- handler: ToolHandler<TContext, TArgs, TResult>;
72
+ handler: ToolHandler<TContext, TArgs, TResult, TExtracted>;
53
73
  /** Description of what the tool does */
54
74
  description?: string;
55
75
  /** Parameter schema or description */
56
76
  parameters?: unknown;
77
+ /** Domain this tool belongs to (set when added via agent.addDomain) */
78
+ domainName?: string;
57
79
  }
package/src/utils/id.ts CHANGED
@@ -53,16 +53,6 @@ export function generateStateId(
53
53
  return `state_${routeId}_${suffix}`;
54
54
  }
55
55
 
56
- /**
57
- * Generate a deterministic observation ID
58
- * Format: observation_{sanitized_description}_{hash}
59
- */
60
- export function generateObservationId(description: string): string {
61
- const sanitized = sanitize(description.substring(0, 50)); // Limit length
62
- const hash = simpleHash(description);
63
- return `observation_${sanitized}_${hash}`;
64
- }
65
-
66
56
  /**
67
57
  * Generate a deterministic tool ID
68
58
  * Format: tool_{sanitized_name}_{hash}
@@ -0,0 +1,32 @@
1
+ import type { StructuredSchema } from "../types/schema";
2
+
3
+ /**
4
+ * Convert our StructuredSchema to the OpenAI/OpenRouter JSON schema format
5
+ * (they already accept standard JSON Schema for responses.parse)
6
+ */
7
+ export function convertToOpenAIJsonSchema(schema: StructuredSchema): object {
8
+ // For now our schema aligns well with JSON Schema draft-like structure
9
+ // Return as-is; callers should ensure correctness
10
+ return schema as object;
11
+ }
12
+
13
+ /**
14
+ * Convert our StructuredSchema to Gemini responseSchema (Type mapping)
15
+ * The @google/genai expects a slightly different shape
16
+ */
17
+ export function convertToGeminiSchema(schema: StructuredSchema): object {
18
+ // Basic passthrough. If needed, a deeper mapping can be added later.
19
+ // Gemini supports a similar structure (type, properties, items, enum, etc.)
20
+ return schema as object;
21
+ }
22
+
23
+ /**
24
+ * Convert our StructuredSchema into Anthropic system prompt constraints.
25
+ * Since Anthropic lacks native schema parsing, we embed a concise instruction.
26
+ */
27
+ export function convertToAnthropicConstraint(schema: StructuredSchema): string {
28
+ // Keep it concise to avoid context bloat
29
+ return `You must respond with valid JSON that matches this schema: ${JSON.stringify(
30
+ schema
31
+ )}`;
32
+ }
@@ -1,72 +0,0 @@
1
- /**
2
- * ConditionEvaluator - Handles AI-powered condition evaluation
3
- *
4
- * This class is responsible for:
5
- * - Evaluating guideline conditions
6
- * - Evaluating transition conditions
7
- * - Extracting tool arguments from context and history
8
- */
9
- import type { Event, AiProvider } from "../types/index";
10
- import type { Guideline } from "../types/agent";
11
- import type { ToolRef } from "../types/tool";
12
- /**
13
- * Result of guideline condition evaluation
14
- */
15
- export interface GuidelineEvaluationResult {
16
- matches: boolean;
17
- rationale?: string;
18
- }
19
- /**
20
- * Result of transition condition evaluation
21
- */
22
- export interface TransitionEvaluationResult {
23
- shouldFollow: boolean;
24
- rationale?: string;
25
- }
26
- /**
27
- * Result of tool argument extraction
28
- */
29
- export interface ArgumentExtractionResult {
30
- arguments: unknown[];
31
- rationale?: string;
32
- }
33
- /**
34
- * ConditionEvaluator - Evaluates conditions using AI
35
- */
36
- export declare class ConditionEvaluator<TContext = unknown> {
37
- private readonly ai;
38
- constructor(ai: AiProvider);
39
- /**
40
- * Evaluate a guideline condition against context and history
41
- */
42
- evaluateGuidelineCondition(guideline: Guideline, context: TContext, history: Event[]): Promise<GuidelineEvaluationResult>;
43
- /**
44
- * Evaluate a transition condition
45
- */
46
- evaluateTransitionCondition(condition: string, context: TContext, history: Event[]): Promise<TransitionEvaluationResult>;
47
- /**
48
- * Extract tool arguments from context and history
49
- */
50
- extractToolArguments(tool: ToolRef<TContext, unknown[], unknown>, context: TContext, history: Event[]): Promise<ArgumentExtractionResult>;
51
- /**
52
- * Simple argument extraction from context (fallback)
53
- */
54
- simpleArgumentExtraction(tool: ToolRef<TContext, unknown[], unknown>, context: TContext): unknown[];
55
- /**
56
- * Extract recent messages from history
57
- */
58
- private extractRecentMessages;
59
- /**
60
- * Parse guideline evaluation from text response (fallback)
61
- */
62
- private parseGuidelineResponse;
63
- /**
64
- * Parse transition evaluation from text response (fallback)
65
- */
66
- private parseTransitionResponse;
67
- /**
68
- * Parse argument extraction from text response (fallback)
69
- */
70
- private parseArgumentResponse;
71
- }
72
- //# sourceMappingURL=ConditionEvaluator.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ConditionEvaluator.d.ts","sourceRoot":"","sources":["../../../src/core/ConditionEvaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAoB,MAAM,gBAAgB,CAAC;AAE1E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC,YAAY,EAAE,OAAO,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,SAAS,EAAE,OAAO,EAAE,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AA0BD;;GAEG;AACH,qBAAa,kBAAkB,CAAC,QAAQ,GAAG,OAAO;IACpC,OAAO,CAAC,QAAQ,CAAC,EAAE;gBAAF,EAAE,EAAE,UAAU;IAE3C;;OAEG;IACG,0BAA0B,CAC9B,SAAS,EAAE,SAAS,EACpB,OAAO,EAAE,QAAQ,EACjB,OAAO,EAAE,KAAK,EAAE,GACf,OAAO,CAAC,yBAAyB,CAAC;IA0DrC;;OAEG;IACG,2BAA2B,CAC/B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,QAAQ,EACjB,OAAO,EAAE,KAAK,EAAE,GACf,OAAO,CAAC,0BAA0B,CAAC;IAyDtC;;OAEG;IACG,oBAAoB,CACxB,IAAI,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,OAAO,CAAC,EAC3C,OAAO,EAAE,QAAQ,EACjB,OAAO,EAAE,KAAK,EAAE,GACf,OAAO,CAAC,wBAAwB,CAAC;IAiEpC;;OAEG;IACH,wBAAwB,CACtB,IAAI,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,OAAO,CAAC,EAC3C,OAAO,EAAE,QAAQ,GAChB,OAAO,EAAE;IAgCZ;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAc7B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAW9B;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAc/B;;OAEG;IACH,OAAO,CAAC,qBAAqB;CAsB9B"}