@falai/agent 0.9.0-alpha-2 → 0.9.2

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 (179) hide show
  1. package/README.md +42 -34
  2. package/dist/cjs/src/core/Agent.d.ts +48 -44
  3. package/dist/cjs/src/core/Agent.d.ts.map +1 -1
  4. package/dist/cjs/src/core/Agent.js +151 -1110
  5. package/dist/cjs/src/core/Agent.js.map +1 -1
  6. package/dist/cjs/src/core/ResponseModal.d.ts +211 -0
  7. package/dist/cjs/src/core/ResponseModal.d.ts.map +1 -0
  8. package/dist/cjs/src/core/ResponseModal.js +1394 -0
  9. package/dist/cjs/src/core/ResponseModal.js.map +1 -0
  10. package/dist/cjs/src/core/ResponsePipeline.d.ts +8 -4
  11. package/dist/cjs/src/core/ResponsePipeline.d.ts.map +1 -1
  12. package/dist/cjs/src/core/ResponsePipeline.js +48 -20
  13. package/dist/cjs/src/core/ResponsePipeline.js.map +1 -1
  14. package/dist/cjs/src/core/Route.d.ts +12 -5
  15. package/dist/cjs/src/core/Route.d.ts.map +1 -1
  16. package/dist/cjs/src/core/Route.js +26 -5
  17. package/dist/cjs/src/core/Route.js.map +1 -1
  18. package/dist/cjs/src/core/RoutingEngine.d.ts +5 -0
  19. package/dist/cjs/src/core/RoutingEngine.d.ts.map +1 -1
  20. package/dist/cjs/src/core/RoutingEngine.js +37 -25
  21. package/dist/cjs/src/core/RoutingEngine.js.map +1 -1
  22. package/dist/cjs/src/core/SessionManager.d.ts +9 -1
  23. package/dist/cjs/src/core/SessionManager.d.ts.map +1 -1
  24. package/dist/cjs/src/core/SessionManager.js +27 -5
  25. package/dist/cjs/src/core/SessionManager.js.map +1 -1
  26. package/dist/cjs/src/core/Step.d.ts +60 -7
  27. package/dist/cjs/src/core/Step.d.ts.map +1 -1
  28. package/dist/cjs/src/core/Step.js +151 -4
  29. package/dist/cjs/src/core/Step.js.map +1 -1
  30. package/dist/cjs/src/core/ToolManager.d.ts +234 -0
  31. package/dist/cjs/src/core/ToolManager.d.ts.map +1 -0
  32. package/dist/cjs/src/core/ToolManager.js +1117 -0
  33. package/dist/cjs/src/core/ToolManager.js.map +1 -0
  34. package/dist/cjs/src/index.d.ts +5 -4
  35. package/dist/cjs/src/index.d.ts.map +1 -1
  36. package/dist/cjs/src/index.js +11 -3
  37. package/dist/cjs/src/index.js.map +1 -1
  38. package/dist/cjs/src/types/agent.d.ts +2 -1
  39. package/dist/cjs/src/types/agent.d.ts.map +1 -1
  40. package/dist/cjs/src/types/ai.d.ts +1 -1
  41. package/dist/cjs/src/types/ai.d.ts.map +1 -1
  42. package/dist/cjs/src/types/index.d.ts +3 -2
  43. package/dist/cjs/src/types/index.d.ts.map +1 -1
  44. package/dist/cjs/src/types/index.js +3 -1
  45. package/dist/cjs/src/types/index.js.map +1 -1
  46. package/dist/cjs/src/types/route.d.ts +6 -4
  47. package/dist/cjs/src/types/route.d.ts.map +1 -1
  48. package/dist/cjs/src/types/tool.d.ts +84 -14
  49. package/dist/cjs/src/types/tool.d.ts.map +1 -1
  50. package/dist/cjs/src/types/tool.js +13 -0
  51. package/dist/cjs/src/types/tool.js.map +1 -1
  52. package/dist/cjs/src/utils/clone.d.ts.map +1 -1
  53. package/dist/cjs/src/utils/clone.js +0 -4
  54. package/dist/cjs/src/utils/clone.js.map +1 -1
  55. package/dist/cjs/src/utils/history.d.ts +30 -1
  56. package/dist/cjs/src/utils/history.d.ts.map +1 -1
  57. package/dist/cjs/src/utils/history.js +169 -23
  58. package/dist/cjs/src/utils/history.js.map +1 -1
  59. package/dist/cjs/src/utils/index.d.ts +1 -1
  60. package/dist/cjs/src/utils/index.d.ts.map +1 -1
  61. package/dist/cjs/src/utils/index.js +5 -1
  62. package/dist/cjs/src/utils/index.js.map +1 -1
  63. package/dist/src/core/Agent.d.ts +48 -44
  64. package/dist/src/core/Agent.d.ts.map +1 -1
  65. package/dist/src/core/Agent.js +152 -1111
  66. package/dist/src/core/Agent.js.map +1 -1
  67. package/dist/src/core/ResponseModal.d.ts +211 -0
  68. package/dist/src/core/ResponseModal.d.ts.map +1 -0
  69. package/dist/src/core/ResponseModal.js +1389 -0
  70. package/dist/src/core/ResponseModal.js.map +1 -0
  71. package/dist/src/core/ResponsePipeline.d.ts +8 -4
  72. package/dist/src/core/ResponsePipeline.d.ts.map +1 -1
  73. package/dist/src/core/ResponsePipeline.js +48 -20
  74. package/dist/src/core/ResponsePipeline.js.map +1 -1
  75. package/dist/src/core/Route.d.ts +12 -5
  76. package/dist/src/core/Route.d.ts.map +1 -1
  77. package/dist/src/core/Route.js +26 -5
  78. package/dist/src/core/Route.js.map +1 -1
  79. package/dist/src/core/RoutingEngine.d.ts +5 -0
  80. package/dist/src/core/RoutingEngine.d.ts.map +1 -1
  81. package/dist/src/core/RoutingEngine.js +37 -25
  82. package/dist/src/core/RoutingEngine.js.map +1 -1
  83. package/dist/src/core/SessionManager.d.ts +9 -1
  84. package/dist/src/core/SessionManager.d.ts.map +1 -1
  85. package/dist/src/core/SessionManager.js +27 -5
  86. package/dist/src/core/SessionManager.js.map +1 -1
  87. package/dist/src/core/Step.d.ts +60 -7
  88. package/dist/src/core/Step.d.ts.map +1 -1
  89. package/dist/src/core/Step.js +151 -4
  90. package/dist/src/core/Step.js.map +1 -1
  91. package/dist/src/core/ToolManager.d.ts +234 -0
  92. package/dist/src/core/ToolManager.d.ts.map +1 -0
  93. package/dist/src/core/ToolManager.js +1111 -0
  94. package/dist/src/core/ToolManager.js.map +1 -0
  95. package/dist/src/index.d.ts +5 -4
  96. package/dist/src/index.d.ts.map +1 -1
  97. package/dist/src/index.js +3 -2
  98. package/dist/src/index.js.map +1 -1
  99. package/dist/src/types/agent.d.ts +2 -1
  100. package/dist/src/types/agent.d.ts.map +1 -1
  101. package/dist/src/types/ai.d.ts +1 -1
  102. package/dist/src/types/ai.d.ts.map +1 -1
  103. package/dist/src/types/index.d.ts +3 -2
  104. package/dist/src/types/index.d.ts.map +1 -1
  105. package/dist/src/types/index.js +1 -0
  106. package/dist/src/types/index.js.map +1 -1
  107. package/dist/src/types/route.d.ts +6 -4
  108. package/dist/src/types/route.d.ts.map +1 -1
  109. package/dist/src/types/tool.d.ts +84 -14
  110. package/dist/src/types/tool.d.ts.map +1 -1
  111. package/dist/src/types/tool.js +12 -1
  112. package/dist/src/types/tool.js.map +1 -1
  113. package/dist/src/utils/clone.d.ts.map +1 -1
  114. package/dist/src/utils/clone.js +0 -4
  115. package/dist/src/utils/clone.js.map +1 -1
  116. package/dist/src/utils/history.d.ts +30 -1
  117. package/dist/src/utils/history.d.ts.map +1 -1
  118. package/dist/src/utils/history.js +165 -23
  119. package/dist/src/utils/history.js.map +1 -1
  120. package/dist/src/utils/index.d.ts +1 -1
  121. package/dist/src/utils/index.d.ts.map +1 -1
  122. package/dist/src/utils/index.js +1 -1
  123. package/dist/src/utils/index.js.map +1 -1
  124. package/docs/CONTRIBUTING.md +40 -0
  125. package/docs/README.md +14 -6
  126. package/docs/api/README.md +235 -45
  127. package/docs/api/overview.md +140 -33
  128. package/docs/core/agent/session-management.md +152 -5
  129. package/docs/core/ai-integration/response-processing.md +115 -4
  130. package/docs/core/conversation-flows/routes.md +130 -0
  131. package/docs/core/error-handling.md +638 -0
  132. package/docs/core/tools/tool-definition.md +684 -60
  133. package/docs/core/tools/tool-scoping.md +244 -53
  134. package/docs/guides/error-handling-patterns.md +578 -0
  135. package/docs/guides/getting-started/README.md +139 -28
  136. package/docs/guides/migration/README.md +72 -0
  137. package/docs/guides/migration/response-modal-refactor.md +518 -0
  138. package/examples/advanced-patterns/knowledge-based-agent.ts +6 -6
  139. package/examples/advanced-patterns/persistent-onboarding.ts +30 -43
  140. package/examples/advanced-patterns/streaming-responses.ts +169 -96
  141. package/examples/ai-providers/anthropic-integration.ts +9 -5
  142. package/examples/ai-providers/openai-integration.ts +11 -7
  143. package/examples/core-concepts/basic-agent.ts +106 -67
  144. package/examples/core-concepts/modern-streaming-api.ts +309 -0
  145. package/examples/core-concepts/schema-driven-extraction.ts +10 -7
  146. package/examples/core-concepts/session-management.ts +71 -18
  147. package/examples/integrations/healthcare-integration.ts +15 -29
  148. package/examples/integrations/server-session-management.ts +3 -3
  149. package/examples/persistence/memory-sessions.ts +3 -3
  150. package/examples/tools/basic-tools.ts +293 -89
  151. package/examples/tools/data-enrichment-tools.ts +185 -75
  152. package/package.json +1 -1
  153. package/src/core/Agent.ts +190 -1529
  154. package/src/core/ResponseModal.ts +1798 -0
  155. package/src/core/ResponsePipeline.ts +83 -57
  156. package/src/core/Route.ts +39 -12
  157. package/src/core/RoutingEngine.ts +46 -42
  158. package/src/core/SessionManager.ts +39 -7
  159. package/src/core/Step.ts +198 -20
  160. package/src/core/ToolManager.ts +1394 -0
  161. package/src/index.ts +19 -3
  162. package/src/types/agent.ts +2 -1
  163. package/src/types/ai.ts +1 -1
  164. package/src/types/index.ts +13 -2
  165. package/src/types/route.ts +6 -4
  166. package/src/types/tool.ts +116 -25
  167. package/src/utils/clone.ts +6 -8
  168. package/src/utils/history.ts +190 -27
  169. package/src/utils/index.ts +4 -0
  170. package/dist/cjs/src/core/ToolExecutor.d.ts +0 -45
  171. package/dist/cjs/src/core/ToolExecutor.d.ts.map +0 -1
  172. package/dist/cjs/src/core/ToolExecutor.js +0 -84
  173. package/dist/cjs/src/core/ToolExecutor.js.map +0 -1
  174. package/dist/src/core/ToolExecutor.d.ts +0 -45
  175. package/dist/src/core/ToolExecutor.d.ts.map +0 -1
  176. package/dist/src/core/ToolExecutor.js +0 -80
  177. package/dist/src/core/ToolExecutor.js.map +0 -1
  178. package/docs/core/tools/tool-execution.md +0 -815
  179. package/src/core/ToolExecutor.ts +0 -126
