@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
@@ -1,17 +1,13 @@
1
1
  /**
2
2
  * Core Agent implementation
3
3
  */
4
- import { EventKind, MessageRole } from "../types/history";
5
- import { enterRoute, enterStep, mergeCollected, logger, LoggerLevel, render, getLastMessageFromHistory, normalizeHistory, cloneDeep, } from "../utils";
4
+ import { mergeCollected, logger, LoggerLevel, render, } from "../utils";
6
5
  import { Route } from "./Route";
7
- import { Step } from "./Step";
8
6
  import { PersistenceManager } from "./PersistenceManager";
9
7
  import { SessionManager } from "./SessionManager";
10
8
  import { RoutingEngine } from "./RoutingEngine";
11
- import { ResponseEngine } from "./ResponseEngine";
12
- import { ToolExecutor } from "./ToolExecutor";
13
- import { ResponsePipeline } from "./ResponsePipeline";
14
- import { END_ROUTE_ID } from "../constants";
9
+ import { ResponseModal } from "./ResponseModal";
10
+ import { ToolManager } from "./ToolManager";
15
11
  /**
16
12
  * Error thrown when data validation fails
17
13
  */
@@ -75,14 +71,14 @@ export class Agent {
75
71
  }
76
72
  // Initialize current session if provided
77
73
  this.currentSession = options.session;
78
- // Initialize routing and response engines
74
+ // Initialize routing engine
79
75
  this.routingEngine = new RoutingEngine({
80
76
  maxCandidates: 5,
81
77
  allowRouteSwitch: true,
82
78
  switchThreshold: 70,
83
79
  });
84
- this.responseEngine = new ResponseEngine();
85
- this.responsePipeline = new ResponsePipeline(options, this.routes, this.tools, this.routingEngine, this.updateContext.bind(this), this.updateData.bind(this), this.updateCollectedData.bind(this));
80
+ // Initialize ResponseModal for handling all response generation
81
+ this.responseModal = new ResponseModal(this);
86
82
  // Initialize persistence if configured
