@falai/agent 2.2.4 → 2.4.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.
- package/README.md +2 -2
- package/dist/adapters/MemoryAdapter.d.ts.map +1 -1
- package/dist/adapters/MemoryAdapter.js +10 -1
- package/dist/adapters/MemoryAdapter.js.map +1 -1
- package/dist/adapters/MongoAdapter.d.ts.map +1 -1
- package/dist/adapters/MongoAdapter.js +33 -2
- package/dist/adapters/MongoAdapter.js.map +1 -1
- package/dist/adapters/OpenSearchAdapter.d.ts.map +1 -1
- package/dist/adapters/OpenSearchAdapter.js +15 -1
- package/dist/adapters/OpenSearchAdapter.js.map +1 -1
- package/dist/adapters/PostgreSQLAdapter.d.ts.map +1 -1
- package/dist/adapters/PostgreSQLAdapter.js +35 -5
- package/dist/adapters/PostgreSQLAdapter.js.map +1 -1
- package/dist/adapters/PrismaAdapter.d.ts.map +1 -1
- package/dist/adapters/PrismaAdapter.js +58 -15
- package/dist/adapters/PrismaAdapter.js.map +1 -1
- package/dist/adapters/RedisAdapter.d.ts.map +1 -1
- package/dist/adapters/RedisAdapter.js +10 -1
- package/dist/adapters/RedisAdapter.js.map +1 -1
- package/dist/adapters/SQLiteAdapter.d.ts.map +1 -1
- package/dist/adapters/SQLiteAdapter.js +38 -6
- package/dist/adapters/SQLiteAdapter.js.map +1 -1
- package/dist/cjs/adapters/MemoryAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/MemoryAdapter.js +10 -1
- package/dist/cjs/adapters/MemoryAdapter.js.map +1 -1
- package/dist/cjs/adapters/MongoAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/MongoAdapter.js +33 -2
- package/dist/cjs/adapters/MongoAdapter.js.map +1 -1
- package/dist/cjs/adapters/OpenSearchAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/OpenSearchAdapter.js +15 -1
- package/dist/cjs/adapters/OpenSearchAdapter.js.map +1 -1
- package/dist/cjs/adapters/PostgreSQLAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/PostgreSQLAdapter.js +35 -5
- package/dist/cjs/adapters/PostgreSQLAdapter.js.map +1 -1
- package/dist/cjs/adapters/PrismaAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/PrismaAdapter.js +58 -15
- package/dist/cjs/adapters/PrismaAdapter.js.map +1 -1
- package/dist/cjs/adapters/RedisAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/RedisAdapter.js +10 -1
- package/dist/cjs/adapters/RedisAdapter.js.map +1 -1
- package/dist/cjs/adapters/SQLiteAdapter.d.ts.map +1 -1
- package/dist/cjs/adapters/SQLiteAdapter.js +38 -6
- package/dist/cjs/adapters/SQLiteAdapter.js.map +1 -1
- package/dist/cjs/core/Agent.d.ts +28 -18
- package/dist/cjs/core/Agent.d.ts.map +1 -1
- package/dist/cjs/core/Agent.js +58 -68
- package/dist/cjs/core/Agent.js.map +1 -1
- package/dist/cjs/core/AutoChainExecutor.d.ts.map +1 -1
- package/dist/cjs/core/AutoChainExecutor.js +14 -20
- package/dist/cjs/core/AutoChainExecutor.js.map +1 -1
- package/dist/cjs/core/BranchEvaluator.d.ts +4 -3
- package/dist/cjs/core/BranchEvaluator.d.ts.map +1 -1
- package/dist/cjs/core/BranchEvaluator.js +18 -23
- package/dist/cjs/core/BranchEvaluator.js.map +1 -1
- package/dist/cjs/core/Flow.d.ts +2 -1
- package/dist/cjs/core/Flow.d.ts.map +1 -1
- package/dist/cjs/core/Flow.js +10 -3
- package/dist/cjs/core/Flow.js.map +1 -1
- package/dist/cjs/core/FlowRouter.d.ts +1 -0
- package/dist/cjs/core/FlowRouter.d.ts.map +1 -1
- package/dist/cjs/core/FlowRouter.js +28 -5
- package/dist/cjs/core/FlowRouter.js.map +1 -1
- package/dist/cjs/core/PersistenceManager.d.ts +3 -0
- package/dist/cjs/core/PersistenceManager.d.ts.map +1 -1
- package/dist/cjs/core/PersistenceManager.js +57 -5
- package/dist/cjs/core/PersistenceManager.js.map +1 -1
- package/dist/cjs/core/PromptComposer.d.ts.map +1 -1
- package/dist/cjs/core/PromptComposer.js +24 -10
- package/dist/cjs/core/PromptComposer.js.map +1 -1
- package/dist/cjs/core/ResponseGenerationError.d.ts +30 -0
- package/dist/cjs/core/ResponseGenerationError.d.ts.map +1 -0
- package/dist/cjs/core/ResponseGenerationError.js +37 -0
- package/dist/cjs/core/ResponseGenerationError.js.map +1 -0
- package/dist/cjs/core/ResponseModal.d.ts +43 -102
- package/dist/cjs/core/ResponseModal.d.ts.map +1 -1
- package/dist/cjs/core/ResponseModal.js +178 -1194
- package/dist/cjs/core/ResponseModal.js.map +1 -1
- package/dist/cjs/core/ResponsePipeline.d.ts +58 -152
- package/dist/cjs/core/ResponsePipeline.d.ts.map +1 -1
- package/dist/cjs/core/ResponsePipeline.js +408 -457
- package/dist/cjs/core/ResponsePipeline.js.map +1 -1
- package/dist/cjs/core/SessionFinalizer.d.ts +34 -0
- package/dist/cjs/core/SessionFinalizer.d.ts.map +1 -0
- package/dist/cjs/core/SessionFinalizer.js +61 -0
- package/dist/cjs/core/SessionFinalizer.js.map +1 -0
- package/dist/cjs/core/SessionManager.d.ts +1 -1
- package/dist/cjs/core/SessionManager.d.ts.map +1 -1
- package/dist/cjs/core/SessionManager.js +18 -7
- package/dist/cjs/core/SessionManager.js.map +1 -1
- package/dist/cjs/core/SignalCoordinator.d.ts +103 -0
- package/dist/cjs/core/SignalCoordinator.d.ts.map +1 -0
- package/dist/cjs/core/SignalCoordinator.js +207 -0
- package/dist/cjs/core/SignalCoordinator.js.map +1 -0
- package/dist/cjs/core/SignalEvaluator.d.ts +2 -2
- package/dist/cjs/core/SignalEvaluator.d.ts.map +1 -1
- package/dist/cjs/core/SignalEvaluator.js +11 -26
- package/dist/cjs/core/SignalEvaluator.js.map +1 -1
- package/dist/cjs/core/SignalProcessor.d.ts.map +1 -1
- package/dist/cjs/core/SignalProcessor.js +28 -11
- package/dist/cjs/core/SignalProcessor.js.map +1 -1
- package/dist/cjs/core/Step.d.ts +3 -1
- package/dist/cjs/core/Step.d.ts.map +1 -1
- package/dist/cjs/core/Step.js +10 -3
- package/dist/cjs/core/Step.js.map +1 -1
- package/dist/cjs/core/StepLifecycle.d.ts +33 -0
- package/dist/cjs/core/StepLifecycle.d.ts.map +1 -0
- package/dist/cjs/core/StepLifecycle.js +97 -0
- package/dist/cjs/core/StepLifecycle.js.map +1 -0
- package/dist/cjs/core/ToolLoopExecutor.d.ts +104 -0
- package/dist/cjs/core/ToolLoopExecutor.d.ts.map +1 -0
- package/dist/cjs/core/ToolLoopExecutor.js +391 -0
- package/dist/cjs/core/ToolLoopExecutor.js.map +1 -0
- package/dist/cjs/core/ToolManager.d.ts +1 -1
- package/dist/cjs/core/ToolManager.d.ts.map +1 -1
- package/dist/cjs/core/ToolManager.js.map +1 -1
- package/dist/cjs/index.d.ts +4 -5
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +7 -6
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/providers/AnthropicProvider.d.ts +2 -0
- package/dist/cjs/providers/AnthropicProvider.d.ts.map +1 -1
- package/dist/cjs/providers/AnthropicProvider.js +28 -56
- package/dist/cjs/providers/AnthropicProvider.js.map +1 -1
- package/dist/cjs/providers/DeepSeekProvider.d.ts +25 -21
- package/dist/cjs/providers/DeepSeekProvider.d.ts.map +1 -1
- package/dist/cjs/providers/DeepSeekProvider.js +48 -407
- package/dist/cjs/providers/DeepSeekProvider.js.map +1 -1
- package/dist/cjs/providers/GeminiProvider.d.ts +2 -0
- package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
- package/dist/cjs/providers/GeminiProvider.js +27 -56
- package/dist/cjs/providers/GeminiProvider.js.map +1 -1
- package/dist/cjs/providers/OpenAICompatibleProvider.d.ts +129 -0
- package/dist/cjs/providers/OpenAICompatibleProvider.d.ts.map +1 -0
- package/dist/cjs/providers/OpenAICompatibleProvider.js +485 -0
- package/dist/cjs/providers/OpenAICompatibleProvider.js.map +1 -0
- package/dist/cjs/providers/OpenAIProvider.d.ts +9 -28
- package/dist/cjs/providers/OpenAIProvider.d.ts.map +1 -1
- package/dist/cjs/providers/OpenAIProvider.js +23 -417
- package/dist/cjs/providers/OpenAIProvider.js.map +1 -1
- package/dist/cjs/providers/OpenRouterProvider.d.ts +10 -27
- package/dist/cjs/providers/OpenRouterProvider.d.ts.map +1 -1
- package/dist/cjs/providers/OpenRouterProvider.js +28 -417
- package/dist/cjs/providers/OpenRouterProvider.js.map +1 -1
- package/dist/cjs/providers/errorClassification.d.ts +61 -0
- package/dist/cjs/providers/errorClassification.d.ts.map +1 -0
- package/dist/cjs/providers/errorClassification.js +123 -0
- package/dist/cjs/providers/errorClassification.js.map +1 -0
- package/dist/cjs/providers/index.d.ts +4 -0
- package/dist/cjs/providers/index.d.ts.map +1 -1
- package/dist/cjs/providers/index.js +7 -1
- package/dist/cjs/providers/index.js.map +1 -1
- package/dist/cjs/types/agent.d.ts +2 -1
- package/dist/cjs/types/agent.d.ts.map +1 -1
- package/dist/cjs/types/ai.d.ts +20 -0
- package/dist/cjs/types/ai.d.ts.map +1 -1
- package/dist/cjs/types/errors.d.ts +33 -0
- package/dist/cjs/types/errors.d.ts.map +1 -1
- package/dist/cjs/types/errors.js +37 -1
- package/dist/cjs/types/errors.js.map +1 -1
- package/dist/cjs/types/flow.d.ts +10 -5
- package/dist/cjs/types/flow.d.ts.map +1 -1
- package/dist/cjs/types/history.d.ts +1 -1
- package/dist/cjs/types/history.d.ts.map +1 -1
- package/dist/cjs/types/index.d.ts +5 -4
- package/dist/cjs/types/index.d.ts.map +1 -1
- package/dist/cjs/types/index.js +3 -1
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/types/persistence.d.ts +43 -2
- package/dist/cjs/types/persistence.d.ts.map +1 -1
- package/dist/cjs/types/session.d.ts +8 -0
- package/dist/cjs/types/session.d.ts.map +1 -1
- package/dist/cjs/types/signals.d.ts +18 -2
- package/dist/cjs/types/signals.d.ts.map +1 -1
- package/dist/cjs/types/template.d.ts +3 -1
- package/dist/cjs/types/template.d.ts.map +1 -1
- package/dist/cjs/types/tool.d.ts +4 -4
- package/dist/cjs/types/tool.d.ts.map +1 -1
- package/dist/cjs/utils/condition.d.ts +19 -0
- package/dist/cjs/utils/condition.d.ts.map +1 -1
- package/dist/cjs/utils/condition.js +86 -15
- package/dist/cjs/utils/condition.js.map +1 -1
- package/dist/cjs/utils/session.d.ts +1 -0
- package/dist/cjs/utils/session.d.ts.map +1 -1
- package/dist/cjs/utils/session.js +1 -0
- package/dist/cjs/utils/session.js.map +1 -1
- package/dist/core/Agent.d.ts +28 -18
- package/dist/core/Agent.d.ts.map +1 -1
- package/dist/core/Agent.js +58 -68
- package/dist/core/Agent.js.map +1 -1
- package/dist/core/AutoChainExecutor.d.ts.map +1 -1
- package/dist/core/AutoChainExecutor.js +14 -20
- package/dist/core/AutoChainExecutor.js.map +1 -1
- package/dist/core/BranchEvaluator.d.ts +4 -3
- package/dist/core/BranchEvaluator.d.ts.map +1 -1
- package/dist/core/BranchEvaluator.js +18 -23
- package/dist/core/BranchEvaluator.js.map +1 -1
- package/dist/core/Flow.d.ts +2 -1
- package/dist/core/Flow.d.ts.map +1 -1
- package/dist/core/Flow.js +10 -3
- package/dist/core/Flow.js.map +1 -1
- package/dist/core/FlowRouter.d.ts +1 -0
- package/dist/core/FlowRouter.d.ts.map +1 -1
- package/dist/core/FlowRouter.js +28 -5
- package/dist/core/FlowRouter.js.map +1 -1
- package/dist/core/PersistenceManager.d.ts +3 -0
- package/dist/core/PersistenceManager.d.ts.map +1 -1
- package/dist/core/PersistenceManager.js +58 -6
- package/dist/core/PersistenceManager.js.map +1 -1
- package/dist/core/PromptComposer.d.ts.map +1 -1
- package/dist/core/PromptComposer.js +24 -10
- package/dist/core/PromptComposer.js.map +1 -1
- package/dist/core/ResponseGenerationError.d.ts +30 -0
- package/dist/core/ResponseGenerationError.d.ts.map +1 -0
- package/dist/core/ResponseGenerationError.js +33 -0
- package/dist/core/ResponseGenerationError.js.map +1 -0
- package/dist/core/ResponseModal.d.ts +43 -102
- package/dist/core/ResponseModal.d.ts.map +1 -1
- package/dist/core/ResponseModal.js +171 -1186
- package/dist/core/ResponseModal.js.map +1 -1
- package/dist/core/ResponsePipeline.d.ts +58 -152
- package/dist/core/ResponsePipeline.d.ts.map +1 -1
- package/dist/core/ResponsePipeline.js +409 -458
- package/dist/core/ResponsePipeline.js.map +1 -1
- package/dist/core/SessionFinalizer.d.ts +34 -0
- package/dist/core/SessionFinalizer.d.ts.map +1 -0
- package/dist/core/SessionFinalizer.js +57 -0
- package/dist/core/SessionFinalizer.js.map +1 -0
- package/dist/core/SessionManager.d.ts +1 -1
- package/dist/core/SessionManager.d.ts.map +1 -1
- package/dist/core/SessionManager.js +18 -7
- package/dist/core/SessionManager.js.map +1 -1
- package/dist/core/SignalCoordinator.d.ts +103 -0
- package/dist/core/SignalCoordinator.d.ts.map +1 -0
- package/dist/core/SignalCoordinator.js +203 -0
- package/dist/core/SignalCoordinator.js.map +1 -0
- package/dist/core/SignalEvaluator.d.ts +2 -2
- package/dist/core/SignalEvaluator.d.ts.map +1 -1
- package/dist/core/SignalEvaluator.js +11 -26
- package/dist/core/SignalEvaluator.js.map +1 -1
- package/dist/core/SignalProcessor.d.ts.map +1 -1
- package/dist/core/SignalProcessor.js +28 -11
- package/dist/core/SignalProcessor.js.map +1 -1
- package/dist/core/Step.d.ts +3 -1
- package/dist/core/Step.d.ts.map +1 -1
- package/dist/core/Step.js +10 -3
- package/dist/core/Step.js.map +1 -1
- package/dist/core/StepLifecycle.d.ts +33 -0
- package/dist/core/StepLifecycle.d.ts.map +1 -0
- package/dist/core/StepLifecycle.js +93 -0
- package/dist/core/StepLifecycle.js.map +1 -0
- package/dist/core/ToolLoopExecutor.d.ts +104 -0
- package/dist/core/ToolLoopExecutor.d.ts.map +1 -0
- package/dist/core/ToolLoopExecutor.js +387 -0
- package/dist/core/ToolLoopExecutor.js.map +1 -0
- package/dist/core/ToolManager.d.ts +1 -1
- package/dist/core/ToolManager.d.ts.map +1 -1
- package/dist/core/ToolManager.js.map +1 -1
- package/dist/index.d.ts +4 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/providers/AnthropicProvider.d.ts +2 -0
- package/dist/providers/AnthropicProvider.d.ts.map +1 -1
- package/dist/providers/AnthropicProvider.js +22 -50
- package/dist/providers/AnthropicProvider.js.map +1 -1
- package/dist/providers/DeepSeekProvider.d.ts +25 -21
- package/dist/providers/DeepSeekProvider.d.ts.map +1 -1
- package/dist/providers/DeepSeekProvider.js +49 -408
- package/dist/providers/DeepSeekProvider.js.map +1 -1
- package/dist/providers/GeminiProvider.d.ts +2 -0
- package/dist/providers/GeminiProvider.d.ts.map +1 -1
- package/dist/providers/GeminiProvider.js +21 -50
- package/dist/providers/GeminiProvider.js.map +1 -1
- package/dist/providers/OpenAICompatibleProvider.d.ts +129 -0
- package/dist/providers/OpenAICompatibleProvider.d.ts.map +1 -0
- package/dist/providers/OpenAICompatibleProvider.js +481 -0
- package/dist/providers/OpenAICompatibleProvider.js.map +1 -0
- package/dist/providers/OpenAIProvider.d.ts +9 -28
- package/dist/providers/OpenAIProvider.d.ts.map +1 -1
- package/dist/providers/OpenAIProvider.js +23 -417
- package/dist/providers/OpenAIProvider.js.map +1 -1
- package/dist/providers/OpenRouterProvider.d.ts +10 -27
- package/dist/providers/OpenRouterProvider.d.ts.map +1 -1
- package/dist/providers/OpenRouterProvider.js +28 -417
- package/dist/providers/OpenRouterProvider.js.map +1 -1
- package/dist/providers/errorClassification.d.ts +61 -0
- package/dist/providers/errorClassification.d.ts.map +1 -0
- package/dist/providers/errorClassification.js +116 -0
- package/dist/providers/errorClassification.js.map +1 -0
- package/dist/providers/index.d.ts +4 -0
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +2 -0
- package/dist/providers/index.js.map +1 -1
- package/dist/types/agent.d.ts +2 -1
- package/dist/types/agent.d.ts.map +1 -1
- package/dist/types/ai.d.ts +20 -0
- package/dist/types/ai.d.ts.map +1 -1
- package/dist/types/errors.d.ts +33 -0
- package/dist/types/errors.d.ts.map +1 -1
- package/dist/types/errors.js +34 -0
- package/dist/types/errors.js.map +1 -1
- package/dist/types/flow.d.ts +10 -5
- package/dist/types/flow.d.ts.map +1 -1
- package/dist/types/history.d.ts +1 -1
- package/dist/types/history.d.ts.map +1 -1
- package/dist/types/index.d.ts +5 -4
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/persistence.d.ts +43 -2
- package/dist/types/persistence.d.ts.map +1 -1
- package/dist/types/session.d.ts +8 -0
- package/dist/types/session.d.ts.map +1 -1
- package/dist/types/signals.d.ts +18 -2
- package/dist/types/signals.d.ts.map +1 -1
- package/dist/types/template.d.ts +3 -1
- package/dist/types/template.d.ts.map +1 -1
- package/dist/types/tool.d.ts +4 -4
- package/dist/types/tool.d.ts.map +1 -1
- package/dist/utils/condition.d.ts +19 -0
- package/dist/utils/condition.d.ts.map +1 -1
- package/dist/utils/condition.js +84 -15
- package/dist/utils/condition.js.map +1 -1
- package/dist/utils/session.d.ts +1 -0
- package/dist/utils/session.d.ts.map +1 -1
- package/dist/utils/session.js +1 -0
- package/dist/utils/session.js.map +1 -1
- package/docs/README.md +1 -1
- package/docs/guides/branching.md +1 -1
- package/docs/guides/compaction.md +12 -5
- package/docs/guides/conditions.md +15 -2
- package/docs/guides/error-handling.md +59 -9
- package/docs/guides/instructions.md +2 -2
- package/docs/guides/persistence.md +69 -2
- package/docs/guides/streaming.md +2 -0
- package/docs/migration/README.md +5 -1
- package/docs/migration/v2-3-to-v2-4.md +316 -0
- package/docs/reference/adapters.md +55 -7
- package/docs/reference/branches.md +2 -2
- package/docs/reference/create-agent.md +3 -3
- package/docs/reference/errors.md +66 -1
- package/docs/reference/flow.md +1 -1
- package/docs/reference/instruction.md +4 -4
- package/docs/reference/providers.md +100 -3
- package/docs/reference/signals.md +14 -3
- package/docs/reference/step.md +2 -2
- package/docs/reference/tool.md +3 -1
- package/docs/start/05-go-to-production.md +3 -0
- package/package.json +1 -1
- package/src/adapters/MemoryAdapter.ts +15 -1
- package/src/adapters/MongoAdapter.ts +41 -2
- package/src/adapters/OpenSearchAdapter.ts +24 -1
- package/src/adapters/PostgreSQLAdapter.ts +45 -5
- package/src/adapters/PrismaAdapter.ts +82 -16
- package/src/adapters/RedisAdapter.ts +19 -1
- package/src/adapters/SQLiteAdapter.ts +47 -5
- package/src/core/Agent.ts +70 -85
- package/src/core/AutoChainExecutor.ts +27 -57
- package/src/core/BranchEvaluator.ts +24 -30
- package/src/core/Flow.ts +10 -3
- package/src/core/FlowRouter.ts +36 -4
- package/src/core/PersistenceManager.ts +79 -10
- package/src/core/PromptComposer.ts +25 -12
- package/src/core/ResponseGenerationError.ts +56 -0
- package/src/core/ResponseModal.ts +233 -1482
- package/src/core/ResponsePipeline.ts +492 -662
- package/src/core/SessionFinalizer.ts +78 -0
- package/src/core/SessionManager.ts +21 -9
- package/src/core/SignalCoordinator.ts +263 -0
- package/src/core/SignalEvaluator.ts +12 -29
- package/src/core/SignalProcessor.ts +34 -11
- package/src/core/Step.ts +11 -3
- package/src/core/StepLifecycle.ts +139 -0
- package/src/core/ToolLoopExecutor.ts +492 -0
- package/src/core/ToolManager.ts +2 -1
- package/src/index.ts +7 -5
- package/src/providers/AnthropicProvider.ts +30 -72
- package/src/providers/DeepSeekProvider.ts +74 -586
- package/src/providers/GeminiProvider.ts +29 -70
- package/src/providers/OpenAICompatibleProvider.ts +738 -0
- package/src/providers/OpenAIProvider.ts +29 -602
- package/src/providers/OpenRouterProvider.ts +38 -596
- package/src/providers/errorClassification.ts +172 -0
- package/src/providers/index.ts +13 -0
- package/src/types/agent.ts +2 -1
- package/src/types/ai.ts +22 -0
- package/src/types/errors.ts +57 -0
- package/src/types/flow.ts +10 -5
- package/src/types/history.ts +1 -2
- package/src/types/index.ts +5 -1
- package/src/types/persistence.ts +50 -2
- package/src/types/session.ts +9 -0
- package/src/types/signals.ts +20 -2
- package/src/types/template.ts +3 -1
- package/src/types/tool.ts +10 -10
- package/src/utils/condition.ts +115 -18
- package/src/utils/session.ts +2 -0
|
@@ -3,38 +3,15 @@
|
|
|
3
3
|
* Provides both streaming and non-streaming response generation with unified logic
|
|
4
4
|
*/
|
|
5
5
|
import { ResponseEngine } from "./ResponseEngine";
|
|
6
|
-
import { ResponsePipeline
|
|
6
|
+
import { ResponsePipeline } from "./ResponsePipeline";
|
|
7
7
|
import { AutoChainExecutor } from "./AutoChainExecutor";
|
|
8
|
-
import {
|
|
8
|
+
import { StepLifecycle } from "./StepLifecycle";
|
|
9
|
+
import { SessionFinalizer } from "./SessionFinalizer";
|
|
10
|
+
import { ToolLoopExecutor } from "./ToolLoopExecutor";
|
|
11
|
+
import { SignalCoordinator } from "./SignalCoordinator";
|
|
12
|
+
import { ResponseGenerationError } from "./ResponseGenerationError";
|
|
13
|
+
import { cloneDeep, mergeCollected, logger, historyToEvents, completeCurrentFlow, render } from "../utils";
|
|
9
14
|
import { createTemplateContext } from "../utils/template";
|
|
10
|
-
/**
|
|
11
|
-
* Error class for response generation failures
|
|
12
|
-
*/
|
|
13
|
-
export class ResponseGenerationError extends Error {
|
|
14
|
-
constructor(message, details) {
|
|
15
|
-
super(message);
|
|
16
|
-
this.details = details;
|
|
17
|
-
this.name = 'ResponseGenerationError';
|
|
18
|
-
// Preserve stack trace from original error if available
|
|
19
|
-
if (details?.originalError instanceof Error && details.originalError.stack) {
|
|
20
|
-
this.stack = `${this.stack}\nCaused by: ${details.originalError.stack}`;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Create a ResponseGenerationError from an unknown error
|
|
25
|
-
*/
|
|
26
|
-
static fromError(error, phase, params, context) {
|
|
27
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
28
|
-
return new ResponseGenerationError(`[ResponseGenerationError] Response generation failed in ${phase}: ${message}. ` +
|
|
29
|
-
`Check provider configuration and the ${phase} phase handler.`, { originalError: error, params, phase, context });
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Check if an error is a ResponseGenerationError
|
|
33
|
-
*/
|
|
34
|
-
static isResponseGenerationError(error) {
|
|
35
|
-
return error instanceof ResponseGenerationError;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
15
|
/**
|
|
39
16
|
* ResponseModal class that encapsulates all response generation logic
|
|
40
17
|
* Uses unified approach for both streaming and non-streaming responses
|
|
@@ -45,24 +22,64 @@ export class ResponseModal {
|
|
|
45
22
|
this.options = options;
|
|
46
23
|
// Initialize response engine
|
|
47
24
|
this.responseEngine = new ResponseEngine(this.agent.promptSectionCache);
|
|
25
|
+
// Signal pre/post phase orchestration
|
|
26
|
+
this.signalCoordinator = new SignalCoordinator({
|
|
27
|
+
getFlows: () => this.agent.getFlows(),
|
|
28
|
+
signalProcessor: this.agent.signalProcessor,
|
|
29
|
+
});
|
|
48
30
|
// Initialize response pipeline with agent dependencies
|
|
49
31
|
this.responsePipeline = new ResponsePipeline(this.agent.getAgentOptions(), () => this.agent.getFlows(), // Pass a function to get flows dynamically
|
|
50
|
-
this.agent.
|
|
32
|
+
this.agent.getFlowRouter(), this.signalCoordinator, this.agent.updateCollectedData.bind(this.agent), () => this.agent.schema);
|
|
33
|
+
// Step prepare/finalize execution, shared by the prepare phase and finalizer
|
|
34
|
+
this.stepLifecycle = new StepLifecycle({
|
|
35
|
+
getFlows: () => this.agent.getFlows(),
|
|
36
|
+
toolManager: this.getToolManager(),
|
|
37
|
+
updateContext: this.agent.updateContext.bind(this.agent),
|
|
38
|
+
updateData: this.agent.updateCollectedData.bind(this.agent),
|
|
39
|
+
});
|
|
40
|
+
// Single owner of end-of-turn finalization (compaction + persistence + sync)
|
|
41
|
+
this.sessionFinalizer = new SessionFinalizer({
|
|
42
|
+
getCompactionOptions: () => this.agent.getCompactionOptions(),
|
|
43
|
+
getPersistenceManager: () => this.agent.getPersistenceManager(),
|
|
44
|
+
getAgentOptions: () => this.agent.getAgentOptions(),
|
|
45
|
+
getCurrentSession: () => this.agent.currentSession,
|
|
46
|
+
setCurrentSession: (session) => { this.agent.currentSession = session; },
|
|
47
|
+
stepLifecycle: this.stepLifecycle,
|
|
48
|
+
enableAutoSave: this.options?.enableAutoSave,
|
|
49
|
+
});
|
|
50
|
+
// Tool follow-up loop (run tools, ask the LLM again) + streaming batch execution
|
|
51
|
+
this.toolLoopExecutor = new ToolLoopExecutor({
|
|
52
|
+
toolManager: this.getToolManager(),
|
|
53
|
+
getAgentOptions: () => this.agent.getAgentOptions(),
|
|
54
|
+
updateContext: this.agent.updateContext.bind(this.agent),
|
|
55
|
+
updateCollectedData: this.agent.updateCollectedData.bind(this.agent),
|
|
56
|
+
updateSessionData: this.agent.getUpdateDataMethod(),
|
|
57
|
+
maxToolLoops: this.options?.maxToolLoops,
|
|
58
|
+
});
|
|
51
59
|
}
|
|
52
60
|
/**
|
|
53
61
|
* Generate a non-streaming response using unified logic
|
|
54
62
|
*/
|
|
55
63
|
async respond(params) {
|
|
64
|
+
// Snapshot the managed session so a failed turn has no in-memory effect:
|
|
65
|
+
// without this, mutations made before the failure leave the live session
|
|
66
|
+
// diverged from persisted state
|
|
67
|
+
const preTurnSession = this.agent.session.current
|
|
68
|
+
? cloneDeep(this.agent.session.current)
|
|
69
|
+
: undefined;
|
|
56
70
|
try {
|
|
57
71
|
// Use unified response preparation and routing
|
|
58
72
|
const responseContext = await this.prepareUnifiedResponseContext(params);
|
|
59
73
|
// Generate response using unified logic
|
|
60
74
|
const result = await this.generateUnifiedResponse(responseContext);
|
|
61
|
-
// Finalize session
|
|
62
|
-
await this.
|
|
75
|
+
// Finalize session — the non-streaming turn's single finalize
|
|
76
|
+
await this.sessionFinalizer.finalize(result.session, responseContext.effectiveContext);
|
|
63
77
|
return result;
|
|
64
78
|
}
|
|
65
79
|
catch (error) {
|
|
80
|
+
if (preTurnSession) {
|
|
81
|
+
this.agent.session.syncSession(preTurnSession);
|
|
82
|
+
}
|
|
66
83
|
throw new ResponseGenerationError(`[ResponseGenerationError] Response generation failed: ${error instanceof Error ? error.message : String(error)}. ` +
|
|
67
84
|
`Check provider configuration and network connectivity.`, { originalError: error, params, phase: 'response_generation' });
|
|
68
85
|
}
|
|
@@ -71,6 +88,10 @@ export class ResponseModal {
|
|
|
71
88
|
* Generate a streaming response using unified logic
|
|
72
89
|
*/
|
|
73
90
|
async *respondStream(params) {
|
|
91
|
+
// Same failed-turn rollback semantics as respond()
|
|
92
|
+
const preTurnSession = this.agent.session.current
|
|
93
|
+
? cloneDeep(this.agent.session.current)
|
|
94
|
+
: undefined;
|
|
74
95
|
try {
|
|
75
96
|
// Use unified response preparation and routing
|
|
76
97
|
const responseContext = await this.prepareUnifiedResponseContext(params);
|
|
@@ -78,6 +99,9 @@ export class ResponseModal {
|
|
|
78
99
|
yield* this.generateUnifiedStreamingResponse(responseContext);
|
|
79
100
|
}
|
|
80
101
|
catch (error) {
|
|
102
|
+
if (preTurnSession) {
|
|
103
|
+
this.agent.session.syncSession(preTurnSession);
|
|
104
|
+
}
|
|
81
105
|
// Stream error to caller
|
|
82
106
|
yield {
|
|
83
107
|
delta: "",
|
|
@@ -105,16 +129,9 @@ export class ResponseModal {
|
|
|
105
129
|
}
|
|
106
130
|
history = this.agent.session.getHistory();
|
|
107
131
|
}
|
|
108
|
-
// Get or create session
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const collectedData = this.agent.getCollectedData();
|
|
112
|
-
if (Object.keys(collectedData).length > 0) {
|
|
113
|
-
session = mergeCollected(session, collectedData);
|
|
114
|
-
// Update the session manager with the merged data
|
|
115
|
-
await this.agent.session.setData(collectedData);
|
|
116
|
-
logger.debug("[ResponseModal] Merged agent collected data into stream session:", collectedData);
|
|
117
|
-
}
|
|
132
|
+
// Get or create session — session.data is the single source of truth,
|
|
133
|
+
// so no agent-side data merge is needed
|
|
134
|
+
const session = await this.agent.session.getOrCreate();
|
|
118
135
|
// Stream response using existing respondStream method
|
|
119
136
|
let finalMessage = "";
|
|
120
137
|
let finalizedSession;
|
|
@@ -158,16 +175,9 @@ export class ResponseModal {
|
|
|
158
175
|
}
|
|
159
176
|
history = this.agent.session.getHistory();
|
|
160
177
|
}
|
|
161
|
-
// Get or create session
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
const collectedData = this.agent.getCollectedData();
|
|
165
|
-
if (Object.keys(collectedData).length > 0) {
|
|
166
|
-
session = mergeCollected(session, collectedData);
|
|
167
|
-
// Update the session manager with the merged data
|
|
168
|
-
await this.agent.session.setData(collectedData);
|
|
169
|
-
logger.debug("[ResponseModal] Merged agent collected data into generate session:", collectedData);
|
|
170
|
-
}
|
|
178
|
+
// Get or create session — session.data is the single source of truth,
|
|
179
|
+
// so no agent-side data merge is needed
|
|
180
|
+
const session = await this.agent.session.getOrCreate();
|
|
171
181
|
// Generate response using existing respond method
|
|
172
182
|
const result = await this.respond({
|
|
173
183
|
history,
|
|
@@ -211,14 +221,6 @@ export class ResponseModal {
|
|
|
211
221
|
getToolManager() {
|
|
212
222
|
return this.agent.tool;
|
|
213
223
|
}
|
|
214
|
-
/**
|
|
215
|
-
* Post-phase signal replies replace the user-visible message after the
|
|
216
|
-
* response has otherwise completed. Undefined means "leave it unchanged";
|
|
217
|
-
* an empty string is an explicit replacement.
|
|
218
|
-
*/
|
|
219
|
-
applyPostSignalReply(message, directive) {
|
|
220
|
-
return directive?.reply !== undefined ? directive.reply : message;
|
|
221
|
-
}
|
|
222
224
|
/**
|
|
223
225
|
* Collect scoped instructions from agent, flow, and step into a ScopedInstructions value.
|
|
224
226
|
* @private
|
|
@@ -249,47 +251,48 @@ export class ResponseModal {
|
|
|
249
251
|
const historyEvents = historyToEvents(simpleHistory);
|
|
250
252
|
// Keep original HistoryItem[] format for external APIs
|
|
251
253
|
const history = simpleHistory;
|
|
252
|
-
// Use ResponsePipeline for
|
|
253
|
-
//
|
|
254
|
+
// Use ResponsePipeline for context and session preparation; context
|
|
255
|
+
// and session are passed explicitly — the pipeline holds no state
|
|
254
256
|
let responseContext;
|
|
255
257
|
try {
|
|
256
|
-
// Set current context and session in pipeline for consistency
|
|
257
|
-
this.responsePipeline.setContext(await this.agent.getContext());
|
|
258
|
-
this.responsePipeline.setCurrentSession(this.agent.currentSession);
|
|
259
258
|
responseContext = await this.responsePipeline.prepareResponseContext({
|
|
260
259
|
contextOverride,
|
|
261
260
|
session: params.session ? cloneDeep(params.session) : undefined,
|
|
261
|
+
currentContext: await this.agent.getContext(),
|
|
262
|
+
currentSession: this.agent.currentSession,
|
|
262
263
|
});
|
|
263
264
|
}
|
|
264
265
|
catch (error) {
|
|
265
266
|
throw ResponseGenerationError.fromError(error, 'pipeline_context_preparation', params);
|
|
266
267
|
}
|
|
267
|
-
const { effectiveContext } = responseContext;
|
|
268
|
+
const { effectiveContext, contextAfterHook } = responseContext;
|
|
268
269
|
let session = responseContext.session;
|
|
269
|
-
//
|
|
270
|
-
|
|
271
|
-
if (storedContext !== undefined) {
|
|
270
|
+
// Sync the beforeRespond hook's context result back to the agent
|
|
271
|
+
if (contextAfterHook !== undefined) {
|
|
272
272
|
try {
|
|
273
|
-
await this.agent.updateContext(
|
|
273
|
+
await this.agent.updateContext(contextAfterHook);
|
|
274
274
|
}
|
|
275
275
|
catch (error) {
|
|
276
|
-
throw ResponseGenerationError.fromError(error, 'context_update_from_pipeline', params, {
|
|
276
|
+
throw ResponseGenerationError.fromError(error, 'context_update_from_pipeline', params, { contextAfterHook });
|
|
277
277
|
}
|
|
278
278
|
}
|
|
279
|
-
//
|
|
280
|
-
|
|
281
|
-
|
|
279
|
+
// Apply data staged before any session existed (initialData,
|
|
280
|
+
// pre-session updateCollectedData calls). Reading the live session's
|
|
281
|
+
// data here would leak state across sessions when an explicit
|
|
282
|
+
// session is passed, so only the staging buffer is merged.
|
|
283
|
+
const stagedData = this.agent.consumePendingData();
|
|
284
|
+
if (Object.keys(stagedData).length > 0) {
|
|
282
285
|
try {
|
|
283
|
-
session = mergeCollected(session,
|
|
284
|
-
logger.debug("[ResponseModal] Merged agent
|
|
286
|
+
session = mergeCollected(session, stagedData);
|
|
287
|
+
logger.debug("[ResponseModal] Merged staged agent data into session:", stagedData);
|
|
285
288
|
}
|
|
286
289
|
catch (error) {
|
|
287
|
-
throw ResponseGenerationError.fromError(error, 'data_merging', params, {
|
|
290
|
+
throw ResponseGenerationError.fromError(error, 'data_merging', params, { stagedData });
|
|
288
291
|
}
|
|
289
292
|
}
|
|
290
293
|
// PHASE 1: PREPARE - Execute prepare function if current step has one
|
|
291
294
|
try {
|
|
292
|
-
await this.
|
|
295
|
+
await this.stepLifecycle.runPrepare(session, effectiveContext);
|
|
293
296
|
}
|
|
294
297
|
catch (error) {
|
|
295
298
|
throw ResponseGenerationError.fromError(error, 'step_preparation', params, { session, effectiveContext });
|
|
@@ -298,7 +301,7 @@ export class ResponseModal {
|
|
|
298
301
|
// Performs pre-extraction and step selection
|
|
299
302
|
let routingResult;
|
|
300
303
|
try {
|
|
301
|
-
routingResult = await this.
|
|
304
|
+
routingResult = await this.responsePipeline.routeAndSelectStep({
|
|
302
305
|
session,
|
|
303
306
|
history: historyEvents,
|
|
304
307
|
context: effectiveContext,
|
|
@@ -331,443 +334,6 @@ export class ResponseModal {
|
|
|
331
334
|
throw ResponseGenerationError.fromError(error, 'preparation', params);
|
|
332
335
|
}
|
|
333
336
|
}
|
|
334
|
-
/**
|
|
335
|
-
* Unified routing and step selection logic using ResponsePipeline for optimization
|
|
336
|
-
* @private
|
|
337
|
-
*/
|
|
338
|
-
async handleUnifiedRoutingAndStepSelection(params) {
|
|
339
|
-
try {
|
|
340
|
-
// Create a fresh chain tracker for this turn (Requirement 22.1)
|
|
341
|
-
this.responsePipeline.createChainTracker();
|
|
342
|
-
// ROUTING SKIP OPTIMIZATION (Requirements 20.1, 20.2, 20.3):
|
|
343
|
-
// When the current step has collect fields AND pre-extraction populates at least
|
|
344
|
-
// one of those fields, skip FlowRouter.decideFlowAndStep for this turn.
|
|
345
|
-
const routingSkipResult = await this.attemptRoutingSkipForCollect(params);
|
|
346
|
-
if (routingSkipResult) {
|
|
347
|
-
// Even when routing is skipped, run pre-signal phase if processor is present
|
|
348
|
-
if (this.agent.signalProcessor) {
|
|
349
|
-
const signalResult = await this.responsePipeline.runPreSignalPhase(params.session, params.context, params.history);
|
|
350
|
-
// If signal halts, override the routing skip result
|
|
351
|
-
if (signalResult.mergedDirective?.halt) {
|
|
352
|
-
return {
|
|
353
|
-
...routingSkipResult,
|
|
354
|
-
session: signalResult.updatedSession,
|
|
355
|
-
signalFirings: signalResult.firings,
|
|
356
|
-
signalHalted: true,
|
|
357
|
-
signalHaltReply: signalResult.mergedDirective.reply,
|
|
358
|
-
};
|
|
359
|
-
}
|
|
360
|
-
// If signal has position fields, override routing skip result
|
|
361
|
-
if (hasDirectivePositionField(signalResult.mergedDirective)) {
|
|
362
|
-
return this.applySignalPositionDirective(signalResult, params);
|
|
363
|
-
}
|
|
364
|
-
// Non-position directive: propagate for pre-LLM augmentation
|
|
365
|
-
return {
|
|
366
|
-
...routingSkipResult,
|
|
367
|
-
session: signalResult.updatedSession,
|
|
368
|
-
signalFirings: signalResult.firings,
|
|
369
|
-
signalPreDirective: signalResult.mergedDirective || undefined,
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
return routingSkipResult;
|
|
373
|
-
}
|
|
374
|
-
// ── PARALLEL PRE-SIGNAL PHASE + ROUTING (Algorithm 5) ────────────────
|
|
375
|
-
// When signalProcessor is present, run pre-signals in parallel with routing.
|
|
376
|
-
// When absent, call the router directly (zero overhead, preserve current behavior).
|
|
377
|
-
if (this.agent.signalProcessor) {
|
|
378
|
-
// Run pre-signal phase in parallel with routing (Requirement 8.1)
|
|
379
|
-
const [signalResult, routingResult] = await Promise.all([
|
|
380
|
-
this.responsePipeline.runPreSignalPhase(params.session, params.context, params.history),
|
|
381
|
-
this.responsePipeline.handleRoutingAndStepSelection({
|
|
382
|
-
session: params.session,
|
|
383
|
-
history: params.history,
|
|
384
|
-
context: params.context,
|
|
385
|
-
signal: params.signal,
|
|
386
|
-
}),
|
|
387
|
-
]);
|
|
388
|
-
// ── Requirement 8.2: halt → discard routing, skip LLM ────────────
|
|
389
|
-
if (signalResult.mergedDirective?.halt) {
|
|
390
|
-
return {
|
|
391
|
-
selectedFlow: undefined,
|
|
392
|
-
selectedStep: undefined,
|
|
393
|
-
session: signalResult.updatedSession,
|
|
394
|
-
isFlowComplete: false,
|
|
395
|
-
signalFirings: signalResult.firings,
|
|
396
|
-
signalHalted: true,
|
|
397
|
-
signalHaltReply: signalResult.mergedDirective.reply,
|
|
398
|
-
};
|
|
399
|
-
}
|
|
400
|
-
// ── Requirement 8.3: position directive → discard routing, apply signal position ──
|
|
401
|
-
if (hasDirectivePositionField(signalResult.mergedDirective)) {
|
|
402
|
-
return this.applySignalPositionDirective(signalResult, params);
|
|
403
|
-
}
|
|
404
|
-
// ── Requirement 8.4: non-position directive → use routing, propagate augmentation ──
|
|
405
|
-
// ── Requirement 8.5: no directive → use routing as-is ─────────────
|
|
406
|
-
let updatedSession = signalResult.updatedSession;
|
|
407
|
-
// Apply data/context updates from signal to the routed session
|
|
408
|
-
if (signalResult.mergedDirective?.dataUpdate) {
|
|
409
|
-
updatedSession = mergeCollected(updatedSession, signalResult.mergedDirective.dataUpdate);
|
|
410
|
-
}
|
|
411
|
-
// Use routing result for flow/step, but carry signal session state
|
|
412
|
-
// Merge routing session changes on top of signal session
|
|
413
|
-
const routingSession = routingResult.session;
|
|
414
|
-
updatedSession = {
|
|
415
|
-
...updatedSession,
|
|
416
|
-
currentFlow: routingSession.currentFlow,
|
|
417
|
-
currentStep: routingSession.currentStep,
|
|
418
|
-
flowHistory: routingSession.flowHistory,
|
|
419
|
-
pendingDirective: routingSession.pendingDirective,
|
|
420
|
-
};
|
|
421
|
-
const isFlowComplete = routingResult.isFlowComplete;
|
|
422
|
-
// PRE-EXTRACTION: same logic as below — extract data from user message
|
|
423
|
-
if (routingResult.selectedFlow && !isFlowComplete) {
|
|
424
|
-
if (this.shouldPreExtractData(routingResult.selectedFlow)) {
|
|
425
|
-
logger.debug(`[ResponseModal] Pre-extracting data for flow: ${routingResult.selectedFlow.title}`);
|
|
426
|
-
const extractedData = await this.preExtractFlowData({
|
|
427
|
-
route: routingResult.selectedFlow,
|
|
428
|
-
history: params.history,
|
|
429
|
-
context: params.context,
|
|
430
|
-
session: updatedSession,
|
|
431
|
-
signal: params.signal,
|
|
432
|
-
});
|
|
433
|
-
if (extractedData && Object.keys(extractedData).length > 0) {
|
|
434
|
-
logger.debug(`[ResponseModal] Pre-extracted data:`, extractedData);
|
|
435
|
-
updatedSession = mergeCollected(updatedSession, extractedData);
|
|
436
|
-
await this.agent.updateCollectedData(extractedData);
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
// Determine next step
|
|
441
|
-
const stepResult = await this.responsePipeline.determineNextStep({
|
|
442
|
-
selectedFlow: routingResult.selectedFlow,
|
|
443
|
-
selectedStep: routingResult.selectedStep,
|
|
444
|
-
session: updatedSession,
|
|
445
|
-
isFlowComplete,
|
|
446
|
-
});
|
|
447
|
-
return {
|
|
448
|
-
selectedFlow: stepResult.flowChanged || routingResult.selectedFlow,
|
|
449
|
-
selectedStep: stepResult.nextStep,
|
|
450
|
-
responseDirectives: routingResult.responseDirectives,
|
|
451
|
-
session: stepResult.session,
|
|
452
|
-
isFlowComplete: stepResult.flowChanged ? false : isFlowComplete,
|
|
453
|
-
signalFirings: signalResult.firings,
|
|
454
|
-
signalPreDirective: signalResult.mergedDirective || undefined,
|
|
455
|
-
};
|
|
456
|
-
}
|
|
457
|
-
// ── No signal processor: existing behavior (zero overhead) ────────────
|
|
458
|
-
const routingResult = await this.responsePipeline.handleRoutingAndStepSelection({
|
|
459
|
-
session: params.session,
|
|
460
|
-
history: params.history,
|
|
461
|
-
context: params.context,
|
|
462
|
-
signal: params.signal,
|
|
463
|
-
});
|
|
464
|
-
let updatedSession = routingResult.session;
|
|
465
|
-
const isFlowComplete = routingResult.isFlowComplete;
|
|
466
|
-
// PRE-EXTRACTION: If entering a flow that collects data, extract data from user message first
|
|
467
|
-
// This allows us to skip steps whose data is already provided
|
|
468
|
-
if (routingResult.selectedFlow && !isFlowComplete) {
|
|
469
|
-
// Always pre-extract when flow collects data (not just on new flow entry)
|
|
470
|
-
// This ensures step selection has the most up-to-date data
|
|
471
|
-
if (this.shouldPreExtractData(routingResult.selectedFlow)) {
|
|
472
|
-
logger.debug(`[ResponseModal] Pre-extracting data for flow: ${routingResult.selectedFlow.title}`);
|
|
473
|
-
const extractedData = await this.preExtractFlowData({
|
|
474
|
-
route: routingResult.selectedFlow,
|
|
475
|
-
history: params.history,
|
|
476
|
-
context: params.context,
|
|
477
|
-
session: updatedSession,
|
|
478
|
-
signal: params.signal,
|
|
479
|
-
});
|
|
480
|
-
if (extractedData && Object.keys(extractedData).length > 0) {
|
|
481
|
-
logger.debug(`[ResponseModal] Pre-extracted data:`, extractedData);
|
|
482
|
-
// Merge pre-extracted data into session before step selection
|
|
483
|
-
updatedSession = mergeCollected(updatedSession, extractedData);
|
|
484
|
-
// Also update agent's collected data
|
|
485
|
-
await this.agent.updateCollectedData(extractedData);
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
// Determine next step using pipeline method for consistency
|
|
490
|
-
const stepResult = await this.responsePipeline.determineNextStep({
|
|
491
|
-
selectedFlow: routingResult.selectedFlow,
|
|
492
|
-
selectedStep: routingResult.selectedStep,
|
|
493
|
-
session: updatedSession, // Use updated session with pre-extracted data
|
|
494
|
-
isFlowComplete, // Use updated completion status
|
|
495
|
-
});
|
|
496
|
-
return {
|
|
497
|
-
selectedFlow: stepResult.flowChanged || routingResult.selectedFlow,
|
|
498
|
-
selectedStep: stepResult.nextStep, // Use the determined next step
|
|
499
|
-
responseDirectives: routingResult.responseDirectives,
|
|
500
|
-
session: stepResult.session,
|
|
501
|
-
// If a branch changed the flow, the original isFlowComplete no longer applies
|
|
502
|
-
isFlowComplete: stepResult.flowChanged ? false : isFlowComplete,
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
catch (error) {
|
|
506
|
-
throw ResponseGenerationError.fromError(error, 'routing_optimization', params);
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
/**
|
|
510
|
-
* Apply a signal's position directive (goTo, goToStep, complete, abort, reset).
|
|
511
|
-
* Discards routing result and uses the signal's position decision.
|
|
512
|
-
* @private
|
|
513
|
-
* @requirements 8.3
|
|
514
|
-
*/
|
|
515
|
-
applySignalPositionDirective(signalResult, _params) {
|
|
516
|
-
const directive = signalResult.mergedDirective;
|
|
517
|
-
let session = signalResult.updatedSession;
|
|
518
|
-
const flows = this.agent.getFlows();
|
|
519
|
-
let selectedFlow;
|
|
520
|
-
let selectedStep;
|
|
521
|
-
let isFlowComplete = false;
|
|
522
|
-
// Apply data updates if present alongside position
|
|
523
|
-
if (directive.dataUpdate) {
|
|
524
|
-
session = mergeCollected(session, directive.dataUpdate);
|
|
525
|
-
}
|
|
526
|
-
if (directive.goTo) {
|
|
527
|
-
const flowTarget = typeof directive.goTo === 'string'
|
|
528
|
-
? directive.goTo
|
|
529
|
-
: directive.goTo.flow ?? directive.goTo.step;
|
|
530
|
-
if (flowTarget) {
|
|
531
|
-
const targetFlow = flows.find(f => f.id === flowTarget || f.title === flowTarget);
|
|
532
|
-
if (targetFlow) {
|
|
533
|
-
session = enterFlow(session, targetFlow.id, targetFlow.title);
|
|
534
|
-
selectedFlow = targetFlow;
|
|
535
|
-
if (typeof directive.goTo === 'object' && directive.goTo.step) {
|
|
536
|
-
const targetStep = targetFlow.getStep(directive.goTo.step);
|
|
537
|
-
if (targetStep) {
|
|
538
|
-
session = enterStep(session, targetStep.id, targetStep.description);
|
|
539
|
-
selectedStep = targetStep;
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
else {
|
|
544
|
-
logger.warn(`[Signals] Pre-phase goTo target not found: "${flowTarget}". Falling back to no flow.`);
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
else if (directive.goToStep) {
|
|
549
|
-
const stepTarget = typeof directive.goToStep === 'string'
|
|
550
|
-
? directive.goToStep
|
|
551
|
-
: directive.goToStep.step;
|
|
552
|
-
const flowTarget = typeof directive.goToStep === 'object'
|
|
553
|
-
? directive.goToStep.flow
|
|
554
|
-
: undefined;
|
|
555
|
-
if (flowTarget) {
|
|
556
|
-
const targetFlow = flows.find(f => f.id === flowTarget || f.title === flowTarget);
|
|
557
|
-
if (targetFlow) {
|
|
558
|
-
session = enterFlow(session, targetFlow.id, targetFlow.title);
|
|
559
|
-
selectedFlow = targetFlow;
|
|
560
|
-
const targetStep = targetFlow.getStep(stepTarget);
|
|
561
|
-
if (targetStep) {
|
|
562
|
-
session = enterStep(session, targetStep.id, targetStep.description);
|
|
563
|
-
selectedStep = targetStep;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
else if (session.currentFlow) {
|
|
568
|
-
const currentFlow = flows.find(f => f.id === session.currentFlow?.id);
|
|
569
|
-
if (currentFlow) {
|
|
570
|
-
selectedFlow = currentFlow;
|
|
571
|
-
const targetStep = currentFlow.getStep(stepTarget);
|
|
572
|
-
if (targetStep) {
|
|
573
|
-
session = enterStep(session, targetStep.id, targetStep.description);
|
|
574
|
-
selectedStep = targetStep;
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
else if (directive.complete) {
|
|
580
|
-
isFlowComplete = true;
|
|
581
|
-
}
|
|
582
|
-
else if (directive.abort) {
|
|
583
|
-
// Abort — no flow, session cleared or marked
|
|
584
|
-
isFlowComplete = true;
|
|
585
|
-
}
|
|
586
|
-
else if (directive.reset) {
|
|
587
|
-
if (session.currentFlow) {
|
|
588
|
-
const currentFlow = flows.find(f => f.id === session.currentFlow?.id);
|
|
589
|
-
if (currentFlow) {
|
|
590
|
-
selectedFlow = currentFlow;
|
|
591
|
-
const resetStep = typeof directive.reset === 'object' && directive.reset.step
|
|
592
|
-
? directive.reset.step
|
|
593
|
-
: undefined;
|
|
594
|
-
if (resetStep) {
|
|
595
|
-
const targetStep = currentFlow.getStep(resetStep);
|
|
596
|
-
if (targetStep) {
|
|
597
|
-
session = enterStep(session, targetStep.id, targetStep.description);
|
|
598
|
-
selectedStep = targetStep;
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
else {
|
|
602
|
-
const initialStep = currentFlow.initialStep;
|
|
603
|
-
session = enterStep(session, initialStep.id, initialStep.description);
|
|
604
|
-
selectedStep = initialStep;
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
return {
|
|
610
|
-
selectedFlow,
|
|
611
|
-
selectedStep,
|
|
612
|
-
session,
|
|
613
|
-
isFlowComplete,
|
|
614
|
-
signalFirings: signalResult.firings,
|
|
615
|
-
signalPreDirective: signalResult.mergedDirective || undefined,
|
|
616
|
-
};
|
|
617
|
-
}
|
|
618
|
-
/**
|
|
619
|
-
* Routing skip optimization (Requirements 20.1, 20.2, 20.3):
|
|
620
|
-
* When the current step declares `collect` fields AND pre-extraction populates
|
|
621
|
-
* at least one of those fields from the user's message, skip routing for this turn.
|
|
622
|
-
*
|
|
623
|
-
* Returns the routing result if the skip applies, or undefined to fall through
|
|
624
|
-
* to normal routing.
|
|
625
|
-
* @private
|
|
626
|
-
*/
|
|
627
|
-
async attemptRoutingSkipForCollect(params) {
|
|
628
|
-
const { session } = params;
|
|
629
|
-
// Only applies when we already have a current flow and step
|
|
630
|
-
if (!session.currentFlow || !session.currentStep) {
|
|
631
|
-
return undefined;
|
|
632
|
-
}
|
|
633
|
-
// Also skip this optimization if there's a pending directive (it takes priority)
|
|
634
|
-
if (session.pendingDirective) {
|
|
635
|
-
return undefined;
|
|
636
|
-
}
|
|
637
|
-
// Look up the actual Flow and Step objects to access `collect`
|
|
638
|
-
const currentFlow = this.agent.getFlows().find((f) => f.id === session.currentFlow?.id);
|
|
639
|
-
if (!currentFlow) {
|
|
640
|
-
return undefined;
|
|
641
|
-
}
|
|
642
|
-
const currentStep = currentFlow.getStep(session.currentStep.id);
|
|
643
|
-
if (!currentStep || !currentStep.collect || currentStep.collect.length === 0) {
|
|
644
|
-
return undefined;
|
|
645
|
-
}
|
|
646
|
-
// We have a step with collect fields. Run pre-extraction to see if the
|
|
647
|
-
// user's message populates any of them.
|
|
648
|
-
const collectFields = currentStep.collect;
|
|
649
|
-
// Snapshot current data for comparison
|
|
650
|
-
const dataBefore = { ...session.data };
|
|
651
|
-
// Run pre-extraction against the current flow
|
|
652
|
-
const extractedData = await this.preExtractFlowData({
|
|
653
|
-
route: currentFlow,
|
|
654
|
-
history: params.history,
|
|
655
|
-
context: params.context,
|
|
656
|
-
session,
|
|
657
|
-
signal: params.signal,
|
|
658
|
-
});
|
|
659
|
-
if (!extractedData || Object.keys(extractedData).length === 0) {
|
|
660
|
-
return undefined;
|
|
661
|
-
}
|
|
662
|
-
// Determine which collect fields were newly populated by pre-extraction
|
|
663
|
-
const populatedCollectFields = [];
|
|
664
|
-
for (const field of collectFields) {
|
|
665
|
-
const key = field;
|
|
666
|
-
const hadValue = dataBefore[field] !== undefined && dataBefore[field] !== null;
|
|
667
|
-
const hasNewValue = extractedData[field] !== undefined && extractedData[field] !== null;
|
|
668
|
-
if (hasNewValue && !hadValue) {
|
|
669
|
-
populatedCollectFields.push(key);
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
if (populatedCollectFields.length === 0) {
|
|
673
|
-
// Pre-extraction didn't populate any declared collect field — no skip
|
|
674
|
-
return undefined;
|
|
675
|
-
}
|
|
676
|
-
// ROUTING SKIP: pre-extraction populated collect fields → retain current flow/step
|
|
677
|
-
logger.debug(`[ResponseModal] Routing skip: pre-extraction populated collect fields [${populatedCollectFields.join(', ')}] for step "${currentStep.id}" — skipping FlowRouter`);
|
|
678
|
-
// Merge extracted data into session
|
|
679
|
-
const updatedSession = mergeCollected(session, extractedData);
|
|
680
|
-
await this.agent.updateCollectedData(extractedData);
|
|
681
|
-
// Determine next step using pipeline method for consistency
|
|
682
|
-
// Pass the current flow/step as the routing result (retained)
|
|
683
|
-
const stepResult = await this.responsePipeline.determineNextStep({
|
|
684
|
-
selectedFlow: currentFlow,
|
|
685
|
-
selectedStep: currentStep,
|
|
686
|
-
session: updatedSession,
|
|
687
|
-
isFlowComplete: false,
|
|
688
|
-
});
|
|
689
|
-
return {
|
|
690
|
-
selectedFlow: stepResult.flowChanged || currentFlow,
|
|
691
|
-
selectedStep: stepResult.nextStep,
|
|
692
|
-
responseDirectives: undefined,
|
|
693
|
-
session: stepResult.session,
|
|
694
|
-
isFlowComplete: stepResult.flowChanged ? false : false,
|
|
695
|
-
};
|
|
696
|
-
}
|
|
697
|
-
/**
|
|
698
|
-
* Check if a flow should pre-extract data before determining the initial step
|
|
699
|
-
* @private
|
|
700
|
-
*/
|
|
701
|
-
shouldPreExtractData(flow) {
|
|
702
|
-
// Pre-extract if flow has declared required or optional fields
|
|
703
|
-
if (flow.requiredFields && flow.requiredFields.length > 0) {
|
|
704
|
-
return true;
|
|
705
|
-
}
|
|
706
|
-
if (flow.optionalFields && flow.optionalFields.length > 0) {
|
|
707
|
-
return true;
|
|
708
|
-
}
|
|
709
|
-
// Pre-extract if any step in the flow collects data
|
|
710
|
-
const steps = flow.getAllSteps();
|
|
711
|
-
const hasDataCollectionSteps = steps.some(step => step.collect && step.collect.length > 0);
|
|
712
|
-
return hasDataCollectionSteps;
|
|
713
|
-
}
|
|
714
|
-
/**
|
|
715
|
-
* Pre-extract data from user message when entering a flow
|
|
716
|
-
* This allows skipping steps whose data is already provided
|
|
717
|
-
* @private
|
|
718
|
-
*/
|
|
719
|
-
async preExtractFlowData(params) {
|
|
720
|
-
const { route: flow, history, signal } = params;
|
|
721
|
-
// Build a schema for data extraction based on flow's fields
|
|
722
|
-
const extractionSchema = this.agent.schema;
|
|
723
|
-
if (!extractionSchema) {
|
|
724
|
-
logger.warn(`[ResponseModal] No schema available for pre-extraction`);
|
|
725
|
-
return {};
|
|
726
|
-
}
|
|
727
|
-
// Get last user message
|
|
728
|
-
const lastMessage = getLastMessageFromHistory(history);
|
|
729
|
-
// Build extraction prompt
|
|
730
|
-
const extractionPrompt = [
|
|
731
|
-
`Extract any relevant information from the user's message that matches the following data fields.`,
|
|
732
|
-
`Only extract information that is explicitly stated or clearly implied.`,
|
|
733
|
-
``,
|
|
734
|
-
`User's message: "${lastMessage}"`,
|
|
735
|
-
``,
|
|
736
|
-
`Extract data for these fields if present:`,
|
|
737
|
-
];
|
|
738
|
-
// Add field descriptions
|
|
739
|
-
if (flow.requiredFields) {
|
|
740
|
-
extractionPrompt.push(`Required fields: ${flow.requiredFields.join(', ')}`);
|
|
741
|
-
}
|
|
742
|
-
if (flow.optionalFields) {
|
|
743
|
-
extractionPrompt.push(`Optional fields: ${flow.optionalFields.join(', ')}`);
|
|
744
|
-
}
|
|
745
|
-
extractionPrompt.push(``, `Return ONLY the extracted data as JSON. If no data can be extracted, return an empty object {}.`);
|
|
746
|
-
// Convert Event[] to HistoryItem[] for provider call
|
|
747
|
-
const historyItems = eventsToHistory(history);
|
|
748
|
-
// Call AI to extract data
|
|
749
|
-
const agentOptions = this.agent.getAgentOptions();
|
|
750
|
-
try {
|
|
751
|
-
const result = await agentOptions.provider.generateMessage({
|
|
752
|
-
prompt: extractionPrompt.join('\n'),
|
|
753
|
-
history: historyItems,
|
|
754
|
-
context: {}, // Passed as empty object so AI doesn't "extract" from context
|
|
755
|
-
// NOTE: context is intentionally NOT passed here.
|
|
756
|
-
// Passing context caused the AI to "extract" data from the lead's context
|
|
757
|
-
// (e.g., name, sector, city) instead of from what the user actually said.
|
|
758
|
-
signal,
|
|
759
|
-
parameters: {
|
|
760
|
-
jsonSchema: extractionSchema,
|
|
761
|
-
schemaName: 'data_extraction',
|
|
762
|
-
},
|
|
763
|
-
});
|
|
764
|
-
return result.structured || {};
|
|
765
|
-
}
|
|
766
|
-
catch (error) {
|
|
767
|
-
logger.error(`[ResponseModal] Pre-extraction failed:`, error);
|
|
768
|
-
return {};
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
337
|
/**
|
|
772
338
|
* Unified response generation for non-streaming responses
|
|
773
339
|
* @private
|
|
@@ -785,15 +351,12 @@ export class ResponseModal {
|
|
|
785
351
|
if (signalHalted) {
|
|
786
352
|
const haltMessage = signalHaltReply || '';
|
|
787
353
|
// Run post-signal phase even on halt (post-phase sees complete turn context)
|
|
788
|
-
const
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
}
|
|
795
|
-
const message = this.applyPostSignalReply(haltMessage, postResult.mergedDirective);
|
|
796
|
-
await this.finalizeSession(session, effectiveContext);
|
|
354
|
+
const post = await this.signalCoordinator.applyPostPhase({
|
|
355
|
+
session, context: effectiveContext, historyEvents, message: haltMessage,
|
|
356
|
+
});
|
|
357
|
+
session = post.session;
|
|
358
|
+
signalFirings.push(...post.firings);
|
|
359
|
+
const message = post.message;
|
|
797
360
|
return {
|
|
798
361
|
message,
|
|
799
362
|
session,
|
|
@@ -827,12 +390,12 @@ export class ResponseModal {
|
|
|
827
390
|
flow: selectedFlow,
|
|
828
391
|
});
|
|
829
392
|
session = autoResult.session;
|
|
830
|
-
// Handle halt: emit verbatim reply,
|
|
393
|
+
// Handle halt: emit verbatim reply, return — no LLM call.
|
|
394
|
+
// respond() finalizes the returned session exactly once.
|
|
831
395
|
if (autoResult.stoppedReason === 'halt') {
|
|
832
396
|
message = autoResult.mergedDirective?.reply || '';
|
|
833
397
|
stoppedReason = 'halt';
|
|
834
398
|
executedSteps = [];
|
|
835
|
-
await this.finalizeSession(session, effectiveContext);
|
|
836
399
|
return {
|
|
837
400
|
message,
|
|
838
401
|
session,
|
|
@@ -854,7 +417,6 @@ export class ResponseModal {
|
|
|
854
417
|
context: effectiveContext,
|
|
855
418
|
history,
|
|
856
419
|
});
|
|
857
|
-
await this.finalizeSession(session, effectiveContext);
|
|
858
420
|
return {
|
|
859
421
|
message: '',
|
|
860
422
|
session,
|
|
@@ -934,17 +496,13 @@ export class ResponseModal {
|
|
|
934
496
|
// Runs after finalize/onComplete and before session persistence.
|
|
935
497
|
// Post-phase signals see the complete turn result: assistant message in
|
|
936
498
|
// history, collected data, tool results.
|
|
937
|
-
const
|
|
938
|
-
|
|
499
|
+
const post = await this.signalCoordinator.applyPostPhase({
|
|
500
|
+
session, context: effectiveContext, historyEvents, message,
|
|
501
|
+
});
|
|
502
|
+
session = post.session;
|
|
939
503
|
// Append post-phase firings to the accumulator (preserves fire order)
|
|
940
|
-
signalFirings.push(...
|
|
941
|
-
|
|
942
|
-
// (no mid-turn re-entry per D6 decision). Pre-LLM-only fields are already
|
|
943
|
-
// dropped inside runPostSignalPhase per Phase 4.5.
|
|
944
|
-
if (postResult.mergedDirective && hasDirectivePositionField(postResult.mergedDirective)) {
|
|
945
|
-
session = { ...session, pendingDirective: postResult.mergedDirective };
|
|
946
|
-
}
|
|
947
|
-
message = this.applyPostSignalReply(message, postResult.mergedDirective);
|
|
504
|
+
signalFirings.push(...post.firings);
|
|
505
|
+
message = post.message;
|
|
948
506
|
// Ensure response structure completeness (Requirement 8.1, 8.2, 8.3)
|
|
949
507
|
// - executedSteps: array of steps executed (empty array if none)
|
|
950
508
|
// - stoppedReason: why execution stopped (undefined for fallback)
|
|
@@ -960,43 +518,6 @@ export class ResponseModal {
|
|
|
960
518
|
triggeredSignals: signalFirings.length > 0 ? signalFirings : undefined,
|
|
961
519
|
};
|
|
962
520
|
}
|
|
963
|
-
/**
|
|
964
|
-
* Execute prepare function for current step if available
|
|
965
|
-
* @private
|
|
966
|
-
*/
|
|
967
|
-
async executeStepPrepare(session, context) {
|
|
968
|
-
if (session.currentFlow && session.currentStep) {
|
|
969
|
-
const currentFlow = this.agent.getFlows().find((r) => r.id === session.currentFlow?.id);
|
|
970
|
-
if (currentFlow) {
|
|
971
|
-
const currentStep = currentFlow.getStep(session.currentStep.id);
|
|
972
|
-
// Skip auto-steps — their prepare is handled by AutoChainExecutor
|
|
973
|
-
if (currentStep?.auto) {
|
|
974
|
-
logger.debug(`[ResponseModal] Skipping pre-routing prepare for auto-step: ${currentStep.id}`);
|
|
975
|
-
return;
|
|
976
|
-
}
|
|
977
|
-
if (currentStep?.prepare) {
|
|
978
|
-
logger.debug(`[ResponseModal] Executing prepare for step: ${currentStep.id}`);
|
|
979
|
-
await this.executePrepareFinalize(currentStep.prepare, context, session.data, currentFlow, currentStep);
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
/**
|
|
985
|
-
* Execute finalize function for current step if available
|
|
986
|
-
* @private
|
|
987
|
-
*/
|
|
988
|
-
async executeStepFinalize(session, context) {
|
|
989
|
-
if (session.currentFlow && session.currentStep) {
|
|
990
|
-
const currentFlow = this.agent.getFlows().find((r) => r.id === session.currentFlow?.id);
|
|
991
|
-
if (currentFlow) {
|
|
992
|
-
const currentStep = currentFlow.getStep(session.currentStep.id);
|
|
993
|
-
if (currentStep?.finalize) {
|
|
994
|
-
logger.debug(`[ResponseModal] Executing finalize for step: ${currentStep.id}`);
|
|
995
|
-
await this.executePrepareFinalize(currentStep.finalize, context, session.data, currentFlow, currentStep);
|
|
996
|
-
}
|
|
997
|
-
}
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
521
|
/**
|
|
1001
522
|
* Process flow response with unified tool execution and data collection
|
|
1002
523
|
* @private
|
|
@@ -1004,79 +525,20 @@ export class ResponseModal {
|
|
|
1004
525
|
async processFlowResponse(params) {
|
|
1005
526
|
const { selectedFlow, selectedStep, responseDirectives, history, context, historyEvents, signal, transientAppendage, mergedPreDirective } = params;
|
|
1006
527
|
let session = params.session;
|
|
1007
|
-
//
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
logger.debug(`[ResponseModal] Step determination: flow match=${isInSameFlow}, currentFlow=${session.currentFlow?.id}, selectedFlow=${selectedFlow.id}, currentStep=${currentStep?.id || 'none'}`);
|
|
1019
|
-
// STEP 1 (Algorithm 1): branches win over linear chain
|
|
1020
|
-
if (currentStep?.branches && currentStep.branches.length > 0) {
|
|
1021
|
-
const branchResult = await this.responsePipeline.evaluateStepBranches(currentStep, selectedFlow, session, context);
|
|
1022
|
-
if (branchResult) {
|
|
1023
|
-
if (branchResult.nextStep) {
|
|
1024
|
-
nextStep = branchResult.nextStep;
|
|
1025
|
-
session = branchResult.session;
|
|
1026
|
-
}
|
|
1027
|
-
else {
|
|
1028
|
-
// Flow transition or completion — no local step to render
|
|
1029
|
-
// Return empty message with updated session; caller handles flow transition
|
|
1030
|
-
return { message: '', session: branchResult.session };
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
if (!nextStep) {
|
|
1035
|
-
// Get candidate steps based on current position in the flow
|
|
1036
|
-
const flowRouter = this.agent.getFlowRouter();
|
|
1037
|
-
const candidates = await flowRouter.getCandidateStepsWithConditions(selectedFlow, currentStep, // Pass current step instead of undefined to maintain progression
|
|
1038
|
-
createTemplateContext({ data: session.data, session, context }));
|
|
1039
|
-
logger.debug(`[ResponseModal] Found ${candidates.length} candidate steps${currentStep ? ' from current step ' + currentStep.id : ' (new flow entry)'}`);
|
|
1040
|
-
if (candidates.length > 0) {
|
|
1041
|
-
nextStep = candidates[0].step;
|
|
1042
|
-
logger.debug(`[ResponseModal] Using first valid step: ${nextStep.id}${currentStep ? ' (progressing from ' + currentStep.id + ')' : ' for new flow'}`);
|
|
1043
|
-
}
|
|
1044
|
-
else {
|
|
1045
|
-
// Fallback to initial step even if it should be skipped
|
|
1046
|
-
nextStep = selectedFlow.initialStep;
|
|
1047
|
-
logger.warn(`[FlowConfigurationError] No valid steps found: all candidates were skipped in flow. Falling back to initial step "${nextStep.id}". Review step skip conditions.`);
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
// Update session with next step
|
|
1052
|
-
// If the next step has requires fields that are missing, stay at the previous step
|
|
1053
|
-
if (nextStep.requires && nextStep.requires.length > 0) {
|
|
1054
|
-
const sessionData = session.data || {};
|
|
1055
|
-
const missingRequires = nextStep.requires.filter(field => sessionData[String(field)] === undefined);
|
|
1056
|
-
if (missingRequires.length > 0) {
|
|
1057
|
-
const warning = `[FlowConfigurationError] Cannot advance to step "${nextStep.description || nextStep.id}": ` +
|
|
1058
|
-
`missing required fields [${missingRequires.join(', ')}]. Staying at current step. Ensure preceding steps collect these fields.`;
|
|
1059
|
-
logger.warn(warning);
|
|
1060
|
-
console.warn(warning);
|
|
1061
|
-
// Stay at the current step - don't enter the next one
|
|
1062
|
-
const currentStepId = session.currentStep?.id;
|
|
1063
|
-
if (currentStepId) {
|
|
1064
|
-
const currentStepInstance = selectedFlow.getStep(currentStepId);
|
|
1065
|
-
if (currentStepInstance) {
|
|
1066
|
-
nextStep = currentStepInstance;
|
|
1067
|
-
logger.debug(`[ResponseModal] Staying at current step: ${nextStep.id} due to missing requires`);
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
else {
|
|
1072
|
-
session = enterStep(session, nextStep.id, nextStep.description);
|
|
1073
|
-
logger.debug(`[ResponseModal] Entered step: ${nextStep.id}`);
|
|
1074
|
-
}
|
|
1075
|
-
}
|
|
1076
|
-
else {
|
|
1077
|
-
session = enterStep(session, nextStep.id, nextStep.description);
|
|
1078
|
-
logger.debug(`[ResponseModal] Entered step: ${nextStep.id}`);
|
|
528
|
+
// Resolve the step to render (branches win over linear chain; requires enforced)
|
|
529
|
+
const stepResolution = await this.responsePipeline.resolveRenderStep({
|
|
530
|
+
selectedFlow,
|
|
531
|
+
selectedStep,
|
|
532
|
+
session,
|
|
533
|
+
context,
|
|
534
|
+
});
|
|
535
|
+
if (stepResolution.flowTransition) {
|
|
536
|
+
// Flow transition or completion — no local step to render
|
|
537
|
+
// Return empty message with updated session; caller handles flow transition
|
|
538
|
+
return { message: '', session: stepResolution.session };
|
|
1079
539
|
}
|
|
540
|
+
const nextStep = stepResolution.nextStep;
|
|
541
|
+
session = stepResolution.session;
|
|
1080
542
|
// Build response schema for this flow (with collect fields from step)
|
|
1081
543
|
const responseSchema = this.responseEngine.responseSchemaForFlow(selectedFlow, nextStep, this.agent.schema);
|
|
1082
544
|
// ── HALT SHORT-CIRCUIT (Requirement 2.5, 2.6, 2.7) ──────────────────────
|
|
@@ -1149,7 +611,7 @@ export class ResponseModal {
|
|
|
1149
611
|
toolNames: toolCalls?.map(tc => tc.toolName) || [],
|
|
1150
612
|
});
|
|
1151
613
|
// Execute tools with unified loop handling
|
|
1152
|
-
const toolResult = await this.
|
|
614
|
+
const toolResult = await this.toolLoopExecutor.runLoop({
|
|
1153
615
|
toolCalls,
|
|
1154
616
|
context,
|
|
1155
617
|
session,
|
|
@@ -1195,14 +657,13 @@ export class ResponseModal {
|
|
|
1195
657
|
if (signalHalted) {
|
|
1196
658
|
const haltMessage = signalHaltReply || '';
|
|
1197
659
|
// Run post-signal phase even on halt
|
|
1198
|
-
const
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
await this.finalizeSession(session, effectiveContext);
|
|
660
|
+
const post = await this.signalCoordinator.applyPostPhase({
|
|
661
|
+
session, context: effectiveContext, historyEvents, message: haltMessage,
|
|
662
|
+
});
|
|
663
|
+
session = post.session;
|
|
664
|
+
signalFirings.push(...post.firings);
|
|
665
|
+
const message = post.message;
|
|
666
|
+
await this.sessionFinalizer.finalize(session, effectiveContext);
|
|
1206
667
|
yield {
|
|
1207
668
|
delta: message,
|
|
1208
669
|
accumulated: message,
|
|
@@ -1235,7 +696,7 @@ export class ResponseModal {
|
|
|
1235
696
|
// Handle halt: emit verbatim reply as a single chunk, done.
|
|
1236
697
|
if (autoResult.stoppedReason === 'halt') {
|
|
1237
698
|
const reply = autoResult.mergedDirective?.reply || '';
|
|
1238
|
-
await this.
|
|
699
|
+
await this.sessionFinalizer.finalize(session, effectiveContext);
|
|
1239
700
|
yield {
|
|
1240
701
|
delta: reply,
|
|
1241
702
|
accumulated: reply,
|
|
@@ -1312,24 +773,26 @@ export class ResponseModal {
|
|
|
1312
773
|
session,
|
|
1313
774
|
});
|
|
1314
775
|
}
|
|
1315
|
-
// ── Intercept the inner stream
|
|
1316
|
-
//
|
|
1317
|
-
//
|
|
1318
|
-
// (Requirement 11.2).
|
|
776
|
+
// ── Intercept the inner stream on the final chunk ──────────────────────
|
|
777
|
+
// Mirrors the non-streaming path: post-signal phase runs first, then the
|
|
778
|
+
// session (including post-phase mutations) is finalized exactly once,
|
|
779
|
+
// attaching triggeredSignals to the final chunk (Requirement 11.2).
|
|
1319
780
|
for await (const chunk of innerStream) {
|
|
1320
781
|
if (chunk.done) {
|
|
1321
782
|
// Run post-signal phase on final chunk (Requirement 9.1, 9.2)
|
|
1322
|
-
const
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
const
|
|
1331
|
-
|
|
1332
|
-
|
|
783
|
+
const post = await this.signalCoordinator.applyPostPhase({
|
|
784
|
+
session: chunk.session || session,
|
|
785
|
+
context: effectiveContext,
|
|
786
|
+
historyEvents,
|
|
787
|
+
message: chunk.accumulated,
|
|
788
|
+
});
|
|
789
|
+
const finalSession = post.session;
|
|
790
|
+
signalFirings.push(...post.firings);
|
|
791
|
+
const accumulated = post.message;
|
|
792
|
+
const delta = post.replyOverridden ? accumulated : chunk.delta;
|
|
793
|
+
// Single streaming exit: finalize the post-phase session so
|
|
794
|
+
// post-signal mutations (e.g. pendingDirective) are persisted
|
|
795
|
+
await this.sessionFinalizer.finalize(finalSession, effectiveContext);
|
|
1333
796
|
yield {
|
|
1334
797
|
...chunk,
|
|
1335
798
|
delta,
|
|
@@ -1350,80 +813,25 @@ export class ResponseModal {
|
|
|
1350
813
|
async *processFlowStreamingResponse(params) {
|
|
1351
814
|
const { selectedFlow, selectedStep, responseDirectives, history, context, historyEvents, signal, transientAppendage, mergedPreDirective } = params;
|
|
1352
815
|
let session = params.session;
|
|
1353
|
-
//
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
session = branchResult.session;
|
|
1370
|
-
nextStep = branchResult.nextStep;
|
|
1371
|
-
}
|
|
1372
|
-
else {
|
|
1373
|
-
// Flow transition or completion — no step to render
|
|
1374
|
-
yield {
|
|
1375
|
-
delta: '',
|
|
1376
|
-
accumulated: '',
|
|
1377
|
-
done: true,
|
|
1378
|
-
session: branchResult.session,
|
|
1379
|
-
};
|
|
1380
|
-
return;
|
|
1381
|
-
}
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
if (!nextStep) {
|
|
1385
|
-
// Get candidate steps based on current position in the flow
|
|
1386
|
-
const flowRouter = this.agent.getFlowRouter();
|
|
1387
|
-
const candidates = await flowRouter.getCandidateStepsWithConditions(selectedFlow, currentStep, // Pass current step instead of undefined to maintain progression
|
|
1388
|
-
createTemplateContext({ data: session.data, session, context }));
|
|
1389
|
-
if (candidates.length > 0) {
|
|
1390
|
-
nextStep = candidates[0].step;
|
|
1391
|
-
logger.debug(`[ResponseModal] Using first valid step: ${nextStep.id}${currentStep ? ' (progressing from ' + currentStep.id + ')' : ' for new flow'}`);
|
|
1392
|
-
}
|
|
1393
|
-
else {
|
|
1394
|
-
nextStep = selectedFlow.initialStep;
|
|
1395
|
-
logger.warn(`[FlowConfigurationError] No valid steps found: all candidates were skipped in flow. Falling back to initial step "${nextStep.id}". Review step skip conditions.`);
|
|
1396
|
-
}
|
|
1397
|
-
}
|
|
1398
|
-
}
|
|
1399
|
-
// Update session with next step
|
|
1400
|
-
// If the next step has requires fields that are missing, stay at the previous step
|
|
1401
|
-
if (nextStep.requires && nextStep.requires.length > 0) {
|
|
1402
|
-
const sessionData = session.data || {};
|
|
1403
|
-
const missingRequires = nextStep.requires.filter(field => sessionData[String(field)] === undefined);
|
|
1404
|
-
if (missingRequires.length > 0) {
|
|
1405
|
-
const warning = `[FlowConfigurationError] Cannot advance to step "${nextStep.description || nextStep.id}": ` +
|
|
1406
|
-
`missing required fields [${missingRequires.join(', ')}]. Staying at current step. Ensure preceding steps collect these fields.`;
|
|
1407
|
-
logger.warn(warning);
|
|
1408
|
-
console.warn(warning);
|
|
1409
|
-
const currentStepId = session.currentStep?.id;
|
|
1410
|
-
if (currentStepId) {
|
|
1411
|
-
const currentStepInstance = selectedFlow.getStep(currentStepId);
|
|
1412
|
-
if (currentStepInstance) {
|
|
1413
|
-
nextStep = currentStepInstance;
|
|
1414
|
-
logger.debug(`[ResponseModal] Staying at current step: ${nextStep.id} due to missing requires`);
|
|
1415
|
-
}
|
|
1416
|
-
}
|
|
1417
|
-
}
|
|
1418
|
-
else {
|
|
1419
|
-
session = enterStep(session, nextStep.id, nextStep.description);
|
|
1420
|
-
logger.debug(`[ResponseModal] Entered step: ${nextStep.id}`);
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1423
|
-
else {
|
|
1424
|
-
session = enterStep(session, nextStep.id, nextStep.description);
|
|
1425
|
-
logger.debug(`[ResponseModal] Entered step: ${nextStep.id}`);
|
|
816
|
+
// Resolve the step to render (same logic as non-streaming)
|
|
817
|
+
const stepResolution = await this.responsePipeline.resolveRenderStep({
|
|
818
|
+
selectedFlow,
|
|
819
|
+
selectedStep,
|
|
820
|
+
session,
|
|
821
|
+
context,
|
|
822
|
+
});
|
|
823
|
+
if (stepResolution.flowTransition) {
|
|
824
|
+
// Flow transition or completion — no step to render
|
|
825
|
+
yield {
|
|
826
|
+
delta: '',
|
|
827
|
+
accumulated: '',
|
|
828
|
+
done: true,
|
|
829
|
+
session: stepResolution.session,
|
|
830
|
+
};
|
|
831
|
+
return;
|
|
1426
832
|
}
|
|
833
|
+
const nextStep = stepResolution.nextStep;
|
|
834
|
+
session = stepResolution.session;
|
|
1427
835
|
// Build response schema and prompt (same as non-streaming)
|
|
1428
836
|
const responseSchema = this.responseEngine.responseSchemaForFlow(selectedFlow, nextStep, this.agent.schema);
|
|
1429
837
|
// ── HALT SHORT-CIRCUIT (Requirement 2.5, 2.6, 2.7) ──────────────────────
|
|
@@ -1433,7 +841,6 @@ export class ResponseModal {
|
|
|
1433
841
|
const reply = mergedPreDirective.reply || '';
|
|
1434
842
|
const reason = mergedPreDirective.reply ? 'reply' : 'halt';
|
|
1435
843
|
logger.debug(`[ResponseModal] Halt (streaming) — skipping LLM call for step ${nextStep.id}, stoppedReason: ${reason}`);
|
|
1436
|
-
await this.finalizeSession(session, context);
|
|
1437
844
|
yield {
|
|
1438
845
|
delta: reply,
|
|
1439
846
|
accumulated: reply,
|
|
@@ -1451,7 +858,6 @@ export class ResponseModal {
|
|
|
1451
858
|
if (nextStep.reply != null) {
|
|
1452
859
|
const effectiveReply = mergedPreDirective?.reply ?? await render(nextStep.reply, createTemplateContext({ data: session.data || {}, context, session }));
|
|
1453
860
|
logger.debug(`[ResponseModal] Step.reply (streaming) — skipping LLM call for step ${nextStep.id}`);
|
|
1454
|
-
await this.finalizeSession(session, context);
|
|
1455
861
|
yield {
|
|
1456
862
|
delta: effectiveReply,
|
|
1457
863
|
accumulated: effectiveReply,
|
|
@@ -1500,70 +906,23 @@ export class ResponseModal {
|
|
|
1500
906
|
// Extract tool calls from AI response on final chunk
|
|
1501
907
|
if (chunk.done && chunk.structured?.toolCalls) {
|
|
1502
908
|
toolCalls = chunk.structured.toolCalls;
|
|
1503
|
-
|
|
1504
|
-
//
|
|
1505
|
-
{
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
step: nextStep,
|
|
1521
|
-
})) {
|
|
1522
|
-
// Apply context updates
|
|
1523
|
-
if (update.contextUpdate) {
|
|
1524
|
-
try {
|
|
1525
|
-
await this.agent.updateContext(update.contextUpdate);
|
|
1526
|
-
}
|
|
1527
|
-
catch (error) {
|
|
1528
|
-
logger.error(`[ResponseModal] Failed to update context from concurrent tool:`, error);
|
|
1529
|
-
}
|
|
1530
|
-
}
|
|
1531
|
-
// Apply data updates
|
|
1532
|
-
if (update.dataUpdate) {
|
|
1533
|
-
try {
|
|
1534
|
-
const updateDataMethod = this.agent.getUpdateDataMethod();
|
|
1535
|
-
session = await updateDataMethod(session, update.dataUpdate);
|
|
1536
|
-
}
|
|
1537
|
-
catch (error) {
|
|
1538
|
-
logger.error(`[ResponseModal] Failed to update data from concurrent tool:`, error);
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
// Yield progress updates immediately
|
|
1542
|
-
if (update.progress) {
|
|
1543
|
-
yield {
|
|
1544
|
-
delta: '',
|
|
1545
|
-
accumulated: chunk.accumulated,
|
|
1546
|
-
done: false,
|
|
1547
|
-
session,
|
|
1548
|
-
toolCalls: undefined,
|
|
1549
|
-
isFlowComplete: false,
|
|
1550
|
-
metadata: { toolProgress: update.progress, toolCallId: update.toolCallId },
|
|
1551
|
-
};
|
|
1552
|
-
}
|
|
1553
|
-
}
|
|
1554
|
-
logger.debug(`[ResponseModal] Concurrent tool execution completed for ${toolCallRequests.length} tools`);
|
|
1555
|
-
}
|
|
1556
|
-
catch (error) {
|
|
1557
|
-
logger.error(`[ResponseModal] Concurrent tool execution failed, falling back to sequential:`, error);
|
|
1558
|
-
// Fall back to the unified tool loop on failure
|
|
1559
|
-
const toolResult = await this.executeUnifiedToolLoop({
|
|
1560
|
-
toolCalls, context, session, history, selectedFlow,
|
|
1561
|
-
responsePrompt, availableTools, responseSchema, signal,
|
|
1562
|
-
});
|
|
1563
|
-
session = toolResult.session;
|
|
1564
|
-
toolCalls = toolResult.finalToolCalls;
|
|
1565
|
-
}
|
|
1566
|
-
}
|
|
909
|
+
// Concurrent execution for the initial batch of tool calls,
|
|
910
|
+
// yielding tool-progress chunks as they arrive
|
|
911
|
+
const batchResult = yield* this.toolLoopExecutor.runStreamingBatch({
|
|
912
|
+
toolCalls,
|
|
913
|
+
context,
|
|
914
|
+
session,
|
|
915
|
+
history,
|
|
916
|
+
selectedFlow,
|
|
917
|
+
step: nextStep,
|
|
918
|
+
accumulated: chunk.accumulated,
|
|
919
|
+
responsePrompt,
|
|
920
|
+
availableTools,
|
|
921
|
+
responseSchema,
|
|
922
|
+
signal,
|
|
923
|
+
});
|
|
924
|
+
session = batchResult.session;
|
|
925
|
+
toolCalls = batchResult.toolCalls;
|
|
1567
926
|
}
|
|
1568
927
|
// Extract collected data on final chunk
|
|
1569
928
|
if (chunk.done && chunk.structured && nextStep.collect) {
|
|
@@ -1574,10 +933,6 @@ export class ResponseModal {
|
|
|
1574
933
|
session,
|
|
1575
934
|
});
|
|
1576
935
|
}
|
|
1577
|
-
// Handle session finalization on final chunk
|
|
1578
|
-
if (chunk.done) {
|
|
1579
|
-
await this.finalizeSession(session, context);
|
|
1580
|
-
}
|
|
1581
936
|
// Response structure completeness (Requirement 8.1, 8.2, 8.3)
|
|
1582
937
|
// - executedSteps: single step executed in this response
|
|
1583
938
|
// - stoppedReason: 'needs_input' for single-step execution (waiting for user input)
|
|
@@ -1605,293 +960,6 @@ export class ResponseModal {
|
|
|
1605
960
|
}
|
|
1606
961
|
}
|
|
1607
962
|
/**
|
|
1608
|
-
* Unified tool execution logic with loop handling
|
|
1609
|
-
* Consolidates the complex tool execution logic from both streaming and non-streaming responses
|
|
1610
|
-
* @private
|
|
1611
|
-
*/
|
|
1612
|
-
async executeUnifiedToolLoop(params) {
|
|
1613
|
-
try {
|
|
1614
|
-
const { context, history, selectedFlow, responsePrompt, availableTools, responseSchema, signal } = params;
|
|
1615
|
-
let { toolCalls, session } = params;
|
|
1616
|
-
// Convert HistoryItem[] to Event[] for internal processing
|
|
1617
|
-
const historyEvents = historyToEvents(history);
|
|
1618
|
-
// Map to store tool execution results for history
|
|
1619
|
-
const toolResultsMap = new Map();
|
|
1620
|
-
// Map to store tool call arguments for history reconstruction
|
|
1621
|
-
const toolArgsMap = new Map();
|
|
1622
|
-
// Execute initial dynamic tool calls
|
|
1623
|
-
if (toolCalls && toolCalls.length > 0) {
|
|
1624
|
-
logger.debug(`[ResponseModal] Executing ${toolCalls.length} dynamic tool calls:`, toolCalls.map(tc => tc.toolName));
|
|
1625
|
-
for (const toolCall of toolCalls) {
|
|
1626
|
-
const tool = this.findAvailableTool(toolCall.toolName, selectedFlow);
|
|
1627
|
-
if (!tool) {
|
|
1628
|
-
logger.warn(`[ToolExecutionError] Tool not found: "${toolCall.toolName}" is not registered in any scope. Skipping this tool call. Register the tool or check the tool name.`);
|
|
1629
|
-
continue;
|
|
1630
|
-
}
|
|
1631
|
-
try {
|
|
1632
|
-
// Use ToolManager for unified tool execution
|
|
1633
|
-
const toolManager = this.getToolManager();
|
|
1634
|
-
const toolResult = await toolManager.executeTool({
|
|
1635
|
-
tool: tool,
|
|
1636
|
-
context,
|
|
1637
|
-
updateContext: this.agent.updateContext.bind(this.agent),
|
|
1638
|
-
updateData: this.agent.updateCollectedData.bind(this.agent),
|
|
1639
|
-
history: historyEvents, // Use Event[] for tool execution
|
|
1640
|
-
data: session.data,
|
|
1641
|
-
toolArguments: toolCall.arguments,
|
|
1642
|
-
});
|
|
1643
|
-
// Store the actual tool result data for history
|
|
1644
|
-
toolResultsMap.set(toolCall.toolName, serializeToolResult(toolResult));
|
|
1645
|
-
toolArgsMap.set(toolCall.toolName, toolCall.arguments);
|
|
1646
|
-
// Check if tool execution was successful
|
|
1647
|
-
if (!toolResult.success) {
|
|
1648
|
-
logger.error(`[ResponseModal] Tool execution failed: ${toolCall.toolName} - ${toolResult.error}`);
|
|
1649
|
-
// Continue with other tools rather than failing completely
|
|
1650
|
-
continue;
|
|
1651
|
-
}
|
|
1652
|
-
// Update context with tool results
|
|
1653
|
-
if (toolResult.contextUpdate) {
|
|
1654
|
-
try {
|
|
1655
|
-
await this.agent.updateContext(toolResult.contextUpdate);
|
|
1656
|
-
}
|
|
1657
|
-
catch (error) {
|
|
1658
|
-
logger.error(`[ResponseModal] Failed to update context from tool ${toolCall.toolName}:`, error);
|
|
1659
|
-
// Continue execution but log the error
|
|
1660
|
-
}
|
|
1661
|
-
}
|
|
1662
|
-
// Update collected data with tool results
|
|
1663
|
-
if (toolResult.dataUpdate) {
|
|
1664
|
-
try {
|
|
1665
|
-
const updateDataMethod = this.agent.getUpdateDataMethod();
|
|
1666
|
-
session = await updateDataMethod(session, toolResult.dataUpdate);
|
|
1667
|
-
logger.debug(`[ResponseModal] Tool updated collected data:`, toolResult.dataUpdate);
|
|
1668
|
-
}
|
|
1669
|
-
catch (error) {
|
|
1670
|
-
logger.error(`[ResponseModal] Failed to update data from tool ${toolCall.toolName}:`, error);
|
|
1671
|
-
// Continue execution but log the error
|
|
1672
|
-
}
|
|
1673
|
-
}
|
|
1674
|
-
logger.debug(`[ResponseModal] Executed dynamic tool: ${toolCall.toolName} (success: ${toolResult.success})`);
|
|
1675
|
-
}
|
|
1676
|
-
catch (error) {
|
|
1677
|
-
logger.error(`[ResponseModal] Tool execution error for ${toolCall.toolName}:`, error);
|
|
1678
|
-
// Continue with other tools rather than failing the entire response
|
|
1679
|
-
continue;
|
|
1680
|
-
}
|
|
1681
|
-
}
|
|
1682
|
-
}
|
|
1683
|
-
// TOOL LOOP: Allow AI to make follow-up tool calls after initial tool execution
|
|
1684
|
-
const MAX_TOOL_LOOPS = this.options?.maxToolLoops || 5;
|
|
1685
|
-
let toolLoopCount = 0;
|
|
1686
|
-
let hasToolCalls = toolCalls && toolCalls.length > 0;
|
|
1687
|
-
let finalMessage;
|
|
1688
|
-
let followUpStructured;
|
|
1689
|
-
while (hasToolCalls && toolLoopCount < MAX_TOOL_LOOPS) {
|
|
1690
|
-
toolLoopCount++;
|
|
1691
|
-
logger.debug(`[ResponseModal] Starting tool loop ${toolLoopCount}/${MAX_TOOL_LOOPS} with ${toolCalls?.length || 0} tool calls`);
|
|
1692
|
-
// Create tool result history items
|
|
1693
|
-
const toolResultHistoryItems = [];
|
|
1694
|
-
for (const toolCall of toolCalls || []) {
|
|
1695
|
-
const tool = this.findAvailableTool(toolCall.toolName, selectedFlow);
|
|
1696
|
-
if (tool) {
|
|
1697
|
-
// Create HistoryItem format for tool results
|
|
1698
|
-
// Add assistant message with tool_calls
|
|
1699
|
-
toolResultHistoryItems.push({
|
|
1700
|
-
role: "assistant",
|
|
1701
|
-
content: null,
|
|
1702
|
-
tool_calls: [{
|
|
1703
|
-
id: toolCall.toolName,
|
|
1704
|
-
name: toolCall.toolName,
|
|
1705
|
-
arguments: toolCall.arguments,
|
|
1706
|
-
}],
|
|
1707
|
-
});
|
|
1708
|
-
// Add tool result
|
|
1709
|
-
toolResultHistoryItems.push({
|
|
1710
|
-
role: "tool",
|
|
1711
|
-
tool_call_id: toolCall.toolName,
|
|
1712
|
-
name: toolCall.toolName,
|
|
1713
|
-
content: toolResultsMap.get(toolCall.toolName) || "Tool executed successfully",
|
|
1714
|
-
});
|
|
1715
|
-
}
|
|
1716
|
-
}
|
|
1717
|
-
// Create updated history with tool results
|
|
1718
|
-
const updatedHistory = [...history, ...toolResultHistoryItems];
|
|
1719
|
-
// Make follow-up AI call to see if more tools are needed
|
|
1720
|
-
// After first iteration, don't provide tools to force a text response
|
|
1721
|
-
const agentOptions = this.agent.getAgentOptions();
|
|
1722
|
-
const shouldProvideTools = toolLoopCount === 1;
|
|
1723
|
-
logger.debug(`[ResponseModal] Making follow-up AI call (loop ${toolLoopCount}):`, {
|
|
1724
|
-
providingTools: shouldProvideTools,
|
|
1725
|
-
toolsCount: shouldProvideTools ? availableTools.length : 0,
|
|
1726
|
-
addingTextInstruction: toolLoopCount > 1,
|
|
1727
|
-
});
|
|
1728
|
-
const followUpResult = await agentOptions.provider.generateMessage({
|
|
1729
|
-
prompt: responsePrompt + (toolLoopCount > 1 ? "\n\nProvide a text response to the user based on the tool results." : ""),
|
|
1730
|
-
history: updatedHistory, // Use HistoryItem[] for AI provider
|
|
1731
|
-
context,
|
|
1732
|
-
tools: shouldProvideTools ? availableTools : [], // Only provide tools on first iteration
|
|
1733
|
-
parameters: responseSchema ? {
|
|
1734
|
-
jsonSchema: responseSchema,
|
|
1735
|
-
schemaName: "tool_followup",
|
|
1736
|
-
} : undefined,
|
|
1737
|
-
signal,
|
|
1738
|
-
});
|
|
1739
|
-
// Check if follow-up call has more tool calls
|
|
1740
|
-
const followUpToolCalls = followUpResult.structured?.toolCalls;
|
|
1741
|
-
hasToolCalls = followUpToolCalls && followUpToolCalls.length > 0;
|
|
1742
|
-
logger.debug(`[ResponseModal] Follow-up AI response (loop ${toolLoopCount}):`, {
|
|
1743
|
-
hasMessage: !!followUpResult.message,
|
|
1744
|
-
messageLength: followUpResult.message?.length || 0,
|
|
1745
|
-
hasToolCalls,
|
|
1746
|
-
toolCallsCount: followUpToolCalls?.length || 0,
|
|
1747
|
-
toolNames: followUpToolCalls?.map(tc => tc.toolName) || [],
|
|
1748
|
-
});
|
|
1749
|
-
if (hasToolCalls) {
|
|
1750
|
-
logger.debug(`[ResponseModal] Follow-up call produced ${followUpToolCalls.length} additional tool calls`);
|
|
1751
|
-
// Execute the follow-up tool calls
|
|
1752
|
-
for (const toolCall of followUpToolCalls) {
|
|
1753
|
-
const tool = this.findAvailableTool(toolCall.toolName, selectedFlow);
|
|
1754
|
-
if (!tool) {
|
|
1755
|
-
logger.warn(`[ToolExecutionError] Tool not found in follow-up: "${toolCall.toolName}" is not registered in any scope. Skipping this tool call. Register the tool or check the tool name.`);
|
|
1756
|
-
continue;
|
|
1757
|
-
}
|
|
1758
|
-
try {
|
|
1759
|
-
// Use ToolManager for unified tool execution
|
|
1760
|
-
const toolManager = this.getToolManager();
|
|
1761
|
-
const toolResult = await toolManager.executeTool({
|
|
1762
|
-
tool: tool,
|
|
1763
|
-
context,
|
|
1764
|
-
updateContext: this.agent.updateContext.bind(this.agent),
|
|
1765
|
-
updateData: this.agent.updateCollectedData.bind(this.agent),
|
|
1766
|
-
history: historyToEvents(updatedHistory), // Convert to Event[] for tool execution
|
|
1767
|
-
data: session.data,
|
|
1768
|
-
toolArguments: toolCall.arguments,
|
|
1769
|
-
});
|
|
1770
|
-
// Check if tool execution was successful
|
|
1771
|
-
if (!toolResult.success) {
|
|
1772
|
-
logger.error(`[ResponseModal] Follow-up tool execution failed: ${toolCall.toolName} - ${toolResult.error}`);
|
|
1773
|
-
continue;
|
|
1774
|
-
}
|
|
1775
|
-
// Update context with follow-up tool results
|
|
1776
|
-
if (toolResult.contextUpdate) {
|
|
1777
|
-
try {
|
|
1778
|
-
await this.agent.updateContext(toolResult.contextUpdate);
|
|
1779
|
-
}
|
|
1780
|
-
catch (error) {
|
|
1781
|
-
logger.error(`[ResponseModal] Failed to update context from follow-up tool ${toolCall.toolName}:`, error);
|
|
1782
|
-
}
|
|
1783
|
-
}
|
|
1784
|
-
if (toolResult.dataUpdate) {
|
|
1785
|
-
try {
|
|
1786
|
-
const updateDataMethod = this.agent.getUpdateDataMethod();
|
|
1787
|
-
session = await updateDataMethod(session, toolResult.dataUpdate);
|
|
1788
|
-
logger.debug(`[ResponseModal] Follow-up tool updated collected data:`, toolResult.dataUpdate);
|
|
1789
|
-
}
|
|
1790
|
-
catch (error) {
|
|
1791
|
-
logger.error(`[ResponseModal] Failed to update data from follow-up tool ${toolCall.toolName}:`, error);
|
|
1792
|
-
}
|
|
1793
|
-
}
|
|
1794
|
-
// Store the follow-up tool result for potential next loop iteration
|
|
1795
|
-
toolResultsMap.set(toolCall.toolName, serializeToolResult(toolResult));
|
|
1796
|
-
toolArgsMap.set(toolCall.toolName, toolCall.arguments);
|
|
1797
|
-
logger.debug(`[ResponseModal] Executed follow-up tool: ${toolCall.toolName} (success: ${toolResult.success})`);
|
|
1798
|
-
}
|
|
1799
|
-
catch (error) {
|
|
1800
|
-
logger.error(`[ResponseModal] Follow-up tool execution error for ${toolCall.toolName}:`, error);
|
|
1801
|
-
continue;
|
|
1802
|
-
}
|
|
1803
|
-
}
|
|
1804
|
-
// Update toolCalls for next iteration or final response
|
|
1805
|
-
toolCalls = followUpToolCalls;
|
|
1806
|
-
}
|
|
1807
|
-
else {
|
|
1808
|
-
logger.debug(`[ResponseModal] Tool loop completed after ${toolLoopCount} iterations`);
|
|
1809
|
-
// Update final message and toolCalls from follow-up result if no more tools
|
|
1810
|
-
finalMessage = followUpResult.structured?.message || followUpResult.message;
|
|
1811
|
-
followUpStructured = followUpResult.structured;
|
|
1812
|
-
toolCalls = followUpToolCalls || [];
|
|
1813
|
-
break;
|
|
1814
|
-
}
|
|
1815
|
-
}
|
|
1816
|
-
if (toolLoopCount >= MAX_TOOL_LOOPS) {
|
|
1817
|
-
logger.warn(`[ResponseGenerationError] Tool loop limit reached: ${toolLoopCount} iterations hit the cap (${MAX_TOOL_LOOPS}). Stopping tool execution. Increase MAX_TOOL_LOOPS or reduce recursive tool calls.`);
|
|
1818
|
-
}
|
|
1819
|
-
// If tools were executed but no final text message was produced,
|
|
1820
|
-
// make one more LLM call to generate a proper text response from tool results.
|
|
1821
|
-
// This prevents the original tool-invocation message (e.g. "Let me check...")
|
|
1822
|
-
// from being returned as the final user-facing response.
|
|
1823
|
-
if (!finalMessage && toolLoopCount > 0) {
|
|
1824
|
-
logger.debug(`[ResponseModal] No final message after tool loop, making additional LLM call for text response`);
|
|
1825
|
-
// Build tool result history from toolResultsMap which contains ALL
|
|
1826
|
-
// tool executions (initial + follow-up). We can't use `toolCalls` here
|
|
1827
|
-
// because it was reassigned to the (empty) follow-up tool calls when
|
|
1828
|
-
// the while loop broke out.
|
|
1829
|
-
const finalToolResultHistoryItems = [];
|
|
1830
|
-
for (const [toolName, toolResult] of toolResultsMap) {
|
|
1831
|
-
finalToolResultHistoryItems.push({
|
|
1832
|
-
role: "assistant",
|
|
1833
|
-
content: null,
|
|
1834
|
-
tool_calls: [{
|
|
1835
|
-
id: toolName,
|
|
1836
|
-
name: toolName,
|
|
1837
|
-
arguments: toolArgsMap.get(toolName) || {},
|
|
1838
|
-
}],
|
|
1839
|
-
});
|
|
1840
|
-
finalToolResultHistoryItems.push({
|
|
1841
|
-
role: "tool",
|
|
1842
|
-
tool_call_id: toolName,
|
|
1843
|
-
name: toolName,
|
|
1844
|
-
content: toolResult,
|
|
1845
|
-
});
|
|
1846
|
-
}
|
|
1847
|
-
const finalHistory = [...history, ...finalToolResultHistoryItems];
|
|
1848
|
-
const agentOptions = this.agent.getAgentOptions();
|
|
1849
|
-
try {
|
|
1850
|
-
const textResult = await agentOptions.provider.generateMessage({
|
|
1851
|
-
prompt: responsePrompt + "\n\nProvide a text response to the user based on the tool results. Do not call any tools.",
|
|
1852
|
-
history: finalHistory,
|
|
1853
|
-
context,
|
|
1854
|
-
tools: [], // No tools - force text response
|
|
1855
|
-
parameters: responseSchema ? {
|
|
1856
|
-
jsonSchema: responseSchema,
|
|
1857
|
-
schemaName: "tool_final_text",
|
|
1858
|
-
} : undefined,
|
|
1859
|
-
signal,
|
|
1860
|
-
});
|
|
1861
|
-
finalMessage = textResult.structured?.message || textResult.message;
|
|
1862
|
-
if (textResult.structured) {
|
|
1863
|
-
followUpStructured = textResult.structured;
|
|
1864
|
-
}
|
|
1865
|
-
logger.debug(`[ResponseModal] Generated final text response after tool loop:`, {
|
|
1866
|
-
hasMessage: !!finalMessage,
|
|
1867
|
-
messageLength: finalMessage?.length || 0,
|
|
1868
|
-
});
|
|
1869
|
-
}
|
|
1870
|
-
catch (error) {
|
|
1871
|
-
logger.error(`[ResponseModal] Failed to generate final text response after tool loop:`, error);
|
|
1872
|
-
// finalMessage remains undefined; caller will use original message as fallback
|
|
1873
|
-
}
|
|
1874
|
-
}
|
|
1875
|
-
logger.debug(`[ResponseModal] Tool loop completed:`, {
|
|
1876
|
-
totalIterations: toolLoopCount,
|
|
1877
|
-
hasFinalMessage: !!finalMessage,
|
|
1878
|
-
finalMessageLength: finalMessage?.length || 0,
|
|
1879
|
-
finalToolCallsCount: toolCalls?.length || 0,
|
|
1880
|
-
});
|
|
1881
|
-
return {
|
|
1882
|
-
session,
|
|
1883
|
-
finalToolCalls: toolCalls,
|
|
1884
|
-
finalMessage,
|
|
1885
|
-
structured: followUpStructured,
|
|
1886
|
-
};
|
|
1887
|
-
}
|
|
1888
|
-
catch (error) {
|
|
1889
|
-
throw ResponseGenerationError.fromError(error, 'tool_execution', params, {
|
|
1890
|
-
toolCallsCount: params.toolCalls?.length || 0,
|
|
1891
|
-
availableToolsCount: params.availableTools.length
|
|
1892
|
-
});
|
|
1893
|
-
}
|
|
1894
|
-
} /**
|
|
1895
963
|
* Unified data collection from AI response
|
|
1896
964
|
* @private
|
|
1897
965
|
*/
|
|
@@ -2037,10 +1105,6 @@ export class ResponseModal {
|
|
|
2037
1105
|
}
|
|
2038
1106
|
return nextSession;
|
|
2039
1107
|
}
|
|
2040
|
-
/**
|
|
2041
|
-
* Stream flow completion response
|
|
2042
|
-
* @private
|
|
2043
|
-
*/
|
|
2044
1108
|
/**
|
|
2045
1109
|
* Stream a flow completion as a single terminal chunk.
|
|
2046
1110
|
*
|
|
@@ -2062,7 +1126,6 @@ export class ResponseModal {
|
|
|
2062
1126
|
context,
|
|
2063
1127
|
history,
|
|
2064
1128
|
});
|
|
2065
|
-
await this.finalizeSession(session, context);
|
|
2066
1129
|
yield {
|
|
2067
1130
|
delta: '',
|
|
2068
1131
|
accumulated: '',
|
|
@@ -2137,10 +1200,6 @@ export class ResponseModal {
|
|
|
2137
1200
|
},
|
|
2138
1201
|
});
|
|
2139
1202
|
for await (const chunk of stream) {
|
|
2140
|
-
// Update current session if we have one
|
|
2141
|
-
if (chunk.done) {
|
|
2142
|
-
await this.finalizeSession(session, context);
|
|
2143
|
-
}
|
|
2144
1203
|
// Response structure completeness (Requirement 8.1, 8.2, 8.3)
|
|
2145
1204
|
// - executedSteps: empty for fallback (no flow/step execution)
|
|
2146
1205
|
// - stoppedReason: undefined for fallback (no flow context)
|
|
@@ -2160,39 +1219,9 @@ export class ResponseModal {
|
|
|
2160
1219
|
};
|
|
2161
1220
|
}
|
|
2162
1221
|
}
|
|
2163
|
-
/**
|
|
2164
|
-
* Handle session persistence and finalization
|
|
2165
|
-
* @private
|
|
2166
|
-
*/
|
|
2167
|
-
async finalizeSession(session, context) {
|
|
2168
|
-
// Auto-save session step to persistence if configured
|
|
2169
|
-
const persistenceManager = this.agent.getPersistenceManager();
|
|
2170
|
-
const agentOptions = this.agent.getAgentOptions();
|
|
2171
|
-
if (persistenceManager &&
|
|
2172
|
-
session.id &&
|
|
2173
|
-
(this.options?.enableAutoSave !== false && agentOptions.persistence?.autoSave !== false)) {
|
|
2174
|
-
await persistenceManager.saveSessionState(session.id, session);
|
|
2175
|
-
logger.debug(`[ResponseModal] Auto-saved session step to persistence: ${session.id}`);
|
|
2176
|
-
}
|
|
2177
|
-
// Execute finalize function
|
|
2178
|
-
await this.executeStepFinalize(session, context);
|
|
2179
|
-
// Update current session if we have one
|
|
2180
|
-
const currentSession = this.agent.currentSession;
|
|
2181
|
-
if (currentSession) {
|
|
2182
|
-
this.agent.currentSession = session;
|
|
2183
|
-
}
|
|
2184
|
-
}
|
|
2185
1222
|
// ============================================================================
|
|
2186
1223
|
// UTILITY METHODS - Helper methods for tool management and other utilities
|
|
2187
1224
|
// ============================================================================
|
|
2188
|
-
/**
|
|
2189
|
-
* Find an available tool by name for the given flow.
|
|
2190
|
-
* Delegates to ToolManager for unified tool resolution.
|
|
2191
|
-
* @private
|
|
2192
|
-
*/
|
|
2193
|
-
findAvailableTool(toolName, flow) {
|
|
2194
|
-
return this.getToolManager().find(toolName, undefined, undefined, flow);
|
|
2195
|
-
}
|
|
2196
1225
|
/**
|
|
2197
1226
|
* Collect all available tools for the given flow and step context.
|
|
2198
1227
|
* Delegates to ToolManager for unified tool resolution and deduplication.
|
|
@@ -2207,49 +1236,5 @@ export class ResponseModal {
|
|
|
2207
1236
|
parameters: tool.parameters,
|
|
2208
1237
|
}));
|
|
2209
1238
|
}
|
|
2210
|
-
/**
|
|
2211
|
-
* Execute a prepare or finalize function/tool
|
|
2212
|
-
* @private
|
|
2213
|
-
*/
|
|
2214
|
-
async executePrepareFinalize(prepareOrFinalize, context, data, flow, step) {
|
|
2215
|
-
if (!prepareOrFinalize)
|
|
2216
|
-
return;
|
|
2217
|
-
if (typeof prepareOrFinalize === "function") {
|
|
2218
|
-
// It's a function - call it directly
|
|
2219
|
-
await prepareOrFinalize(context, data);
|
|
2220
|
-
}
|
|
2221
|
-
else {
|
|
2222
|
-
// It's a tool reference - find and execute the tool
|
|
2223
|
-
let tool;
|
|
2224
|
-
if (typeof prepareOrFinalize === "string") {
|
|
2225
|
-
// Tool ID - use ToolManager for unified resolution
|
|
2226
|
-
tool = this.getToolManager().find(prepareOrFinalize, undefined, step, flow);
|
|
2227
|
-
}
|
|
2228
|
-
else {
|
|
2229
|
-
// Tool object - use directly
|
|
2230
|
-
tool = prepareOrFinalize;
|
|
2231
|
-
}
|
|
2232
|
-
if (tool) {
|
|
2233
|
-
// Use ToolManager for unified tool execution
|
|
2234
|
-
const result = await this.getToolManager().executeTool({
|
|
2235
|
-
tool,
|
|
2236
|
-
context,
|
|
2237
|
-
updateContext: this.agent.updateContext.bind(this.agent),
|
|
2238
|
-
updateData: this.agent.updateCollectedData.bind(this.agent),
|
|
2239
|
-
history: [], // Empty history for prepare/finalize
|
|
2240
|
-
data,
|
|
2241
|
-
});
|
|
2242
|
-
if (!result.success) {
|
|
2243
|
-
logger.error(`[ResponseModal] Tool execution failed in prepare/finalize: ${result.error}`);
|
|
2244
|
-
throw new Error(`Tool execution failed: ${result.error}`);
|
|
2245
|
-
}
|
|
2246
|
-
}
|
|
2247
|
-
else {
|
|
2248
|
-
logger.warn(`[ResponseModal] Tool not found for prepare/finalize: ${typeof prepareOrFinalize === "string"
|
|
2249
|
-
? prepareOrFinalize
|
|
2250
|
-
: "inline tool"}`);
|
|
2251
|
-
}
|
|
2252
|
-
}
|
|
2253
|
-
}
|
|
2254
1239
|
}
|
|
2255
1240
|
//# sourceMappingURL=ResponseModal.js.map
|