package/src/index.ts CHANGED
@@ -8,11 +8,17 @@
8
8
  export { Agent } from "./core/Agent";
9
9
  export { Route } from "./core/Route";
10
10
  export { Step } from "./core/Step";
11
+ export { ResponseModal } from "./core/ResponseModal";
12
+ export type {
13
+ ResponseModalOptions,
14
+ RespondParams,
15
+ StreamOptions,
16
+ GenerateOptions
17
+ } from "./core/ResponseModal";
11
18
  export { adaptEvent, convertHistoryToEvents } from "./core/Events";
12
19
  export { PersistenceManager } from "./core/PersistenceManager";
13
20
  export { SessionManager } from "./core/SessionManager";
14
- export { ToolExecutor } from "./core/ToolExecutor";
15
- export type { ToolExecutionResult } from "./core/ToolExecutor";
21
+ export { ToolManager, ToolCreationError, ToolExecutionError } from "./core/ToolManager";
16
22
 
17
23
  // Providers
18
24
  export { GeminiProvider } from "./providers/GeminiProvider";
@@ -67,6 +73,10 @@ export { generateRouteId, generateStepId, generateToolId } from "./utils/id";
67
73
  export { formatKnowledgeBase } from "./utils/template";
68
74
  export {
69
75
  normalizeHistory,
76
+ historyItemToEvent,
77
+ historyToEvents,
78
+ eventToHistoryItem,
79
+ eventsToHistory,
70
80
  userMessage,
71
81
  assistantMessage,
72
82
  toolMessage,
@@ -91,7 +101,6 @@ export type {
91
101
  StepRef,
92
102
  RouteOptions,
93
103
  StepOptions,
94
- StepResult,
95
104
  RouteTransitionConfig,
96
105
  RouteCompletionHandler,
97
106
  SessionState,
@@ -100,6 +109,13 @@ export type {
100
109
  ToolResult,
101
110
  ToolHandler,
102
111
  Tool,
112
+
113
+ DataEnrichmentConfig,
114
+ ValidationConfig,
115
+ ValidationError,
116
+ ApiCallConfig,
117
+ ComputationConfig,
118
+ ToolScope,
103
119
  AiProvider,
104
120
  GenerateMessageInput,
105
121
  GenerateMessageOutput,
@@ -99,7 +99,7 @@ export interface AgentOptions<TContext = unknown, TData = unknown> {
99
99
  /** Initial guidelines for agent behavior */
100
100
  guidelines?: Guideline<TContext, TData>[];
101
101
  /** Global tools available to all routes */
102
- tools?: Tool<TContext, TData, unknown[], unknown>[];
102
+ tools?: Tool<TContext, TData, unknown>[];
103
103
  /** Initial routes (will be instantiated as Route objects) */
104
104
  routes?: RouteOptions<TContext, TData>[];
105
105
  /** Optional persistence configuration for auto-saving sessions and messages */
@@ -173,6 +173,7 @@ export interface AgentResponseStreamChunk<TData = Record<string, unknown>> {
173
173
  [key: string]: unknown;
174
174
  };
175
175
  structured?: AgentStructuredResponse;
176
+ error?: Error;
176
177
  }
177
178
 
178
179
  /**
package/src/types/ai.ts CHANGED
@@ -66,7 +66,7 @@ export interface GenerateMessageInput<TContext = unknown> {
66
66
  /**
67
67
  * Structured response from AI containing message and metadata
68
68
  */
69
- export interface AgentStructuredResponse {
69
+ export interface AgentStructuredResponse extends Record<string, unknown> {
70
70
  /** The actual message to send to the user */
71
71
  message: string;
72
72
  /** Route chosen by the agent (route title or null if no route) */
@@ -45,8 +45,8 @@ export type {
45
45
  RouteRef,
46
46
  StepRef,
47
47
  StepOptions,
48
- StepResult,
49
48
  BranchSpec,
49
+ StepResult,
50
50
  BranchResult,
51
51
  RouteCompletionHandler,
52
52
  RouteTransitionConfig,
@@ -58,7 +58,18 @@ export * from "./route";
58
58
  export type { SessionState, PendingTransition } from "./session";
59
59
 
60
60
  // Tool types
61
- export type { Tool, ToolContext, ToolResult, ToolHandler } from "./tool";
61
+ export type {
62
+ Tool,
63
+ ToolContext,
64
+ ToolResult,
65
+ ToolHandler,
66
+ ToolExecutionResult,
67
+ DataEnrichmentConfig,
68
+ ValidationConfig,
69
+ ApiCallConfig,
70
+ ComputationConfig
71
+ } from "./tool";
72
+ export { ToolScope } from "./tool";
62
73
 
63
74
  // AI provider types
64
75
  export type {
@@ -104,7 +104,7 @@ export interface RouteOptions<TContext = unknown, TData = unknown> {
104
104
  /** Initial terms for the route's domain glossary */
105
105
  terms?: Term<TContext>[];
106
106
  /** Tools available in this route */
107
- tools?: Tool<TContext, TData, unknown[], unknown>[];
107
+ tools?: Tool<TContext, TData>[];
108
108
  /** Absolute rules the agent must follow in this route */
109
109
  rules?: Template<TContext, TData>[];
110
110
  /** Absolute prohibitions the agent must never do in this route */
@@ -197,16 +197,16 @@ export interface StepOptions<TContext = unknown, TData = unknown> {
197
197
  /** Transition to a chat state with this description */
198
198
  prompt?: Template<TContext, TData>;
199
199
  /** Tools available for AI to call in this step (by ID reference or inline definition) */
200
- tools?: (string | Tool<TContext, TData, unknown[], unknown>)[];
200
+ tools?: (string | Tool<TContext, TData>)[];
201
201
  /** Programmatic function or tool to run before AI responds */
202
202
  prepare?:
203
203
  | string
204
- | Tool<TContext, TData, unknown[], unknown>
204
+ | Tool<TContext, TData>
205
205
  | ((context: TContext, data?: Partial<TData>) => void | Promise<void>);
206
206
  /** Programmatic function or tool to run after AI responds */
207
207
  finalize?:
208
208
  | string
209
- | Tool<TContext, TData, unknown[], unknown>
209
+ | Tool<TContext, TData>
210
210
  | ((context: TContext, data?: Partial<TData>) => void | Promise<void>);
211
211
  /** Transition to a specific step or end marker */
212
212
  step?: StepRef | symbol;
@@ -267,4 +267,6 @@ export interface StepResult<TContext = unknown, TData = unknown>
267
267
  branch: (
268
268
  branches: BranchSpec<TContext, TData>[]
269
269
  ) => BranchResult<TContext, TData>;
270
+ /** Shortcut to end the current route */
271
+ endRoute: (options?: Omit<StepOptions<TContext, TData>, "step">) => StepResult<TContext, TData>;
270
272
  }
package/src/types/tool.ts CHANGED
@@ -1,36 +1,44 @@
1
+ /* eslint @typescript-eslint/no-explicit-any: "off"*/
1
2
  /**
2
3
  * Tool system type definitions
3
4
  */
4
5
 
5
- import type { Event, StepRef } from "./index";
6
+ import type { Event, StepRef, ValidationResult } from "./index";
6
7
 
7
8
  /**
8
9
  * Context provided to tool handlers
9
10
  */
10
- export interface ToolContext<TContext = unknown, TData = unknown> {
11
+ export interface ToolContext<TContext = any, TData = any> {
11
12
  /** The agent's context data */
12
13
  context: TContext;
13
- /** Update the agent's context (triggers lifecycle hooks if configured) */
14
- updateContext: (updates: Partial<TContext>) => Promise<void>;
15
- /** Update the agent's collected data (triggers lifecycle hooks if configured) */
16
- updateData: (updates: Partial<TData>) => Promise<void>;
17
- /** Current step reference (if in a route) */
18
- step?: StepRef;
14
+ /** Complete agent-level data collected so far */
15
+ data: Partial<TData>;
19
16
  /** Interaction history */
20
17
  history: Event[];
21
- /** Complete agent-level data collected so far */
22
- data?: Partial<TData>;
18
+ /** Current step reference (if in a route) */
19
+ step?: StepRef;
23
20
  /** Additional metadata */
24
21
  metadata?: Record<string, unknown>;
22
+
23
+ /** Update the agent's context (triggers lifecycle hooks if configured) */
24
+ updateContext: (updates: Partial<TContext>) => Promise<void>;
25
+ /** Update the agent's collected data (triggers lifecycle hooks if configured) */
26
+ updateData: (updates: Partial<TData>) => Promise<void>;
27
+ /** Get a specific field from collected data */
28
+ getField<K extends keyof TData>(key: K): TData[K] | undefined;
29
+ /** Set a specific field in collected data */
30
+ setField<K extends keyof TData>(key: K, value: TData[K]): Promise<void>;
31
+ /** Check if a field exists in collected data */
32
+ hasField<K extends keyof TData>(key: K): boolean;
25
33
  }
26
34
 
27
35
  /**
28
36
  * Result returned by a tool
29
37
  */
30
38
  export interface ToolResult<
31
- TResultData = unknown,
32
- TContext = unknown,
33
- TData = unknown
39
+ TResultData = any,
40
+ TContext = any,
41
+ TData = any
34
42
  > {
35
43
  /** The result data */
36
44
  data?: TResultData;
@@ -50,34 +58,117 @@ export interface ToolResult<
50
58
  * Handler function for a tool
51
59
  */
52
60
  export type ToolHandler<
53
- TContext,
54
- TData = unknown,
55
- TArgs extends unknown[] = unknown[],
56
- TResult = unknown
61
+ TContext = any,
62
+ TData = any,
63
+ TResult = any
57
64
  > = (
58
65
  context: ToolContext<TContext, TData>,
59
- ...args: TArgs
66
+ args?: Record<string, unknown>
60
67
  ) =>
61
- | Promise<ToolResult<TResult, TContext, TData>>
62
- | ToolResult<TResult, TContext, TData>;
68
+ | Promise<TResult | ToolResult<TResult, TContext, TData>>
69
+ | TResult
70
+ | ToolResult<TResult, TContext, TData>;
63
71
 
64
72
  /**
65
73
  * Tool definition - plain object interface
66
74
  */
67
75
  export interface Tool<
68
- TContext = unknown,
69
- TData = unknown,
70
- TArgs extends unknown[] = unknown[],
71
- TResult = unknown
76
+ TContext = any,
77
+ TData = any,
78
+ TResult = any
72
79
  > {
73
80
  /** Tool identifier */
74
81
  id: string;
75
82
  /** Tool display name (shown to AI models) */
76
83
  name?: string;
77
84
  /** Tool handler function */
78
- handler: ToolHandler<TContext, TData, TArgs, TResult>;
85
+ handler: ToolHandler<TContext, TData, TResult>;
79
86
  /** Description of what the tool does (for AI discovery) */
80
87
  description?: string;
81
88
  /** Parameter schema or description */
82
89
  parameters?: unknown;
83
90
  }
91
+
92
+
93
+
94
+ /**
95
+ * Tool execution result
96
+ */
97
+ export interface ToolExecutionResult {
98
+ success: boolean;
99
+ data?: unknown;
100
+ error?: string;
101
+ contextUpdate?: Record<string, unknown>;
102
+ dataUpdate?: Record<string, unknown>;
103
+ metadata?: Record<string, unknown>;
104
+ }
105
+
106
+ /**
107
+ * Tool scope enumeration
108
+ */
109
+ export enum ToolScope {
110
+ AGENT = 'agent',
111
+ ROUTE = 'route',
112
+ STEP = 'step',
113
+ REGISTERED = 'registered',
114
+ ALL = 'all'
115
+ }
116
+
117
+
118
+
119
+ /**
120
+ * Configuration for data enrichment tools
121
+ */
122
+ export interface DataEnrichmentConfig<TContext, TData, TFields extends keyof TData> {
123
+ id: string;
124
+ name?: string;
125
+ description?: string;
126
+ fields: TFields[];
127
+ enricher: (
128
+ context: TContext,
129
+ data: Pick<TData, TFields>
130
+ ) => Promise<Partial<TData>> | Partial<TData>;
131
+ }
132
+
133
+ /**
134
+ * Configuration for validation tools
135
+ */
136
+ export interface ValidationConfig<TContext, TData, TFields extends keyof TData> {
137
+ id: string;
138
+ name?: string;
139
+ description?: string;
140
+ fields: TFields[];
141
+ validator: (
142
+ context: TContext,
143
+ data: Pick<TData, TFields>
144
+ ) => Promise<ValidationResult> | ValidationResult;
145
+ }
146
+
147
+ /**
148
+ * Configuration for API call tools
149
+ */
150
+ export interface ApiCallConfig<TContext, TData, TResult> {
151
+ id: string;
152
+ name?: string;
153
+ description?: string;
154
+ endpoint: string | ((context: TContext, data: Partial<TData>) => string);
155
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
156
+ headers?: Record<string, string> | ((context: TContext) => Record<string, string>);
157
+ body?: (context: TContext, data: Partial<TData>, args?: Record<string, unknown>) => unknown;
158
+ transform?: (response: unknown) => TResult;
159
+ }
160
+
161
+ /**
162
+ * Configuration for computation tools
163
+ */
164
+ export interface ComputationConfig<TContext, TData, TResult> {
165
+ id: string;
166
+ name?: string;
167
+ description?: string;
168
+ inputs: (keyof TData)[];
169
+ compute: (
170
+ context: TContext,
171
+ inputs: Partial<TData>,
172
+ args?: Record<string, unknown>
173
+ ) => Promise<TResult> | TResult;
174
+ }
@@ -1,4 +1,4 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
1
+
2
2
  /**
3
3
  * Deep clone utility to avoid adding large dependencies like lodash.
4
4
  * Handles objects, arrays, dates, and primitives.
@@ -11,21 +11,19 @@ export function cloneDeep<T>(obj: T): T {
11
11
  }
12
12
 
13
13
  if (obj instanceof Date) {
14
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
15
- return new Date(obj.getTime()) as any;
14
+ return new Date(obj.getTime()) as T;
16
15
  }
17
16
 
18
17
  if (Array.isArray(obj)) {
19
- const arrCopy = [] as any[];
18
+ const arrCopy: unknown[] = [];
20
19
  for (let i = 0; i < obj.length; i++) {
21
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
20
+
22
21
  arrCopy[i] = cloneDeep(obj[i]);
23
22
  }
24
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
25
- return arrCopy as any;
23
+ return arrCopy as T;
26
24
  }
27
25
 
28
- const objCopy = {} as { [key: string]: any };
26
+ const objCopy: Record<string, unknown> = {};
29
27
  for (const key in obj) {
30
28
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
31
29
  objCopy[key] = cloneDeep((obj as Record<string, unknown>)[key]);
@@ -3,33 +3,53 @@
3
3
  * Convert simplified history format to internal Event format
4
4
  */
5
5
 
6
- import type { Event, MessageEventData } from "../types";
6
+ import type { Event, MessageEventData, ToolEventData, StatusEventData } from "../types";
7
7
  import { EventKind, MessageRole } from "../types";
8
- import type { History, HistoryItem } from "../types/history";
8
+ import type { History, HistoryItem, UserHistoryItem, AssistantHistoryItem, ToolHistoryItem } from "../types/history";
9
9
 
10
10
  /**
11
11
  * Convert a simplified history item to an internal Event
12
+ * @param item - The HistoryItem to convert
13
+ * @returns Event with proper type-safe structure
14
+ * @throws Error if the history item is malformed or has invalid data
12
15
  */
13
- function convertHistoryItemToEvent(item: HistoryItem): Event {
16
+ export function historyItemToEvent(item: HistoryItem): Event<MessageEventData | ToolEventData | StatusEventData> {
17
+ if (!item || typeof item !== 'object') {
18
+ throw new Error('Invalid history item: must be a non-null object');
19
+ }
20
+
21
+ if (!item.role || typeof item.role !== 'string') {
22
+ throw new Error('Invalid history item: role is required and must be a string');
23
+ }
24
+
14
25
  const timestamp = new Date().toISOString();
15
26
 
16
27
  switch (item.role) {
17
28
  case "user": {
29
+ const userItem = item;
30
+ if (typeof userItem.content !== 'string') {
31
+ throw new Error('Invalid user history item: content must be a string');
32
+ }
33
+
18
34
  return {
19
35
  kind: EventKind.MESSAGE,
20
36
  source: MessageRole.USER,
21
37
  timestamp,
22
38
  data: {
23
39
  participant: {
24
- display_name: item.name || "User",
40
+ display_name: userItem.name || "User",
25
41
  },
26
- message: item.content,
42
+ message: userItem.content,
27
43
  },
28
44
  };
29
45
  }
30
46
  case "assistant": {
31
- // Handle assistant message with optional tool calls
32
- const event: Event = {
47
+ const assistantItem = item;
48
+ if (assistantItem.content !== null && typeof assistantItem.content !== 'string') {
49
+ throw new Error('Invalid assistant history item: content must be a string or null');
50
+ }
51
+
52
+ const event: Event<MessageEventData> = {
33
53
  kind: EventKind.MESSAGE,
34
54
  source: MessageRole.ASSISTANT,
35
55
  timestamp,
@@ -37,19 +57,36 @@ function convertHistoryItemToEvent(item: HistoryItem): Event {
37
57
  participant: {
38
58
  display_name: "Assistant",
39
59
  },
40
- message: item.content || "",
60
+ message: assistantItem.content || "",
41
61
  },
42
62
  };
43
63
 
44
- // If there are tool calls, we need to create a separate tool event
45
- // But for now, we'll just store the tool calls in the message data
46
- if (item.tool_calls && item.tool_calls.length > 0) {
47
- (event.data as MessageEventData).toolCalls = item.tool_calls;
64
+ // If there are tool calls, validate and add them
65
+ if (assistantItem.tool_calls && assistantItem.tool_calls.length > 0) {
66
+ if (!Array.isArray(assistantItem.tool_calls)) {
67
+ throw new Error('Invalid assistant history item: tool_calls must be an array');
68
+ }
69
+
70
+ for (const toolCall of assistantItem.tool_calls) {
71
+ if (!toolCall.id || !toolCall.name || typeof toolCall.arguments !== 'object') {
72
+ throw new Error('Invalid tool call: id, name, and arguments are required');
73
+ }
74
+ }
75
+
76
+ event.data.toolCalls = assistantItem.tool_calls;
48
77
  }
49
78
 
50
79
  return event;
51
80
  }
52
81
  case "tool": {
82
+ const toolItem = item;
83
+ if (!toolItem.tool_call_id || typeof toolItem.tool_call_id !== 'string') {
84
+ throw new Error('Invalid tool history item: tool_call_id is required and must be a string');
85
+ }
86
+ if (!toolItem.name || typeof toolItem.name !== 'string') {
87
+ throw new Error('Invalid tool history item: name is required and must be a string');
88
+ }
89
+
53
90
  return {
54
91
  kind: EventKind.TOOL,
55
92
  source: MessageRole.AGENT,
@@ -57,10 +94,10 @@ function convertHistoryItemToEvent(item: HistoryItem): Event {
57
94
  data: {
58
95
  tool_calls: [
59
96
  {
60
- tool_id: item.tool_call_id,
97
+ tool_id: toolItem.tool_call_id,
61
98
  arguments: {}, // Tool results don't have arguments
62
99
  result: {
63
- data: item.content,
100
+ data: toolItem.content,
64
101
  },
65
102
  },
66
103
  ],
@@ -68,6 +105,11 @@ function convertHistoryItemToEvent(item: HistoryItem): Event {
68
105
  };
69
106
  }
70
107
  case "system": {
108
+ const systemItem = item;
109
+ if (typeof systemItem.content !== 'string') {
110
+ throw new Error('Invalid system history item: content must be a string');
111
+ }
112
+
71
113
  return {
72
114
  kind: EventKind.MESSAGE,
73
115
  source: MessageRole.SYSTEM,
@@ -76,31 +118,152 @@ function convertHistoryItemToEvent(item: HistoryItem): Event {
76
118
  participant: {
77
119
  display_name: "System",
78
120
  },
79
- message: item.content,
121
+ message: systemItem.content,
80
122
  },
81
123
  };
82
124
  }
83
125
  default:
84
- // This should never happen due to TypeScript, but fallback just in case
126
+ throw new Error(`Invalid history item role: ${String((item as { role?: unknown }).role)}`);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Convert an array of HistoryItems to Events
132
+ * @param history - Array of HistoryItems to convert
133
+ * @returns Array of Events with proper type-safe structure
134
+ * @throws Error if any history item is malformed
135
+ */
136
+ export function historyToEvents(history: History): Event<MessageEventData | ToolEventData | StatusEventData>[] {
137
+ if (!Array.isArray(history)) {
138
+ throw new Error('Invalid history: must be an array');
139
+ }
140
+
141
+ return history.map((item, index) => {
142
+ try {
143
+ return historyItemToEvent(item);
144
+ } catch (error) {
145
+ throw new Error(`Error converting history item at index ${index}: ${error instanceof Error ? error.message : 'Unknown error'}`);
146
+ }
147
+ });
148
+ }
149
+
150
+ /**
151
+ * Convert an Event back to a HistoryItem
152
+ * @param event - The Event to convert
153
+ * @returns HistoryItem with simplified structure
154
+ * @throws Error if the event is malformed or has invalid data
155
+ */
156
+ export function eventToHistoryItem(event: Event): HistoryItem {
157
+ if (!event || typeof event !== 'object') {
158
+ throw new Error('Invalid event: must be a non-null object');
159
+ }
160
+
161
+ if (!event.kind || !event.source || !event.data) {
162
+ throw new Error('Invalid event: kind, source, and data are required');
163
+ }
164
+
165
+ switch (event.kind) {
166
+ case EventKind.MESSAGE: {
167
+ const messageData = event.data as MessageEventData;
168
+ if (!messageData.message && messageData.message !== '') {
169
+ throw new Error('Invalid message event: message is required');
170
+ }
171
+
172
+ switch (event.source) {
173
+ case MessageRole.USER: {
174
+ const userItem: UserHistoryItem = {
175
+ role: "user",
176
+ content: messageData.message,
177
+ };
178
+
179
+ if (messageData.participant?.display_name && messageData.participant.display_name !== "User") {
180
+ userItem.name = messageData.participant.display_name;
181
+ }
182
+
183
+ return userItem;
184
+ }
185
+ case MessageRole.ASSISTANT: {
186
+ const assistantItem: AssistantHistoryItem = {
187
+ role: "assistant",
188
+ content: messageData.message || null,
189
+ };
190
+
191
+ if (messageData.toolCalls && messageData.toolCalls.length > 0) {
192
+ assistantItem.tool_calls = messageData.toolCalls;
193
+ }
194
+
195
+ return assistantItem;
196
+ }
197
+ case MessageRole.SYSTEM: {
198
+ return {
199
+ role: "system",
200
+ content: messageData.message,
201
+ };
202
+ }
203
+ default:
204
+ throw new Error(`Unsupported message source for conversion: ${event.source}`);
205
+ }
206
+ }
207
+ case EventKind.TOOL: {
208
+ const toolData = event.data as ToolEventData;
209
+ if (!toolData.tool_calls || !Array.isArray(toolData.tool_calls) || toolData.tool_calls.length === 0) {
210
+ throw new Error('Invalid tool event: tool_calls array is required and must not be empty');
211
+ }
212
+
213
+ const firstToolCall = toolData.tool_calls[0];
214
+ if (!firstToolCall.tool_id) {
215
+ throw new Error('Invalid tool call: tool_id is required');
216
+ }
217
+
218
+ const toolItem: ToolHistoryItem = {
219
+ role: "tool",
220
+ tool_call_id: firstToolCall.tool_id,
221
+ name: firstToolCall.tool_id, // Use tool_id as name for simplicity
222
+ content: firstToolCall.result?.data,
223
+ };
224
+
225
+ return toolItem;
226
+ }
227
+ case EventKind.STATUS: {
228
+ // Status events don't have a direct HistoryItem equivalent
229
+ // Convert to system message for compatibility
230
+ const statusData = event.data as StatusEventData;
85
231
  return {
86
- kind: EventKind.MESSAGE,
87
- source: MessageRole.SYSTEM,
88
- timestamp,
89
- data: {
90
- participant: {
91
- display_name: "Unknown",
92
- },
93
- message: "Unknown message type",
94
- },
232
+ role: "system",
233
+ content: statusData.status || "Status update",
95
234
  };
235
+ }
236
+ default:
237
+ throw new Error(`Unsupported event kind for conversion: ${String(event.kind)}`);
96
238
  }
97
239
  }
98
240
 
241
+ /**
242
+ * Convert an array of Events back to HistoryItems
243
+ * @param events - Array of Events to convert
244
+ * @returns Array of HistoryItems with simplified structure
245
+ * @throws Error if any event is malformed
246
+ */
247
+ export function eventsToHistory(events: Event[]): History {
248
+ if (!Array.isArray(events)) {
249
+ throw new Error('Invalid events: must be an array');
250
+ }
251
+
252
+ return events.map((event, index) => {
253
+ try {
254
+ return eventToHistoryItem(event);
255
+ } catch (error) {
256
+ throw new Error(`Error converting event at index ${index}: ${error instanceof Error ? error.message : 'Unknown error'}`);
257
+ }
258
+ });
259
+ }
260
+
99
261
  /**
100
262
  * Normalize a simplified history array to internal Event array
263
+ * @deprecated Use historyToEvents instead
101
264
  */
102
265
  export function normalizeHistory(history: History): Event[] {
103
- return history.map(convertHistoryItemToEvent);
266
+ return historyToEvents(history);
104
267
  }
105
268
 
106
269
  /**
@@ -140,4 +303,4 @@ export function toolMessage(
140
303
  */
141
304
  export function systemMessage(content: string): HistoryItem {
142
305
  return { role: "system", content };
143
- }
306
+ }
@@ -39,6 +39,10 @@ export { getLastMessageFromHistory } from "./event";
39
39
  // History utilities
40
40
  export {
41
41
  normalizeHistory,
42
+ historyItemToEvent,
43
+ historyToEvents,
44
+ eventToHistoryItem,
45
+ eventsToHistory,
42
46
  userMessage,
43
47
  assistantMessage,
44
48
  toolMessage,