87
83
  if (options.persistence) {
88
84
  try {
@@ -135,12 +131,21 @@ export class Agent {
135
131
  if (options.knowledgeBase) {
136
132
  this.knowledgeBase = { ...options.knowledgeBase };
137
133
  }
138
- // Initialize session manager
139
- this.session = new SessionManager(this.persistenceManager);
134
+ // Initialize session manager with reference to this agent for bidirectional sync
135
+ this.session = new SessionManager(this.persistenceManager, this);
136
+ // Initialize tool manager with proper type inference
137
+ this.tool = new ToolManager(this);
140
138
  // Store sessionId for later use in getOrCreate calls
141
139
  if (options.sessionId) {
140
+ this.session.setDefaultSessionId(options.sessionId);
142
141
  // The session will be loaded on first getOrCreate call
143
- this.session.getOrCreate(options.sessionId).catch((err) => {
142
+ this.session.getOrCreate(options.sessionId).then((session) => {
143
+ // Sync session data to agent collected data
144
+ if (session.data && Object.keys(session.data).length > 0) {
145
+ this.collectedData = { ...session.data };
146
+ logger.debug("[Agent] Synced session data to collected data:", this.collectedData);
147
+ }
148
+ }).catch((err) => {
144
149
  logger.error("Failed to start session", err);
145
150
  });
146
151
  }
@@ -222,6 +227,8 @@ export class Agent {
222
227
  * Get the current collected data
223
228
  */
224
229
  getCollectedData() {
230
+ // Ensure agent collected data is synced with session
231
+ this.syncSessionDataToCollectedData();
225
232
  return { ...this.collectedData };
226
233
  }
227
234
  /**
@@ -253,6 +260,12 @@ export class Agent {
253
260
  if (this.currentSession) {
254
261
  this.currentSession = mergeCollected(this.currentSession, this.collectedData);
255
262
  }
263
+ // Also update the session manager's session data (avoid circular call)
264
+ const sessionManagerSession = this.session.current;
265
+ if (sessionManagerSession) {
266
+ sessionManagerSession.data = { ...this.collectedData };
267
+ sessionManagerSession.metadata.lastUpdatedAt = new Date();
268
+ }
256
269
  logger.debug("[Agent] Collected data updated:", updates);
257
270
  }
258
271
  /**
@@ -299,7 +312,7 @@ export class Agent {
299
312
  `Must be valid keys from agent schema. Available fields: ${Object.keys(this.schema.properties).join(', ')}.`);
300
313
  }
301
314
  }
302
- const route = new Route(options);
315
+ const route = new Route(options, this);
303
316
  this.routes.push(route);
304
317
  return route;
305
318
  }
@@ -323,17 +336,47 @@ export class Agent {
323
336
  return this;
324
337
  }
325
338
  /**
326
- * Register a tool at the agent level
339
+ * Add a tool to the agent using the unified Tool interface
340
+ * Creates and adds the tool to agent scope in one operation (BREAKING CHANGE: replaces createTool)
341
+ */
342
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
343
+ addTool(tool) {
344
+ // Validate tool before adding
345
+ if (!tool || !tool.id || !tool.handler) {
346
+ throw new Error('Invalid tool: must have id and handler properties');
347
+ }
348
+ // Add directly to agent's tools array, preserving the TResult type
349
+ this.tools.push(tool);
350
+ logger.debug(`[Agent] Added tool to agent scope: ${tool.id}`);
351
+ return this;
352
+ }
353
+ /**
354
+ * Register a tool at the agent level (legacy method for backward compatibility)
355
+ * @deprecated Use addTool() with Tool interface instead
327
356
  */
357
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
328
358
  createTool(tool) {
359
+ // Validate tool before adding
360
+ if (!tool || !tool.id || !tool.handler) {
361
+ throw new Error('Invalid tool: must have id and handler properties');
362
+ }
329
363
  this.tools.push(tool);
364
+ logger.debug(`[Agent] Created tool (legacy): ${tool.id}`);
330
365
  return this;
331
366
  }
332
367
  /**
333
368
  * Register multiple tools at the agent level
334
369
  */
370
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
335
371
  registerTools(tools) {
336
- tools.forEach((tool) => this.createTool(tool));
372
+ tools.forEach((tool) => {
373
+ // Validate each tool before adding
374
+ if (!tool || !tool.id || !tool.handler) {
375
+ throw new Error(`Invalid tool in batch: must have id and handler properties (tool: ${tool?.id || 'unknown'})`);
376
+ }
377
+ this.tools.push(tool);
378
+ });
379
+ logger.debug(`[Agent] Registered ${tools.length} tools`);
337
380
  return this;
338
381
  }
339
382
  /**
@@ -409,916 +452,15 @@ export class Agent {
409
452
  * Generate a response based on history and context as a stream
410
453
  */
411
454
  async *respondStream(params) {
412
- const { history: simpleHistory, signal } = params;
413
- const history = normalizeHistory(simpleHistory);
414
- // Prepare context and session using the response pipeline
415
- this.responsePipeline.setContext(this.context);
416
- this.responsePipeline.setCurrentSession(this.currentSession);
417
- let session;
418
- const responseContext = await this.responsePipeline.prepareResponseContext({
419
- contextOverride: params.contextOverride,
420
- session: params.session ? cloneDeep(params.session) : undefined,
421
- });
422
- const { effectiveContext } = responseContext;
423
- session = responseContext.session;
424
- // Merge agent's collected data into session (agent data takes precedence)
425
- if (Object.keys(this.collectedData).length > 0) {
426
- session = mergeCollected(session, this.collectedData);
427
- logger.debug("[Agent] Merged agent collected data into session:", this.collectedData);
428
- }
429
- // Update our stored context if it was modified by beforeRespond hook
430
- this.context = this.responsePipeline.getStoredContext();
431
- // PHASE 1: PREPARE - Execute prepare function if current step has one
432
- if (session.currentRoute && session.currentStep) {
433
- const currentRoute = this.routes.find((r) => r.id === session.currentRoute?.id);
434
- if (currentRoute) {
435
- const currentStep = currentRoute.getStep(session.currentStep.id);
436
- if (currentStep?.prepare) {
437
- logger.debug(`[Agent] Executing prepare for step: ${currentStep.id}`);
438
- await this.executePrepareFinalize(currentStep.prepare, effectiveContext, session.data, currentRoute, currentStep);
439
- }
440
- }
441
- }
442
- // PHASE 2: ROUTING + STEP SELECTION - Use response pipeline
443
- const routingResult = await this.responsePipeline.handleRoutingAndStepSelection({
444
- session,
445
- history,
446
- context: effectiveContext,
447
- signal,
448
- });
449
- const selectedRoute = routingResult.selectedRoute;
450
- const selectedStep = routingResult.selectedStep;
451
- const responseDirectives = routingResult.responseDirectives;
452
- const isRouteComplete = routingResult.isRouteComplete;
453
- session = routingResult.session;
454
- // PHASE 3: DETERMINE NEXT STEP - Use pipeline method
455
- const stepResult = this.responsePipeline.determineNextStep({
456
- selectedRoute,
457
- selectedStep,
458
- session,
459
- isRouteComplete,
460
- });
461
- const nextStep = stepResult.nextStep;
462
- session = stepResult.session;
463
- if (selectedRoute && !isRouteComplete) {
464
- // PHASE 4: RESPONSE GENERATION - Stream message using selected route and step
465
- // Get last user message
466
- const lastUserMessage = getLastMessageFromHistory(history);
467
- // Build response schema for this route (with collect fields from step)
468
- const responseSchema = this.responseEngine.responseSchemaForRoute(selectedRoute, nextStep, this.schema);
469
- // Check if selected route and next step are defined
470
- if (!selectedRoute || !nextStep) {
471
- logger.error("[Agent] Selected route or next step is not defined", {
472
- selectedRoute,
473
- nextStep,
474
- });
475
- throw new Error("Selected route or next step is not defined");
476
- }
477
- // Build response prompt
478
- const responsePrompt = await this.responseEngine.buildResponsePrompt({
479
- route: selectedRoute,
480
- currentStep: nextStep,
481
- rules: selectedRoute.getRules(),
482
- prohibitions: selectedRoute.getProhibitions(),
483
- directives: responseDirectives,
484
- history,
485
- lastMessage: lastUserMessage,
486
- agentOptions: this.options,
487
- // Combine agent and route properties according to the specified logic
488
- combinedGuidelines: [
489
- ...this.getGuidelines(),
490
- ...selectedRoute.getGuidelines(),
491
- ],
492
- combinedTerms: this.mergeTerms(this.getTerms(), selectedRoute.getTerms()),
493
- context: effectiveContext,
494
- session,
495
- agentSchema: this.schema,
496
- });
497
- // Collect available tools for AI
498
- const availableTools = this.collectAvailableTools(selectedRoute, nextStep);
499
- // Generate message stream using AI provider
500
- const stream = this.options.provider.generateMessageStream({
501
- prompt: responsePrompt,
502
- history,
503
- context: effectiveContext,
504
- tools: availableTools,
505
- signal,
506
- parameters: {
507
- jsonSchema: responseSchema,
508
- schemaName: "response_stream_output",
509
- },
510
- });
511
- // Stream chunks to caller
512
- for await (const chunk of stream) {
513
- let toolCalls = undefined;
514
- // Extract tool calls from AI response on final chunk
515
- if (chunk.done && chunk.structured?.toolCalls) {
516
- toolCalls = chunk.structured.toolCalls;
517
- // Execute dynamic tool calls
518
- if (toolCalls.length > 0) {
519
- logger.debug(`[Agent] Executing ${toolCalls.length} dynamic tool calls`);
520
- for (const toolCall of toolCalls) {
521
- const tool = this.findAvailableTool(toolCall.toolName, selectedRoute);
522
- if (!tool) {
523
- logger.warn(`[Agent] Tool not found: ${toolCall.toolName}`);
524
- continue;
525
- }
526
- const toolExecutor = new ToolExecutor();
527
- const result = await toolExecutor.executeTool({
528
- tool: tool,
529
- context: effectiveContext,
530
- updateContext: this.updateContext.bind(this),
531
- updateData: this.updateCollectedData.bind(this),
532
- history,
533
- data: session.data,
534
- toolArguments: toolCall.arguments,
535
- });
536
- // Update context with tool results
537
- if (result.contextUpdate) {
538
- await this.updateContext(result.contextUpdate);
539
- }
540
- // Update collected data with tool results
541
- if (result.dataUpdate) {
542
- session = await this.updateData(session, result.dataUpdate);
543
- logger.debug(`[Agent] Tool updated collected data:`, result.dataUpdate);
544
- }
545
- logger.debug(`[Agent] Executed dynamic tool: ${result.toolName} (success: ${result.success})`);
546
- }
547
- }
548
- }
549
- // TOOL LOOP: Allow AI to make follow-up tool calls after initial tool execution (streaming)
550
- const MAX_TOOL_LOOPS = 5;
551
- let toolLoopCount = 0;
552
- let hasToolCalls = toolCalls && toolCalls.length > 0;
553
- while (hasToolCalls && toolLoopCount < MAX_TOOL_LOOPS) {
554
- toolLoopCount++;
555
- logger.debug(`[Agent] Starting streaming tool loop ${toolLoopCount}/${MAX_TOOL_LOOPS}`);
556
- // Add tool execution results to history so AI knows what happened
557
- const toolResultsEvents = [];
558
- for (const toolCall of toolCalls || []) {
559
- const tool = this.findAvailableTool(toolCall.toolName, selectedRoute);
560
- if (tool) {
561
- toolResultsEvents.push({
562
- kind: EventKind.TOOL,
563
- source: MessageRole.AGENT,
564
- timestamp: new Date().toISOString(),
565
- data: {
566
- tool_calls: [
567
- {
568
- tool_id: toolCall.toolName,
569
- arguments: toolCall.arguments,
570
- result: {
571
- data: "Tool executed successfully",
572
- },
573
- },
574
- ],
575
- },
576
- });
577
- }
578
- }
579
- // Create updated history with tool results
580
- const updatedHistory = [...history, ...toolResultsEvents];
581
- // Make follow-up streaming AI call to see if more tools are needed
582
- const followUpStream = this.options.provider.generateMessageStream({
583
- prompt: responsePrompt,
584
- history: updatedHistory,
585
- context: effectiveContext,
586
- tools: availableTools,
587
- parameters: {
588
- jsonSchema: responseSchema,
589
- schemaName: "tool_followup",
590
- },
591
- signal,
592
- });
593
- let followUpToolCalls;
594
- for await (const followUpChunk of followUpStream) {
595
- // Extract tool calls from follow-up stream
596
- if (followUpChunk.done && followUpChunk.structured?.toolCalls) {
597
- followUpToolCalls = followUpChunk.structured.toolCalls;
598
- }
599
- }
600
- hasToolCalls = followUpToolCalls && followUpToolCalls.length > 0;
601
- if (hasToolCalls) {
602
- logger.debug(`[Agent] Follow-up streaming call produced ${followUpToolCalls.length} additional tool calls`);
603
- // Execute the follow-up tool calls
604
- for (const toolCall of followUpToolCalls) {
605
- const tool = this.findAvailableTool(toolCall.toolName, selectedRoute);
606
- if (!tool) {
607
- logger.warn(`[Agent] Tool not found in streaming follow-up: ${toolCall.toolName}`);
608
- continue;
609
- }
610
- const toolExecutor = new ToolExecutor();
611
- const result = await toolExecutor.executeTool({
612
- tool: tool,
613
- context: effectiveContext,
614
- updateContext: this.updateContext.bind(this),
615
- updateData: this.updateCollectedData.bind(this),
616
- history: updatedHistory,
617
- data: session.data,
618
- toolArguments: toolCall.arguments,
619
- });
620
- // Update context with follow-up tool results
621
- if (result.contextUpdate) {
622
- await this.updateContext(result.contextUpdate);
623
- }
624
- if (result.dataUpdate) {
625
- session = await this.updateData(session, result.dataUpdate);
626
- logger.debug(`[Agent] Streaming follow-up tool updated collected data:`, result.dataUpdate);
627
- }
628
- logger.debug(`[Agent] Executed streaming follow-up tool: ${result.toolName} (success: ${result.success})`);
629
- }
630
- // Update toolCalls for next iteration
631
- toolCalls = followUpToolCalls;
632
- }
633
- else {
634
- logger.debug(`[Agent] Streaming tool loop completed after ${toolLoopCount} iterations`);
635
- // Update toolCalls for final response
636
- toolCalls = followUpToolCalls || [];
637
- break;
638
- }
639
- }
640
- if (toolLoopCount >= MAX_TOOL_LOOPS) {
641
- logger.warn(`[Agent] Streaming tool loop limit reached (${MAX_TOOL_LOOPS}), stopping`);
642
- }
643
- // Extract collected data on final chunk
644
- if (chunk.done && chunk.structured && nextStep.collect) {
645
- const collectedData = {};
646
- // The structured response includes both base fields and collected extraction fields
647
- const structuredData = chunk.structured;
648
- for (const field of nextStep.collect) {
649
- const fieldKey = String(field);
650
- if (fieldKey in structuredData) {
651
- collectedData[fieldKey] = structuredData[fieldKey];
652
- }
653
- }
654
- // Merge collected data into session using agent-level data validation
655
- if (Object.keys(collectedData).length > 0) {
656
- // Update agent-level collected data with validation
657
- await this.updateCollectedData(collectedData);
658
- // Update session with validated data
659
- session = await this.updateData(session, collectedData);
660
- logger.debug(`[Agent] Collected data:`, collectedData);
661
- }
662
- }
663
- // Extract any additional data from structured response on final chunk
664
- if (chunk.done &&
665
- chunk.structured &&
666
- typeof chunk.structured === "object" &&
667
- "contextUpdate" in chunk.structured) {
668
- await this.updateContext(chunk.structured
669
- .contextUpdate);
670
- }
671
- // Auto-save session step on final chunk
672
- if (chunk.done &&
673
- this.persistenceManager &&
674
- session.id &&
675
- this.options.persistence?.autoSave !== false) {
676
- await this.persistenceManager.saveSessionState(session.id, session);
677
- logger.debug(`[Agent] Auto-saved session step to persistence: ${session.id}`);
678
- }
679
- // Execute finalize function on final chunk
680
- if (chunk.done && session.currentRoute && session.currentStep) {
681
- const currentRoute = this.routes.find((r) => r.id === session.currentRoute?.id);
682
- if (currentRoute) {
683
- const currentStep = currentRoute.getStep(session.currentStep.id);
684
- if (currentStep?.finalize) {
685
- logger.debug(`[Agent] Executing finalize for step: ${currentStep.id}`);
686
- await this.executePrepareFinalize(currentStep.finalize, effectiveContext, session.data, currentRoute, currentStep);
687
- }
688
- }
689
- }
690
- // Update current session if we have one
691
- if (chunk.done && this.currentSession) {
692
- this.currentSession = session;
693
- }
694
- yield {
695
- delta: chunk.delta,
696
- accumulated: chunk.accumulated,
697
- done: chunk.done,
698
- session, // Return updated session
699
- toolCalls,
700
- isRouteComplete,
701
- metadata: chunk.metadata,
702
- structured: chunk.structured,
703
- };
704
- }
705
- }
706
- else if (isRouteComplete && selectedRoute) {
707
- // Route is complete - generate completion message then check for onComplete transition
708
- const lastUserMessage = getLastMessageFromHistory(history);
709
- // Get endStep spec from route
710
- const endStepSpec = selectedRoute.endStepSpec;
711
- // Create a temporary step for completion message generation using endStep configuration
712
- const completionStep = new Step(selectedRoute.id, {
713
- description: endStepSpec.description,
714
- id: endStepSpec.id || END_ROUTE_ID,
715
- collect: endStepSpec.collect,
716
- requires: endStepSpec.requires,
717
- prompt: endStepSpec.prompt ||
718
- "Summarize what was accomplished and confirm completion based on the conversation history and collected data",
719
- });
720
- // Build response schema for completion
721
- const responseSchema = this.responseEngine.responseSchemaForRoute(selectedRoute, completionStep, this.schema);
722
- const templateContext = {
723
- context: effectiveContext,
724
- session,
725
- history,
726
- };
727
- // Build completion response prompt
728
- const completionPrompt = await this.responseEngine.buildResponsePrompt({
729
- route: selectedRoute,
730
- currentStep: completionStep,
731
- rules: selectedRoute.getRules(),
732
- prohibitions: selectedRoute.getProhibitions(),
733
- directives: undefined, // No directives for completion
734
- history,
735
- lastMessage: lastUserMessage,
736
- agentOptions: this.options,
737
- // Combine agent and route properties according to the specified logic
738
- combinedGuidelines: [
739
- ...this.getGuidelines(),
740
- ...selectedRoute.getGuidelines(),
741
- ],
742
- combinedTerms: this.mergeTerms(this.getTerms(), selectedRoute.getTerms()),
743
- context: effectiveContext,
744
- session,
745
- agentSchema: this.schema,
746
- });
747
- // Stream completion message using AI provider
748
- const stream = this.options.provider.generateMessageStream({
749
- prompt: completionPrompt,
750
- history,
751
- context: effectiveContext,
752
- signal,
753
- parameters: {
754
- jsonSchema: responseSchema,
755
- schemaName: "completion_message_stream",
756
- },
757
- });
758
- logger.debug(`[Agent] Streaming completion message for route: ${selectedRoute.title}`);
759
- // Check for onComplete transition
760
- const transitionConfig = await selectedRoute.evaluateOnComplete({ data: session.data }, effectiveContext);
761
- if (transitionConfig) {
762
- // Find target route by ID or title
763
- const targetRoute = this.routes.find((r) => r.id === transitionConfig.nextStep ||
764
- r.title === transitionConfig.nextStep);
765
- if (targetRoute) {
766
- const renderedCondition = await render(transitionConfig.condition, templateContext);
767
- // Set pending transition in session
768
- session = {
769
- ...session,
770
- pendingTransition: {
771
- targetRouteId: targetRoute.id,
772
- condition: renderedCondition,
773
- reason: "route_complete",
774
- },
775
- };
776
- logger.debug(`[Agent] Route ${selectedRoute.title} completed with pending transition to: ${targetRoute.title}`);
777
- }
778
- else {
779
- logger.warn(`[Agent] Route ${selectedRoute.title} completed but target route not found: ${transitionConfig.nextStep}`);
780
- }
781
- }
782
- // Set step to END_ROUTE marker
783
- session = enterStep(session, END_ROUTE_ID, "Route completed");
784
- logger.debug(`[Agent] Route ${selectedRoute.title} completed. Entered END_ROUTE step.`);
785
- // Stream completion chunks
786
- for await (const chunk of stream) {
787
- // Update current session if we have one
788
- if (chunk.done && this.currentSession) {
789
- this.currentSession = session;
790
- }
791
- yield {
792
- delta: chunk.delta,
793
- accumulated: chunk.accumulated,
794
- done: chunk.done,
795
- session,
796
- toolCalls: undefined,
797
- isRouteComplete: true,
798
- metadata: chunk.metadata,
799
- structured: chunk.structured,
800
- };
801
- }
802
- }
803
- else {
804
- // Fallback: No routes defined, stream a simple response
805
- const fallbackPrompt = await this.responseEngine.buildFallbackPrompt({
806
- history,
807
- agentOptions: this.options,
808
- terms: this.terms,
809
- guidelines: this.guidelines,
810
- context: effectiveContext,
811
- session,
812
- });
813
- const stream = this.options.provider.generateMessageStream({
814
- prompt: fallbackPrompt,
815
- history,
816
- context: effectiveContext,
817
- signal,
818
- parameters: {
819
- jsonSchema: {
820
- type: "object",
821
- properties: {
822
- message: { type: "string" },
823
- },
824
- required: ["message"],
825
- additionalProperties: false,
826
- },
827
- schemaName: "fallback_stream_response",
828
- },
829
- });
830
- for await (const chunk of stream) {
831
- // Update current session if we have one
832
- if (chunk.done && this.currentSession) {
833
- this.currentSession = session;
834
- }
835
- yield {
836
- delta: chunk.delta,
837
- accumulated: chunk.accumulated,
838
- done: chunk.done,
839
- session, // Return updated session
840
- toolCalls: undefined,
841
- isRouteComplete: false,
842
- metadata: chunk.metadata,
843
- structured: chunk.structured,
844
- };
845
- }
846
- }
455
+ // Delegate to ResponseModal
456
+ yield* this.responseModal.respondStream(params);
847
457
  }
848
458
  /**
849
459
  * Generate a response based on history and context
850
460
  */
851
461
  async respond(params) {
852
- const { history: simpleHistory, contextOverride, signal } = params;
853
- const history = normalizeHistory(simpleHistory);
854
- // Get current context (may fetch from provider)
855
- let currentContext = await this.getContext();
856
- // Call beforeRespond hook if configured
857
- if (this.options.hooks?.beforeRespond && currentContext !== undefined) {
858
- currentContext = await this.options.hooks.beforeRespond(currentContext);
859
- // Update stored context with the result from beforeRespond
860
- this.context = currentContext;
861
- }
862
- // Merge context with override
863
- const effectiveContext = {
864
- ...currentContext,
865
- ...contextOverride,
866
- };
867
- // Initialize or get session (use current session if available)
868
- let session = cloneDeep(params.session) ||
869
- cloneDeep(this.currentSession) ||
870
- (await this.session.getOrCreate());
871
- // Merge agent's collected data into session (agent data takes precedence)
872
- if (Object.keys(this.collectedData).length > 0) {
873
- session = mergeCollected(session, this.collectedData);
874
- logger.debug("[Agent] Merged agent collected data into session:", this.collectedData);
875
- }
876
- // PHASE 1: PREPARE - Execute prepare function if current step has one
877
- if (session.currentRoute && session.currentStep) {
878
- const currentRoute = this.routes.find((r) => r.id === session.currentRoute?.id);
879
- if (currentRoute) {
880
- const currentStep = currentRoute.getStep(session.currentStep.id);
881
- if (currentStep?.prepare) {
882
- logger.debug(`[Agent] Executing prepare for step: ${currentStep.id}`);
883
- await this.executePrepareFinalize(currentStep.prepare, effectiveContext, session.data, currentRoute, currentStep);
884
- }
885
- }
886
- }
887
- // PHASE 2: ROUTING + STEP SELECTION - Determine which route and step to use (combined)
888
- let selectedRoute;
889
- let responseDirectives;
890
- let selectedStep;
891
- let isRouteComplete = false;
892
- // Check for pending transition from previous route completion
893
- if (session.pendingTransition) {
894
- const targetRoute = this.routes.find((r) => r.id === session.pendingTransition?.targetRouteId);
895
- if (targetRoute) {
896
- logger.debug(`[Agent] Auto-transitioning from pending transition to route: ${targetRoute.title}`);
897
- // Clear pending transition and enter new route
898
- session = {
899
- ...session,
900
- pendingTransition: undefined,
901
- };
902
- session = enterRoute(session, targetRoute.id, targetRoute.title);
903
- // Merge initial data if available
904
- if (targetRoute.initialData) {
905
- session = mergeCollected(session, targetRoute.initialData);
906
- }
907
- selectedRoute = targetRoute;
908
- }
909
- else {
910
- logger.warn(`[Agent] Pending transition target route not found: ${session.pendingTransition.targetRouteId}`);
911
- // Clear invalid transition
912
- session = {
913
- ...session,
914
- pendingTransition: undefined,
915
- };
916
- }
917
- }
918
- // If no pending transition or transition handled, do normal routing
919
- if (this.routes.length > 0 && !selectedRoute) {
920
- const orchestration = await this.routingEngine.decideRouteAndStep({
921
- routes: this.routes,
922
- session,
923
- history,
924
- agentOptions: this.options,
925
- provider: this.options.provider,
926
- context: effectiveContext,
927
- signal,
928
- });
929
- selectedRoute = orchestration.selectedRoute;
930
- selectedStep = orchestration.selectedStep;
931
- responseDirectives = orchestration.responseDirectives;
932
- session = orchestration.session;
933
- isRouteComplete = orchestration.isRouteComplete || false;
934
- // Log if route is complete
935
- if (isRouteComplete) {
936
- logger.debug(`[Agent] Route complete: all required data collected, END_ROUTE reached`);
937
- }
938
- }
939
- // PHASE 3: DETERMINE NEXT STEP - Use step from combined decision or get initial step
940
- let message;
941
- let toolCalls = undefined;
942
- let responsePrompt;
943
- let availableTools = [];
944
- let responseSchema;
945
- let nextStep;
946
- // Get last user message (needed for both route and completion handling)
947
- const lastUserMessage = getLastMessageFromHistory(history);
948
- if (selectedRoute && !isRouteComplete) {
949
- // If we have a selected step from the combined routing decision, use it
950
- if (selectedStep) {
951
- nextStep = selectedStep;
952
- }
953
- else {
954
- // New route or no step selected - get initial step or first valid step
955
- const candidates = this.routingEngine.getCandidateSteps(selectedRoute, undefined, session.data || {});
956
- if (candidates.length > 0) {
957
- nextStep = candidates[0].step;
958
- logger.debug(`[Agent] Using first valid step: ${nextStep.id} for new route`);
959
- }
960
- else {
961
- // Fallback to initial step even if it should be skipped
962
- nextStep = selectedRoute.initialStep;
963
- logger.warn(`[Agent] No valid steps found, using initial step: ${nextStep.id}`);
964
- }
965
- }
966
- // Update session with next step
967
- session = enterStep(session, nextStep.id, nextStep.description);
968
- logger.debug(`[Agent] Entered step: ${nextStep.id}`);
969
- // PHASE 4: RESPONSE GENERATION - Generate message using selected route and step
970
- // Get last user message
971
- const lastUserMessage = getLastMessageFromHistory(history);
972
- // Build response schema for this route (with collect fields from step)
973
- responseSchema = this.responseEngine.responseSchemaForRoute(selectedRoute, nextStep, this.schema);
974
- // Build response prompt
975
- responsePrompt = await this.responseEngine.buildResponsePrompt({
976
- route: selectedRoute,
977
- currentStep: nextStep,
978
- rules: selectedRoute.getRules(),
979
- prohibitions: selectedRoute.getProhibitions(),
980
- directives: responseDirectives,
981
- history,
982
- lastMessage: lastUserMessage,
983
- agentOptions: this.options,
984
- // Combine agent and route properties according to the specified logic
985
- combinedGuidelines: [
986
- ...this.getGuidelines(),
987
- ...selectedRoute.getGuidelines(),
988
- ],
989
- combinedTerms: this.mergeTerms(this.getTerms(), selectedRoute.getTerms()),
990
- context: effectiveContext,
991
- session,
992
- agentSchema: this.schema,
993
- });
994
- // Collect available tools for AI
995
- availableTools = this.collectAvailableTools(selectedRoute, nextStep);
996
- }
997
- else {
998
- // No route selected - generate basic response without route context
999
- logger.debug(`[Agent] No route selected, generating basic response`);
1000
- // Build basic response prompt without route context
1001
- responsePrompt = await this.responseEngine.buildFallbackPrompt({
1002
- history,
1003
- agentOptions: this.options,
1004
- terms: this.getTerms(),
1005
- guidelines: this.getGuidelines(),
1006
- context: effectiveContext,
1007
- session,
1008
- });
1009
- // Use agent-level tools only
1010
- availableTools = this.collectAvailableTools();
1011
- responseSchema = undefined;
1012
- }
1013
- // Generate message using AI provider (common for both route and no-route cases)
1014
- const result = await this.options.provider.generateMessage({
1015
- prompt: responsePrompt,
1016
- history,
1017
- context: effectiveContext,
1018
- tools: availableTools,
1019
- signal,
1020
- parameters: responseSchema
1021
- ? {
1022
- jsonSchema: responseSchema,
1023
- schemaName: "response_output",
1024
- }
1025
- : undefined,
1026
- });
1027
- message = result.structured?.message || result.message;
1028
- // Process dynamic tool calls from AI response (common for both route and no-route cases)
1029
- if (result.structured?.toolCalls) {
1030
- toolCalls = result.structured.toolCalls;
1031
- // Execute dynamic tool calls
1032
- if (toolCalls.length > 0) {
1033
- logger.debug(`[Agent] Executing ${toolCalls.length} dynamic tool calls`);
1034
- for (const toolCall of toolCalls) {
1035
- const tool = this.findAvailableTool(toolCall.toolName, selectedRoute);
1036
- if (!tool) {
1037
- logger.warn(`[Agent] Tool not found: ${toolCall.toolName}`);
1038
- continue;
1039
- }
1040
- const toolExecutor = new ToolExecutor();
1041
- const toolResult = await toolExecutor.executeTool({
1042
- tool: tool,
1043
- context: effectiveContext,
1044
- updateContext: this.updateContext.bind(this),
1045
- updateData: this.updateCollectedData.bind(this),
1046
- history,
1047
- data: session.data,
1048
- toolArguments: toolCall.arguments,
1049
- });
1050
- // Update context with tool results
1051
- if (toolResult.contextUpdate) {
1052
- await this.updateContext(toolResult.contextUpdate);
1053
- }
1054
- // Update collected data with tool results
1055
- if (toolResult.dataUpdate) {
1056
- session = await this.updateData(session, toolResult.dataUpdate);
1057
- logger.debug(`[Agent] Tool updated collected data:`, toolResult.dataUpdate);
1058
- }
1059
- logger.debug(`[Agent] Executed dynamic tool: ${toolResult.toolName} (success: ${toolResult.success})`);
1060
- }
1061
- }
1062
- }
1063
- // TOOL LOOP: Allow AI to make follow-up tool calls after initial tool execution
1064
- const MAX_TOOL_LOOPS = 5;
1065
- let toolLoopCount = 0;
1066
- let hasToolCalls = toolCalls && toolCalls.length > 0;
1067
- while (hasToolCalls && toolLoopCount < MAX_TOOL_LOOPS) {
1068
- toolLoopCount++;
1069
- logger.debug(`[Agent] Starting tool loop ${toolLoopCount}/${MAX_TOOL_LOOPS}`);
1070
- // Add tool execution results to history so AI knows what happened
1071
- const toolResultsEvents = [];
1072
- for (const toolCall of toolCalls || []) {
1073
- const tool = this.findAvailableTool(toolCall.toolName, selectedRoute);
1074
- if (tool) {
1075
- toolResultsEvents.push({
1076
- kind: EventKind.TOOL,
1077
- source: MessageRole.AGENT,
1078
- timestamp: new Date().toISOString(),
1079
- data: {
1080
- tool_calls: [
1081
- {
1082
- tool_id: toolCall.toolName,
1083
- arguments: toolCall.arguments,
1084
- result: {
1085
- data: "Tool executed successfully",
1086
- },
1087
- },
1088
- ],
1089
- },
1090
- });
1091
- }
1092
- }
1093
- // Create updated history with tool results
1094
- const updatedHistory = [...history, ...toolResultsEvents];
1095
- // Make follow-up AI call to see if more tools are needed
1096
- const followUpResult = await this.options.provider.generateMessage({
1097
- prompt: responsePrompt,
1098
- history: updatedHistory,
1099
- context: effectiveContext,
1100
- tools: availableTools,
1101
- parameters: {
1102
- jsonSchema: responseSchema,
1103
- schemaName: "tool_followup",
1104
- },
1105
- signal,
1106
- });
1107
- // Check if follow-up call has more tool calls
1108
- const followUpToolCalls = followUpResult.structured?.toolCalls;
1109
- hasToolCalls = followUpToolCalls && followUpToolCalls.length > 0;
1110
- if (hasToolCalls) {
1111
- logger.debug(`[Agent] Follow-up call produced ${followUpToolCalls.length} additional tool calls`);
1112
- // Execute the follow-up tool calls
1113
- for (const toolCall of followUpToolCalls) {
1114
- const tool = this.findAvailableTool(toolCall.toolName, selectedRoute);
1115
- if (!tool) {
1116
- logger.warn(`[Agent] Tool not found in follow-up: ${toolCall.toolName}`);
1117
- continue;
1118
- }
1119
- const toolExecutor = new ToolExecutor();
1120
- const toolResult = await toolExecutor.executeTool({
1121
- tool: tool,
1122
- context: effectiveContext,
1123
- updateContext: this.updateContext.bind(this),
1124
- updateData: this.updateCollectedData.bind(this),
1125
- history: updatedHistory,
1126
- data: session.data,
1127
- toolArguments: toolCall.arguments,
1128
- });
1129
- // Update context with follow-up tool results
1130
- if (toolResult.contextUpdate) {
1131
- await this.updateContext(toolResult.contextUpdate);
1132
- }
1133
- if (toolResult.dataUpdate) {
1134
- session = await this.updateData(session, toolResult.dataUpdate);
1135
- logger.debug(`[Agent] Follow-up tool updated collected data:`, toolResult.dataUpdate);
1136
- }
1137
- logger.debug(`[Agent] Executed follow-up tool: ${toolResult.toolName} (success: ${toolResult.success})`);
1138
- }
1139
- // Update toolCalls for next iteration or final response
1140
- toolCalls = followUpToolCalls;
1141
- }
1142
- else {
1143
- logger.debug(`[Agent] Tool loop completed after ${toolLoopCount} iterations`);
1144
- // Update final message and toolCalls from follow-up result if no more tools
1145
- message = followUpResult.structured?.message || followUpResult.message;
1146
- toolCalls = followUpToolCalls || [];
1147
- break;
1148
- }
1149
- }
1150
- if (toolLoopCount >= MAX_TOOL_LOOPS) {
1151
- logger.warn(`[Agent] Tool loop limit reached (${MAX_TOOL_LOOPS}), stopping`);
1152
- }
1153
- // Extract collected data from final response (only for route-based interactions)
1154
- if (selectedRoute && result.structured && nextStep?.collect) {
1155
- const collectedData = {};
1156
- // The structured response includes both base fields and collected extraction fields
1157
- const structuredData = result.structured;
1158
- for (const field of nextStep.collect) {
1159
- const fieldKey = String(field);
1160
- if (fieldKey in structuredData) {
1161
- collectedData[fieldKey] = structuredData[fieldKey];
1162
- }
1163
- }
1164
- // Merge collected data into session using agent-level data validation
1165
- if (Object.keys(collectedData).length > 0) {
1166
- // Update agent-level collected data with validation
1167
- await this.updateCollectedData(collectedData);
1168
- // Update session with validated data
1169
- session = await this.updateData(session, collectedData);
1170
- logger.debug(`[Agent] Collected data:`, collectedData);
1171
- }
1172
- }
1173
- // Extract any additional data from structured response
1174
- if (result.structured &&
1175
- typeof result.structured === "object" &&
1176
- "contextUpdate" in result.structured) {
1177
- await this.updateContext(result.structured
1178
- .contextUpdate);
1179
- }
1180
- // Handle route completion if route is complete
1181
- if (isRouteComplete) {
1182
- // Route is complete - generate completion message then check for onComplete transition
1183
- // Get endStep spec from route
1184
- const endStepSpec = selectedRoute.endStepSpec;
1185
- // Create a temporary step for completion message generation using endStep configuration
1186
- const completionStep = new Step(selectedRoute.id, {
1187
- description: endStepSpec.description,
1188
- id: endStepSpec.id || END_ROUTE_ID,
1189
- collect: endStepSpec.collect,
1190
- requires: endStepSpec.requires,
1191
- prompt: endStepSpec.prompt ||
1192
- "Summarize what was accomplished and confirm completion based on the conversation history and collected data",
1193
- });
1194
- if (!selectedRoute) {
1195
- throw new Error("Selected route is not defined");
1196
- }
1197
- // Build response schema for completion
1198
- const responseSchema = this.responseEngine.responseSchemaForRoute(selectedRoute, completionStep, this.schema);
1199
- const templateContext = {
1200
- context: effectiveContext,
1201
- session,
1202
- history,
1203
- };
1204
- // Build completion response prompt
1205
- const completionPrompt = await this.responseEngine.buildResponsePrompt({
1206
- route: selectedRoute,
1207
- currentStep: completionStep,
1208
- rules: selectedRoute.getRules(),
1209
- prohibitions: selectedRoute.getProhibitions(),
1210
- directives: undefined, // No directives for completion
1211
- history,
1212
- lastMessage: lastUserMessage,
1213
- agentOptions: this.options,
1214
- // Combine agent and route properties according to the specified logic
1215
- combinedGuidelines: [
1216
- ...this.getGuidelines(),
1217
- ...selectedRoute.getGuidelines(),
1218
- ],
1219
- combinedTerms: this.mergeTerms(this.getTerms(), selectedRoute.getTerms()),
1220
- context: effectiveContext,
1221
- session,
1222
- agentSchema: this.schema,
1223
- });
1224
- // Generate completion message using AI provider
1225
- const completionResult = await this.options.provider.generateMessage({
1226
- prompt: completionPrompt,
1227
- history,
1228
- context: effectiveContext,
1229
- signal,
1230
- parameters: {
1231
- jsonSchema: responseSchema,
1232
- schemaName: "completion_message",
1233
- },
1234
- });
1235
- message =
1236
- completionResult.structured?.message || completionResult.message;
1237
- logger.debug(`[Agent] Generated completion message for route: ${selectedRoute.title}`);
1238
- // Check for onComplete transition
1239
- const transitionConfig = await selectedRoute.evaluateOnComplete({ data: session.data }, effectiveContext);
1240
- if (transitionConfig) {
1241
- // Find target route by ID or title
1242
- const targetRoute = this.routes.find((r) => r.id === transitionConfig.nextStep ||
1243
- r.title === transitionConfig.nextStep);
1244
- if (targetRoute) {
1245
- const renderedCondition = await render(transitionConfig.condition, templateContext);
1246
- // Set pending transition in session
1247
- session = {
1248
- ...session,
1249
- pendingTransition: {
1250
- targetRouteId: targetRoute.id,
1251
- condition: renderedCondition,
1252
- reason: "route_complete",
1253
- },
1254
- };
1255
- logger.debug(`[Agent] Route ${selectedRoute.title} completed with pending transition to: ${targetRoute.title}`);
1256
- }
1257
- else {
1258
- logger.warn(`[Agent] Route ${selectedRoute.title} completed but target route not found: ${transitionConfig.nextStep}`);
1259
- }
1260
- }
1261
- // Set step to END_ROUTE marker
1262
- session = enterStep(session, END_ROUTE_ID, "Route completed");
1263
- logger.debug(`[Agent] Route ${selectedRoute.title} completed. Entered END_ROUTE step.`);
1264
- }
1265
- else {
1266
- // Fallback: No routes defined, generate a simple response
1267
- const fallbackPrompt = await this.responseEngine.buildFallbackPrompt({
1268
- history,
1269
- agentOptions: this.options,
1270
- terms: this.terms,
1271
- guidelines: this.guidelines,
1272
- context: effectiveContext,
1273
- session,
1274
- });
1275
- const result = await this.options.provider.generateMessage({
1276
- prompt: fallbackPrompt,
1277
- history,
1278
- context: effectiveContext,
1279
- signal,
1280
- parameters: {
1281
- jsonSchema: {
1282
- type: "object",
1283
- properties: {
1284
- message: { type: "string" },
1285
- },
1286
- required: ["message"],
1287
- additionalProperties: false,
1288
- },
1289
- schemaName: "fallback_response",
1290
- },
1291
- });
1292
- message = result.structured?.message || result.message;
1293
- }
1294
- // Auto-save session step to persistence if configured
1295
- if (this.persistenceManager &&
1296
- session.id &&
1297
- this.options.persistence?.autoSave !== false) {
1298
- await this.persistenceManager.saveSessionState(session.id, session);
1299
- logger.debug(`[Agent] Auto-saved session step to persistence: ${session.id}`);
1300
- }
1301
- // Execute finalize function
1302
- if (session.currentRoute && session.currentStep) {
1303
- const currentRoute = this.routes.find((r) => r.id === session.currentRoute?.id);
1304
- if (currentRoute) {
1305
- const currentStep = currentRoute.getStep(session.currentStep.id);
1306
- if (currentStep?.finalize) {
1307
- logger.debug(`[Agent] Executing finalize for step: ${currentStep.id}`);
1308
- await this.executePrepareFinalize(currentStep.finalize, effectiveContext, session.data, currentRoute, currentStep);
1309
- }
1310
- }
1311
- }
1312
- // Update current session if we have one
1313
- if (this.currentSession) {
1314
- this.currentSession = session;
1315
- }
1316
- return {
1317
- message,
1318
- session, // Return updated session with route/step info
1319
- toolCalls,
1320
- isRouteComplete, // Indicates if the route has reached END_ROUTE with all data collected
1321
- };
462
+ // Delegate to ResponseModal
463
+ return this.responseModal.respond(params);
1322
464
  }
1323
465
  /**
1324
466
  * Get all routes
@@ -1326,6 +468,27 @@ export class Agent {
1326
468
  getRoutes() {
1327
469
  return [...this.routes];
1328
470
  }
471
+ /**
472
+ * Get agent options
473
+ * @internal Used by ResponseModal
474
+ */
475
+ getAgentOptions() {
476
+ return this.options;
477
+ }
478
+ /**
479
+ * Get routing engine
480
+ * @internal Used by ResponseModal
481
+ */
482
+ getRoutingEngine() {
483
+ return this.routingEngine;
484
+ }
485
+ /**
486
+ * Get the updateData method bound to this agent
487
+ * @internal Used by ResponseModal
488
+ */
489
+ getUpdateDataMethod() {
490
+ return this.updateData.bind(this);
491
+ }
1329
492
  /**
1330
493
  * Get all terms
1331
494
  */
@@ -1339,85 +502,45 @@ export class Agent {
1339
502
  return [...this.tools];
1340
503
  }
1341
504
  /**
1342
- * Find an available tool by name for the given route
1343
- * Route-level tools take precedence over agent-level tools
1344
- * @private
505
+ * Get all guidelines
1345
506
  */
1346
- findAvailableTool(toolName, route) {
1347
- // Check route-level tools first (if route provided)
1348
- if (route) {
1349
- const routeTool = route
1350
- .getTools()
1351
- .find((tool) => tool.id === toolName || tool.name === toolName);
1352
- if (routeTool)
1353
- return routeTool;
1354
- }
1355
- // Fall back to agent-level tools
1356
- return this.tools.find((tool) => tool.id === toolName || tool.name === toolName);
507
+ getGuidelines() {
508
+ return [...this.guidelines];
1357
509
  }
1358
510
  /**
1359
- * Collect all available tools for the given route and step context
1360
- * @private
511
+ * Get the agent's knowledge base
1361
512
  */
1362
- collectAvailableTools(route, step) {
1363
- const availableTools = new Map();
1364
- // Add agent-level tools
1365
- this.tools.forEach((tool) => {
1366
- availableTools.set(tool.id, tool);
1367
- });
1368
- // Add route-level tools (these take precedence)
1369
- if (route) {
1370
- route.getTools().forEach((tool) => {
1371
- availableTools.set(tool.id, tool);
1372
- });
1373
- }
1374
- // Filter by step-level allowed tools if specified
1375
- if (step?.tools) {
1376
- const allowedToolIds = new Set();
1377
- const stepTools = [];
1378
- for (const toolRef of step.tools) {
1379
- if (typeof toolRef === "string") {
1380
- // Reference to registered tool
1381
- allowedToolIds.add(toolRef);
1382
- }
1383
- else {
1384
- // Inline tool definition
1385
- if (toolRef.id) {
1386
- allowedToolIds.add(toolRef.id);
1387
- stepTools.push(toolRef);
1388
- }
1389
- }
1390
- }
1391
- // If step specifies tools, only include those
1392
- if (allowedToolIds.size > 0) {
1393
- const filteredTools = new Map();
1394
- for (const toolId of allowedToolIds) {
1395
- const tool = availableTools.get(toolId);
1396
- if (tool) {
1397
- filteredTools.set(toolId, tool);
1398
- }
1399
- }
1400
- // Add inline tools
1401
- stepTools.forEach((tool) => {
1402
- if (tool.id) {
1403
- filteredTools.set(tool.id, tool);
1404
- }
1405
- });
1406
- availableTools.clear();
1407
- filteredTools.forEach((tool, id) => availableTools.set(id, tool));
1408
- }
1409
- }
1410
- // Convert to the format expected by AI providers
1411
- return Array.from(availableTools.values()).map((tool) => ({
1412
- id: tool.id,
1413
- name: tool.name || tool.id,
1414
- description: tool.description,
1415
- parameters: tool.parameters,
1416
- }));
513
+ getKnowledgeBase() {
514
+ return { ...this.knowledgeBase };
515
+ }
516
+ /**
517
+ * Get the persistence manager (if configured)
518
+ */
519
+ getPersistenceManager() {
520
+ return this.persistenceManager;
521
+ }
522
+ /**
523
+ * Check if persistence is enabled
524
+ */
525
+ hasPersistence() {
526
+ return this.persistenceManager !== undefined;
527
+ }
528
+ /**
529
+ * Set the current session for convenience methods
530
+ * @param session - Session step to use for subsequent calls
531
+ */
532
+ setCurrentSession(session) {
533
+ this.currentSession = session;
534
+ }
535
+ /**
536
+ * Get the current session (if set)
537
+ */
538
+ getCurrentSession() {
539
+ return this.currentSession;
1417
540
  }
1418
541
  /**
1419
542
  * Execute a prepare or finalize function/tool
1420
- * @private
543
+ * @internal Used by ResponseModal
1421
544
  */
1422
545
  async executePrepareFinalize(prepareOrFinalize, context, data, route, step) {
1423
546
  if (!prepareOrFinalize)
@@ -1430,38 +553,22 @@ export class Agent {
1430
553
  // It's a tool reference - find and execute the tool
1431
554
  let tool;
1432
555
  if (typeof prepareOrFinalize === "string") {
1433
- // Tool ID - find it in available tools
1434
- const availableTools = new Map();
1435
- // Add agent-level tools
1436
- this.tools.forEach((t) => {
1437
- availableTools.set(t.id, t);
1438
- });
1439
- // Add route-level tools
1440
- if (route) {
1441
- route.getTools().forEach((t) => {
1442
- availableTools.set(t.id, t);
1443
- });
1444
- }
1445
- // Add step-level tools
1446
- if (step?.tools) {
1447
- for (const toolRef of step.tools) {
1448
- if (typeof toolRef === "string") {
1449
- // Keep as is
1450
- }
1451
- else if (toolRef.id) {
1452
- availableTools.set(toolRef.id, toolRef);
1453
- }
1454
- }
1455
- }
1456
- tool = availableTools.get(prepareOrFinalize);
556
+ // Tool ID - use ToolManager to find it across all scopes
557
+ tool = this.tool.find(prepareOrFinalize, undefined, step, route);
1457
558
  }
1458
559
  else {
1459
- // Tool object - use directly
1460
- tool = prepareOrFinalize;
560
+ // Tool object - validate it has required properties
561
+ if (prepareOrFinalize.id && typeof prepareOrFinalize.handler === 'function') {
562
+ tool = prepareOrFinalize;
563
+ }
564
+ else {
565
+ logger.error(`[Agent] Invalid tool object for prepare/finalize: missing id or invalid handler`);
566
+ return;
567
+ }
1461
568
  }
1462
569
  if (tool) {
1463
- const toolExecutor = new ToolExecutor();
1464
- const result = await toolExecutor.executeTool({
570
+ // Use ToolManager for execution
571
+ const result = await this.tool.executeTool({
1465
572
  tool,
1466
573
  context,
1467
574
  updateContext: this.updateContext.bind(this),
@@ -1481,73 +588,31 @@ export class Agent {
1481
588
  }
1482
589
  }
1483
590
  }
1484
- /**
1485
- * Get all guidelines
1486
- */
1487
- getGuidelines() {
1488
- return [...this.guidelines];
1489
- }
1490
- /**
1491
- * Get the agent's knowledge base
1492
- */
1493
- getKnowledgeBase() {
1494
- return { ...this.knowledgeBase };
1495
- }
1496
- /**
1497
- * Merge terms with route-specific taking precedence on conflicts
1498
- * @private
1499
- */
1500
- mergeTerms(agentTerms, routeTerms) {
1501
- const merged = new Map();
1502
- // Add agent terms first
1503
- agentTerms.forEach((term) => {
1504
- const name = typeof term.name === "string" ? term.name : term.name.toString();
1505
- merged.set(name, term);
1506
- });
1507
- // Add route terms (these take precedence)
1508
- routeTerms.forEach((term) => {
1509
- const name = typeof term.name === "string" ? term.name : term.name.toString();
1510
- merged.set(name, term);
1511
- });
1512
- return Array.from(merged.values());
1513
- }
1514
- /**
1515
- * Get the persistence manager (if configured)
1516
- */
1517
- getPersistenceManager() {
1518
- return this.persistenceManager;
1519
- }
1520
- /**
1521
- * Check if persistence is enabled
1522
- */
1523
- hasPersistence() {
1524
- return this.persistenceManager !== undefined;
1525
- }
1526
- /**
1527
- * Set the current session for convenience methods
1528
- * @param session - Session step to use for subsequent calls
1529
- */
1530
- setCurrentSession(session) {
1531
- this.currentSession = session;
1532
- }
1533
- /**
1534
- * Get the current session (if set)
1535
- */
1536
- getCurrentSession() {
1537
- return this.currentSession;
1538
- }
1539
591
  /**
1540
592
  * Clear the current session
1541
593
  */
1542
594
  clearCurrentSession() {
1543
595
  this.currentSession = undefined;
1544
596
  }
597
+ /**
598
+ * Sync session data to agent collected data
599
+ * @internal Used to keep agent and session data in sync
600
+ */
601
+ syncSessionDataToCollectedData() {
602
+ const sessionData = this.session.getData();
603
+ if (sessionData && Object.keys(sessionData).length > 0) {
604
+ this.collectedData = { ...sessionData };
605
+ logger.debug("[Agent] Synced session data to collected data:", this.collectedData);
606
+ }
607
+ }
1545
608
  /**
1546
609
  * Get collected data from current session or agent-level collected data
1547
610
  * @param routeId - Optional route ID to get data for (uses current route if not provided)
1548
611
  * @returns The collected data from the current session or agent-level data
1549
612
  */
1550
613
  getData() {
614
+ // Ensure agent collected data is synced with session
615
+ this.syncSessionDataToCollectedData();
1551
616
  // If we have a current session, use session data
1552
617
  if (this.currentSession) {
1553
618
  // With agent-level data, all routes share the same data structure
@@ -1613,44 +678,20 @@ export class Agent {
1613
678
  * Automatically manages conversation history through the session
1614
679
  */
1615
680
  async chat(message, options) {
1616
- // Determine which history to use
1617
- let history;
1618
- if (options?.history) {
1619
- // Use provided history for this response only
1620
- history = options.history;
1621
- }
1622
- else {
1623
- // Add user message to session history if provided
1624
- if (message) {
1625
- await this.session.addMessage("user", message);
1626
- }
1627
- history = this.session.getHistory();
1628
- }
1629
- // Get or create session
1630
- let session = await this.session.getOrCreate();
1631
- // Merge agent's collected data into session (agent data takes precedence)
1632
- if (Object.keys(this.collectedData).length > 0) {
1633
- session = mergeCollected(session, this.collectedData);
1634
- // Update the session manager with the merged data
1635
- await this.session.setData(this.collectedData);
1636
- logger.debug("[Agent] Merged agent collected data into chat session:", this.collectedData);
1637
- }
1638
- // Use existing respond method with session-managed history
1639
- const result = await this.respond({
1640
- history,
1641
- session,
681
+ // Delegate to ResponseModal.generate()
682
+ return this.responseModal.generate(message, options);
683
+ }
684
+ /**
685
+ * Modern streaming API - simple interface like chat() but returns a stream
686
+ * Automatically manages conversation history through the session
687
+ */
688
+ async *stream(message, options) {
689
+ // Delegate to ResponseModal with the same options structure as chat()
690
+ yield* this.responseModal.stream(message, {
691
+ history: options?.history,
1642
692
  contextOverride: options?.contextOverride,
1643
693
  signal: options?.signal,
1644
694
  });
1645
- // Add agent response to session history (only if not using override history)
1646
- if (!options?.history) {
1647
- await this.session.addMessage("assistant", result.message);
1648
- }
1649
- // Ensure the result includes the current session
1650
- return {
1651
- ...result,
1652
- session: result.session || this.session.current,
1653
- };
1654
695
  }
1655
696
  }
1656
697
  //# sourceMappingURL=Agent.js.map