@falai/agent 0.1.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 (129) hide show
  1. package/README.md +516 -0
  2. package/dist/constants/index.d.ts +5 -0
  3. package/dist/constants/index.d.ts.map +1 -0
  4. package/dist/constants/index.js +5 -0
  5. package/dist/constants/index.js.map +1 -0
  6. package/dist/core/Agent.d.ts +98 -0
  7. package/dist/core/Agent.d.ts.map +1 -0
  8. package/dist/core/Agent.js +248 -0
  9. package/dist/core/Agent.js.map +1 -0
  10. package/dist/core/DomainRegistry.d.ts +26 -0
  11. package/dist/core/DomainRegistry.d.ts.map +1 -0
  12. package/dist/core/DomainRegistry.js +41 -0
  13. package/dist/core/DomainRegistry.js.map +1 -0
  14. package/dist/core/Events.d.ts +19 -0
  15. package/dist/core/Events.d.ts.map +1 -0
  16. package/dist/core/Events.js +79 -0
  17. package/dist/core/Events.js.map +1 -0
  18. package/dist/core/Observation.d.ts +24 -0
  19. package/dist/core/Observation.d.ts.map +1 -0
  20. package/dist/core/Observation.js +35 -0
  21. package/dist/core/Observation.js.map +1 -0
  22. package/dist/core/PromptBuilder.d.ts +121 -0
  23. package/dist/core/PromptBuilder.d.ts.map +1 -0
  24. package/dist/core/PromptBuilder.js +339 -0
  25. package/dist/core/PromptBuilder.js.map +1 -0
  26. package/dist/core/Route.d.ts +46 -0
  27. package/dist/core/Route.d.ts.map +1 -0
  28. package/dist/core/Route.js +113 -0
  29. package/dist/core/Route.js.map +1 -0
  30. package/dist/core/State.d.ts +50 -0
  31. package/dist/core/State.d.ts.map +1 -0
  32. package/dist/core/State.js +110 -0
  33. package/dist/core/State.js.map +1 -0
  34. package/dist/core/Tool.d.ts +31 -0
  35. package/dist/core/Tool.d.ts.map +1 -0
  36. package/dist/core/Tool.js +33 -0
  37. package/dist/core/Tool.js.map +1 -0
  38. package/dist/core/Transition.d.ts +32 -0
  39. package/dist/core/Transition.d.ts.map +1 -0
  40. package/dist/core/Transition.js +59 -0
  41. package/dist/core/Transition.js.map +1 -0
  42. package/dist/index.d.ts +34 -0
  43. package/dist/index.d.ts.map +1 -0
  44. package/dist/index.js +26 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/providers/GeminiProvider.d.ts +40 -0
  47. package/dist/providers/GeminiProvider.d.ts.map +1 -0
  48. package/dist/providers/GeminiProvider.js +126 -0
  49. package/dist/providers/GeminiProvider.js.map +1 -0
  50. package/dist/providers/OpenAIProvider.d.ts +42 -0
  51. package/dist/providers/OpenAIProvider.d.ts.map +1 -0
  52. package/dist/providers/OpenAIProvider.js +164 -0
  53. package/dist/providers/OpenAIProvider.js.map +1 -0
  54. package/dist/providers/OpenRouterProvider.d.ts +46 -0
  55. package/dist/providers/OpenRouterProvider.d.ts.map +1 -0
  56. package/dist/providers/OpenRouterProvider.js +171 -0
  57. package/dist/providers/OpenRouterProvider.js.map +1 -0
  58. package/dist/types/agent.d.ts +105 -0
  59. package/dist/types/agent.d.ts.map +1 -0
  60. package/dist/types/agent.js +18 -0
  61. package/dist/types/agent.js.map +1 -0
  62. package/dist/types/ai.d.ts +78 -0
  63. package/dist/types/ai.d.ts.map +1 -0
  64. package/dist/types/ai.js +5 -0
  65. package/dist/types/ai.js.map +1 -0
  66. package/dist/types/history.d.ts +112 -0
  67. package/dist/types/history.d.ts.map +1 -0
  68. package/dist/types/history.js +34 -0
  69. package/dist/types/history.js.map +1 -0
  70. package/dist/types/index.d.ts +14 -0
  71. package/dist/types/index.d.ts.map +1 -0
  72. package/dist/types/index.js +7 -0
  73. package/dist/types/index.js.map +1 -0
  74. package/dist/types/observation.d.ts +25 -0
  75. package/dist/types/observation.d.ts.map +1 -0
  76. package/dist/types/observation.js +5 -0
  77. package/dist/types/observation.js.map +1 -0
  78. package/dist/types/prompt.d.ts +46 -0
  79. package/dist/types/prompt.d.ts.map +1 -0
  80. package/dist/types/prompt.js +16 -0
  81. package/dist/types/prompt.js.map +1 -0
  82. package/dist/types/route.d.ts +59 -0
  83. package/dist/types/route.d.ts.map +1 -0
  84. package/dist/types/route.js +5 -0
  85. package/dist/types/route.js.map +1 -0
  86. package/dist/types/tool.d.ts +46 -0
  87. package/dist/types/tool.d.ts.map +1 -0
  88. package/dist/types/tool.js +5 -0
  89. package/dist/types/tool.js.map +1 -0
  90. package/dist/utils/retry.d.ts +13 -0
  91. package/dist/utils/retry.d.ts.map +1 -0
  92. package/dist/utils/retry.js +70 -0
  93. package/dist/utils/retry.js.map +1 -0
  94. package/docs/API_REFERENCE.md +517 -0
  95. package/docs/CONSTRUCTOR_OPTIONS.md +256 -0
  96. package/docs/CONTRIBUTING.md +481 -0
  97. package/docs/GETTING_STARTED.md +328 -0
  98. package/docs/PROVIDERS.md +472 -0
  99. package/docs/PUBLISHING.md +174 -0
  100. package/docs/README.md +68 -0
  101. package/docs/STRUCTURE.md +32 -0
  102. package/examples/declarative-agent.ts +217 -0
  103. package/examples/healthcare-agent.ts +283 -0
  104. package/examples/openai-agent.ts +167 -0
  105. package/examples/travel-agent.ts +342 -0
  106. package/package.json +73 -0
  107. package/src/constants/index.ts +5 -0
  108. package/src/core/Agent.ts +307 -0
  109. package/src/core/DomainRegistry.ts +50 -0
  110. package/src/core/Events.ts +101 -0
  111. package/src/core/Observation.ts +46 -0
  112. package/src/core/PromptBuilder.ts +511 -0
  113. package/src/core/Route.ts +136 -0
  114. package/src/core/State.ts +153 -0
  115. package/src/core/Tool.ts +54 -0
  116. package/src/core/Transition.ts +66 -0
  117. package/src/index.ts +83 -0
  118. package/src/providers/GeminiProvider.ts +220 -0
  119. package/src/providers/OpenAIProvider.ts +272 -0
  120. package/src/providers/OpenRouterProvider.ts +282 -0
  121. package/src/types/agent.ts +112 -0
  122. package/src/types/ai.ts +85 -0
  123. package/src/types/history.ts +125 -0
  124. package/src/types/index.ts +56 -0
  125. package/src/types/observation.ts +27 -0
  126. package/src/types/prompt.ts +49 -0
  127. package/src/types/route.ts +68 -0
  128. package/src/types/tool.ts +53 -0
  129. package/src/utils/retry.ts +96 -0
@@ -0,0 +1,85 @@
1
+ /**
2
+ * AI provider strategy types
3
+ */
4
+
5
+ import type { Event } from "./history";
6
+
7
+ /**
8
+ * Reasoning/thinking configuration for AI models
9
+ */
10
+ export interface ReasoningConfig {
11
+ /**
12
+ * Effort level for reasoning models (OpenAI: gpt-5, o-series)
13
+ * - minimal: Fastest, least reasoning
14
+ * - low: Basic reasoning
15
+ * - medium: Balanced reasoning
16
+ * - high: Maximum reasoning effort
17
+ */
18
+ effort?: "minimal" | "low" | "medium" | "high";
19
+ /**
20
+ * Summary detail level of reasoning process
21
+ * - auto: Model decides
22
+ * - concise: Brief summary
23
+ * - detailed: Full reasoning details
24
+ */
25
+ summary?: "auto" | "concise" | "detailed";
26
+ /**
27
+ * Whether to include thinking/reasoning in response (Gemini)
28
+ */
29
+ includeThoughts?: boolean;
30
+ }
31
+
32
+ /**
33
+ * Input for AI message generation
34
+ */
35
+ export interface GenerateMessageInput<TContext = unknown> {
36
+ /** The constructed prompt */
37
+ prompt: string;
38
+ /** Interaction history */
39
+ history: Event[];
40
+ /** Context data */
41
+ context: TContext;
42
+ /** Additional generation parameters */
43
+ parameters?: {
44
+ /** Maximum output tokens to generate */
45
+ maxOutputTokens?: number;
46
+ /** Reasoning/thinking configuration */
47
+ reasoning?: ReasoningConfig;
48
+ };
49
+ /** Abort signal for cancellation */
50
+ signal?: AbortSignal;
51
+ }
52
+
53
+ /**
54
+ * Output from AI message generation
55
+ */
56
+ export interface GenerateMessageOutput {
57
+ /** The generated message */
58
+ message: string;
59
+ /** Optional metadata about generation */
60
+ metadata?: {
61
+ /** Model used */
62
+ model?: string;
63
+ /** Tokens consumed */
64
+ tokensUsed?: number;
65
+ /** Finish reason */
66
+ finishReason?: string;
67
+ /** Additional provider-specific data */
68
+ [key: string]: unknown;
69
+ };
70
+ }
71
+
72
+ /**
73
+ * AI provider interface (strategy pattern)
74
+ */
75
+ export interface AiProvider {
76
+ /** Provider name/identifier */
77
+ readonly name: string;
78
+
79
+ /**
80
+ * Generate a message based on prompt and context
81
+ */
82
+ generateMessage<TContext = unknown>(
83
+ input: GenerateMessageInput<TContext>
84
+ ): Promise<GenerateMessageOutput>;
85
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Event history and interaction types
3
+ */
4
+
5
+ /**
6
+ * Types of events in the interaction history
7
+ */
8
+ export enum EventKind {
9
+ /** A text message event */
10
+ MESSAGE = "message",
11
+ /** A tool execution event */
12
+ TOOL = "tool",
13
+ /** A status update event */
14
+ STATUS = "status",
15
+ }
16
+
17
+ /**
18
+ * Source of an event
19
+ */
20
+ export enum EventSource {
21
+ /** Event originated from the customer/user */
22
+ CUSTOMER = "customer",
23
+ /** Event from customer UI application */
24
+ CUSTOMER_UI = "customer_ui",
25
+ /** Event from human service agent */
26
+ HUMAN_AGENT = "human_agent",
27
+ /** Human agent acting on behalf of AI agent */
28
+ HUMAN_AGENT_ON_BEHALF_OF_AI_AGENT = "human_agent_on_behalf_of_ai_agent",
29
+ /** Event generated by AI agent */
30
+ AI_AGENT = "ai_agent",
31
+ /** System-generated event */
32
+ SYSTEM = "system",
33
+ }
34
+
35
+ /**
36
+ * Participant in a conversation
37
+ */
38
+ export interface Participant {
39
+ /** Display name */
40
+ display_name: string;
41
+ /** Unique identifier */
42
+ id?: string;
43
+ }
44
+
45
+ /**
46
+ * Data for a message event
47
+ */
48
+ export interface MessageEventData {
49
+ /** The participant who sent the message */
50
+ participant: Participant;
51
+ /** The message content */
52
+ message: string;
53
+ /** Whether the message was flagged/censored */
54
+ flagged?: boolean;
55
+ /** Tags/reasons if flagged */
56
+ tags?: string[];
57
+ }
58
+
59
+ /**
60
+ * Result of a tool execution
61
+ */
62
+ export interface ToolResult<TData = unknown> {
63
+ /** The result data */
64
+ data: TData;
65
+ /** Optional metadata */
66
+ meta?: Record<string, unknown>;
67
+ }
68
+
69
+ /**
70
+ * A single tool call within a tool event
71
+ */
72
+ export interface ToolCall<TArgs = unknown, TResult = unknown> {
73
+ /** Tool identifier */
74
+ tool_id: string;
75
+ /** Arguments passed to the tool */
76
+ arguments: TArgs;
77
+ /** Result returned by the tool */
78
+ result: ToolResult<TResult>;
79
+ }
80
+
81
+ /**
82
+ * Data for a tool event
83
+ */
84
+ export interface ToolEventData {
85
+ /** Array of tool calls executed */
86
+ tool_calls: ToolCall[];
87
+ }
88
+
89
+ /**
90
+ * Data for a status event
91
+ */
92
+ export interface StatusEventData {
93
+ /** Status message */
94
+ status: string;
95
+ /** Additional details */
96
+ details?: Record<string, unknown>;
97
+ }
98
+
99
+ /**
100
+ * Base event structure
101
+ */
102
+ export interface Event<
103
+ TData = MessageEventData | ToolEventData | StatusEventData
104
+ > {
105
+ /** Type of event */
106
+ kind: EventKind;
107
+ /** Source of the event */
108
+ source: EventSource;
109
+ /** Event-specific data */
110
+ data: TData;
111
+ /** Timestamp (ISO string) */
112
+ timestamp?: string;
113
+ /** Unique event identifier */
114
+ id?: string;
115
+ }
116
+
117
+ /**
118
+ * An emitted event (staged for inclusion)
119
+ */
120
+ export interface EmittedEvent<
121
+ TData = MessageEventData | ToolEventData | StatusEventData
122
+ > extends Event<TData> {
123
+ /** Whether this event has been committed */
124
+ committed?: boolean;
125
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Central type definitions export
3
+ */
4
+
5
+ // Agent types
6
+ export type {
7
+ AgentOptions,
8
+ Term,
9
+ Guideline,
10
+ Capability,
11
+ GuidelineMatch,
12
+ } from "./agent";
13
+ export { CompositionMode } from "./agent";
14
+
15
+ // History types
16
+ export type {
17
+ Event,
18
+ EmittedEvent,
19
+ MessageEventData,
20
+ ToolEventData,
21
+ StatusEventData,
22
+ Participant,
23
+ ToolResult as EventToolResult,
24
+ ToolCall,
25
+ } from "./history";
26
+ export { EventKind, EventSource } from "./history";
27
+
28
+ // Route types
29
+ export type {
30
+ RouteRef,
31
+ StateRef,
32
+ RouteOptions,
33
+ TransitionSpec,
34
+ TransitionResult,
35
+ } from "./route";
36
+
37
+ // Tool types
38
+ export type { ToolContext, ToolResult, ToolHandler, ToolRef } from "./tool";
39
+
40
+ // AI provider types
41
+ export type {
42
+ AiProvider,
43
+ GenerateMessageInput,
44
+ GenerateMessageOutput,
45
+ } from "./ai";
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";
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Observation types for disambiguation
3
+ */
4
+
5
+ import type { RouteRef } from "./route";
6
+
7
+ /**
8
+ * An observation that can disambiguate between multiple routes
9
+ */
10
+ export interface Observation {
11
+ /** Unique identifier */
12
+ id: string;
13
+ /** The observation description */
14
+ description: string;
15
+ /** Routes this observation can disambiguate between */
16
+ routes?: RouteRef[];
17
+ }
18
+
19
+ /**
20
+ * Options for creating an observation
21
+ */
22
+ export interface ObservationOptions {
23
+ /** The observation description */
24
+ description: string;
25
+ /** Route IDs or titles to disambiguate between (can be set later with disambiguate()) */
26
+ routeRefs?: string[];
27
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Prompt building types
3
+ */
4
+
5
+ /**
6
+ * Status of a prompt section
7
+ */
8
+ export enum SectionStatus {
9
+ /** Section has active information */
10
+ ACTIVE = "active",
11
+ /** Section is inactive but may have empty-state text */
12
+ PASSIVE = "passive",
13
+ /** Section is not included */
14
+ NONE = "none",
15
+ }
16
+
17
+ /**
18
+ * A section within a prompt
19
+ */
20
+ export interface PromptSection {
21
+ /** Template string (may contain placeholders) */
22
+ template: string;
23
+ /** Properties to fill template placeholders */
24
+ props: Record<string, unknown>;
25
+ /** Status of this section */
26
+ status?: SectionStatus;
27
+ }
28
+
29
+ /**
30
+ * Context variable with value
31
+ */
32
+ export interface ContextVariable {
33
+ /** Variable name */
34
+ name: string;
35
+ /** Variable description */
36
+ description?: string;
37
+ /** Variable type */
38
+ type?: string;
39
+ }
40
+
41
+ /**
42
+ * Value for a context variable
43
+ */
44
+ export interface ContextVariableValue {
45
+ /** The variable definition */
46
+ variable: ContextVariable;
47
+ /** The current value */
48
+ value: unknown;
49
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Route/Journey DSL type definitions
3
+ */
4
+
5
+ import type { ToolRef } from "./tool";
6
+
7
+ /**
8
+ * Reference to a route
9
+ */
10
+ export interface RouteRef {
11
+ /** Route identifier */
12
+ id: string;
13
+ }
14
+
15
+ /**
16
+ * Reference to a state within a route
17
+ */
18
+ export interface StateRef {
19
+ /** State identifier */
20
+ id: string;
21
+ /** Route this state belongs to */
22
+ routeId: string;
23
+ }
24
+
25
+ /**
26
+ * Forward declare Guideline for circular dependency
27
+ */
28
+ import type { Guideline } from "./agent";
29
+
30
+ /**
31
+ * Options for creating a route
32
+ */
33
+ export interface RouteOptions {
34
+ /** Title of the route */
35
+ title: string;
36
+ /** Description of what this route accomplishes */
37
+ description?: string;
38
+ /** Conditions that activate this route */
39
+ conditions?: string[];
40
+ /** Initial guidelines for this route */
41
+ guidelines?: Guideline[];
42
+ }
43
+
44
+ /**
45
+ * Specification for a state transition
46
+ */
47
+ export interface TransitionSpec {
48
+ /** Transition to a chat state with this description */
49
+ chatState?: string;
50
+ /** Transition to execute a tool */
51
+ toolState?: ToolRef<unknown, unknown[], unknown>;
52
+ /** Transition to a specific state or end marker */
53
+ state?: StateRef | symbol;
54
+ }
55
+
56
+ /**
57
+ * Result of a transition operation
58
+ */
59
+ export interface TransitionResult {
60
+ /** The target state after transition */
61
+ target: StateRef & {
62
+ /** Allow chaining transitions */
63
+ transitionTo: (
64
+ spec: TransitionSpec,
65
+ condition?: string
66
+ ) => TransitionResult;
67
+ };
68
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Tool system type definitions
3
+ */
4
+
5
+ import type { Event, StateRef } from "./index";
6
+
7
+ /**
8
+ * Context provided to tool handlers
9
+ */
10
+ export interface ToolContext<TContext = unknown> {
11
+ /** The agent's context data */
12
+ context: TContext;
13
+ /** Current state reference (if in a route) */
14
+ state?: StateRef;
15
+ /** Interaction history */
16
+ history: Event[];
17
+ /** Additional metadata */
18
+ metadata?: Record<string, unknown>;
19
+ }
20
+
21
+ /**
22
+ * Result returned by a tool
23
+ */
24
+ export interface ToolResult<TData = unknown> {
25
+ /** The result data */
26
+ data: TData;
27
+ /** Optional metadata about the execution */
28
+ meta?: Record<string, unknown>;
29
+ }
30
+
31
+ /**
32
+ * Handler function for a tool
33
+ */
34
+ export type ToolHandler<TContext, TArgs extends unknown[], TResult> = (
35
+ context: ToolContext<TContext>,
36
+ ...args: TArgs
37
+ ) => Promise<ToolResult<TResult>> | ToolResult<TResult>;
38
+
39
+ /**
40
+ * Reference to a defined tool
41
+ */
42
+ export interface ToolRef<TContext, TArgs extends unknown[], TResult> {
43
+ /** Tool identifier */
44
+ id: string;
45
+ /** Tool name */
46
+ name: string;
47
+ /** Tool handler function */
48
+ handler: ToolHandler<TContext, TArgs, TResult>;
49
+ /** Description of what the tool does */
50
+ description?: string;
51
+ /** Parameter schema or description */
52
+ parameters?: unknown;
53
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Retry utility with exponential backoff
3
+ */
4
+
5
+ export interface RetryOptions<T> {
6
+ operation: () => Promise<T>;
7
+ maxRetries: number;
8
+ delay: (attempt: number) => number;
9
+ onRetry?: (attempt: number, error: unknown) => void;
10
+ onFailure?: (error: unknown) => boolean;
11
+ }
12
+
13
+ export async function retry<T>(options: RetryOptions<T>): Promise<T> {
14
+ const { operation, maxRetries, delay, onRetry, onFailure } = options;
15
+
16
+ let lastError: unknown;
17
+
18
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
19
+ try {
20
+ return await operation();
21
+ } catch (error: unknown) {
22
+ lastError = error;
23
+
24
+ if (attempt === maxRetries) {
25
+ const shouldRethrow = onFailure ? onFailure(lastError) : true;
26
+ if (shouldRethrow) {
27
+ throw lastError;
28
+ }
29
+ break;
30
+ }
31
+
32
+ if (onRetry) {
33
+ onRetry(attempt, lastError);
34
+ }
35
+
36
+ const delayMs = delay(attempt);
37
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
38
+ }
39
+ }
40
+
41
+ // eslint-disable-next-line @typescript-eslint/only-throw-error
42
+ throw lastError ?? new Error("Operation failed");
43
+ }
44
+
45
+ export const withTimeoutAndRetry = async <T>(
46
+ operation: () => Promise<T>,
47
+ timeoutMs: number = 60000,
48
+ maxRetries: number = 3,
49
+ operationName: string = "AI operation"
50
+ ): Promise<T> => {
51
+ const createTimeoutOperation = () => async (): Promise<T> => {
52
+ const controller = new AbortController();
53
+ const timeoutId = setTimeout(() => {
54
+ controller.abort();
55
+ }, timeoutMs);
56
+
57
+ try {
58
+ const result = await Promise.race([
59
+ operation(),
60
+ new Promise<never>((_, reject) => {
61
+ controller.signal.addEventListener("abort", () => {
62
+ reject(new Error(`Operation timed out after ${timeoutMs}ms`));
63
+ });
64
+ }),
65
+ ]);
66
+
67
+ clearTimeout(timeoutId);
68
+ return result;
69
+ } catch (error: unknown) {
70
+ clearTimeout(timeoutId);
71
+ throw error;
72
+ }
73
+ };
74
+
75
+ return retry<T>({
76
+ operation: createTimeoutOperation(),
77
+ maxRetries,
78
+ delay: (attempt: number) => Math.min(1000 * Math.pow(2, attempt), 5000),
79
+ onRetry: (attempt: number, error: unknown) => {
80
+ const message = error instanceof Error ? error.message : String(error);
81
+ console.error(
82
+ `[${operationName}] Failed attempt ${attempt + 1}:`,
83
+ message
84
+ );
85
+ const delay = Math.min(1000 * Math.pow(2, attempt), 5000);
86
+ console.log(`[${operationName}] Retrying in ${delay}ms...`);
87
+ console.log(
88
+ `[${operationName}] Attempt ${attempt + 2}/${maxRetries + 1}`
89
+ );
90
+ },
91
+ onFailure: (_error: unknown) => {
92
+ console.error(`[${operationName}] All ${maxRetries + 1} attempts failed`);
93
+ return true;
94
+ },
95
+ });
96
+ };