@signalwire/sdk 2.0.4 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +785 -0
- package/LICENSE +21 -0
- package/README.md +163 -68
- package/dist/AGENTS.md +13 -0
- package/dist/AgentBase.d.ts +550 -163
- package/dist/AgentBase.js +1640 -514
- package/dist/AgentBase.js.map +1 -1
- package/dist/AgentServer.d.ts +21 -0
- package/dist/AgentServer.js +154 -47
- package/dist/AgentServer.js.map +1 -1
- package/dist/AuthHandler.d.ts +14 -2
- package/dist/AuthHandler.js +7 -2
- package/dist/AuthHandler.js.map +1 -1
- package/dist/ConfigLoader.d.ts +5 -13
- package/dist/ConfigLoader.js +15 -29
- package/dist/ConfigLoader.js.map +1 -1
- package/dist/ContextBuilder.d.ts +202 -9
- package/dist/ContextBuilder.js +219 -36
- package/dist/ContextBuilder.js.map +1 -1
- package/dist/DataMap.d.ts +158 -45
- package/dist/DataMap.js +167 -52
- package/dist/DataMap.js.map +1 -1
- package/dist/FunctionResult.d.ts +277 -83
- package/dist/FunctionResult.js +444 -116
- package/dist/FunctionResult.js.map +1 -1
- package/dist/Logger.d.ts +30 -5
- package/dist/Logger.js +77 -19
- package/dist/Logger.js.map +1 -1
- package/dist/POM/PromptObjectModel.d.ts +163 -0
- package/dist/POM/PromptObjectModel.js +481 -0
- package/dist/POM/PromptObjectModel.js.map +1 -0
- package/dist/ParameterSchema.d.ts +306 -0
- package/dist/ParameterSchema.js +251 -0
- package/dist/ParameterSchema.js.map +1 -0
- package/dist/PlatformContracts.d.ts +21 -0
- package/dist/PlatformContracts.generated.d.ts +109 -0
- package/dist/PlatformContracts.generated.js +8 -0
- package/dist/PlatformContracts.generated.js.map +1 -0
- package/dist/PlatformContracts.js +2 -0
- package/dist/PlatformContracts.js.map +1 -0
- package/dist/PomBuilder.d.ts +28 -0
- package/dist/PomBuilder.js +81 -3
- package/dist/PomBuilder.js.map +1 -1
- package/dist/PostPrompt.d.ts +110 -0
- package/dist/PostPrompt.js +204 -0
- package/dist/PostPrompt.js.map +1 -0
- package/dist/PromptManager.d.ts +29 -1
- package/dist/PromptManager.js +37 -1
- package/dist/PromptManager.js.map +1 -1
- package/dist/PublicFetch.d.ts +132 -0
- package/dist/PublicFetch.js +311 -0
- package/dist/PublicFetch.js.map +1 -0
- package/dist/RobotsTxt.d.ts +41 -0
- package/dist/RobotsTxt.js +152 -0
- package/dist/RobotsTxt.js.map +1 -0
- package/dist/SWMLHandler.js.map +1 -1
- package/dist/SWMLService.d.ts +265 -66
- package/dist/SWMLService.js +652 -112
- package/dist/SWMLService.js.map +1 -1
- package/dist/SchemaUtils.d.ts +115 -2
- package/dist/SchemaUtils.js +444 -12
- package/dist/SchemaUtils.js.map +1 -1
- package/dist/SecurityUtils.d.ts +55 -8
- package/dist/SecurityUtils.js +162 -49
- package/dist/SecurityUtils.js.map +1 -1
- package/dist/ServerlessAdapter.d.ts +156 -7
- package/dist/ServerlessAdapter.js +399 -42
- package/dist/ServerlessAdapter.js.map +1 -1
- package/dist/SessionManager.d.ts +11 -2
- package/dist/SessionManager.js +50 -18
- package/dist/SessionManager.js.map +1 -1
- package/dist/SslConfig.d.ts +2 -1
- package/dist/SslConfig.js +4 -1
- package/dist/SslConfig.js.map +1 -1
- package/dist/SwaigActions.generated.d.ts +23 -0
- package/dist/SwaigActions.generated.js +8 -0
- package/dist/SwaigActions.generated.js.map +1 -0
- package/dist/SwaigContracts.d.ts +15 -0
- package/dist/SwaigContracts.generated.d.ts +264 -0
- package/dist/SwaigContracts.generated.js +12 -0
- package/dist/SwaigContracts.generated.js.map +1 -0
- package/dist/SwaigContracts.js +2 -0
- package/dist/SwaigContracts.js.map +1 -0
- package/dist/SwaigFunction.d.ts +110 -4
- package/dist/SwaigFunction.js +151 -19
- package/dist/SwaigFunction.js.map +1 -1
- package/dist/SwmlBuilder.d.ts +68 -19
- package/dist/SwmlBuilder.js +74 -38
- package/dist/SwmlBuilder.js.map +1 -1
- package/dist/SwmlVerbMethods.generated.d.ts +41 -4
- package/dist/SwmlVerbMethods.generated.js +1 -1
- package/dist/TypeInference.d.ts +39 -3
- package/dist/TypeInference.js +256 -16
- package/dist/TypeInference.js.map +1 -1
- package/dist/WebService.d.ts +79 -11
- package/dist/WebService.js +320 -109
- package/dist/WebService.js.map +1 -1
- package/dist/WebhookMiddleware.d.ts +119 -0
- package/dist/WebhookMiddleware.js +271 -0
- package/dist/WebhookMiddleware.js.map +1 -0
- package/dist/WebhookValidator.d.ts +92 -0
- package/dist/WebhookValidator.js +409 -0
- package/dist/WebhookValidator.js.map +1 -0
- package/dist/agents/BedrockAgent.d.ts +162 -0
- package/dist/agents/BedrockAgent.js +323 -0
- package/dist/agents/BedrockAgent.js.map +1 -0
- package/dist/ai-chat/AIChatClient.d.ts +316 -0
- package/dist/ai-chat/AIChatClient.js +535 -0
- package/dist/ai-chat/AIChatClient.js.map +1 -0
- package/dist/ai-chat/ChatGateway.d.ts +408 -0
- package/dist/ai-chat/ChatGateway.js +747 -0
- package/dist/ai-chat/ChatGateway.js.map +1 -0
- package/dist/ai-chat/HandoffRouter.d.ts +282 -0
- package/dist/ai-chat/HandoffRouter.js +518 -0
- package/dist/ai-chat/HandoffRouter.js.map +1 -0
- package/dist/ai-chat/index.d.ts +12 -0
- package/dist/ai-chat/index.js +10 -0
- package/dist/ai-chat/index.js.map +1 -0
- package/dist/capabilities.d.ts +64 -0
- package/dist/capabilities.js +95 -0
- package/dist/capabilities.js.map +1 -0
- package/dist/cli/agent-loader.d.ts +32 -6
- package/dist/cli/agent-loader.js +95 -34
- package/dist/cli/agent-loader.js.map +1 -1
- package/dist/cli/datamap-exec.d.ts +175 -0
- package/dist/cli/datamap-exec.js +1284 -0
- package/dist/cli/datamap-exec.js.map +1 -0
- package/dist/cli/function-args.d.ts +40 -0
- package/dist/cli/function-args.js +146 -0
- package/dist/cli/function-args.js.map +1 -0
- package/dist/cli/simulation.d.ts +99 -0
- package/dist/cli/simulation.js +490 -0
- package/dist/cli/simulation.js.map +1 -0
- package/dist/cli/swaig-test.d.ts +12 -25
- package/dist/cli/swaig-test.js +935 -367
- package/dist/cli/swaig-test.js.map +1 -1
- package/dist/cli/tsdocs/agentsNote.d.ts +30 -0
- package/dist/cli/tsdocs/agentsNote.js +92 -0
- package/dist/cli/tsdocs/agentsNote.js.map +1 -0
- package/dist/cli/tsdocs/api-index.json +1 -0
- package/dist/cli/tsdocs/api.d.ts +91 -0
- package/dist/cli/tsdocs/api.js +372 -0
- package/dist/cli/tsdocs/api.js.map +1 -0
- package/dist/cli/tsdocs/apiTypes.d.ts +64 -0
- package/dist/cli/tsdocs/apiTypes.js +7 -0
- package/dist/cli/tsdocs/apiTypes.js.map +1 -0
- package/dist/cli/tsdocs/bin.d.ts +6 -0
- package/dist/cli/tsdocs/bin.js +23 -0
- package/dist/cli/tsdocs/bin.js.map +1 -0
- package/dist/cli/tsdocs/files.d.ts +108 -0
- package/dist/cli/tsdocs/files.js +287 -0
- package/dist/cli/tsdocs/files.js.map +1 -0
- package/dist/cli/tsdocs/index.d.ts +28 -0
- package/dist/cli/tsdocs/index.js +307 -0
- package/dist/cli/tsdocs/index.js.map +1 -0
- package/dist/cli/tsdocs/live.d.ts +41 -0
- package/dist/cli/tsdocs/live.js +202 -0
- package/dist/cli/tsdocs/live.js.map +1 -0
- package/dist/cli/tsdocs/locate.d.ts +51 -0
- package/dist/cli/tsdocs/locate.js +75 -0
- package/dist/cli/tsdocs/locate.js.map +1 -0
- package/dist/cli/tsdocs/render.d.ts +75 -0
- package/dist/cli/tsdocs/render.js +323 -0
- package/dist/cli/tsdocs/render.js.map +1 -0
- package/dist/cli/tsdocs/topics.d.ts +43 -0
- package/dist/cli/tsdocs/topics.js +916 -0
- package/dist/cli/tsdocs/topics.js.map +1 -0
- package/dist/index.d.ts +102 -39
- package/dist/index.js +107 -30
- package/dist/index.js.map +1 -1
- package/dist/livewire/index.d.ts +229 -155
- package/dist/livewire/index.js +298 -195
- package/dist/livewire/index.js.map +1 -1
- package/dist/llms.txt +65 -0
- package/dist/prefabs/CallSessionStore.d.ts +52 -0
- package/dist/prefabs/CallSessionStore.js +72 -0
- package/dist/prefabs/CallSessionStore.js.map +1 -0
- package/dist/prefabs/ConciergeAgent.d.ts +13 -1
- package/dist/prefabs/ConciergeAgent.js +36 -31
- package/dist/prefabs/ConciergeAgent.js.map +1 -1
- package/dist/prefabs/FAQBotAgent.d.ts +9 -1
- package/dist/prefabs/FAQBotAgent.js +113 -47
- package/dist/prefabs/FAQBotAgent.js.map +1 -1
- package/dist/prefabs/InfoGathererAgent.d.ts +22 -3
- package/dist/prefabs/InfoGathererAgent.js +67 -58
- package/dist/prefabs/InfoGathererAgent.js.map +1 -1
- package/dist/prefabs/ReceptionistAgent.d.ts +16 -5
- package/dist/prefabs/ReceptionistAgent.js +39 -31
- package/dist/prefabs/ReceptionistAgent.js.map +1 -1
- package/dist/prefabs/SurveyAgent.d.ts +22 -4
- package/dist/prefabs/SurveyAgent.js +84 -68
- package/dist/prefabs/SurveyAgent.js.map +1 -1
- package/dist/relay/Action.d.ts +44 -21
- package/dist/relay/Action.js +75 -17
- package/dist/relay/Action.js.map +1 -1
- package/dist/relay/Call.d.ts +312 -47
- package/dist/relay/Call.js +369 -18
- package/dist/relay/Call.js.map +1 -1
- package/dist/relay/Deferred.js.map +1 -1
- package/dist/relay/Message.d.ts +26 -5
- package/dist/relay/Message.js +36 -6
- package/dist/relay/Message.js.map +1 -1
- package/dist/relay/RelayClient.d.ts +79 -14
- package/dist/relay/RelayClient.js +268 -61
- package/dist/relay/RelayClient.js.map +1 -1
- package/dist/relay/RelayError.d.ts +14 -0
- package/dist/relay/RelayError.js +15 -0
- package/dist/relay/RelayError.js.map +1 -1
- package/dist/relay/RelayEvent.d.ts +96 -65
- package/dist/relay/RelayEvent.js +85 -56
- package/dist/relay/RelayEvent.js.map +1 -1
- package/dist/relay/closedSets.d.ts +111 -0
- package/dist/relay/closedSets.js +83 -0
- package/dist/relay/closedSets.js.map +1 -0
- package/dist/relay/index.d.ts +3 -1
- package/dist/relay/index.js +1 -0
- package/dist/relay/index.js.map +1 -1
- package/dist/relay/normalize.js.map +1 -1
- package/dist/relay/protocol.types.generated.d.ts +1195 -0
- package/dist/relay/protocol.types.generated.js +8 -0
- package/dist/relay/protocol.types.generated.js.map +1 -0
- package/dist/relay/types.d.ts +81 -39
- package/dist/rest/HttpClient.d.ts +36 -8
- package/dist/rest/HttpClient.js +233 -40
- package/dist/rest/HttpClient.js.map +1 -1
- package/dist/rest/RequestOptions.d.ts +110 -0
- package/dist/rest/RequestOptions.js +113 -0
- package/dist/rest/RequestOptions.js.map +1 -0
- package/dist/rest/RestError.d.ts +52 -6
- package/dist/rest/RestError.js +89 -5
- package/dist/rest/RestError.js.map +1 -1
- package/dist/rest/base/CrudResource.d.ts +16 -26
- package/dist/rest/base/CrudResource.js +19 -33
- package/dist/rest/base/CrudResource.js.map +1 -1
- package/dist/rest/base/CrudWithAddresses.d.ts +3 -2
- package/dist/rest/base/CrudWithAddresses.js +2 -2
- package/dist/rest/base/CrudWithAddresses.js.map +1 -1
- package/dist/rest/base/FabricResource.d.ts +15 -0
- package/dist/rest/base/FabricResource.js +16 -0
- package/dist/rest/base/FabricResource.js.map +1 -0
- package/dist/rest/base/ReadResource.d.ts +62 -0
- package/dist/rest/base/ReadResource.js +69 -0
- package/dist/rest/base/ReadResource.js.map +1 -0
- package/dist/rest/callHandler.d.ts +63 -0
- package/dist/rest/callHandler.js +62 -0
- package/dist/rest/callHandler.js.map +1 -0
- package/dist/rest/index.d.ts +19 -76
- package/dist/rest/index.js +49 -120
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/namespaces/_client_tree_generated.d.ts +103 -0
- package/dist/rest/namespaces/_client_tree_generated.js +171 -0
- package/dist/rest/namespaces/_client_tree_generated.js.map +1 -0
- package/dist/rest/namespaces/addresses.d.ts +3 -42
- package/dist/rest/namespaces/addresses.js +3 -50
- package/dist/rest/namespaces/addresses.js.map +1 -1
- package/dist/rest/namespaces/calling.d.ts +6 -378
- package/dist/rest/namespaces/calling.js +6 -473
- package/dist/rest/namespaces/calling.js.map +1 -1
- package/dist/rest/namespaces/calling.resources.generated.d.ts +165 -0
- package/dist/rest/namespaces/calling.resources.generated.js +477 -0
- package/dist/rest/namespaces/calling.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/calling.types.generated.d.ts +2917 -0
- package/dist/rest/namespaces/calling.types.generated.js +8 -0
- package/dist/rest/namespaces/calling.types.generated.js.map +1 -0
- package/dist/rest/namespaces/chat.d.ts +4 -18
- package/dist/rest/namespaces/chat.js +4 -21
- package/dist/rest/namespaces/chat.js.map +1 -1
- package/dist/rest/namespaces/chat.resources.generated.d.ts +12 -0
- package/dist/rest/namespaces/chat.resources.generated.js +29 -0
- package/dist/rest/namespaces/chat.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/chat.types.generated.d.ts +56 -0
- package/dist/rest/namespaces/chat.types.generated.js +8 -0
- package/dist/rest/namespaces/chat.types.generated.js.map +1 -0
- package/dist/rest/namespaces/datasphere.d.ts +6 -62
- package/dist/rest/namespaces/datasphere.js +6 -72
- package/dist/rest/namespaces/datasphere.js.map +1 -1
- package/dist/rest/namespaces/datasphere.resources.generated.d.ts +25 -0
- package/dist/rest/namespaces/datasphere.resources.generated.js +50 -0
- package/dist/rest/namespaces/datasphere.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/datasphere.types.generated.d.ts +180 -0
- package/dist/rest/namespaces/datasphere.types.generated.js +8 -0
- package/dist/rest/namespaces/datasphere.types.generated.js.map +1 -0
- package/dist/rest/namespaces/fabric.d.ts +11 -273
- package/dist/rest/namespaces/fabric.js +14 -363
- package/dist/rest/namespaces/fabric.js.map +1 -1
- package/dist/rest/namespaces/fabric.resources.generated.d.ts +195 -0
- package/dist/rest/namespaces/fabric.resources.generated.js +399 -0
- package/dist/rest/namespaces/fabric.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/fabric.types.generated.d.ts +4557 -0
- package/dist/rest/namespaces/fabric.types.generated.js +8 -0
- package/dist/rest/namespaces/fabric.types.generated.js.map +1 -0
- package/dist/rest/namespaces/fax.resources.generated.d.ts +6 -0
- package/dist/rest/namespaces/fax.resources.generated.js +14 -0
- package/dist/rest/namespaces/fax.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/fax.types.generated.d.ts +131 -0
- package/dist/rest/namespaces/fax.types.generated.js +8 -0
- package/dist/rest/namespaces/fax.types.generated.js.map +1 -0
- package/dist/rest/namespaces/imported-numbers.d.ts +3 -18
- package/dist/rest/namespaces/imported-numbers.js +3 -21
- package/dist/rest/namespaces/imported-numbers.js.map +1 -1
- package/dist/rest/namespaces/logs.d.ts +10 -101
- package/dist/rest/namespaces/logs.js +10 -128
- package/dist/rest/namespaces/logs.js.map +1 -1
- package/dist/rest/namespaces/logs.resources.generated.d.ts +9 -0
- package/dist/rest/namespaces/logs.resources.generated.js +17 -0
- package/dist/rest/namespaces/logs.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/logs.types.generated.d.ts +131 -0
- package/dist/rest/namespaces/logs.types.generated.js +8 -0
- package/dist/rest/namespaces/logs.types.generated.js.map +1 -0
- package/dist/rest/namespaces/lookup.d.ts +3 -25
- package/dist/rest/namespaces/lookup.js +3 -27
- package/dist/rest/namespaces/lookup.js.map +1 -1
- package/dist/rest/namespaces/message.resources.generated.d.ts +6 -0
- package/dist/rest/namespaces/message.resources.generated.js +14 -0
- package/dist/rest/namespaces/message.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/message.types.generated.d.ts +122 -0
- package/dist/rest/namespaces/message.types.generated.js +8 -0
- package/dist/rest/namespaces/message.types.generated.js.map +1 -0
- package/dist/rest/namespaces/messages.resources.generated.d.ts +18 -0
- package/dist/rest/namespaces/messages.resources.generated.js +44 -0
- package/dist/rest/namespaces/messages.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/messages.types.generated.d.ts +99 -0
- package/dist/rest/namespaces/messages.types.generated.js +8 -0
- package/dist/rest/namespaces/messages.types.generated.js.map +1 -0
- package/dist/rest/namespaces/mfa.d.ts +3 -42
- package/dist/rest/namespaces/mfa.js +3 -49
- package/dist/rest/namespaces/mfa.js.map +1 -1
- package/dist/rest/namespaces/number-groups.d.ts +3 -45
- package/dist/rest/namespaces/number-groups.js +3 -53
- package/dist/rest/namespaces/number-groups.js.map +1 -1
- package/dist/rest/namespaces/phone-numbers.d.ts +9 -57
- package/dist/rest/namespaces/phone-numbers.js +9 -63
- package/dist/rest/namespaces/phone-numbers.js.map +1 -1
- package/dist/rest/namespaces/project.d.ts +6 -42
- package/dist/rest/namespaces/project.js +6 -51
- package/dist/rest/namespaces/project.js.map +1 -1
- package/dist/rest/namespaces/project.resources.generated.d.ts +17 -0
- package/dist/rest/namespaces/project.resources.generated.js +44 -0
- package/dist/rest/namespaces/project.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/project.types.generated.d.ts +58 -0
- package/dist/rest/namespaces/project.types.generated.js +8 -0
- package/dist/rest/namespaces/project.types.generated.js.map +1 -0
- package/dist/rest/namespaces/projects.resources.generated.d.ts +12 -0
- package/dist/rest/namespaces/projects.resources.generated.js +25 -0
- package/dist/rest/namespaces/projects.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/projects.types.generated.d.ts +77 -0
- package/dist/rest/namespaces/projects.types.generated.js +8 -0
- package/dist/rest/namespaces/projects.types.generated.js.map +1 -0
- package/dist/rest/namespaces/pubsub.d.ts +4 -18
- package/dist/rest/namespaces/pubsub.js +4 -21
- package/dist/rest/namespaces/pubsub.js.map +1 -1
- package/dist/rest/namespaces/pubsub.resources.generated.d.ts +12 -0
- package/dist/rest/namespaces/pubsub.resources.generated.js +29 -0
- package/dist/rest/namespaces/pubsub.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/pubsub.types.generated.d.ts +60 -0
- package/dist/rest/namespaces/pubsub.types.generated.js +8 -0
- package/dist/rest/namespaces/pubsub.types.generated.js.map +1 -0
- package/dist/rest/namespaces/queues.d.ts +3 -38
- package/dist/rest/namespaces/queues.js +3 -44
- package/dist/rest/namespaces/queues.js.map +1 -1
- package/dist/rest/namespaces/recordings.d.ts +3 -34
- package/dist/rest/namespaces/recordings.js +3 -40
- package/dist/rest/namespaces/recordings.js.map +1 -1
- package/dist/rest/namespaces/registry.d.ts +6 -137
- package/dist/rest/namespaces/registry.js +6 -173
- package/dist/rest/namespaces/registry.js.map +1 -1
- package/dist/rest/namespaces/relay-rest.resources.generated.d.ts +168 -0
- package/dist/rest/namespaces/relay-rest.resources.generated.js +430 -0
- package/dist/rest/namespaces/relay-rest.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/relay-rest.types.generated.d.ts +1906 -0
- package/dist/rest/namespaces/relay-rest.types.generated.js +8 -0
- package/dist/rest/namespaces/relay-rest.types.generated.js.map +1 -0
- package/dist/rest/namespaces/short-codes.d.ts +3 -35
- package/dist/rest/namespaces/short-codes.js +3 -41
- package/dist/rest/namespaces/short-codes.js.map +1 -1
- package/dist/rest/namespaces/sip-profile.d.ts +3 -24
- package/dist/rest/namespaces/sip-profile.js +3 -29
- package/dist/rest/namespaces/sip-profile.js.map +1 -1
- package/dist/rest/namespaces/verified-callers.d.ts +3 -29
- package/dist/rest/namespaces/verified-callers.js +3 -34
- package/dist/rest/namespaces/verified-callers.js.map +1 -1
- package/dist/rest/namespaces/video.d.ts +10 -227
- package/dist/rest/namespaces/video.js +10 -288
- package/dist/rest/namespaces/video.js.map +1 -1
- package/dist/rest/namespaces/video.resources.generated.d.ts +81 -0
- package/dist/rest/namespaces/video.resources.generated.js +171 -0
- package/dist/rest/namespaces/video.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/video.types.generated.d.ts +771 -0
- package/dist/rest/namespaces/video.types.generated.js +8 -0
- package/dist/rest/namespaces/video.types.generated.js.map +1 -0
- package/dist/rest/namespaces/voice.resources.generated.d.ts +9 -0
- package/dist/rest/namespaces/voice.resources.generated.js +17 -0
- package/dist/rest/namespaces/voice.resources.generated.js.map +1 -0
- package/dist/rest/namespaces/voice.types.generated.d.ts +214 -0
- package/dist/rest/namespaces/voice.types.generated.js +8 -0
- package/dist/rest/namespaces/voice.types.generated.js.map +1 -0
- package/dist/rest/pagination.d.ts +5 -1
- package/dist/rest/pagination.js +40 -20
- package/dist/rest/pagination.js.map +1 -1
- package/dist/rest/types.d.ts +21 -3
- package/dist/schema.json +299 -98
- package/dist/skills/SkillBase.d.ts +97 -20
- package/dist/skills/SkillBase.js +100 -17
- package/dist/skills/SkillBase.js.map +1 -1
- package/dist/skills/SkillManager.d.ts +66 -13
- package/dist/skills/SkillManager.js +101 -20
- package/dist/skills/SkillManager.js.map +1 -1
- package/dist/skills/SkillName.d.ts +44 -0
- package/dist/skills/SkillName.js +2 -0
- package/dist/skills/SkillName.js.map +1 -0
- package/dist/skills/SkillRegistry.d.ts +47 -7
- package/dist/skills/SkillRegistry.js +85 -13
- package/dist/skills/SkillRegistry.js.map +1 -1
- package/dist/skills/builtin/api_ninjas_trivia.d.ts +3 -1
- package/dist/skills/builtin/api_ninjas_trivia.js +24 -8
- package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -1
- package/dist/skills/builtin/ask_claude.d.ts +14 -4
- package/dist/skills/builtin/ask_claude.js +36 -14
- package/dist/skills/builtin/ask_claude.js.map +1 -1
- package/dist/skills/builtin/claude_skills.d.ts +3 -1
- package/dist/skills/builtin/claude_skills.js +19 -15
- package/dist/skills/builtin/claude_skills.js.map +1 -1
- package/dist/skills/builtin/custom_skills.d.ts +10 -3
- package/dist/skills/builtin/custom_skills.js +26 -9
- package/dist/skills/builtin/custom_skills.js.map +1 -1
- package/dist/skills/builtin/datasphere.d.ts +5 -3
- package/dist/skills/builtin/datasphere.js +34 -25
- package/dist/skills/builtin/datasphere.js.map +1 -1
- package/dist/skills/builtin/datasphere_serverless.d.ts +12 -1
- package/dist/skills/builtin/datasphere_serverless.js +17 -6
- package/dist/skills/builtin/datasphere_serverless.js.map +1 -1
- package/dist/skills/builtin/datetime.d.ts +3 -1
- package/dist/skills/builtin/datetime.js +11 -7
- package/dist/skills/builtin/datetime.js.map +1 -1
- package/dist/skills/builtin/google_maps.d.ts +29 -14
- package/dist/skills/builtin/google_maps.js +89 -269
- package/dist/skills/builtin/google_maps.js.map +1 -1
- package/dist/skills/builtin/index.d.ts +8 -6
- package/dist/skills/builtin/index.js +8 -6
- package/dist/skills/builtin/index.js.map +1 -1
- package/dist/skills/builtin/info_gatherer.d.ts +4 -2
- package/dist/skills/builtin/info_gatherer.js +20 -12
- package/dist/skills/builtin/info_gatherer.js.map +1 -1
- package/dist/skills/builtin/joke.d.ts +16 -6
- package/dist/skills/builtin/joke.js +54 -37
- package/dist/skills/builtin/joke.js.map +1 -1
- package/dist/skills/builtin/math.d.ts +3 -1
- package/dist/skills/builtin/math.js +14 -9
- package/dist/skills/builtin/math.js.map +1 -1
- package/dist/skills/builtin/mcp_gateway.d.ts +34 -5
- package/dist/skills/builtin/mcp_gateway.js +77 -46
- package/dist/skills/builtin/mcp_gateway.js.map +1 -1
- package/dist/skills/builtin/native_vector_search.d.ts +19 -5
- package/dist/skills/builtin/native_vector_search.js +179 -61
- package/dist/skills/builtin/native_vector_search.js.map +1 -1
- package/dist/skills/builtin/play_background_file.d.ts +21 -15
- package/dist/skills/builtin/play_background_file.js +43 -122
- package/dist/skills/builtin/play_background_file.js.map +1 -1
- package/dist/skills/builtin/spider.d.ts +46 -1
- package/dist/skills/builtin/spider.js +317 -101
- package/dist/skills/builtin/spider.js.map +1 -1
- package/dist/skills/builtin/swml_transfer.d.ts +14 -3
- package/dist/skills/builtin/swml_transfer.js +45 -24
- package/dist/skills/builtin/swml_transfer.js.map +1 -1
- package/dist/skills/builtin/weather_api.d.ts +24 -13
- package/dist/skills/builtin/weather_api.js +57 -31
- package/dist/skills/builtin/weather_api.js.map +1 -1
- package/dist/skills/builtin/web_search.d.ts +48 -10
- package/dist/skills/builtin/web_search.js +301 -84
- package/dist/skills/builtin/web_search.js.map +1 -1
- package/dist/skills/builtin/wikipedia_search.d.ts +4 -2
- package/dist/skills/builtin/wikipedia_search.js +32 -14
- package/dist/skills/builtin/wikipedia_search.js.map +1 -1
- package/dist/skills/index.d.ts +3 -2
- package/dist/skills/index.js +1 -1
- package/dist/skills/index.js.map +1 -1
- package/dist/swml_verbs_generated.d.ts +2824 -0
- package/dist/swml_verbs_generated.js +12 -0
- package/dist/swml_verbs_generated.js.map +1 -0
- package/dist/types.d.ts +65 -6
- package/dist/web.d.ts +27 -0
- package/dist/web.js +20 -0
- package/dist/web.js.map +1 -0
- package/docs/agent-guide.md +1034 -0
- package/docs/ai_chat.md +560 -0
- package/docs/api-reference.md +3534 -0
- package/docs/architecture.md +846 -0
- package/docs/bedrock_agent.md +411 -0
- package/docs/cli-guide.md +403 -0
- package/docs/cloud_functions_guide.md +399 -0
- package/docs/configuration.md +548 -0
- package/docs/contexts-guide.md +884 -0
- package/docs/datamap-guide.md +1160 -0
- package/docs/developer_pain_points.md +548 -0
- package/docs/llm_parameters.md +298 -0
- package/docs/mcp_gateway_reference.md +354 -0
- package/docs/mcp_integration.md +162 -0
- package/docs/pgi_agent_guide.md +1820 -0
- package/docs/prefabs-guide.md +815 -0
- package/docs/programmatically_governed_inference.md +301 -0
- package/docs/sdk_features.md +501 -0
- package/docs/security.md +559 -0
- package/docs/serverless-guide.md +520 -0
- package/docs/skills-guide.md +1223 -0
- package/docs/skills-system.md +405 -0
- package/docs/skills_parameter_schema.md +417 -0
- package/docs/swaig-reference.md +1938 -0
- package/docs/swml_service_guide.md +573 -0
- package/docs/third_party_skills.md +410 -0
- package/docs/web_service.md +666 -0
- package/examples/README.md +202 -0
- package/examples/advanced-datamap.ts +108 -0
- package/examples/advanced-dynamic-config.ts +70 -0
- package/examples/auto-vivified.ts +95 -0
- package/examples/call-flow.ts +65 -0
- package/examples/comprehensive-dynamic.ts +125 -0
- package/examples/contexts-steps.ts +65 -0
- package/examples/custom-path.ts +45 -0
- package/examples/datamap-tools.ts +51 -0
- package/examples/datasphere-multi-instance.ts +66 -0
- package/examples/datasphere-serverless-env.ts +87 -0
- package/examples/datasphere-webhook-env.ts +65 -0
- package/examples/datasphere.ts +56 -0
- package/examples/declarative.ts +100 -0
- package/examples/dynamic-config.ts +54 -0
- package/examples/dynamic-info-gatherer.ts +69 -0
- package/examples/dynamic-swml-service.ts +67 -0
- package/examples/gather-info.ts +95 -0
- package/examples/gather-per-question-functions-demo.ts +139 -0
- package/examples/joke-agent.ts +34 -0
- package/examples/kubernetes-agent.ts +45 -0
- package/examples/llm-params.ts +75 -0
- package/examples/mcp-agent.ts +89 -0
- package/examples/mcp-gateway.ts +81 -0
- package/examples/multi-agent.ts +80 -0
- package/examples/multi-endpoint.ts +79 -0
- package/examples/pgi/case-domain.ts +114 -0
- package/examples/pgi/serve.ts +16 -0
- package/examples/pgi/support-agent.ts +265 -0
- package/examples/pom-prompt.ts +70 -0
- package/examples/prefab-concierge.ts +42 -0
- package/examples/prefab-faq.ts +58 -0
- package/examples/prefab-info-gatherer.ts +33 -0
- package/examples/prefab-receptionist.ts +36 -0
- package/examples/prefab-survey.ts +69 -0
- package/examples/quickstart-agent.ts +29 -0
- package/examples/quickstart-relay.ts +25 -0
- package/examples/quickstart-rest.ts +25 -0
- package/examples/record-call.ts +65 -0
- package/examples/relay-demo.ts +33 -0
- package/examples/room-and-sip.ts +93 -0
- package/examples/serverless-lambda.ts +43 -0
- package/examples/session-state.ts +83 -0
- package/examples/simple-agent.ts +36 -0
- package/examples/simple-static.ts +29 -0
- package/examples/skills-demo.ts +41 -0
- package/examples/step-function-inheritance-demo.ts +124 -0
- package/examples/swaig-features.ts +193 -0
- package/examples/swml-service-routing.ts +66 -0
- package/examples/swml-service.ts +38 -0
- package/examples/swmlservice_ai_sidecar.ts +104 -0
- package/examples/swmlservice_swaig_standalone.ts +79 -0
- package/examples/tap.ts +67 -0
- package/examples/typed-tools.ts +68 -0
- package/examples/verb-methods.ts +45 -0
- package/examples/web-search-multi-instance.ts +75 -0
- package/examples/web-search.ts +38 -0
- package/examples/wikipedia.ts +36 -0
- package/livewire/README.md +164 -0
- package/livewire/docs/migration-guide.md +251 -0
- package/livewire/examples/livewire-basic-agent.ts +74 -0
- package/livewire/examples/livewire-handoff.ts +196 -0
- package/livewire/examples/livewire-multi-tool.ts +121 -0
- package/package.json +88 -13
- package/relay/README.md +101 -0
- package/relay/docs/call-methods.md +622 -0
- package/relay/docs/client-reference.md +281 -0
- package/relay/docs/events.md +193 -0
- package/relay/docs/getting-started.md +221 -0
- package/relay/docs/guide.md +386 -0
- package/relay/docs/messaging.md +246 -0
- package/relay/examples/relay-inbound.ts +66 -0
- package/relay/examples/relay-messaging.ts +74 -0
- package/relay/examples/relay-outbound.ts +76 -0
- package/rest/README.md +141 -0
- package/rest/docs/calling.md +313 -0
- package/rest/docs/client-reference.md +149 -0
- package/rest/docs/fabric.md +192 -0
- package/rest/docs/getting-started.md +138 -0
- package/rest/docs/guide.md +421 -0
- package/rest/docs/namespaces.md +367 -0
- package/rest/docs/phone-binding.md +116 -0
- package/rest/examples/rest-10dlc-registration.ts +177 -0
- package/rest/examples/rest-bind-phone-to-swml-webhook.ts +66 -0
- package/rest/examples/rest-calling-ivr-and-ai.ts +136 -0
- package/rest/examples/rest-calling-play-and-record.ts +98 -0
- package/rest/examples/rest-client.ts +59 -0
- package/rest/examples/rest-datasphere-search.ts +81 -0
- package/rest/examples/rest-fabric-conferences-and-routing.ts +147 -0
- package/rest/examples/rest-fabric-subscribers-and-sip.ts +106 -0
- package/rest/examples/rest-fabric-swml-and-callflows.ts +101 -0
- package/rest/examples/rest-manage-resources.ts +64 -0
- package/rest/examples/rest-phone-number-management.ts +200 -0
- package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
- package/rest/examples/rest-video-rooms.ts +186 -0
- package/tutorial/fred/fred.ts +218 -0
- package/tutorial/fred/tutorial/01-introduction.md +141 -0
- package/tutorial/fred/tutorial/02-setup.md +304 -0
- package/tutorial/fred/tutorial/03-basic-agent.md +284 -0
- package/tutorial/fred/tutorial/04-wikipedia-skill.md +298 -0
- package/tutorial/fred/tutorial/05-custom-functions.md +347 -0
- package/tutorial/fred/tutorial/06-running-testing.md +642 -0
- package/tutorial/fred/tutorial/README.md +56 -0
- package/tutorial/fred/tutorial/appendix-complete-code.md +632 -0
- package/tutorial/fred/tutorial/appendix-docker-deployment.md +504 -0
- package/tutorial/full-guardrails-agent/handlers.ts +436 -0
- package/tutorial/full-guardrails-agent/penny.ts +305 -0
- package/tutorial/full-guardrails-agent/reservations.ts +1109 -0
- package/tutorial/full-guardrails-agent/tutorial/01-why-guardrails.md +149 -0
- package/tutorial/full-guardrails-agent/tutorial/02-design-first.md +139 -0
- package/tutorial/full-guardrails-agent/tutorial/03-rules-first.md +422 -0
- package/tutorial/full-guardrails-agent/tutorial/04-the-shell.md +238 -0
- package/tutorial/full-guardrails-agent/tutorial/05-steps-and-scoping.md +247 -0
- package/tutorial/full-guardrails-agent/tutorial/06-tools-that-decide.md +467 -0
- package/tutorial/full-guardrails-agent/tutorial/07-gather-and-projection.md +160 -0
- package/tutorial/full-guardrails-agent/tutorial/08-the-verification-gate.md +333 -0
- package/tutorial/full-guardrails-agent/tutorial/09-people-and-endings.md +313 -0
- package/tutorial/full-guardrails-agent/tutorial/10-testing-and-running.md +387 -0
- package/tutorial/full-guardrails-agent/tutorial/README.md +106 -0
- package/tutorial/full-guardrails-agent/tutorial/appendix-complete-code.md +2207 -0
- package/tutorial/full-guardrails-agent/tutorial/appendix-deployment.md +191 -0
- package/tutorial/full-guardrails-agent/tutorial/appendix-technique-map.md +117 -0
- package/tutorial/full-guardrails-agent/workflow.ts +219 -0
- package/tutorial/multi_agents/README.md +175 -0
- package/tutorial/multi_agents/advanced_agent.ts +395 -0
- package/tutorial/multi_agents/extending_agents.ts +641 -0
- package/tutorial/multi_agents/knowledge.ts +59 -0
- package/tutorial/multi_agents/lesson1_first_agent.md +368 -0
- package/tutorial/multi_agents/lesson2_knowledge_bases.md +404 -0
- package/tutorial/multi_agents/lesson3_multi_agent_systems.md +621 -0
- package/tutorial/multi_agents/lesson4_advanced_features.md +805 -0
- package/tutorial/multi_agents/lesson5_extending_agents.md +856 -0
- package/tutorial/multi_agents/pc_builder.ts +529 -0
- package/tutorial/multi_agents/sales_agent.ts +88 -0
- package/tutorial/multi_agents/sales_agent_with_search.ts +116 -0
- package/tutorial/multi_agents/sales_knowledge.md +139 -0
- package/tutorial/multi_agents/support_knowledge.md +256 -0
- package/dist/cli/mock-data.d.ts +0 -37
- package/dist/cli/mock-data.js +0 -80
- package/dist/cli/mock-data.js.map +0 -1
- package/dist/generateVerbTypes.d.ts +0 -11
- package/dist/generateVerbTypes.js +0 -265
- package/dist/generateVerbTypes.js.map +0 -1
- package/dist/rest/namespaces/compat.d.ts +0 -585
- package/dist/rest/namespaces/compat.js +0 -735
- package/dist/rest/namespaces/compat.js.map +0 -1
package/dist/AgentBase.js
CHANGED
|
@@ -4,23 +4,199 @@
|
|
|
4
4
|
* Composes PromptManager, SessionManager, SwmlBuilder, and a tool registry
|
|
5
5
|
* into a single HTTP-servable agent.
|
|
6
6
|
*/
|
|
7
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
7
8
|
import { Hono } from 'hono';
|
|
9
|
+
import { getPathNoStrict } from 'hono/utils/url';
|
|
8
10
|
import { basicAuth } from 'hono/basic-auth';
|
|
9
11
|
import { cors } from 'hono/cors';
|
|
10
|
-
import { randomBytes } from 'node:crypto';
|
|
12
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
13
|
+
import { existsSync } from 'node:fs';
|
|
11
14
|
import { PromptManager } from './PromptManager.js';
|
|
12
15
|
import { SessionManager } from './SessionManager.js';
|
|
13
16
|
import { SwmlBuilder } from './SwmlBuilder.js';
|
|
17
|
+
import { SWMLService } from './SWMLService.js';
|
|
14
18
|
import { ConfigLoader } from './ConfigLoader.js';
|
|
15
|
-
import { SwaigFunction } from './SwaigFunction.js';
|
|
19
|
+
import { SwaigFunction, normalizeParameters, } from './SwaigFunction.js';
|
|
16
20
|
import { inferSchema, createTypedHandlerWrapper } from './TypeInference.js';
|
|
17
21
|
import { FunctionResult } from './FunctionResult.js';
|
|
18
|
-
import { ContextBuilder } from './ContextBuilder.js';
|
|
19
|
-
import { getLogger, suppressAllLogs } from './Logger.js';
|
|
20
|
-
import { safeAssign, filterSensitiveHeaders, redactUrl, isValidHostname } from './SecurityUtils.js';
|
|
22
|
+
import { Context as ConversationContext, ContextBuilder, GatherInfo, GatherQuestion, Step, } from './ContextBuilder.js';
|
|
23
|
+
import { getExecutionMode, getLogger, suppressAllLogs } from './Logger.js';
|
|
24
|
+
import { safeAssign, filterSensitiveHeaders, redactUrl, isValidHostname, corsOriginsFromEnv, } from './SecurityUtils.js';
|
|
21
25
|
import { SkillManager } from './skills/SkillManager.js';
|
|
22
26
|
import { SkillRegistry } from './skills/SkillRegistry.js';
|
|
23
|
-
import { ServerlessAdapter } from './ServerlessAdapter.js';
|
|
27
|
+
import { ServerlessAdapter, } from './ServerlessAdapter.js';
|
|
28
|
+
import { webhookValidationMiddleware } from './WebhookMiddleware.js';
|
|
29
|
+
import { _CLIENT_ADDRESS_ENV_KEY, _PLATFORM_BASE_ENV_KEY } from './ServerlessAdapter.js';
|
|
30
|
+
/** A URL's query parameters as a plain object (the last value of a repeated key wins). */
|
|
31
|
+
function queryParamsOf(url) {
|
|
32
|
+
const params = {};
|
|
33
|
+
try {
|
|
34
|
+
new URL(url, 'http://localhost').searchParams.forEach((v, k) => {
|
|
35
|
+
params[k] = v;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
/* not a URL: no query params */
|
|
40
|
+
}
|
|
41
|
+
return params;
|
|
42
|
+
}
|
|
43
|
+
/** A Hono request's headers as a plain object with lower-case names. */
|
|
44
|
+
function headersOf(c) {
|
|
45
|
+
const headers = {};
|
|
46
|
+
c.req.raw.headers.forEach((v, k) => {
|
|
47
|
+
headers[k] = v;
|
|
48
|
+
});
|
|
49
|
+
return headers;
|
|
50
|
+
}
|
|
51
|
+
/** The Hono context of the served request being handled, for onSwmlRequest. */
|
|
52
|
+
const servedRequestContext = new AsyncLocalStorage();
|
|
53
|
+
/** Compare two strings in constant time, whatever their lengths. */
|
|
54
|
+
function constantTimeEqual(a, b) {
|
|
55
|
+
const digest = (v) => createHash('sha256').update(v, 'utf8').digest();
|
|
56
|
+
return timingSafeEqual(digest(a), digest(b));
|
|
57
|
+
}
|
|
58
|
+
/** SDK classes whose instances a per-request copy duplicates field by field. */
|
|
59
|
+
const CLONEABLE_CLASSES = new Set([
|
|
60
|
+
// A tool: its settings are copied, its handler (a function) is shared, so a
|
|
61
|
+
// callback that changes a tool changes it for that request only.
|
|
62
|
+
SwaigFunction,
|
|
63
|
+
ContextBuilder,
|
|
64
|
+
ConversationContext,
|
|
65
|
+
Step,
|
|
66
|
+
GatherInfo,
|
|
67
|
+
GatherQuestion,
|
|
68
|
+
]);
|
|
69
|
+
/**
|
|
70
|
+
* Deep-copy agent configuration for a per-request copy. Arrays, Maps, Sets,
|
|
71
|
+
* Dates, plain objects and the contexts classes (a ContextBuilder and its
|
|
72
|
+
* contexts, steps and gather questions) are copied. Anything else (a URL, a
|
|
73
|
+
* RegExp, a class with private fields, a function) is shared as is: it can't
|
|
74
|
+
* be rebuilt field by field, since its state lives in internal slots.
|
|
75
|
+
* `memo` maps originals to their copies, so shared references stay shared
|
|
76
|
+
* and a reference to the agent can be redirected to the copy.
|
|
77
|
+
*/
|
|
78
|
+
function deepCloneState(value, memo) {
|
|
79
|
+
if (value === null || typeof value !== 'object')
|
|
80
|
+
return value;
|
|
81
|
+
const obj = value;
|
|
82
|
+
if (memo.has(obj))
|
|
83
|
+
return memo.get(obj);
|
|
84
|
+
if (obj instanceof Date)
|
|
85
|
+
return new Date(obj.getTime());
|
|
86
|
+
if (Array.isArray(obj)) {
|
|
87
|
+
const out = [];
|
|
88
|
+
memo.set(obj, out);
|
|
89
|
+
for (const item of obj)
|
|
90
|
+
out.push(deepCloneState(item, memo));
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
if (obj instanceof Map) {
|
|
94
|
+
const out = new Map();
|
|
95
|
+
memo.set(obj, out);
|
|
96
|
+
for (const [k, v] of obj)
|
|
97
|
+
out.set(deepCloneState(k, memo), deepCloneState(v, memo));
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
if (obj instanceof Set) {
|
|
101
|
+
const out = new Set();
|
|
102
|
+
memo.set(obj, out);
|
|
103
|
+
for (const v of obj)
|
|
104
|
+
out.add(deepCloneState(v, memo));
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
const proto = Object.getPrototypeOf(obj);
|
|
108
|
+
const plain = proto === null || proto === Object.prototype;
|
|
109
|
+
if (!plain && !CLONEABLE_CLASSES.has(proto?.constructor))
|
|
110
|
+
return value;
|
|
111
|
+
const out = Object.create(proto);
|
|
112
|
+
memo.set(obj, out);
|
|
113
|
+
for (const key of Reflect.ownKeys(obj)) {
|
|
114
|
+
const desc = Object.getOwnPropertyDescriptor(obj, key);
|
|
115
|
+
if ('value' in desc)
|
|
116
|
+
desc.value = deepCloneState(desc.value, memo);
|
|
117
|
+
Object.defineProperty(out, key, desc);
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The base URL a serverless platform serves the function on, built from the
|
|
123
|
+
* platform's environment as the reference's `get_full_url` builds it, or null
|
|
124
|
+
* in server mode. `FUNCTION_URL` (Google Cloud) and `AZURE_FUNCTION_URL`,
|
|
125
|
+
* which swaig-test's platform flags set, are used when present.
|
|
126
|
+
*/
|
|
127
|
+
function serverlessBaseUrl() {
|
|
128
|
+
const env = process.env;
|
|
129
|
+
switch (getExecutionMode()) {
|
|
130
|
+
case 'cgi': {
|
|
131
|
+
const protocol = env['HTTPS'] === 'on' ? 'https' : 'http';
|
|
132
|
+
const host = env['HTTP_HOST'] || env['SERVER_NAME'] || 'localhost';
|
|
133
|
+
return `${protocol}://${host}${env['SCRIPT_NAME'] ?? ''}`.replace(/\/+$/, '');
|
|
134
|
+
}
|
|
135
|
+
case 'lambda': {
|
|
136
|
+
if (env['AWS_LAMBDA_FUNCTION_URL'])
|
|
137
|
+
return env['AWS_LAMBDA_FUNCTION_URL'].replace(/\/+$/, '');
|
|
138
|
+
const region = env['AWS_REGION'] || 'us-east-1';
|
|
139
|
+
const fn = env['AWS_LAMBDA_FUNCTION_NAME'] || 'unknown';
|
|
140
|
+
return `https://${fn}.lambda-url.${region}.on.aws`;
|
|
141
|
+
}
|
|
142
|
+
case 'google_cloud_function': {
|
|
143
|
+
if (env['FUNCTION_URL'])
|
|
144
|
+
return env['FUNCTION_URL'].replace(/\/+$/, '');
|
|
145
|
+
// K_SERVICE and GOOGLE_CLOUD_PROJECT are also set on Cloud Run and in
|
|
146
|
+
// Cloud Shell; the functions framework sets FUNCTION_TARGET.
|
|
147
|
+
if (!env['FUNCTION_TARGET'])
|
|
148
|
+
return null;
|
|
149
|
+
const project = env['GOOGLE_CLOUD_PROJECT'] || env['GCP_PROJECT'];
|
|
150
|
+
const region = env['FUNCTION_REGION'] || env['GOOGLE_CLOUD_REGION'] || 'us-central1';
|
|
151
|
+
const service = env['K_SERVICE'] || env['FUNCTION_TARGET'] || 'unknown';
|
|
152
|
+
return project
|
|
153
|
+
? `https://${region}-${project}.cloudfunctions.net/${service}`
|
|
154
|
+
: 'https://localhost:8080';
|
|
155
|
+
}
|
|
156
|
+
case 'azure_function': {
|
|
157
|
+
if (env['AZURE_FUNCTION_URL'])
|
|
158
|
+
return env['AZURE_FUNCTION_URL'].replace(/\/+$/, '');
|
|
159
|
+
const app = env['WEBSITE_SITE_NAME'] || env['AZURE_FUNCTIONS_APP_NAME'];
|
|
160
|
+
const fn = env['AZURE_FUNCTION_NAME'] || 'unknown';
|
|
161
|
+
return app
|
|
162
|
+
? `https://${app}.azurewebsites.net/api/${fn}`
|
|
163
|
+
: `https://localhost:7071/api/${fn}`;
|
|
164
|
+
}
|
|
165
|
+
default:
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** The agent's own routes in each app buildApp() makes, normalized. */
|
|
170
|
+
const AGENT_ROUTES = new WeakMap();
|
|
171
|
+
/**
|
|
172
|
+
* Whether the agent's own routes serve a request. HEAD counts as GET, and an
|
|
173
|
+
* OPTIONS preflight counts for a path the agent serves by any method.
|
|
174
|
+
*/
|
|
175
|
+
function ownsRoute(routes, method, path) {
|
|
176
|
+
const p = normalizePath(path);
|
|
177
|
+
const m = method.toUpperCase() === 'HEAD' ? 'GET' : method.toUpperCase();
|
|
178
|
+
if (m === 'OPTIONS')
|
|
179
|
+
return routes.paths.has(p);
|
|
180
|
+
return routes.byMethod.has(`${m} ${p}`) || routes.byMethod.has(`ALL ${p}`);
|
|
181
|
+
}
|
|
182
|
+
/** A path with repeated slashes collapsed and no trailing slash, as routing matches it. */
|
|
183
|
+
function normalizePath(path) {
|
|
184
|
+
return path.replace(/\/{2,}/g, '/').replace(/(.)\/$/, '$1') || '/';
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* A request path relative to where the app handling it is mounted: a
|
|
188
|
+
* middleware registered as `*` reports `routePath` `/agent/*` when its app is
|
|
189
|
+
* mounted at `/agent`, and `*` or `/*` at the root.
|
|
190
|
+
*/
|
|
191
|
+
function relativePath(path, routePath) {
|
|
192
|
+
const base = normalizePath(routePath.replace(/\/?\*$/, '') || '/');
|
|
193
|
+
const normalized = normalizePath(path);
|
|
194
|
+
if (base === '/')
|
|
195
|
+
return normalized;
|
|
196
|
+
if (normalized === base)
|
|
197
|
+
return '/';
|
|
198
|
+
return normalized.startsWith(`${base}/`) ? normalized.slice(base.length) : normalized;
|
|
199
|
+
}
|
|
24
200
|
/**
|
|
25
201
|
* Core agent class that composes an HTTP server, prompt management, session handling,
|
|
26
202
|
* SWAIG tool registry, and 5-phase SWML rendering into a single deployable unit.
|
|
@@ -82,25 +258,19 @@ import { ServerlessAdapter } from './ServerlessAdapter.js';
|
|
|
82
258
|
* @see {@link DataMap} — server-side tools without webhooks
|
|
83
259
|
* @see {@link AgentServer} — host multiple agents on one HTTP server
|
|
84
260
|
*/
|
|
85
|
-
export class AgentBase {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
/** HTTP route path this agent listens on. */
|
|
89
|
-
route;
|
|
90
|
-
/** Hostname the HTTP server binds to. */
|
|
91
|
-
host;
|
|
92
|
-
/** Port number the HTTP server listens on. */
|
|
93
|
-
port;
|
|
261
|
+
export class AgentBase extends SWMLService {
|
|
262
|
+
// name, route, host, port, swmlBuilder, _app, authCredentials, toolRegistry
|
|
263
|
+
// are inherited from SWMLService. Agent-specific state below only.
|
|
94
264
|
/** Unique identifier for this agent instance. */
|
|
95
265
|
agentId;
|
|
96
266
|
// Internal managers
|
|
97
267
|
_promptManager;
|
|
98
268
|
sessionManager;
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
//
|
|
269
|
+
// Auth — mirrors of inherited authCredentials kept for legacy callers that
|
|
270
|
+
// read basicAuthCreds directly. The Hono basicAuth middleware uses the
|
|
271
|
+
// inherited credentials (set in super()).
|
|
102
272
|
basicAuthCreds;
|
|
103
|
-
basicAuthSource = '
|
|
273
|
+
basicAuthSource = 'generated';
|
|
104
274
|
// Call settings
|
|
105
275
|
autoAnswer;
|
|
106
276
|
_recordCall;
|
|
@@ -111,6 +281,7 @@ export class AgentBase {
|
|
|
111
281
|
// AI config
|
|
112
282
|
hints = [];
|
|
113
283
|
languages = [];
|
|
284
|
+
multilingual = {};
|
|
114
285
|
pronounce = [];
|
|
115
286
|
params = {};
|
|
116
287
|
globalData = {};
|
|
@@ -124,13 +295,22 @@ export class AgentBase {
|
|
|
124
295
|
postAnswerVerbs = [];
|
|
125
296
|
postAiVerbs = [];
|
|
126
297
|
// Dynamic config
|
|
127
|
-
|
|
298
|
+
/** Per-request configuration callbacks, run in order on each request's copy. */
|
|
299
|
+
perCallConfigs = [];
|
|
300
|
+
/** Set once serve() runs an HTTP server; getFullUrl then ignores serverless environments. */
|
|
301
|
+
_serving = false;
|
|
302
|
+
/** Handlers registered with {@link onCallEnd}. */
|
|
303
|
+
callEndHandlers = [];
|
|
304
|
+
/** Apps and routers added with {@link mount}, replayed on every app build. */
|
|
305
|
+
mounts = [];
|
|
128
306
|
swaigQueryParams = {};
|
|
129
307
|
// Webhook URL overrides
|
|
130
308
|
webHookUrlOverride = null;
|
|
131
309
|
postPromptUrlOverride = null;
|
|
132
310
|
// Contexts
|
|
133
311
|
contextsBuilder = null;
|
|
312
|
+
/** Contexts given as a plain object, rendered as they are. */
|
|
313
|
+
_rawContexts = null;
|
|
134
314
|
// MCP
|
|
135
315
|
_mcpServers = [];
|
|
136
316
|
_mcpServerEnabled = false;
|
|
@@ -142,56 +322,106 @@ export class AgentBase {
|
|
|
142
322
|
// Debug
|
|
143
323
|
debugEventsEnabled = false;
|
|
144
324
|
debugEventsLevel = 1;
|
|
145
|
-
// Proxy detection
|
|
146
|
-
|
|
147
|
-
_proxyUrlBaseFromEnv = !!process.env['SWML_PROXY_URL_BASE'];
|
|
325
|
+
// Proxy detection — _proxyUrlBase and _proxyUrlBaseFromEnv inherited from
|
|
326
|
+
// SWMLService.
|
|
148
327
|
_proxyDebug = process.env['SWML_PROXY_DEBUG'] === 'true';
|
|
149
328
|
_trustProxyHeaders = process.env['SWML_TRUST_PROXY_HEADERS'] === 'true';
|
|
150
329
|
_enforceHttps = process.env['SWML_ENFORCE_HTTPS'] === 'true';
|
|
151
|
-
/** Structured logger instance for this agent
|
|
330
|
+
/** Structured logger instance for this agent. Override the inherited
|
|
331
|
+
* SWMLService logger with an AgentBase-tagged one. */
|
|
152
332
|
log = getLogger('AgentBase');
|
|
153
|
-
// Skills
|
|
154
|
-
|
|
333
|
+
// Skills. The manager takes `this` as its public back-reference (the
|
|
334
|
+
// reference's `SkillManager(agent)`); a field initializer runs after `super()`
|
|
335
|
+
// so `this` is already bound.
|
|
336
|
+
_skillManager = new SkillManager(this);
|
|
155
337
|
// New constructor params (P1 gaps)
|
|
156
338
|
_enablePostPromptOverride = false;
|
|
157
339
|
_checkForInputOverride = false;
|
|
158
340
|
_schemaValidation = true;
|
|
159
341
|
_configFile = null;
|
|
160
342
|
_schemaPath = null;
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
343
|
+
/**
|
|
344
|
+
* Resolved SignalWire Signing Key. Source of truth for the
|
|
345
|
+
* webhook-validation middleware mounted on POST /, /swaig, /post_prompt.
|
|
346
|
+
* Resolved from constructor opts, falling back to
|
|
347
|
+
* ``SIGNALWIRE_SIGNING_KEY``. When ``null``, signature validation is
|
|
348
|
+
* disabled.
|
|
349
|
+
*
|
|
350
|
+
* NEVER logged. NEVER serialized. Not included in any SWML/SWAIG render or
|
|
351
|
+
* state dump.
|
|
352
|
+
*
|
|
353
|
+
* READABLE, matching the reference's public `self.signing_key`
|
|
354
|
+
* (`core/agent_base.py:253`) and java's `getSigningKey()`. The value came FROM the
|
|
355
|
+
* caller (an explicit `signingKey` option or `SIGNALWIRE_SIGNING_KEY`), so a
|
|
356
|
+
* caller who supplied it must be able to read back which key the agent resolved —
|
|
357
|
+
* the same posture as `getBasicAuthCredentials()`, which already returns the auth
|
|
358
|
+
* secret. Withholding it hides configuration from its own owner without hiding it
|
|
359
|
+
* from anything else (the process already holds it).
|
|
360
|
+
*/
|
|
361
|
+
_signingKey = null;
|
|
362
|
+
/**
|
|
363
|
+
* The resolved SignalWire Signing Key, or `null` when signature validation is
|
|
364
|
+
* disabled — the reference's public `self.signing_key`.
|
|
365
|
+
*
|
|
366
|
+
* Read-only: the resolution order (explicit option → `SIGNALWIRE_SIGNING_KEY` →
|
|
367
|
+
* `null`) runs once at construction and the middleware is mounted against it, so a
|
|
368
|
+
* post-construction write would not take effect.
|
|
369
|
+
*/
|
|
370
|
+
get signingKey() {
|
|
371
|
+
return this._signingKey;
|
|
372
|
+
}
|
|
373
|
+
/** Whether to honor X-Forwarded-* headers when reconstructing the URL. */
|
|
374
|
+
_webhookTrustProxy = false;
|
|
375
|
+
// _routingCallbacks and _app are inherited from SWMLService.
|
|
376
|
+
// AgentBase rebuilds _app in getApp() with its own middleware stack and
|
|
377
|
+
// route handlers, overwriting the parent-init Hono instance. The flag
|
|
378
|
+
// below tracks whether AgentBase's own setup has run; the parent-init
|
|
379
|
+
// Hono is replaced on first AgentBase getApp() call.
|
|
380
|
+
_appBuiltByAgent = false;
|
|
165
381
|
/**
|
|
166
382
|
* Create a new AgentBase instance.
|
|
167
383
|
* @param opts - Agent configuration options including name, route, auth, and call settings.
|
|
168
384
|
*/
|
|
169
385
|
constructor(opts) {
|
|
170
|
-
//
|
|
386
|
+
// Resolve construction-time config (config file + opts) before super(),
|
|
387
|
+
// because TypeScript's strict superclass-call rules require all `this`-
|
|
388
|
+
// touching code to come after super(). Forward the resolved values into
|
|
389
|
+
// SWMLService via super() so name/route/host/port/auth are set on the
|
|
390
|
+
// single source of truth in the parent.
|
|
171
391
|
let serviceConfig = {};
|
|
172
392
|
if (opts.configFile) {
|
|
173
|
-
this._configFile = opts.configFile;
|
|
174
393
|
try {
|
|
175
394
|
const loader = new ConfigLoader(opts.configFile);
|
|
176
|
-
serviceConfig =
|
|
395
|
+
serviceConfig = loader.get('service') ?? {};
|
|
177
396
|
}
|
|
178
397
|
catch {
|
|
179
398
|
// Config file not found or invalid — continue with constructor args
|
|
180
399
|
}
|
|
181
400
|
}
|
|
182
|
-
//
|
|
183
|
-
//
|
|
184
|
-
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
const
|
|
188
|
-
this.host = hostArg !== '0.0.0.0' ? hostArg : (serviceConfig['host'] ?? hostArg);
|
|
401
|
+
// Constructor arguments take precedence: the config file fills in only an
|
|
402
|
+
// argument the caller left out. `name` is required, so it always wins.
|
|
403
|
+
const resolvedName = opts.name;
|
|
404
|
+
const resolvedRoute = (opts.route ?? serviceConfig['route'] ?? '/').replace(/\/+$/, '') ||
|
|
405
|
+
'/';
|
|
406
|
+
const resolvedHost = opts.host ?? serviceConfig['host'] ?? '0.0.0.0';
|
|
189
407
|
const configPort = serviceConfig['port'];
|
|
190
408
|
const parsedPort = opts.port ?? configPort ?? parseInt(process.env['PORT'] ?? '3000', 10);
|
|
191
409
|
if (isNaN(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
|
|
192
410
|
throw new Error(`Invalid port: ${opts.port ?? process.env['PORT']}. Must be between 1 and 65535.`);
|
|
193
411
|
}
|
|
194
|
-
|
|
412
|
+
super({
|
|
413
|
+
name: resolvedName,
|
|
414
|
+
route: resolvedRoute,
|
|
415
|
+
host: resolvedHost,
|
|
416
|
+
port: parsedPort,
|
|
417
|
+
...(opts.basicAuth ? { basicAuth: opts.basicAuth } : {}),
|
|
418
|
+
...(opts.configFile ? { configFile: opts.configFile } : {}),
|
|
419
|
+
...(opts.schemaPath ? { schemaPath: opts.schemaPath } : {}),
|
|
420
|
+
schemaValidation: opts.schemaValidation ?? true,
|
|
421
|
+
});
|
|
422
|
+
if (opts.configFile) {
|
|
423
|
+
this._configFile = opts.configFile;
|
|
424
|
+
}
|
|
195
425
|
this.agentId = opts.agentId ?? randomBytes(8).toString('hex');
|
|
196
426
|
this.autoAnswer = opts.autoAnswer ?? true;
|
|
197
427
|
this._recordCall = opts.recordCall ?? false;
|
|
@@ -204,47 +434,64 @@ export class AgentBase {
|
|
|
204
434
|
this._checkForInputOverride = opts.checkForInputOverride ?? false;
|
|
205
435
|
this._schemaValidation = opts.schemaValidation ?? true;
|
|
206
436
|
this._schemaPath = opts.schemaPath ?? null;
|
|
437
|
+
// Before any warning below, so suppressLogs silences the constructor too.
|
|
207
438
|
if (opts.suppressLogs) {
|
|
208
439
|
suppressAllLogs(true);
|
|
209
440
|
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
//
|
|
213
|
-
//
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
441
|
+
// Webhook signing key: explicit option > SIGNALWIRE_SIGNING_KEY env > null.
|
|
442
|
+
// Per porting-sdk/webhooks.md: when null, validation is disabled and we
|
|
443
|
+
// log a prominent one-shot warning so operators don't ship an unsigned
|
|
444
|
+
// production agent by accident.
|
|
445
|
+
const explicitKey = typeof opts.signingKey === 'string' && opts.signingKey.length > 0 ? opts.signingKey : null;
|
|
446
|
+
const envKey = process.env['SIGNALWIRE_SIGNING_KEY'];
|
|
447
|
+
this._signingKey =
|
|
448
|
+
explicitKey ?? (typeof envKey === 'string' && envKey.length > 0 ? envKey : null);
|
|
449
|
+
this._webhookTrustProxy = opts.webhookTrustProxy ?? false;
|
|
450
|
+
if (this._signingKey === null) {
|
|
451
|
+
// Exact warning text mandated by porting-sdk/webhooks.md so all ports
|
|
452
|
+
// emit the same operator-facing message.
|
|
453
|
+
this.log.warn('[signalwire] webhook signature validation is disabled — set signingKey or SIGNALWIRE_SIGNING_KEY to enable');
|
|
454
|
+
}
|
|
455
|
+
this._promptManager = new PromptManager(opts.usePom ?? true, this);
|
|
456
|
+
// A shared secret (option, then SIGNALWIRE_SWAIG_SECRET) lets tokens minted
|
|
457
|
+
// by one process validate on another replica or after a restart.
|
|
458
|
+
this.sessionManager = new SessionManager(opts.tokenExpirySecs ?? 3600, opts.swaigSecret || process.env['SIGNALWIRE_SWAIG_SECRET'] || undefined);
|
|
459
|
+
// swmlBuilder is inherited from SWMLService (initialized via super()).
|
|
460
|
+
// Setup auth — populate the legacy basicAuthCreds/basicAuthSource
|
|
461
|
+
// mirrors so AgentBase callers that read them still work.
|
|
462
|
+
// SWMLService's authCredentials (set in super()) is the source of truth
|
|
463
|
+
// for HTTP-level enforcement.
|
|
464
|
+
// Resolution order: constructor > config file > environment > generated.
|
|
465
|
+
// SecurityConfig (built by SWMLService from the config file and the
|
|
466
|
+
// environment) applies the middle two and records which supplied it.
|
|
467
|
+
const configured = opts.basicAuth ? null : this.security.getBasicAuth();
|
|
219
468
|
if (opts.basicAuth) {
|
|
220
469
|
this.basicAuthCreds = opts.basicAuth;
|
|
221
470
|
this.basicAuthSource = 'provided';
|
|
222
471
|
}
|
|
472
|
+
else if (configured) {
|
|
473
|
+
this.basicAuthCreds = configured;
|
|
474
|
+
this.basicAuthSource = this.security.basicAuthSource ?? 'environment';
|
|
475
|
+
}
|
|
223
476
|
else {
|
|
224
477
|
const envUser = process.env['SWML_BASIC_AUTH_USER'];
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
this
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
`password that exists only in this process; external callers will ` +
|
|
243
|
-
`get HTTP 401 unless they read the value from this process's env. ` +
|
|
244
|
-
`To fix, set SWML_BASIC_AUTH_USER and SWML_BASIC_AUTH_PASSWORD in ` +
|
|
245
|
-
`your .env, or pass { basicAuth: [user, pass] } to the agent ` +
|
|
246
|
-
`constructor.`);
|
|
247
|
-
}
|
|
478
|
+
// No password in the config file or SWML_BASIC_AUTH_PASSWORD, and
|
|
479
|
+
// the caller did not pass basicAuth. Fall back to a random
|
|
480
|
+
// password that exists only in this process; warn loudly so
|
|
481
|
+
// external callers (tests, RPC clients, MCP) know why they are
|
|
482
|
+
// getting HTTP 401.
|
|
483
|
+
const username = envUser || this.name;
|
|
484
|
+
this.basicAuthCreds = [username, randomBytes(16).toString('hex')];
|
|
485
|
+
this.basicAuthSource = 'generated';
|
|
486
|
+
this.log.warn(`basic_auth_password_autogenerated: username="${username}". ` +
|
|
487
|
+
`No SWML_BASIC_AUTH_PASSWORD found in environment and no basicAuth ` +
|
|
488
|
+
`passed to the agent constructor. The SDK generated a random ` +
|
|
489
|
+
`password that exists only in this process; external callers will ` +
|
|
490
|
+
`get HTTP 401 unless this process hands it to them ` +
|
|
491
|
+
`(getBasicAuthCredentials()). ` +
|
|
492
|
+
`To fix, set SWML_BASIC_AUTH_USER and SWML_BASIC_AUTH_PASSWORD in ` +
|
|
493
|
+
`your .env, or pass { basicAuth: [user, pass] } to the agent ` +
|
|
494
|
+
`constructor.`);
|
|
248
495
|
}
|
|
249
496
|
// Apply static PROMPT_SECTIONS from the class if defined
|
|
250
497
|
const ctor = this.constructor;
|
|
@@ -259,14 +506,55 @@ export class AgentBase {
|
|
|
259
506
|
* Each entry is applied via promptAddSection() in the constructor.
|
|
260
507
|
*/
|
|
261
508
|
static PROMPT_SECTIONS;
|
|
509
|
+
/** Guards {@link ensureToolsDefined} so `defineTools()` runs at most once. */
|
|
510
|
+
_toolsDefined = false;
|
|
262
511
|
/**
|
|
263
|
-
* Lifecycle
|
|
264
|
-
*
|
|
265
|
-
*
|
|
512
|
+
* Lifecycle hook for subclasses to register their SWAIG tools. Override it
|
|
513
|
+
* and call `this.defineTool(...)` inside.
|
|
514
|
+
*
|
|
515
|
+
* You do **not** need to call this yourself — the base class invokes it
|
|
516
|
+
* automatically (exactly once) the first time tools are needed: on
|
|
517
|
+
* {@link renderSwml}, {@link getTools}, {@link serve}/{@link run}, or SWAIG
|
|
518
|
+
* dispatch. It runs lazily rather than from the base constructor because in
|
|
519
|
+
* JS/TS `super()` runs *before* a subclass's field initializers, so a
|
|
520
|
+
* base-constructor call would see `undefined` fields. Deferring to first use
|
|
521
|
+
* guarantees all subclass fields are initialized.
|
|
522
|
+
*
|
|
523
|
+
* Calling `this.defineTools()` manually (the old convention) still works and
|
|
524
|
+
* is safe — the call is idempotent, so it will not double-register tools.
|
|
266
525
|
*/
|
|
267
526
|
defineTools() {
|
|
268
527
|
// Default no-op — subclasses override
|
|
269
528
|
}
|
|
529
|
+
/**
|
|
530
|
+
* Run {@link defineTools} exactly once. Idempotent: safe to call from any
|
|
531
|
+
* tool-consumption entry point and from a subclass constructor. This is how
|
|
532
|
+
* `defineTools()` gets auto-invoked without falling into the JS field-init
|
|
533
|
+
* ordering trap (see {@link defineTools}).
|
|
534
|
+
*/
|
|
535
|
+
ensureToolsDefined() {
|
|
536
|
+
if (this._toolsDefined)
|
|
537
|
+
return;
|
|
538
|
+
this._toolsDefined = true;
|
|
539
|
+
this.defineTools();
|
|
540
|
+
}
|
|
541
|
+
/** Agent-level SWAIG error hook; see {@link onError}. */
|
|
542
|
+
_onError;
|
|
543
|
+
/**
|
|
544
|
+
* Register an agent-level error hook invoked when any SWAIG tool handler
|
|
545
|
+
* throws. It runs after a tool's own `onError` (if any) and lets you report
|
|
546
|
+
* failures (Sentry/Datadog/logging) and optionally control the user-facing
|
|
547
|
+
* response — return a {@link FunctionResult} to override it, or nothing to
|
|
548
|
+
* fall back to the default message. The error is always contained, so a
|
|
549
|
+
* thrown handler never breaks the live call.
|
|
550
|
+
*
|
|
551
|
+
* @param handler - The error hook, or `undefined` to clear it.
|
|
552
|
+
* @returns `this`, for chaining.
|
|
553
|
+
*/
|
|
554
|
+
onError(handler) {
|
|
555
|
+
this._onError = handler;
|
|
556
|
+
return this;
|
|
557
|
+
}
|
|
270
558
|
/**
|
|
271
559
|
* Public access to the list of registered tools.
|
|
272
560
|
*
|
|
@@ -276,6 +564,7 @@ export class AgentBase {
|
|
|
276
564
|
* @returns Array of all registered SwaigFunction instances.
|
|
277
565
|
*/
|
|
278
566
|
getTools() {
|
|
567
|
+
this.ensureToolsDefined();
|
|
279
568
|
const tools = [];
|
|
280
569
|
for (const [, fn] of this.toolRegistry) {
|
|
281
570
|
if (fn instanceof SwaigFunction)
|
|
@@ -293,6 +582,29 @@ export class AgentBase {
|
|
|
293
582
|
get promptManager() {
|
|
294
583
|
return this._promptManager;
|
|
295
584
|
}
|
|
585
|
+
/**
|
|
586
|
+
* Public accessor for the agent's POM as a {@link PromptObjectModel} instance.
|
|
587
|
+
*
|
|
588
|
+
* Python equivalent: ``agent.pom`` instance attribute (agent_base.py line 209)
|
|
589
|
+
* is a ``signalwire.pom.pom.PromptObjectModel`` when ``use_pom=True``,
|
|
590
|
+
* or ``None`` otherwise. This getter returns the equivalent TypeScript
|
|
591
|
+
* ``PromptObjectModel`` instance — callers can use ``addSection``,
|
|
592
|
+
* ``findSection``, ``renderMarkdown``, ``renderXml``, ``toJson``, ``toYaml``
|
|
593
|
+
* exactly as in Python.
|
|
594
|
+
*
|
|
595
|
+
* The instance returned is a fresh snapshot built from the current
|
|
596
|
+
* ``PomBuilder`` state, so mutating it does not feed back into the agent's
|
|
597
|
+
* internal builder. To mutate the agent's prompt, use
|
|
598
|
+
* ``promptAddSection`` / ``promptAddToSection`` / ``promptAddSubsection``.
|
|
599
|
+
*
|
|
600
|
+
* @returns A `PromptObjectModel` populated with the agent's sections, or `null` when POM mode is off.
|
|
601
|
+
*/
|
|
602
|
+
get pom() {
|
|
603
|
+
const builder = this._promptManager.getPomBuilder();
|
|
604
|
+
if (!builder)
|
|
605
|
+
return null;
|
|
606
|
+
return builder.pom;
|
|
607
|
+
}
|
|
296
608
|
/**
|
|
297
609
|
* Public accessor for the native functions list.
|
|
298
610
|
*
|
|
@@ -408,6 +720,19 @@ export class AgentBase {
|
|
|
408
720
|
getPostPrompt() {
|
|
409
721
|
return this._promptManager.getPostPrompt();
|
|
410
722
|
}
|
|
723
|
+
/**
|
|
724
|
+
* Get the raw prompt text whatever `setPromptText` stored, or null when
|
|
725
|
+
* no raw prompt has been set.
|
|
726
|
+
*
|
|
727
|
+
* Matches Python `PromptManager.get_raw_prompt()` which returns the raw
|
|
728
|
+
* stored string or `None`. Use this instead of `getPrompt()` when you
|
|
729
|
+
* need the unrendered text rather than the POM-rendered Markdown.
|
|
730
|
+
*
|
|
731
|
+
* @returns The raw prompt string, or null if not set.
|
|
732
|
+
*/
|
|
733
|
+
getRawPrompt() {
|
|
734
|
+
return this._promptManager.getRawPrompt();
|
|
735
|
+
}
|
|
411
736
|
/**
|
|
412
737
|
* Set the prompt as a POM (Prompt Object Model) dictionary.
|
|
413
738
|
*
|
|
@@ -438,17 +763,20 @@ export class AgentBase {
|
|
|
438
763
|
}
|
|
439
764
|
return this;
|
|
440
765
|
}
|
|
441
|
-
// ── Contexts ────────────────────────────────────────────────────────
|
|
442
|
-
/**
|
|
443
|
-
* Define or replace the contexts configuration for the AI verb.
|
|
444
|
-
* @param contexts - An existing ContextBuilder instance or a plain object; a new ContextBuilder is created if omitted.
|
|
445
|
-
* @returns The active ContextBuilder for further configuration.
|
|
446
|
-
*/
|
|
447
766
|
defineContexts(contexts) {
|
|
767
|
+
if (contexts !== undefined && !(contexts instanceof ContextBuilder)) {
|
|
768
|
+
if (contexts === null || typeof contexts !== 'object' || Array.isArray(contexts)) {
|
|
769
|
+
throw new TypeError('contexts must be an object or a ContextBuilder');
|
|
770
|
+
}
|
|
771
|
+
this._rawContexts = contexts;
|
|
772
|
+
this.contextsBuilder = null;
|
|
773
|
+
return this;
|
|
774
|
+
}
|
|
775
|
+
this._rawContexts = null;
|
|
448
776
|
if (contexts instanceof ContextBuilder) {
|
|
449
777
|
this.contextsBuilder = contexts;
|
|
450
778
|
}
|
|
451
|
-
else {
|
|
779
|
+
else if (!this.contextsBuilder) {
|
|
452
780
|
this.contextsBuilder = new ContextBuilder();
|
|
453
781
|
}
|
|
454
782
|
// Attach agent reference so ContextBuilder.validate() can check
|
|
@@ -469,8 +797,23 @@ export class AgentBase {
|
|
|
469
797
|
if (this.contextsBuilder) {
|
|
470
798
|
this.contextsBuilder.reset();
|
|
471
799
|
}
|
|
800
|
+
this._rawContexts = null;
|
|
472
801
|
return this;
|
|
473
802
|
}
|
|
803
|
+
/**
|
|
804
|
+
* Get the contexts dictionary as serialised SWML, or null when no
|
|
805
|
+
* contexts have been defined yet.
|
|
806
|
+
*
|
|
807
|
+
* Matches Python `PromptManager.get_contexts()` which returns the
|
|
808
|
+
* contexts dict or `None`.
|
|
809
|
+
*
|
|
810
|
+
* @returns Contexts dict, or null when no contexts are defined.
|
|
811
|
+
*/
|
|
812
|
+
getContexts() {
|
|
813
|
+
if (!this.contextsBuilder)
|
|
814
|
+
return this._rawContexts;
|
|
815
|
+
return this.contextsBuilder.toDict();
|
|
816
|
+
}
|
|
474
817
|
// ── AI config methods ───────────────────────────────────────────────
|
|
475
818
|
/**
|
|
476
819
|
* Add a single speech-recognition hint.
|
|
@@ -510,6 +853,10 @@ export class AgentBase {
|
|
|
510
853
|
/**
|
|
511
854
|
* Add a supported language to the AI configuration.
|
|
512
855
|
* @param config - Language configuration including name, code, voice, and optional fillers.
|
|
856
|
+
* `params` may be set to attach engine-specific tuning (voice stability,
|
|
857
|
+
* similarity boost, model knobs, etc.); only emitted into SWML when
|
|
858
|
+
* non-empty so existing entries stay byte-identical when no params are
|
|
859
|
+
* passed (Python ai_config_mixin.py `add_language`).
|
|
513
860
|
* @returns This agent instance for chaining.
|
|
514
861
|
*/
|
|
515
862
|
addLanguage(config) {
|
|
@@ -521,12 +868,39 @@ export class AgentBase {
|
|
|
521
868
|
lang['voice'] = config.voice;
|
|
522
869
|
if (config.engine)
|
|
523
870
|
lang['engine'] = config.engine;
|
|
524
|
-
if (config.
|
|
525
|
-
lang['
|
|
871
|
+
if (config.model)
|
|
872
|
+
lang['model'] = config.model;
|
|
873
|
+
// Fillers as the reference emits them: speech_fillers and function_fillers
|
|
874
|
+
// when both are given, and one given alone as the older `fillers` list.
|
|
875
|
+
// The object forms this SDK once took are flattened into lists.
|
|
876
|
+
const flatten = (value) => {
|
|
877
|
+
if (Array.isArray(value))
|
|
878
|
+
return value.filter((v) => typeof v === 'string');
|
|
879
|
+
if (value && typeof value === 'object')
|
|
880
|
+
return Object.values(value).flatMap(flatten);
|
|
881
|
+
return [];
|
|
882
|
+
};
|
|
883
|
+
const legacyFillers = config.fillers && !Array.isArray(config.fillers);
|
|
884
|
+
const speech = config.speechFillers ?? (config.fillers ? flatten(config.fillers) : undefined);
|
|
885
|
+
const fn = config.functionFillers ? flatten(config.functionFillers) : undefined;
|
|
886
|
+
if (legacyFillers || (config.functionFillers && !Array.isArray(config.functionFillers))) {
|
|
887
|
+
this.log.warn('addLanguage(): fillers keyed by category, and functionFillers keyed by function, are ' +
|
|
888
|
+
'flattened into lists; pass speechFillers and functionFillers as string arrays');
|
|
889
|
+
}
|
|
890
|
+
if (speech?.length && fn?.length) {
|
|
891
|
+
lang['speech_fillers'] = speech;
|
|
892
|
+
lang['function_fillers'] = fn;
|
|
893
|
+
}
|
|
894
|
+
else if (speech?.length || fn?.length) {
|
|
895
|
+
lang['fillers'] = speech?.length ? speech : fn;
|
|
896
|
+
}
|
|
526
897
|
if (config.speechModel)
|
|
527
898
|
lang['speech_model'] = config.speechModel;
|
|
528
|
-
|
|
529
|
-
|
|
899
|
+
// Per-language params — only emit the key when non-empty (Python equivalent:
|
|
900
|
+
// `if params: language["params"] = params`).
|
|
901
|
+
if (config.params && Object.keys(config.params).length > 0) {
|
|
902
|
+
lang['params'] = config.params;
|
|
903
|
+
}
|
|
530
904
|
this.languages.push(lang);
|
|
531
905
|
return this;
|
|
532
906
|
}
|
|
@@ -541,6 +915,69 @@ export class AgentBase {
|
|
|
541
915
|
this.addLanguage(l);
|
|
542
916
|
return this;
|
|
543
917
|
}
|
|
918
|
+
/**
|
|
919
|
+
* Configure ASR-driven multilingual mode (Mode B).
|
|
920
|
+
*
|
|
921
|
+
* Emits a top-level `multilingual` object on the AI verb. The recognizer runs
|
|
922
|
+
* in code-switching mode and the agent answers in whatever language the caller
|
|
923
|
+
* actually spoke — the model does not pick the language. Mutually exclusive
|
|
924
|
+
* with {@link setLanguages}; if both are set the server uses `multilingual` and
|
|
925
|
+
* ignores `languages`.
|
|
926
|
+
*
|
|
927
|
+
* @param config - The multilingual config object (languages, allowed,
|
|
928
|
+
* start_language, min_switch_words, fillers, etc.).
|
|
929
|
+
* @returns This agent instance for chaining.
|
|
930
|
+
*/
|
|
931
|
+
setMultilingual(config) {
|
|
932
|
+
if (config && typeof config === 'object') {
|
|
933
|
+
this.multilingual = config;
|
|
934
|
+
}
|
|
935
|
+
return this;
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Set (or replace) the per-language `params` dict on an already-added
|
|
939
|
+
* language. Useful when language entries are built up via {@link addLanguage}
|
|
940
|
+
* first and engine-specific tuning is added later (e.g., from a config
|
|
941
|
+
* loader).
|
|
942
|
+
*
|
|
943
|
+
* Python equivalent: `set_language_params(code, params)`. Passing an empty
|
|
944
|
+
* object removes the `params` key entirely. Unknown codes are a no-op.
|
|
945
|
+
*
|
|
946
|
+
* @param code - Language code as previously passed to {@link addLanguage} (e.g. `"en-US"`).
|
|
947
|
+
* @param params - Engine-specific params dict to attach. Empty object removes the key.
|
|
948
|
+
* @returns This agent instance for chaining.
|
|
949
|
+
*/
|
|
950
|
+
setLanguageParams(code, params) {
|
|
951
|
+
for (const language of this.languages) {
|
|
952
|
+
if (language['code'] === code) {
|
|
953
|
+
if (params && Object.keys(params).length > 0) {
|
|
954
|
+
language['params'] = params;
|
|
955
|
+
}
|
|
956
|
+
else {
|
|
957
|
+
delete language['params'];
|
|
958
|
+
}
|
|
959
|
+
break;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
return this;
|
|
963
|
+
}
|
|
964
|
+
/**
|
|
965
|
+
* Read the per-language `params` dict for a previously-added language.
|
|
966
|
+
*
|
|
967
|
+
* Python equivalent: `get_language_params(code)`. Returns `undefined` if the
|
|
968
|
+
* code is unknown or the language has no params set — no exception path.
|
|
969
|
+
*
|
|
970
|
+
* @param code - Language code as previously passed to {@link addLanguage}.
|
|
971
|
+
* @returns The params dict if set, `undefined` otherwise (including when the code is unknown).
|
|
972
|
+
*/
|
|
973
|
+
getLanguageParams(code) {
|
|
974
|
+
for (const language of this.languages) {
|
|
975
|
+
if (language['code'] === code) {
|
|
976
|
+
return language['params'];
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
return undefined;
|
|
980
|
+
}
|
|
544
981
|
/**
|
|
545
982
|
* Add a pronunciation override rule for the TTS engine.
|
|
546
983
|
* @param rule - Pronunciation rule specifying the text to replace and its substitute.
|
|
@@ -585,31 +1022,64 @@ export class AgentBase {
|
|
|
585
1022
|
return this;
|
|
586
1023
|
}
|
|
587
1024
|
/**
|
|
588
|
-
*
|
|
1025
|
+
* **MERGES** `data` into the global_data object passed into the AI
|
|
1026
|
+
* configuration. **Despite the name, this does NOT replace** the existing
|
|
1027
|
+
* object — existing keys are preserved and incoming keys overwrite only on
|
|
1028
|
+
* collision (it calls `.update()`-style merge, matching Python
|
|
1029
|
+
* `set_global_data`). This is intentional: skills and other callers each
|
|
1030
|
+
* contribute keys via {@link updateGlobalData}, and a replacing
|
|
1031
|
+
* `setGlobalData` would silently clobber their contributions.
|
|
589
1032
|
*
|
|
590
|
-
*
|
|
591
|
-
*
|
|
592
|
-
*
|
|
593
|
-
*
|
|
594
|
-
* If you need to replace the entire object, assign a new agent instance or use
|
|
595
|
-
* `Object.assign(agent.globalData, {})` to clear first.
|
|
1033
|
+
* - To **add/override** keys while keeping the rest: this method or the
|
|
1034
|
+
* identical {@link updateGlobalData}.
|
|
1035
|
+
* - To **fully replace** global_data (clearing every prior key, including
|
|
1036
|
+
* skill-contributed ones): use {@link replaceGlobalData}.
|
|
596
1037
|
*
|
|
597
1038
|
* @param data - Key-value pairs to merge into global data.
|
|
598
1039
|
* @returns This agent instance for chaining.
|
|
1040
|
+
* @see updateGlobalData - explicit merge alias.
|
|
1041
|
+
* @see replaceGlobalData - true replace semantics.
|
|
599
1042
|
*/
|
|
600
1043
|
setGlobalData(data) {
|
|
601
1044
|
safeAssign(this.globalData, data);
|
|
602
1045
|
return this;
|
|
603
1046
|
}
|
|
604
1047
|
/**
|
|
605
|
-
* Merge additional entries into the existing global_data object.
|
|
1048
|
+
* Merge additional entries into the existing global_data object. Identical in
|
|
1049
|
+
* behavior to {@link setGlobalData} (both merge); use this name when the
|
|
1050
|
+
* intent is explicitly "add to" rather than "set". Skills register their
|
|
1051
|
+
* global data through this path.
|
|
1052
|
+
*
|
|
606
1053
|
* @param data - Key-value pairs to merge into global data.
|
|
607
1054
|
* @returns This agent instance for chaining.
|
|
1055
|
+
* @see replaceGlobalData - to clear prior keys instead of merging.
|
|
608
1056
|
*/
|
|
609
1057
|
updateGlobalData(data) {
|
|
610
1058
|
safeAssign(this.globalData, data);
|
|
611
1059
|
return this;
|
|
612
1060
|
}
|
|
1061
|
+
/**
|
|
1062
|
+
* **REPLACES** the entire global_data object: every previously-set key
|
|
1063
|
+
* (including skill-contributed keys) is cleared, and `data` becomes the new
|
|
1064
|
+
* global_data. Use this when you genuinely want a fresh object — the
|
|
1065
|
+
* unambiguous counterpart to the merging {@link setGlobalData} /
|
|
1066
|
+
* {@link updateGlobalData}.
|
|
1067
|
+
*
|
|
1068
|
+
* A shallow copy of `data` is stored, so later mutations of the caller's
|
|
1069
|
+
* object do not leak into the agent.
|
|
1070
|
+
*
|
|
1071
|
+
* TS-native addition: Python's reference SDK has no replace path (its
|
|
1072
|
+
* `set_global_data` only merges), so this has no Python counterpart — see
|
|
1073
|
+
* `PORT_ADDITIONS.md`.
|
|
1074
|
+
*
|
|
1075
|
+
* @param data - The new global_data object (replaces all prior keys).
|
|
1076
|
+
* @returns This agent instance for chaining.
|
|
1077
|
+
* @see setGlobalData - the merging counterpart (does NOT clear prior keys).
|
|
1078
|
+
*/
|
|
1079
|
+
replaceGlobalData(data) {
|
|
1080
|
+
this.globalData = { ...data };
|
|
1081
|
+
return this;
|
|
1082
|
+
}
|
|
613
1083
|
/**
|
|
614
1084
|
* Set the list of native SWAIG function names (built-in platform functions).
|
|
615
1085
|
* @param funcs - Array of native function names.
|
|
@@ -781,6 +1251,31 @@ export class AgentBase {
|
|
|
781
1251
|
enableSipRouting(autoMap = true, path = '/sip') {
|
|
782
1252
|
this._sipRoutingEnabled = true;
|
|
783
1253
|
this._sipRoute = path;
|
|
1254
|
+
// Register a routing callback at `path` that extracts the SIP username from
|
|
1255
|
+
// the request body and consults this agent's registered usernames. Mirrors
|
|
1256
|
+
// Python `enable_sip_routing` (core/agent_base.py:708-753): the callback is
|
|
1257
|
+
// what makes `_sipUsernames` CONSULTED rather than stored-but-unconsulted.
|
|
1258
|
+
//
|
|
1259
|
+
// Framework-free `(body, headers)` shape; only the body is inspected. When
|
|
1260
|
+
// the username is registered with THIS agent the callback returns null so
|
|
1261
|
+
// the agent serves its own SWML (no redirect — it already handles that
|
|
1262
|
+
// username). An unregistered username also returns null, letting an
|
|
1263
|
+
// enclosing AgentServer's server-level callback (registered at the same
|
|
1264
|
+
// path, checked first) decide the cross-agent redirect.
|
|
1265
|
+
const sipRoutingCallback = (body) => {
|
|
1266
|
+
const sipUsername = AgentBase.extractSipUsername(body);
|
|
1267
|
+
if (sipUsername) {
|
|
1268
|
+
this.log.info(`sip_username_extracted username=${sipUsername}`);
|
|
1269
|
+
if (this._sipUsernames && this._sipUsernames.has(sipUsername.toLowerCase())) {
|
|
1270
|
+
this.log.info(`sip_username_matched username=${sipUsername}`);
|
|
1271
|
+
// Handled by this agent; no redirect needed.
|
|
1272
|
+
return null;
|
|
1273
|
+
}
|
|
1274
|
+
this.log.info(`sip_username_not_matched username=${sipUsername}`);
|
|
1275
|
+
}
|
|
1276
|
+
return null;
|
|
1277
|
+
};
|
|
1278
|
+
this.registerRoutingCallback(sipRoutingCallback, path);
|
|
784
1279
|
if (autoMap) {
|
|
785
1280
|
this._sipAutoMap = true;
|
|
786
1281
|
this.autoMapSipUsernames();
|
|
@@ -837,8 +1332,8 @@ export class AgentBase {
|
|
|
837
1332
|
*
|
|
838
1333
|
* When called, the endpoint at `path` will invoke `callback` with the parsed
|
|
839
1334
|
* request body. If `callback` returns a non-empty route string the server
|
|
840
|
-
* responds with `
|
|
841
|
-
* request to the right agent. If `callback` returns `null` / `undefined` the
|
|
1335
|
+
* responds with a `307` redirect to it (`Location: <route>`), so the
|
|
1336
|
+
* request goes to the right agent. If `callback` returns `null` / `undefined` the
|
|
842
1337
|
* agent's own SWML is returned instead (normal processing).
|
|
843
1338
|
*
|
|
844
1339
|
* Mirrors Python `swml_service.register_routing_callback` /
|
|
@@ -856,8 +1351,11 @@ export class AgentBase {
|
|
|
856
1351
|
if (!normalized.startsWith('/'))
|
|
857
1352
|
normalized = `/${normalized}`;
|
|
858
1353
|
this._routingCallbacks.set(normalized, callback);
|
|
859
|
-
// Invalidate cached app so getApp() re-registers routes with the new callback
|
|
860
|
-
|
|
1354
|
+
// Invalidate cached app so getApp() re-registers routes with the new callback.
|
|
1355
|
+
// _app is non-nullable on the parent (SWMLService); rebuild fresh.
|
|
1356
|
+
this._app = new Hono();
|
|
1357
|
+
this._appBuiltByAgent = false;
|
|
1358
|
+
this._routerApp = null;
|
|
861
1359
|
return this;
|
|
862
1360
|
}
|
|
863
1361
|
/**
|
|
@@ -869,14 +1367,21 @@ export class AgentBase {
|
|
|
869
1367
|
const call = requestBody?.['call'];
|
|
870
1368
|
const callTo = call?.['to'];
|
|
871
1369
|
if (callTo) {
|
|
872
|
-
|
|
873
|
-
if (
|
|
874
|
-
uri =
|
|
1370
|
+
// SIP/SIPS URIs: strip the scheme, then the username is the part before '@'.
|
|
1371
|
+
if (callTo.startsWith('sip:') || callTo.startsWith('sips:')) {
|
|
1372
|
+
const uri = callTo.replace(/^sips?:/, '');
|
|
1373
|
+
const atIdx = uri.indexOf('@');
|
|
1374
|
+
if (atIdx > 0)
|
|
1375
|
+
return uri.substring(0, atIdx);
|
|
1376
|
+
return uri;
|
|
875
1377
|
}
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
1378
|
+
// TEL URIs ("tel:+1234567890") — strip the scheme (parity with
|
|
1379
|
+
// SWMLService.extractSipUsername / Python swml_service.extract_sip_username).
|
|
1380
|
+
if (callTo.startsWith('tel:')) {
|
|
1381
|
+
return callTo.substring(4);
|
|
1382
|
+
}
|
|
1383
|
+
// Otherwise return the whole 'to' field.
|
|
1384
|
+
return callTo;
|
|
880
1385
|
}
|
|
881
1386
|
return null;
|
|
882
1387
|
}
|
|
@@ -902,6 +1407,8 @@ export class AgentBase {
|
|
|
902
1407
|
/**
|
|
903
1408
|
* Expose this agent's tools as an MCP server endpoint at /mcp.
|
|
904
1409
|
* Adds a JSON-RPC 2.0 endpoint that MCP clients (Claude Desktop, other agents) can connect to.
|
|
1410
|
+
* The endpoint requires the agent's basic auth credentials, and lists and
|
|
1411
|
+
* calls only the tools the agent runs itself (not DataMap or external webhook tools).
|
|
905
1412
|
* @returns This agent instance for chaining
|
|
906
1413
|
*/
|
|
907
1414
|
enableMcpServer() {
|
|
@@ -916,30 +1423,24 @@ export class AgentBase {
|
|
|
916
1423
|
getMcpServers() {
|
|
917
1424
|
return [...this._mcpServers];
|
|
918
1425
|
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Whether the /mcp endpoint may list and call this tool: only tools this
|
|
1428
|
+
* agent runs itself. DataMap tools run on SignalWire and external webhook
|
|
1429
|
+
* tools run on another server, so neither has a handler here.
|
|
1430
|
+
*/
|
|
1431
|
+
isMcpCallable(fn) {
|
|
1432
|
+
return fn instanceof SwaigFunction && !fn.isExternal;
|
|
1433
|
+
}
|
|
919
1434
|
/** Build MCP tool list from registered tools. */
|
|
920
1435
|
buildMcpToolList() {
|
|
921
1436
|
const tools = [];
|
|
922
1437
|
for (const [name, fn] of this.toolRegistry) {
|
|
923
|
-
if (fn
|
|
1438
|
+
if (this.isMcpCallable(fn)) {
|
|
924
1439
|
const tool = {
|
|
925
1440
|
name,
|
|
926
1441
|
description: fn.description || name,
|
|
927
1442
|
};
|
|
928
|
-
|
|
929
|
-
if ('type' in fn.parameters && 'properties' in fn.parameters) {
|
|
930
|
-
tool['inputSchema'] = fn.parameters;
|
|
931
|
-
}
|
|
932
|
-
else {
|
|
933
|
-
tool['inputSchema'] = {
|
|
934
|
-
type: 'object',
|
|
935
|
-
properties: fn.parameters,
|
|
936
|
-
...(fn.required.length ? { required: fn.required } : {}),
|
|
937
|
-
};
|
|
938
|
-
}
|
|
939
|
-
}
|
|
940
|
-
else {
|
|
941
|
-
tool['inputSchema'] = { type: 'object', properties: {} };
|
|
942
|
-
}
|
|
1443
|
+
tool['inputSchema'] = normalizeParameters(fn.parameters, fn.required);
|
|
943
1444
|
tools.push(tool);
|
|
944
1445
|
}
|
|
945
1446
|
}
|
|
@@ -952,12 +1453,17 @@ export class AgentBase {
|
|
|
952
1453
|
const reqId = body['id'] ?? null;
|
|
953
1454
|
const params = body['params'] || {};
|
|
954
1455
|
if (jsonrpc !== '2.0') {
|
|
955
|
-
return {
|
|
1456
|
+
return {
|
|
1457
|
+
jsonrpc: '2.0',
|
|
1458
|
+
id: reqId,
|
|
1459
|
+
error: { code: -32600, message: 'Invalid JSON-RPC version' },
|
|
1460
|
+
};
|
|
956
1461
|
}
|
|
957
1462
|
// Initialize handshake
|
|
958
1463
|
if (method === 'initialize') {
|
|
959
1464
|
return {
|
|
960
|
-
jsonrpc: '2.0',
|
|
1465
|
+
jsonrpc: '2.0',
|
|
1466
|
+
id: reqId,
|
|
961
1467
|
result: {
|
|
962
1468
|
protocolVersion: '2025-06-18',
|
|
963
1469
|
capabilities: { tools: {} },
|
|
@@ -978,22 +1484,36 @@ export class AgentBase {
|
|
|
978
1484
|
const toolName = params['name'] || '';
|
|
979
1485
|
const args = params['arguments'] || {};
|
|
980
1486
|
const fn = this.toolRegistry.get(toolName);
|
|
981
|
-
if (!
|
|
982
|
-
return {
|
|
1487
|
+
if (!this.isMcpCallable(fn)) {
|
|
1488
|
+
return {
|
|
1489
|
+
jsonrpc: '2.0',
|
|
1490
|
+
id: reqId,
|
|
1491
|
+
error: { code: -32602, message: `Unknown tool: ${toolName}` },
|
|
1492
|
+
};
|
|
983
1493
|
}
|
|
984
1494
|
try {
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
const
|
|
1495
|
+
// MCP bridge synthesizes a minimal SWAIG payload — only the fields the
|
|
1496
|
+
// handler path needs. Runtime shape unchanged; cast is compile-time only.
|
|
1497
|
+
const rawData = {
|
|
1498
|
+
function: toolName,
|
|
1499
|
+
argument: { parsed: [args] },
|
|
1500
|
+
};
|
|
1501
|
+
const resultDict = await fn._executeAs(this, args, rawData, this._onError);
|
|
1502
|
+
// MCP content is text: a structured { tool_result, tool_prompt }
|
|
1503
|
+
// response goes as its JSON.
|
|
1504
|
+
const response = resultDict['response'] ?? '';
|
|
1505
|
+
const responseText = typeof response === 'string' ? response : JSON.stringify(response);
|
|
988
1506
|
return {
|
|
989
|
-
jsonrpc: '2.0',
|
|
1507
|
+
jsonrpc: '2.0',
|
|
1508
|
+
id: reqId,
|
|
990
1509
|
result: { content: [{ type: 'text', text: responseText }], isError: false },
|
|
991
1510
|
};
|
|
992
1511
|
}
|
|
993
1512
|
catch (e) {
|
|
994
1513
|
const msg = e instanceof Error ? e.message : String(e);
|
|
995
1514
|
return {
|
|
996
|
-
jsonrpc: '2.0',
|
|
1515
|
+
jsonrpc: '2.0',
|
|
1516
|
+
id: reqId,
|
|
997
1517
|
result: { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true },
|
|
998
1518
|
};
|
|
999
1519
|
}
|
|
@@ -1002,83 +1522,18 @@ export class AgentBase {
|
|
|
1002
1522
|
if (method === 'ping') {
|
|
1003
1523
|
return { jsonrpc: '2.0', id: reqId, result: {} };
|
|
1004
1524
|
}
|
|
1005
|
-
return {
|
|
1525
|
+
return {
|
|
1526
|
+
jsonrpc: '2.0',
|
|
1527
|
+
id: reqId,
|
|
1528
|
+
error: { code: -32601, message: `Method not found: ${method}` },
|
|
1529
|
+
};
|
|
1006
1530
|
}
|
|
1007
1531
|
// ── Tools ───────────────────────────────────────────────────────────
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
* A SWAIG function is **exactly the same concept** as a "tool" in
|
|
1014
|
-
* native OpenAI / Anthropic tool calling. On every LLM turn, the SDK
|
|
1015
|
-
* renders each registered SWAIG function into the OpenAI tool schema:
|
|
1016
|
-
*
|
|
1017
|
-
* ```json
|
|
1018
|
-
* {
|
|
1019
|
-
* "type": "function",
|
|
1020
|
-
* "function": {
|
|
1021
|
-
* "name": "your_name_here",
|
|
1022
|
-
* "description": "your description text",
|
|
1023
|
-
* "parameters": { /* your JSON schema *\/ }
|
|
1024
|
-
* }
|
|
1025
|
-
* }
|
|
1026
|
-
* ```
|
|
1027
|
-
*
|
|
1028
|
-
* That schema goes to the model in the same API call that produces
|
|
1029
|
-
* the next assistant message. The model reads:
|
|
1030
|
-
*
|
|
1031
|
-
* - the **function `description`** to decide WHEN to call this tool
|
|
1032
|
-
* - each **parameter `description`** (inside the JSON schema) to
|
|
1033
|
-
* decide HOW to fill in each argument
|
|
1034
|
-
*
|
|
1035
|
-
* This means **descriptions are prompt engineering**, not developer
|
|
1036
|
-
* comments. A vague description is the #1 cause of "the model has the
|
|
1037
|
-
* right tool but doesn't call it" failures.
|
|
1038
|
-
*
|
|
1039
|
-
* ### Bad vs good descriptions
|
|
1040
|
-
*
|
|
1041
|
-
* ```text
|
|
1042
|
-
* BAD : description: 'Lookup function'
|
|
1043
|
-
* GOOD: description: 'Look up a customer's account details by account
|
|
1044
|
-
* number. Use this BEFORE quoting any account-specific info
|
|
1045
|
-
* (balance, plan, status). Do not use for general product
|
|
1046
|
-
* questions.'
|
|
1047
|
-
*
|
|
1048
|
-
* BAD : parameters: { id: { type: 'string', description: 'the id' } }
|
|
1049
|
-
* GOOD: parameters: { account_number: { type: 'string', description:
|
|
1050
|
-
* 'The customer's 8-digit account number, no dashes or spaces.
|
|
1051
|
-
* Ask the user if they don't provide it.' } }
|
|
1052
|
-
* ```
|
|
1053
|
-
*
|
|
1054
|
-
* ### Tool count matters
|
|
1055
|
-
*
|
|
1056
|
-
* LLM tool selection accuracy degrades past ~7-8 simultaneously-active
|
|
1057
|
-
* tools per call. Use Step.setFunctions() to partition tools across
|
|
1058
|
-
* steps so only the relevant subset is active at any moment.
|
|
1059
|
-
*
|
|
1060
|
-
* @param opts - Tool definition including name, description, parameter
|
|
1061
|
-
* schema, and handler callback. `description` and per-parameter
|
|
1062
|
-
* `description` strings are LLM-facing prompt engineering.
|
|
1063
|
-
* @returns This agent instance for chaining.
|
|
1064
|
-
*/
|
|
1065
|
-
defineTool(opts) {
|
|
1066
|
-
const fn = new SwaigFunction({
|
|
1067
|
-
name: opts.name,
|
|
1068
|
-
description: opts.description,
|
|
1069
|
-
parameters: opts.parameters,
|
|
1070
|
-
handler: opts.handler,
|
|
1071
|
-
secure: opts.secure,
|
|
1072
|
-
fillers: opts.fillers,
|
|
1073
|
-
waitFile: opts.waitFile,
|
|
1074
|
-
waitFileLoops: opts.waitFileLoops,
|
|
1075
|
-
required: opts.required,
|
|
1076
|
-
webhookUrl: opts.webhookUrl,
|
|
1077
|
-
extraFields: opts.extraFields,
|
|
1078
|
-
});
|
|
1079
|
-
this.toolRegistry.set(opts.name, fn);
|
|
1080
|
-
return this;
|
|
1081
|
-
}
|
|
1532
|
+
//
|
|
1533
|
+
// `defineTool<P, R>(...)` is inherited from SWMLService — one generic
|
|
1534
|
+
// definition serves both classes. With a flat inline `parameters` map it
|
|
1535
|
+
// infers the handler's `args` precisely (args.phone: string, enum→literal
|
|
1536
|
+
// union, required vs optional); wrapped/loose schemas keep open-record args.
|
|
1082
1537
|
/**
|
|
1083
1538
|
* Register a SWAIG tool with a typed handler that receives named parameters
|
|
1084
1539
|
* instead of the standard `(args, rawData)` convention.
|
|
@@ -1126,50 +1581,9 @@ export class AgentBase {
|
|
|
1126
1581
|
this.toolRegistry.set(opts.name, fn);
|
|
1127
1582
|
return this;
|
|
1128
1583
|
}
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
*/
|
|
1133
|
-
getRegisteredTools() {
|
|
1134
|
-
const tools = [];
|
|
1135
|
-
for (const [name, fn] of this.toolRegistry) {
|
|
1136
|
-
if (fn instanceof SwaigFunction) {
|
|
1137
|
-
tools.push({ name, description: fn.description, parameters: fn.parameters });
|
|
1138
|
-
}
|
|
1139
|
-
else {
|
|
1140
|
-
tools.push({
|
|
1141
|
-
name,
|
|
1142
|
-
description: fn['purpose'] ?? '',
|
|
1143
|
-
parameters: fn['argument'] ?? {},
|
|
1144
|
-
});
|
|
1145
|
-
}
|
|
1146
|
-
}
|
|
1147
|
-
return tools;
|
|
1148
|
-
}
|
|
1149
|
-
/**
|
|
1150
|
-
* Look up a registered SwaigFunction by name.
|
|
1151
|
-
* @param name - The tool name to search for.
|
|
1152
|
-
* @returns The SwaigFunction instance, or undefined if not found or not a SwaigFunction.
|
|
1153
|
-
*/
|
|
1154
|
-
getTool(name) {
|
|
1155
|
-
const fn = this.toolRegistry.get(name);
|
|
1156
|
-
return fn instanceof SwaigFunction ? fn : undefined;
|
|
1157
|
-
}
|
|
1158
|
-
/**
|
|
1159
|
-
* Register a pre-built SwaigFunction instance or a raw function descriptor (e.g. DataMap).
|
|
1160
|
-
* @param fn - A SwaigFunction instance or a plain object with a "function" key.
|
|
1161
|
-
* @returns This agent instance for chaining.
|
|
1162
|
-
*/
|
|
1163
|
-
registerSwaigFunction(fn) {
|
|
1164
|
-
if (fn instanceof SwaigFunction) {
|
|
1165
|
-
this.toolRegistry.set(fn.name, fn);
|
|
1166
|
-
}
|
|
1167
|
-
else {
|
|
1168
|
-
const name = fn['function'];
|
|
1169
|
-
this.toolRegistry.set(name, fn);
|
|
1170
|
-
}
|
|
1171
|
-
return this;
|
|
1172
|
-
}
|
|
1584
|
+
// getRegisteredTools / getTool / registerSwaigFunction are inherited from
|
|
1585
|
+
// SWMLService (the toolRegistry was lifted there so non-AgentBase services
|
|
1586
|
+
// — sidecars, standalone SWAIG hosts — can use the same surface).
|
|
1173
1587
|
/**
|
|
1174
1588
|
* Validate a tool-call token for the given function.
|
|
1175
1589
|
*
|
|
@@ -1201,7 +1615,27 @@ export class AgentBase {
|
|
|
1201
1615
|
return true;
|
|
1202
1616
|
if (!token)
|
|
1203
1617
|
return false;
|
|
1204
|
-
|
|
1618
|
+
try {
|
|
1619
|
+
return this.sessionManager.validateToolToken(functionName, token, callId);
|
|
1620
|
+
}
|
|
1621
|
+
catch {
|
|
1622
|
+
return false;
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
/**
|
|
1626
|
+
* Mint a per-call SWAIG-function token via the agent's SessionManager.
|
|
1627
|
+
*
|
|
1628
|
+
* Mirrors Python reference `core/mixins/state_mixin.py _create_tool_token`:
|
|
1629
|
+
* delegates to `SessionManager.createToolToken` and returns an empty
|
|
1630
|
+
* string on any failure (Python catches all exceptions and returns "").
|
|
1631
|
+
*/
|
|
1632
|
+
createToolToken(toolName, callId) {
|
|
1633
|
+
try {
|
|
1634
|
+
return this.sessionManager.createToolToken(toolName, callId);
|
|
1635
|
+
}
|
|
1636
|
+
catch {
|
|
1637
|
+
return '';
|
|
1638
|
+
}
|
|
1205
1639
|
}
|
|
1206
1640
|
// ── Call flow ───────────────────────────────────────────────────────
|
|
1207
1641
|
/**
|
|
@@ -1281,18 +1715,28 @@ export class AgentBase {
|
|
|
1281
1715
|
* @returns This agent instance for chaining.
|
|
1282
1716
|
*/
|
|
1283
1717
|
async addSkill(skill) {
|
|
1718
|
+
// On a per-request copy, a skill it inherited from the agent is already
|
|
1719
|
+
// loaded, with its tools, prompts, hints and data: nothing to add.
|
|
1720
|
+
if (this._skillManager._inherits(skill))
|
|
1721
|
+
return this;
|
|
1284
1722
|
skill.setAgent(this);
|
|
1285
1723
|
await this._skillManager.addSkill(skill);
|
|
1286
|
-
// Register skill tools
|
|
1724
|
+
// Register skill tools. As in Python's SkillBase.define_tool
|
|
1725
|
+
// (skill_base.py:59-79), swaig_fields are define_tool arguments with the
|
|
1726
|
+
// tool's own fields winning: `secure` sets whether the tool needs a token,
|
|
1727
|
+
// and the other keys go into the SWAIG definition.
|
|
1728
|
+
const { secure: skillSecure, ...skillExtraFields } = skill.swaigFields;
|
|
1287
1729
|
for (const toolDef of skill.getTools()) {
|
|
1288
|
-
this.defineTool(toolDef
|
|
1730
|
+
this.defineTool(toolDef.secure === undefined && typeof skillSecure === 'boolean'
|
|
1731
|
+
? { ...toolDef, secure: skillSecure }
|
|
1732
|
+
: toolDef);
|
|
1289
1733
|
const fn = this.toolRegistry.get(toolDef.name);
|
|
1290
1734
|
if (fn instanceof SwaigFunction) {
|
|
1291
1735
|
// Apply skill-level swaigFields as the base, then let tool-level filler
|
|
1292
1736
|
// flags override — matches Python skill_base.py:70-73 (swaig_fields base,
|
|
1293
1737
|
// explicit kwargs win) and SkillBase.defineTool() ({...swaigDefaults, ...toolDef}).
|
|
1294
|
-
if (Object.keys(
|
|
1295
|
-
safeAssign(fn.extraFields,
|
|
1738
|
+
if (Object.keys(skillExtraFields).length > 0) {
|
|
1739
|
+
safeAssign(fn.extraFields, skillExtraFields);
|
|
1296
1740
|
}
|
|
1297
1741
|
if (toolDef.wait_for_fillers !== undefined) {
|
|
1298
1742
|
fn.extraFields['wait_for_fillers'] = toolDef.wait_for_fillers;
|
|
@@ -1335,6 +1779,13 @@ export class AgentBase {
|
|
|
1335
1779
|
* name via the SkillManager registry. Throws a `ValueError`-equivalent if the
|
|
1336
1780
|
* skill name is not found in the registry.
|
|
1337
1781
|
*
|
|
1782
|
+
* Accepts a typed {@link SkillNameOrString}: one of the built-in
|
|
1783
|
+
* {@link SkillName} values (autocompleted) or any other string for custom
|
|
1784
|
+
* and third-party skills. Because any string is accepted, a misspelled name
|
|
1785
|
+
* compiles, and this rejects at runtime because it isn't registered. The value is
|
|
1786
|
+
* forwarded to the registry unchanged — the typing is erased at runtime, so
|
|
1787
|
+
* this matches Python's bare-`str` `add_skill(skill_name, params)`.
|
|
1788
|
+
*
|
|
1338
1789
|
* @param skillName - The name the skill was registered under in the SkillRegistry.
|
|
1339
1790
|
* @param params - Optional configuration parameters forwarded to the skill factory.
|
|
1340
1791
|
* @returns This agent instance for chaining.
|
|
@@ -1364,6 +1815,11 @@ export class AgentBase {
|
|
|
1364
1815
|
}
|
|
1365
1816
|
/**
|
|
1366
1817
|
* Check whether a skill with the given name is registered.
|
|
1818
|
+
*
|
|
1819
|
+
* Accepts a typed {@link SkillNameOrString} so built-in names autocomplete;
|
|
1820
|
+
* any other string is accepted too (custom skills, matching Python's
|
|
1821
|
+
* bare-`str` `has_skill`), so a misspelled name compiles and returns false.
|
|
1822
|
+
*
|
|
1367
1823
|
* @param skillName - The skill name to check.
|
|
1368
1824
|
* @returns True if a skill with that name exists.
|
|
1369
1825
|
*/
|
|
@@ -1371,11 +1827,11 @@ export class AgentBase {
|
|
|
1371
1827
|
return this._skillManager.hasSkill(skillName);
|
|
1372
1828
|
}
|
|
1373
1829
|
/**
|
|
1374
|
-
* Remove a skill by its name (Python
|
|
1830
|
+
* Remove a skill by its name (matches the Python SDK).
|
|
1375
1831
|
*
|
|
1376
1832
|
* Python's `remove_skill(skill_name)` removes by skill name.
|
|
1377
1833
|
* The existing `removeSkill(instanceId)` removes by instance ID.
|
|
1378
|
-
* This method provides name-based removal
|
|
1834
|
+
* This method provides name-based removal to match the Python SDK.
|
|
1379
1835
|
*
|
|
1380
1836
|
* @param skillName - The skill name to remove.
|
|
1381
1837
|
* @returns True if a skill with that name was found and removed.
|
|
@@ -1389,13 +1845,42 @@ export class AgentBase {
|
|
|
1389
1845
|
}
|
|
1390
1846
|
return false;
|
|
1391
1847
|
}
|
|
1848
|
+
/**
|
|
1849
|
+
* A tool handler that calls `fn` with the agent running the call: with a
|
|
1850
|
+
* dynamic config callback, the request's configured copy (so the handler
|
|
1851
|
+
* sees what the callback configured), otherwise this agent. For handlers
|
|
1852
|
+
* that read the agent's own state; the SDK's prefabs register theirs this
|
|
1853
|
+
* way. A plain handler gets the same agent as its third argument.
|
|
1854
|
+
* @internal
|
|
1855
|
+
*/
|
|
1856
|
+
_onCallAgent(fn) {
|
|
1857
|
+
return (args, rawData, agent) => fn(agent ?? this, args, rawData);
|
|
1858
|
+
}
|
|
1392
1859
|
// ── Dynamic config ──────────────────────────────────────────────────
|
|
1393
1860
|
/**
|
|
1394
|
-
* Set a callback
|
|
1395
|
-
*
|
|
1396
|
-
*
|
|
1397
|
-
*
|
|
1398
|
-
*
|
|
1861
|
+
* Set a callback that configures a per-request copy of this agent.
|
|
1862
|
+
*
|
|
1863
|
+
* On each request that renders SWML, runs a SWAIG function or delivers a
|
|
1864
|
+
* summary, the SDK makes a copy of this agent, calls the callback with the
|
|
1865
|
+
* request's query parameters, body and headers (credential-bearing headers
|
|
1866
|
+
* removed) and the copy, and handles the request with the copy. Tool
|
|
1867
|
+
* handlers get the copy as their third argument, and `onSummary` runs on it.
|
|
1868
|
+
*
|
|
1869
|
+
* The copy has its own prompt, tools, skills list, hints, languages,
|
|
1870
|
+
* pronunciations, params, global data, function includes, LLM params,
|
|
1871
|
+
* fillers, call-flow verbs, SWAIG query params, native functions, MCP
|
|
1872
|
+
* servers, SIP usernames, routing callbacks and contexts, so changing any of
|
|
1873
|
+
* them with the agent's methods affects only this request. Anything else is
|
|
1874
|
+
* shared with this agent and every request in flight: a field a subclass
|
|
1875
|
+
* adds, a skill instance, or an object inside the configuration that isn't
|
|
1876
|
+
* plain data (a `URL`, a class instance). Assigning a new value to such a
|
|
1877
|
+
* field on the copy is safe; mutating a shared object in place is not.
|
|
1878
|
+
*
|
|
1879
|
+
* A handler that captured this agent (an arrow function, or a method passed
|
|
1880
|
+
* with `.bind(this)`) still sees this agent, not the copy: read per-call
|
|
1881
|
+
* configuration from the handler's third argument. A subclass's JavaScript
|
|
1882
|
+
* `#private` fields aren't on the copy, so its methods that read them
|
|
1883
|
+
* throw there; use TypeScript `private` fields.
|
|
1399
1884
|
*
|
|
1400
1885
|
* @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)` where
|
|
1401
1886
|
* `agent` is the ephemeral `AgentBase` copy to mutate. May be async.
|
|
@@ -1412,7 +1897,133 @@ export class AgentBase {
|
|
|
1412
1897
|
* ```
|
|
1413
1898
|
*/
|
|
1414
1899
|
setDynamicConfigCallback(cb) {
|
|
1415
|
-
|
|
1900
|
+
// Replaces the whole chain, including callbacks from addPerCallConfig.
|
|
1901
|
+
this.perCallConfigs = [cb];
|
|
1902
|
+
return this;
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Register a per-request configuration callback, keeping any already set.
|
|
1906
|
+
*
|
|
1907
|
+
* Same signature and contract as {@link setDynamicConfigCallback}, except
|
|
1908
|
+
* that callbacks accumulate instead of replacing each other. They run in
|
|
1909
|
+
* registration order on the same per-request copy, so a later one sees what
|
|
1910
|
+
* an earlier one configured. This is the composable form: a base class and a
|
|
1911
|
+
* subclass, or an agent and a helper, can each register what they own
|
|
1912
|
+
* without knowing about each other. `setDynamicConfigCallback` replaces
|
|
1913
|
+
* every callback registered so far.
|
|
1914
|
+
*
|
|
1915
|
+
* @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)`,
|
|
1916
|
+
* where `agent` is the per-request copy. Configure that, never the agent
|
|
1917
|
+
* itself, or the configuration leaks across callers. May be async.
|
|
1918
|
+
* @returns This agent instance for chaining.
|
|
1919
|
+
*/
|
|
1920
|
+
addPerCallConfig(cb) {
|
|
1921
|
+
// Rebind rather than push: a per-request copy shares this array.
|
|
1922
|
+
this.perCallConfigs = [...this.perCallConfigs, cb];
|
|
1923
|
+
return this;
|
|
1924
|
+
}
|
|
1925
|
+
/**
|
|
1926
|
+
* Register a handler that runs when the call ends, with the transcript.
|
|
1927
|
+
*
|
|
1928
|
+
* Handlers run in registration order with `(callLog, rawData)`: the
|
|
1929
|
+
* conversation as the platform recorded it, and the whole SWAIG request
|
|
1930
|
+
* (with `global_data` and `call_id`). This wraps the platform's reserved
|
|
1931
|
+
* `hangup_hook` function, which fires on hangup and is never offered to the
|
|
1932
|
+
* model, so it can't be called early or skipped.
|
|
1933
|
+
*
|
|
1934
|
+
* Registering a handler also turns on the `swaig_post_conversation`
|
|
1935
|
+
* parameter: without it the hook still fires, but carries no transcript,
|
|
1936
|
+
* and the handler gets an empty list with nothing to say why. If that
|
|
1937
|
+
* parameter is explicitly `false`, it's left alone and a warning is logged.
|
|
1938
|
+
*
|
|
1939
|
+
* A handler's return value is ignored (the call is over), and an exception
|
|
1940
|
+
* is logged, not raised, so a failing handler doesn't stop the others.
|
|
1941
|
+
*
|
|
1942
|
+
* @param handler - Called with `(callLog, rawData)`; may be async.
|
|
1943
|
+
* @returns The handler.
|
|
1944
|
+
*
|
|
1945
|
+
* @example
|
|
1946
|
+
* ```ts
|
|
1947
|
+
* agent.onCallEnd((callLog, rawData) => {
|
|
1948
|
+
* archive(rawData.global_data?.['conversation_id'], callLog);
|
|
1949
|
+
* });
|
|
1950
|
+
* ```
|
|
1951
|
+
*/
|
|
1952
|
+
onCallEnd(handler) {
|
|
1953
|
+
const first = this.callEndHandlers.length === 0;
|
|
1954
|
+
// Rebind rather than push: a per-request copy shares this array.
|
|
1955
|
+
this.callEndHandlers = [...this.callEndHandlers, handler];
|
|
1956
|
+
if (first)
|
|
1957
|
+
this.ensureCallEndHook();
|
|
1958
|
+
return handler;
|
|
1959
|
+
}
|
|
1960
|
+
/** Register the reserved hangup_hook tool once, and turn on its transcript. */
|
|
1961
|
+
ensureCallEndHook() {
|
|
1962
|
+
if (this.params['swaig_post_conversation'] === false) {
|
|
1963
|
+
this.log.warn('[signalwire] onCallEnd handlers are registered but swaig_post_conversation is explicitly false -- they will receive an empty call_log');
|
|
1964
|
+
}
|
|
1965
|
+
else if (!('swaig_post_conversation' in this.params)) {
|
|
1966
|
+
this.params['swaig_post_conversation'] = true;
|
|
1967
|
+
}
|
|
1968
|
+
this.defineTool({
|
|
1969
|
+
name: 'hangup_hook',
|
|
1970
|
+
description: 'Internal: fires when the call ends.',
|
|
1971
|
+
parameters: {},
|
|
1972
|
+
handler: async (_args, rawData, running) => {
|
|
1973
|
+
const raw = (rawData ?? {});
|
|
1974
|
+
// Both spellings are seen, depending on the engine; an empty log
|
|
1975
|
+
// counts as absent, so the other spelling is tried.
|
|
1976
|
+
const log = (v) => Array.isArray(v) && v.length > 0 ? v : null;
|
|
1977
|
+
const callLog = log(raw['call_log']) ?? log(raw['raw_call_log']) ?? [];
|
|
1978
|
+
// The handlers of the agent running the call: a per-call copy may
|
|
1979
|
+
// have added its own.
|
|
1980
|
+
const agent = running instanceof AgentBase ? running : this;
|
|
1981
|
+
for (const callback of agent.callEndHandlers) {
|
|
1982
|
+
// Each handler is isolated, so one failure doesn't stop the others.
|
|
1983
|
+
try {
|
|
1984
|
+
await callback(callLog, rawData);
|
|
1985
|
+
}
|
|
1986
|
+
catch (err) {
|
|
1987
|
+
this.log.error('call_end_handler_failed', {
|
|
1988
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1989
|
+
});
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
return new FunctionResult('');
|
|
1993
|
+
},
|
|
1994
|
+
});
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Mount an extra Hono app, or a fetch handler, alongside this agent's routes.
|
|
1998
|
+
*
|
|
1999
|
+
* Use this instead of adding routes to {@link getApp}'s app by hand: the
|
|
2000
|
+
* agent rebuilds its app when its routes change (a routing callback, say),
|
|
2001
|
+
* and a mount is replayed on every build. A mounted app answers its own
|
|
2002
|
+
* CORS preflights (the agent's CORS and CSRF middleware don't apply to it),
|
|
2003
|
+
* sets its own security headers, and isn't behind the agent's basic auth.
|
|
2004
|
+
* Mount before calling `serve()`.
|
|
2005
|
+
*
|
|
2006
|
+
* @param appOrRouter - A Hono app (its routes are added under `prefix`) or a
|
|
2007
|
+
* fetch handler `(request) => Response` (mounted at `prefix`, which it
|
|
2008
|
+
* doesn't see).
|
|
2009
|
+
* @param opts - `prefix`: the path to mount at, from the host root (a
|
|
2010
|
+
* trailing slash is dropped; default the root). `name`: accepted so
|
|
2011
|
+
* code written for the Python SDK works; it has no effect here.
|
|
2012
|
+
* @returns This agent instance for chaining.
|
|
2013
|
+
*
|
|
2014
|
+
* @example
|
|
2015
|
+
* ```ts
|
|
2016
|
+
* agent.mount(gateway.router(), { prefix: '/chat' });
|
|
2017
|
+
* ```
|
|
2018
|
+
*/
|
|
2019
|
+
mount(appOrRouter, opts = {}) {
|
|
2020
|
+
// opts.name is accepted but unused; the Python SDK names an ASGI mount with it.
|
|
2021
|
+
const clean = (opts.prefix ?? '').replace(/\/+$/, '');
|
|
2022
|
+
this.mounts = [...this.mounts, { app: appOrRouter, prefix: clean }];
|
|
2023
|
+
// Rebuild the apps on next use, with the mount.
|
|
2024
|
+
this._appBuiltByAgent = false;
|
|
2025
|
+
this._routerApp = null;
|
|
2026
|
+
this.log.info('agent_route_mounted', { prefix: clean || '/' });
|
|
1416
2027
|
return this;
|
|
1417
2028
|
}
|
|
1418
2029
|
/**
|
|
@@ -1484,6 +2095,7 @@ export class AgentBase {
|
|
|
1484
2095
|
const hostMatch = forwarded.match(/host=([^;,\s]+)/i);
|
|
1485
2096
|
const protoMatch = forwarded.match(/proto=([^;,\s]+)/i);
|
|
1486
2097
|
if (hostMatch && isValidHostname(hostMatch[1])) {
|
|
2098
|
+
// capture group 1 is present on any successful match
|
|
1487
2099
|
const proto = protoMatch ? protoMatch[1] : 'https';
|
|
1488
2100
|
const url = `${proto}://${hostMatch[1]}`;
|
|
1489
2101
|
if (this._proxyDebug)
|
|
@@ -1544,15 +2156,47 @@ export class AgentBase {
|
|
|
1544
2156
|
base += this.route;
|
|
1545
2157
|
return base;
|
|
1546
2158
|
}
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
2159
|
+
// Serverless: the URL the platform serves the function on, from its
|
|
2160
|
+
// environment, as the reference builds it. Not once serve() runs an HTTP
|
|
2161
|
+
// server: a server on Cloud Run also has K_SERVICE set.
|
|
2162
|
+
const platformBase = this._serving ? null : serverlessBaseUrl();
|
|
2163
|
+
if (platformBase) {
|
|
2164
|
+
let base = includeAuth ? this.insertAuth(platformBase) : platformBase;
|
|
2165
|
+
if (this.route && this.route !== '/' && !base.endsWith(this.route)) {
|
|
2166
|
+
base = `${base}/${this.route.replace(/^\/+/, '')}`;
|
|
2167
|
+
}
|
|
2168
|
+
return base;
|
|
2169
|
+
}
|
|
2170
|
+
// An agent that serves HTTPS itself (SSL configured, as serve() checks)
|
|
2171
|
+
// gives https URLs, on the SSL domain when one is set, as the reference's
|
|
2172
|
+
// _get_base_url does.
|
|
2173
|
+
const tls = this._servesTls();
|
|
2174
|
+
const protocol = this._enforceHttps || tls ? 'https' : 'http';
|
|
2175
|
+
let base;
|
|
2176
|
+
if (tls && this.domain) {
|
|
2177
|
+
base = `${protocol}://${this.domain}${this.port === 443 ? '' : `:${this.port}`}`;
|
|
2178
|
+
}
|
|
2179
|
+
else {
|
|
2180
|
+
const hostPart = this.host === '0.0.0.0' ? 'localhost' : this.host;
|
|
2181
|
+
base = `${protocol}://${hostPart}:${this.port}`;
|
|
2182
|
+
}
|
|
1550
2183
|
if (includeAuth)
|
|
1551
2184
|
base = this.insertAuth(base);
|
|
1552
2185
|
if (this.route && this.route !== '/')
|
|
1553
2186
|
base += this.route;
|
|
1554
2187
|
return base;
|
|
1555
2188
|
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Whether serve() serves HTTPS: SSL enabled with a certificate and key that
|
|
2191
|
+
* exist. getFullUrl() uses the same check, so the webhook URLs match.
|
|
2192
|
+
*/
|
|
2193
|
+
_servesTls() {
|
|
2194
|
+
return !!(this.sslEnabled &&
|
|
2195
|
+
this.sslCertPath &&
|
|
2196
|
+
this.sslKeyPath &&
|
|
2197
|
+
existsSync(this.sslCertPath) &&
|
|
2198
|
+
existsSync(this.sslKeyPath));
|
|
2199
|
+
}
|
|
1556
2200
|
insertAuth(baseUrl) {
|
|
1557
2201
|
const [user, pass] = this.basicAuthCreds;
|
|
1558
2202
|
if (!user || !pass)
|
|
@@ -1564,7 +2208,9 @@ export class AgentBase {
|
|
|
1564
2208
|
const params = { ...extraParams };
|
|
1565
2209
|
const entries = Object.entries(params).filter(([, v]) => v);
|
|
1566
2210
|
if (entries.length) {
|
|
1567
|
-
url +=
|
|
2211
|
+
url +=
|
|
2212
|
+
'?' +
|
|
2213
|
+
entries.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
|
|
1568
2214
|
}
|
|
1569
2215
|
return url;
|
|
1570
2216
|
}
|
|
@@ -1573,7 +2219,7 @@ export class AgentBase {
|
|
|
1573
2219
|
* Lifecycle hook called when a post-prompt summary is received. Override in subclasses.
|
|
1574
2220
|
*
|
|
1575
2221
|
* Invoked once at the end of a call when the AI has produced a structured summary
|
|
1576
|
-
* (configured via `setPostPrompt()`
|
|
2222
|
+
* (configured via `setPostPrompt()`). Use this hook to persist
|
|
1577
2223
|
* call data, notify other systems, or trigger follow-up workflows.
|
|
1578
2224
|
*
|
|
1579
2225
|
* @param _summary - Parsed summary object (JSON when the post-prompt requests
|
|
@@ -1581,6 +2227,12 @@ export class AgentBase {
|
|
|
1581
2227
|
* @param _rawData - Full raw post-prompt payload received from the platform,
|
|
1582
2228
|
* including call metadata, conversation history, and the summary text.
|
|
1583
2229
|
*
|
|
2230
|
+
* With a dynamic config callback set, this runs on the request's configured
|
|
2231
|
+
* copy of the agent. For a request whose `action` is `fetch_conversation`,
|
|
2232
|
+
* an override may return the conversation (for example
|
|
2233
|
+
* `{ conversation_summary: '...' }`); the post-prompt endpoint sends that
|
|
2234
|
+
* back instead of `{ success: true }`.
|
|
2235
|
+
*
|
|
1584
2236
|
* @example
|
|
1585
2237
|
* ```ts
|
|
1586
2238
|
* class MyAgent extends AgentBase {
|
|
@@ -1598,6 +2250,24 @@ export class AgentBase {
|
|
|
1598
2250
|
onSummary(_summary, _rawData) {
|
|
1599
2251
|
// Default no-op
|
|
1600
2252
|
}
|
|
2253
|
+
/**
|
|
2254
|
+
* Lifecycle hook called when SWML is requested. Default delegates to
|
|
2255
|
+
* {@link onSwmlRequest} and returns its result. Subclasses typically
|
|
2256
|
+
* override `onSwmlRequest` rather than this method.
|
|
2257
|
+
*
|
|
2258
|
+
* Matches Python `WebMixin.on_request(request_data, callback_path)`. The
|
|
2259
|
+
* cross-language API is the two-arg form; the Hono `context` argument is
|
|
2260
|
+
* a TypeScript-side extra preserved for callers that already have it but
|
|
2261
|
+
* is not part of the audited surface.
|
|
2262
|
+
*
|
|
2263
|
+
* @param requestData - The parsed request body.
|
|
2264
|
+
* @param callbackPath - Optional callback path from the request.
|
|
2265
|
+
* @returns Optionally a dict of SWML modifications, or undefined for
|
|
2266
|
+
* default rendering.
|
|
2267
|
+
*/
|
|
2268
|
+
onRequest(requestData, callbackPath) {
|
|
2269
|
+
return this.onSwmlRequest(requestData ?? {}, callbackPath ?? undefined);
|
|
2270
|
+
}
|
|
1601
2271
|
/**
|
|
1602
2272
|
* Lifecycle hook called on every SWML request before rendering. Override in subclasses.
|
|
1603
2273
|
*
|
|
@@ -1617,6 +2287,127 @@ export class AgentBase {
|
|
|
1617
2287
|
onSwmlRequest(_rawData, _callbackPath, _context) {
|
|
1618
2288
|
// Default no-op
|
|
1619
2289
|
}
|
|
2290
|
+
/**
|
|
2291
|
+
* Framework-free request-dispatch core for AgentBase.
|
|
2292
|
+
*
|
|
2293
|
+
* Overrides {@link SWMLService.handleRequest} so the primitive dispatch surface
|
|
2294
|
+
* renders SWML via AgentBase's {@link renderSwml} (mirroring the Hono root path)
|
|
2295
|
+
* instead of the base `renderDocument`. Performs basic-auth, the routing-callback
|
|
2296
|
+
* check `(body, headers)`, and `onSwmlRequest` modification over plain
|
|
2297
|
+
* primitives, returning a `[status, headers, bodyString]` triple with the
|
|
2298
|
+
* 401-auth and 307-redirect behavior preserved. Mirrors Python's
|
|
2299
|
+
* `AgentBase.handle_request(method, url, headers, body)`.
|
|
2300
|
+
*
|
|
2301
|
+
* @param method HTTP method, e.g. `"GET"` or `"POST"`.
|
|
2302
|
+
* @param url The full request URL.
|
|
2303
|
+
* @param headers Request headers as a plain dict.
|
|
2304
|
+
* @param body The already-parsed JSON body for POST requests, or `undefined`.
|
|
2305
|
+
* @returns A `[statusCode, responseHeaders, bodyString]` triple.
|
|
2306
|
+
*/
|
|
2307
|
+
async handleRequest(method, url, headers, body) {
|
|
2308
|
+
// The Hono context of a served request (see serveViaHandleRequest), which
|
|
2309
|
+
// onSwmlRequest receives as its third argument; undefined on the
|
|
2310
|
+
// primitive path.
|
|
2311
|
+
const context = servedRequestContext.getStore();
|
|
2312
|
+
const parsedBody = body ?? {};
|
|
2313
|
+
const callbackPath = this._callbackPathForUrl(url);
|
|
2314
|
+
// Auth. A served request (context set) has passed the route's basic-auth
|
|
2315
|
+
// middleware already, which every route that serves through here has, so
|
|
2316
|
+
// validateBasicAuth() isn't run twice; a direct call is checked here.
|
|
2317
|
+
if (!context && !(await this.checkAgentBasicAuth(headers))) {
|
|
2318
|
+
return [401, { 'WWW-Authenticate': 'Basic' }, JSON.stringify({ error: 'Unauthorized' })];
|
|
2319
|
+
}
|
|
2320
|
+
// call_id: from the body for POST, from the `call_id` query parameter for
|
|
2321
|
+
// GET. The GET form is how a caller outside SignalWire fetches the SWML (and
|
|
2322
|
+
// so the per-function `__token`s) for a known call.
|
|
2323
|
+
let callId;
|
|
2324
|
+
if (method === 'GET') {
|
|
2325
|
+
try {
|
|
2326
|
+
callId = new URL(url, 'http://localhost').searchParams.get('call_id') ?? undefined;
|
|
2327
|
+
}
|
|
2328
|
+
catch {
|
|
2329
|
+
callId = undefined;
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
if (method === 'POST' && Object.keys(parsedBody).length > 0) {
|
|
2333
|
+
callId = parsedBody['call_id'] ?? undefined;
|
|
2334
|
+
if (!callId && parsedBody['call'] && typeof parsedBody['call'] === 'object') {
|
|
2335
|
+
callId = parsedBody['call']['call_id'];
|
|
2336
|
+
}
|
|
2337
|
+
// Routing callback: (body, headers) -> route | null.
|
|
2338
|
+
if (callbackPath && this._routingCallbacks.has(callbackPath)) {
|
|
2339
|
+
const callbackFn = this._routingCallbacks.get(callbackPath);
|
|
2340
|
+
try {
|
|
2341
|
+
const route = await callbackFn(parsedBody, headers);
|
|
2342
|
+
if (route != null) {
|
|
2343
|
+
this.log.info(`routing_request route=${route}`);
|
|
2344
|
+
return [307, { Location: route }, ''];
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
catch (err) {
|
|
2348
|
+
this.log.error(`error_in_routing_callback error=${err instanceof Error ? err.message : String(err)}`);
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
// Subclass modification hook, with the Hono context on the served path.
|
|
2353
|
+
let modifications = undefined;
|
|
2354
|
+
try {
|
|
2355
|
+
modifications = await this.onSwmlRequest(parsedBody, callbackPath ?? undefined, context);
|
|
2356
|
+
}
|
|
2357
|
+
catch (err) {
|
|
2358
|
+
this.log.error(`error_in_request_modifier error=${err instanceof Error ? err.message : String(err)}`);
|
|
2359
|
+
}
|
|
2360
|
+
// Per-request dynamic config: render from the configured copy, so the Hono
|
|
2361
|
+
// and primitive paths produce identical SWML.
|
|
2362
|
+
const agentToUse = await this.perCallAgent(queryParamsOf(url), parsedBody, headers);
|
|
2363
|
+
const swml = agentToUse.renderSwml(callId, modifications || undefined);
|
|
2364
|
+
return [200, {}, swml];
|
|
2365
|
+
}
|
|
2366
|
+
/**
|
|
2367
|
+
* The agent a request runs on: this agent, or, when a dynamic config
|
|
2368
|
+
* callback is set, a per-request copy that the callback configured from the
|
|
2369
|
+
* request's query parameters, body and headers (credential-bearing headers
|
|
2370
|
+
* removed). Rendering SWML, running a SWAIG function and delivering a
|
|
2371
|
+
* summary all use it, so a tool the callback registers or secures is the one
|
|
2372
|
+
* that runs, and is checked, when the call invokes it. Mirrors the
|
|
2373
|
+
* reference's `_per_call_agent`.
|
|
2374
|
+
*/
|
|
2375
|
+
async perCallAgent(queryParams, body, headers) {
|
|
2376
|
+
if (this.perCallConfigs.length === 0)
|
|
2377
|
+
return this;
|
|
2378
|
+
const copy = this.createEphemeralCopy();
|
|
2379
|
+
const safeHeaders = filterSensitiveHeaders(headers);
|
|
2380
|
+
try {
|
|
2381
|
+
for (const cb of this.perCallConfigs) {
|
|
2382
|
+
await cb(queryParams, body, safeHeaders, copy);
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
catch (err) {
|
|
2386
|
+
this.log.error(`dynamic_config_error error=${err instanceof Error ? err.message : String(err)}`);
|
|
2387
|
+
}
|
|
2388
|
+
return copy;
|
|
2389
|
+
}
|
|
2390
|
+
/** Validate basic-auth from a plain headers dict (the primitive analog of
|
|
2391
|
+
* the Hono `basicAuth` middleware), through {@link validateBasicAuth}. */
|
|
2392
|
+
async checkAgentBasicAuth(headers) {
|
|
2393
|
+
const [user, pass] = this.basicAuthCreds;
|
|
2394
|
+
if (!user || !pass)
|
|
2395
|
+
return true;
|
|
2396
|
+
const authHeader = headers['authorization'] ?? headers['Authorization'];
|
|
2397
|
+
if (!authHeader || !authHeader.startsWith('Basic '))
|
|
2398
|
+
return false;
|
|
2399
|
+
let decoded;
|
|
2400
|
+
try {
|
|
2401
|
+
decoded = Buffer.from(authHeader.slice(6), 'base64').toString('utf-8');
|
|
2402
|
+
}
|
|
2403
|
+
catch {
|
|
2404
|
+
return false;
|
|
2405
|
+
}
|
|
2406
|
+
const idx = decoded.indexOf(':');
|
|
2407
|
+
if (idx < 0)
|
|
2408
|
+
return false;
|
|
2409
|
+
return await this.validateBasicAuth(decoded.slice(0, idx), decoded.slice(idx + 1));
|
|
2410
|
+
}
|
|
1620
2411
|
/**
|
|
1621
2412
|
* Lifecycle hook called when a debug event webhook is received. Override in subclasses.
|
|
1622
2413
|
* @param _event - The debug event payload.
|
|
@@ -1625,13 +2416,20 @@ export class AgentBase {
|
|
|
1625
2416
|
// Default no-op
|
|
1626
2417
|
}
|
|
1627
2418
|
/**
|
|
1628
|
-
*
|
|
1629
|
-
*
|
|
1630
|
-
*
|
|
2419
|
+
* Check a request's basic-auth credentials. Every route that requires
|
|
2420
|
+
* basic auth calls it. The default compares them with the agent's
|
|
2421
|
+
* credentials in constant time; override it to check credentials another
|
|
2422
|
+
* way, as the Python SDK's `validate_basic_auth` allows. An override
|
|
2423
|
+
* replaces the comparison, so call `super.validateBasicAuth()` to keep it.
|
|
2424
|
+
* @param username - The username from the request.
|
|
2425
|
+
* @param password - The password from the request.
|
|
1631
2426
|
* @returns True if the credentials are valid; false to reject the request.
|
|
1632
2427
|
*/
|
|
1633
|
-
validateBasicAuth(
|
|
1634
|
-
|
|
2428
|
+
validateBasicAuth(username, password) {
|
|
2429
|
+
const [user, pass] = this.basicAuthCreds;
|
|
2430
|
+
if (!user || !pass)
|
|
2431
|
+
return false;
|
|
2432
|
+
return constantTimeEqual(username, user) && constantTimeEqual(password, pass);
|
|
1635
2433
|
}
|
|
1636
2434
|
/**
|
|
1637
2435
|
* Hook called before each SWAIG function execution. Override in subclasses.
|
|
@@ -1640,7 +2438,7 @@ export class AgentBase {
|
|
|
1640
2438
|
* — it retrieves and executes the function, returning the result. In TypeScript,
|
|
1641
2439
|
* `fn.execute()` is called separately after this hook. However, if this method
|
|
1642
2440
|
* returns a non-void value, it is used as the result and the default execution
|
|
1643
|
-
* is skipped, enabling dispatch interception
|
|
2441
|
+
* is skipped, enabling dispatch interception matching the Python SDK.
|
|
1644
2442
|
*
|
|
1645
2443
|
* @param _name - Name of the function about to execute.
|
|
1646
2444
|
* @param _args - Parsed arguments for the function.
|
|
@@ -1651,6 +2449,84 @@ export class AgentBase {
|
|
|
1651
2449
|
onFunctionCall(_name, _args, _rawData) {
|
|
1652
2450
|
// Default no-op
|
|
1653
2451
|
}
|
|
2452
|
+
/**
|
|
2453
|
+
* Extract the tool-call arguments from a SWAIG request body.
|
|
2454
|
+
*
|
|
2455
|
+
* The real platform (mod_openai) POSTs a tool call with the args nested under
|
|
2456
|
+
* the platform envelope `{"argument": {"parsed": [{...args...}], "raw": "..."}}`
|
|
2457
|
+
* — NOT flat. Reading `body.argument` directly hands the handler the WHOLE
|
|
2458
|
+
* envelope (`{parsed, raw}`) instead of the args, so a real platform call
|
|
2459
|
+
* arrives with EMPTY args. This unwraps `argument.parsed[0]` first, falls back
|
|
2460
|
+
* to parsing `argument.raw` JSON, and finally accepts the flat
|
|
2461
|
+
* `{"arguments": {...}}` shape some external integrations send — matching the
|
|
2462
|
+
* Python reference (`core/swml_service.py:836-851`).
|
|
2463
|
+
*
|
|
2464
|
+
* @param body - The parsed SWAIG request body.
|
|
2465
|
+
* @param reqLog - Request-scoped logger for the raw-parse-error path.
|
|
2466
|
+
* @returns The extracted argument object (empty object when none present).
|
|
2467
|
+
*/
|
|
2468
|
+
/**
|
|
2469
|
+
* Check a SWAIG request's token before a function runs.
|
|
2470
|
+
*
|
|
2471
|
+
* A secure function runs only with a valid token minted for that function
|
|
2472
|
+
* and call. The token is in the `web_hook_url` the agent rendered, so a
|
|
2473
|
+
* request without one didn't come from that SWML: a missing token, or a
|
|
2474
|
+
* missing `call_id`, is refused like a wrong token. A non-secure function
|
|
2475
|
+
* runs without a token.
|
|
2476
|
+
*
|
|
2477
|
+
* @returns The SWAIG response to send instead of running the function, or
|
|
2478
|
+
* `null` when the function may run.
|
|
2479
|
+
*/
|
|
2480
|
+
swaigTokenRefusal(fn, token, callId, reqLog) {
|
|
2481
|
+
if (!fn.secure)
|
|
2482
|
+
return null;
|
|
2483
|
+
if (!token) {
|
|
2484
|
+
reqLog.warn('token_missing');
|
|
2485
|
+
}
|
|
2486
|
+
else if (!callId) {
|
|
2487
|
+
reqLog.warn('token_rejected_no_call_id');
|
|
2488
|
+
}
|
|
2489
|
+
else if (this.sessionManager.validateToken(callId, fn.name, token)) {
|
|
2490
|
+
reqLog.debug('token_valid');
|
|
2491
|
+
return null;
|
|
2492
|
+
}
|
|
2493
|
+
else {
|
|
2494
|
+
reqLog.warn('token_invalid');
|
|
2495
|
+
}
|
|
2496
|
+
// The reference's exact wording: the refusal is part of the SWAIG wire contract.
|
|
2497
|
+
return new FunctionResult("I'm sorry, the security token for this function is invalid or expired. I cannot execute this action.").toDict();
|
|
2498
|
+
}
|
|
2499
|
+
extractSwaigArgs(body, reqLog) {
|
|
2500
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
2501
|
+
const argument = body['argument'];
|
|
2502
|
+
if (isPlainObject(argument)) {
|
|
2503
|
+
// Platform-nested shape: argument.parsed[0] holds the real args.
|
|
2504
|
+
const parsed = argument['parsed'];
|
|
2505
|
+
if (Array.isArray(parsed) && parsed.length > 0 && isPlainObject(parsed[0])) {
|
|
2506
|
+
return parsed[0];
|
|
2507
|
+
}
|
|
2508
|
+
// Fallback: argument.raw is a JSON string of the args.
|
|
2509
|
+
const raw = argument['raw'];
|
|
2510
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
2511
|
+
try {
|
|
2512
|
+
const decoded = JSON.parse(raw);
|
|
2513
|
+
if (isPlainObject(decoded))
|
|
2514
|
+
return decoded;
|
|
2515
|
+
}
|
|
2516
|
+
catch (e) {
|
|
2517
|
+
reqLog.error('error_parsing_raw_arguments', {
|
|
2518
|
+
error: e instanceof Error ? e.message : String(e),
|
|
2519
|
+
});
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
return {};
|
|
2523
|
+
}
|
|
2524
|
+
// Flat shape used by some external integrations: {"arguments": {...}}.
|
|
2525
|
+
const flat = body['arguments'];
|
|
2526
|
+
if (isPlainObject(flat))
|
|
2527
|
+
return flat;
|
|
2528
|
+
return {};
|
|
2529
|
+
}
|
|
1654
2530
|
// ── 5-phase SWML rendering ─────────────────────────────────────────
|
|
1655
2531
|
/**
|
|
1656
2532
|
* Render the complete SWML document by assembling all 5 phases: pre-answer, answer,
|
|
@@ -1663,6 +2539,7 @@ export class AgentBase {
|
|
|
1663
2539
|
* @returns The rendered SWML document as a JSON string.
|
|
1664
2540
|
*/
|
|
1665
2541
|
renderSwml(callId, modifications) {
|
|
2542
|
+
this.ensureToolsDefined();
|
|
1666
2543
|
this.swmlBuilder.reset();
|
|
1667
2544
|
const prompt = this.getPrompt();
|
|
1668
2545
|
const postPrompt = this.getPostPrompt();
|
|
@@ -1692,11 +2569,7 @@ export class AgentBase {
|
|
|
1692
2569
|
const entry = {
|
|
1693
2570
|
function: name,
|
|
1694
2571
|
description: fn.description,
|
|
1695
|
-
parameters: fn.parameters
|
|
1696
|
-
? ('type' in fn.parameters && 'properties' in fn.parameters
|
|
1697
|
-
? fn.parameters
|
|
1698
|
-
: { type: 'object', properties: fn.parameters, ...(fn.required.length ? { required: fn.required } : {}) })
|
|
1699
|
-
: { type: 'object', properties: {} },
|
|
2572
|
+
parameters: normalizeParameters(fn.parameters, fn.required),
|
|
1700
2573
|
};
|
|
1701
2574
|
if (fn.fillers && Object.keys(fn.fillers).length)
|
|
1702
2575
|
entry['fillers'] = fn.fillers;
|
|
@@ -1748,35 +2621,45 @@ export class AgentBase {
|
|
|
1748
2621
|
this.swmlBuilder.addVerb(verb, config);
|
|
1749
2622
|
}
|
|
1750
2623
|
// ── PHASE 2: Answer verb ──
|
|
2624
|
+
// Internally-assembled trusted verb — skip the schema pass (its shape is
|
|
2625
|
+
// fixed by the builder, and revalidating it on every render would pay the
|
|
2626
|
+
// full-schema Ajv compile cost on the hot path). User-supplied verbs below
|
|
2627
|
+
// still validate.
|
|
1751
2628
|
if (this.autoAnswer) {
|
|
1752
|
-
this.swmlBuilder.addVerb('answer', this.answerConfig);
|
|
2629
|
+
this.swmlBuilder.addVerb('answer', this.answerConfig, { skipValidation: true });
|
|
1753
2630
|
}
|
|
1754
2631
|
// ── PHASE 3: Post-answer verbs ──
|
|
1755
2632
|
if (this._recordCall) {
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
stereo: this.recordStereo,
|
|
1759
|
-
});
|
|
2633
|
+
// Internally-assembled trusted verb — skip the schema pass (see PHASE 2).
|
|
2634
|
+
this.swmlBuilder.addVerb('record_call', { format: this.recordFormat, stereo: this.recordStereo }, { skipValidation: true });
|
|
1760
2635
|
}
|
|
1761
2636
|
for (const [verb, config] of this.postAnswerVerbs) {
|
|
1762
2637
|
this.swmlBuilder.addVerb(verb, config);
|
|
1763
2638
|
}
|
|
1764
2639
|
// ── PHASE 4: AI verb ──
|
|
1765
2640
|
const aiConfig = {};
|
|
1766
|
-
// Prompt
|
|
1767
|
-
if
|
|
1768
|
-
|
|
1769
|
-
|
|
2641
|
+
// Prompt. Mirror Python (agent_base.py: `prompt_is_pom = isinstance(prompt, list)`;
|
|
2642
|
+
// ai_config = {"prompt": {"text" if not prompt_is_pom else "pom": prompt}}):
|
|
2643
|
+
// when the agent is in POM mode with at least one section AND no raw prompt
|
|
2644
|
+
// string was set, the prompt renders as a structured `pom` array, not `text`.
|
|
2645
|
+
// A raw prompt string (getRawPrompt) always wins, matching PromptManager.getPrompt.
|
|
2646
|
+
const promptPom = this.getRawPrompt() === null ? this.getPromptPom() : null;
|
|
2647
|
+
const buildPromptObj = (fallbackText) => {
|
|
2648
|
+
const obj = promptPom ? { pom: promptPom } : { text: fallbackText };
|
|
1770
2649
|
if (Object.keys(this.promptLlmParams).length)
|
|
1771
|
-
Object.assign(
|
|
2650
|
+
Object.assign(obj, this.promptLlmParams);
|
|
2651
|
+
return obj;
|
|
2652
|
+
};
|
|
2653
|
+
const contextsDict = this.contextsBuilder?.toDict() ?? this._rawContexts;
|
|
2654
|
+
if (contextsDict) {
|
|
2655
|
+
// Contexts live inside the prompt (`ai.prompt.contexts`), where the
|
|
2656
|
+
// platform reads them and the reference SDK renders them.
|
|
2657
|
+
const promptObj = buildPromptObj(prompt || `You are ${this.name}, a helpful AI assistant.`);
|
|
2658
|
+
promptObj['contexts'] = contextsDict;
|
|
1772
2659
|
aiConfig['prompt'] = promptObj;
|
|
1773
|
-
aiConfig['contexts'] = contextsDict;
|
|
1774
2660
|
}
|
|
1775
2661
|
else {
|
|
1776
|
-
|
|
1777
|
-
if (Object.keys(this.promptLlmParams).length)
|
|
1778
|
-
Object.assign(promptObj, this.promptLlmParams);
|
|
1779
|
-
aiConfig['prompt'] = promptObj;
|
|
2662
|
+
aiConfig['prompt'] = buildPromptObj(prompt);
|
|
1780
2663
|
}
|
|
1781
2664
|
// Post-prompt
|
|
1782
2665
|
if (postPrompt) {
|
|
@@ -1795,6 +2678,9 @@ export class AgentBase {
|
|
|
1795
2678
|
aiConfig['hints'] = this.hints;
|
|
1796
2679
|
if (this.languages.length)
|
|
1797
2680
|
aiConfig['languages'] = this.languages;
|
|
2681
|
+
// ASR-driven multilingual mode: a top-level `multilingual` object on the AI verb.
|
|
2682
|
+
if (Object.keys(this.multilingual).length)
|
|
2683
|
+
aiConfig['multilingual'] = this.multilingual;
|
|
1798
2684
|
if (this.pronounce.length)
|
|
1799
2685
|
aiConfig['pronounce'] = this.pronounce;
|
|
1800
2686
|
if (Object.keys(this.params).length)
|
|
@@ -1806,7 +2692,7 @@ export class AgentBase {
|
|
|
1806
2692
|
aiConfig['debug_webhook_url'] = this.buildWebhookUrl('debug_events');
|
|
1807
2693
|
aiConfig['debug_webhook_level'] = this.debugEventsLevel;
|
|
1808
2694
|
}
|
|
1809
|
-
// Apply modifications from onSwmlRequest (Python
|
|
2695
|
+
// Apply modifications from onSwmlRequest (Python equivalent: merge into AI verb config).
|
|
1810
2696
|
// global_data is deep-merged; all other keys override AI config fields directly.
|
|
1811
2697
|
if (modifications && typeof modifications === 'object') {
|
|
1812
2698
|
if (modifications['global_data'] && typeof modifications['global_data'] === 'object') {
|
|
@@ -1821,108 +2707,175 @@ export class AgentBase {
|
|
|
1821
2707
|
}
|
|
1822
2708
|
}
|
|
1823
2709
|
}
|
|
1824
|
-
|
|
2710
|
+
// The assembled ai verb may legitimately carry real SWML the bundled schema
|
|
2711
|
+
// does not yet model (multilingual, SWAIG.mcp_servers, per-language
|
|
2712
|
+
// engine/model/fillers, debug_webhook_url). It is built from typed builder
|
|
2713
|
+
// inputs, not raw user config, so skip the closed-schema check here; the
|
|
2714
|
+
// strict-render contract governs direct addVerb input, not trusted assembly.
|
|
2715
|
+
this.swmlBuilder.addVerb('ai', aiConfig, { skipValidation: true });
|
|
1825
2716
|
// ── PHASE 5: Post-AI verbs ──
|
|
1826
2717
|
for (const [verb, config] of this.postAiVerbs) {
|
|
1827
2718
|
this.swmlBuilder.addVerb(verb, config);
|
|
1828
2719
|
}
|
|
1829
|
-
return this.swmlBuilder.
|
|
2720
|
+
return this.swmlBuilder.render();
|
|
1830
2721
|
}
|
|
1831
2722
|
// ── Ephemeral copy for dynamic config ───────────────────────────────
|
|
1832
2723
|
createEphemeralCopy() {
|
|
1833
2724
|
const copy = Object.create(Object.getPrototypeOf(this));
|
|
1834
2725
|
Object.assign(copy, this);
|
|
1835
|
-
//
|
|
1836
|
-
|
|
1837
|
-
//
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
const
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
copy.
|
|
1848
|
-
copy.
|
|
1849
|
-
copy.
|
|
1850
|
-
copy.
|
|
1851
|
-
copy.
|
|
1852
|
-
copy.
|
|
1853
|
-
copy.
|
|
1854
|
-
|
|
1855
|
-
copy.
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
if (fn instanceof SwaigFunction) {
|
|
1879
|
-
if (Object.keys(skill.swaigFields).length > 0) {
|
|
1880
|
-
safeAssign(fn.extraFields, skill.swaigFields);
|
|
1881
|
-
}
|
|
1882
|
-
if (toolDef.wait_for_fillers !== undefined) {
|
|
1883
|
-
fn.extraFields['wait_for_fillers'] = toolDef.wait_for_fillers;
|
|
1884
|
-
}
|
|
1885
|
-
if (toolDef.skip_fillers !== undefined) {
|
|
1886
|
-
fn.extraFields['skip_fillers'] = toolDef.skip_fillers;
|
|
1887
|
-
}
|
|
1888
|
-
if (toolDef.isHangupHook) {
|
|
1889
|
-
fn.extraFields['is_hangup_hook'] = true;
|
|
1890
|
-
}
|
|
1891
|
-
}
|
|
1892
|
-
}
|
|
1893
|
-
for (const dmFn of skill.getDataMapTools()) {
|
|
1894
|
-
copy.registerSwaigFunction(dmFn);
|
|
1895
|
-
}
|
|
1896
|
-
for (const section of skill.getPromptSections()) {
|
|
1897
|
-
copy.promptAddSection(section.title, section);
|
|
1898
|
-
}
|
|
1899
|
-
const hints = skill.getHints();
|
|
1900
|
-
if (hints.length)
|
|
1901
|
-
copy.addHints(hints);
|
|
1902
|
-
const globalData = skill.getGlobalData();
|
|
1903
|
-
if (Object.keys(globalData).length)
|
|
1904
|
-
copy.updateGlobalData(globalData);
|
|
1905
|
-
}
|
|
1906
|
-
catch (e) {
|
|
1907
|
-
this.log.warn(`Failed to replay skill '${entry.skillName}' in ephemeral copy: ${e}`);
|
|
1908
|
-
}
|
|
1909
|
-
}
|
|
2726
|
+
// Every field starts as a reference to this agent's. The configuration a
|
|
2727
|
+
// per-request callback can change is then replaced with independent
|
|
2728
|
+
// copies, so a callback's changes stay on this request: without that, one
|
|
2729
|
+
// caller's query params, MCP servers or context edits would reach every
|
|
2730
|
+
// later call. References to this agent inside the copied state (the
|
|
2731
|
+
// contexts builder's back-reference) are redirected to the copy.
|
|
2732
|
+
const memo = new Map([[this, copy]]);
|
|
2733
|
+
const clone = (value) => deepCloneState(value, memo);
|
|
2734
|
+
// The copy's own prompt state, with the POM sections copied rather than
|
|
2735
|
+
// rendered to text, so it still emits a structured prompt and a callback
|
|
2736
|
+
// can add sections to it. The back-reference points at the COPY, not
|
|
2737
|
+
// `this` (the clone-drops-configuration defect class).
|
|
2738
|
+
copy._promptManager = this._promptManager._copyFor(copy);
|
|
2739
|
+
copy.toolRegistry = clone(this.toolRegistry);
|
|
2740
|
+
copy.hints = clone(this.hints);
|
|
2741
|
+
copy.languages = clone(this.languages);
|
|
2742
|
+
copy.multilingual = clone(this.multilingual);
|
|
2743
|
+
copy.pronounce = clone(this.pronounce);
|
|
2744
|
+
copy.params = clone(this.params);
|
|
2745
|
+
copy.globalData = clone(this.globalData);
|
|
2746
|
+
copy.functionIncludes = clone(this.functionIncludes);
|
|
2747
|
+
copy.promptLlmParams = clone(this.promptLlmParams);
|
|
2748
|
+
copy.postPromptLlmParams = clone(this.postPromptLlmParams);
|
|
2749
|
+
copy.internalFillers = clone(this.internalFillers);
|
|
2750
|
+
copy.preAnswerVerbs = clone(this.preAnswerVerbs);
|
|
2751
|
+
copy.answerConfig = clone(this.answerConfig);
|
|
2752
|
+
copy.postAnswerVerbs = clone(this.postAnswerVerbs);
|
|
2753
|
+
copy.postAiVerbs = clone(this.postAiVerbs);
|
|
2754
|
+
copy.swaigQueryParams = clone(this.swaigQueryParams);
|
|
2755
|
+
copy._nativeFunctions = clone(this._nativeFunctions);
|
|
2756
|
+
copy._mcpServers = clone(this._mcpServers);
|
|
2757
|
+
copy._sipUsernames = this._sipUsernames ? new Map(this._sipUsernames) : null;
|
|
2758
|
+
copy._routingCallbacks = new Map(this._routingCallbacks);
|
|
2759
|
+
copy.contextsBuilder = clone(this.contextsBuilder);
|
|
2760
|
+
copy._rawContexts = clone(this._rawContexts);
|
|
2761
|
+
// Back-reference points at the COPY, not `this` (see _promptManager above).
|
|
2762
|
+
copy.swmlBuilder = new SwmlBuilder({ service: copy, ...this._builderSchemaOptions });
|
|
2763
|
+
// The copy starts with the skills this agent loaded. Their tools, hints,
|
|
2764
|
+
// prompt sections and global data are already in the state copied above,
|
|
2765
|
+
// so they aren't set up again: running every skill's setup() on every
|
|
2766
|
+
// request was slow, and left the copy's skill list empty until it finished.
|
|
2767
|
+
copy._skillManager = new SkillManager(copy);
|
|
2768
|
+
copy._skillManager._inheritFrom(this._skillManager);
|
|
1910
2769
|
return copy;
|
|
1911
2770
|
}
|
|
1912
2771
|
// ── Hono HTTP app ───────────────────────────────────────────────────
|
|
2772
|
+
/**
|
|
2773
|
+
* Thin Hono adapter over the decomposed {@link handleRequest} core. Extracts
|
|
2774
|
+
* `(method, url, headers, body)` primitives from the Hono `Context`, delegates
|
|
2775
|
+
* the auth / routing-callback / render DECISION to `handleRequest`, and
|
|
2776
|
+
* marshals the returned `[status, headers, body]` triple back into a Hono
|
|
2777
|
+
* `Response` — including the routing-callback **307** (`Location`) and the
|
|
2778
|
+
* **401** (`WWW-Authenticate`). This is what routes serve()/asRouter() through
|
|
2779
|
+
* the same core the primitive path uses, instead of a parallel inline
|
|
2780
|
+
* auth/render/redirect path (mirrors the rust/dotnet/php served path).
|
|
2781
|
+
*
|
|
2782
|
+
* Proxy detection stays here as framework plumbing (it needs the raw request);
|
|
2783
|
+
* everything else comes from `handleRequest`.
|
|
2784
|
+
*/
|
|
2785
|
+
// Call it only from a route behind the basic-auth middleware: handleRequest()
|
|
2786
|
+
// skips its own credential check for a served request.
|
|
2787
|
+
async serveViaHandleRequest(c) {
|
|
2788
|
+
this.detectProxyFromRequest(c);
|
|
2789
|
+
// A serverless adapter passes the base URL the platform was called on
|
|
2790
|
+
// (Azure's /api/<function>, say), so the SWML's webhook URLs point back
|
|
2791
|
+
// there. SWML_PROXY_URL_BASE still wins.
|
|
2792
|
+
const platformBase = c.env?.[_PLATFORM_BASE_ENV_KEY];
|
|
2793
|
+
if (typeof platformBase === 'string' && platformBase && !this._proxyUrlBaseFromEnv) {
|
|
2794
|
+
this._proxyUrlBase = platformBase.replace(/\/+$/, '');
|
|
2795
|
+
}
|
|
2796
|
+
let body = null;
|
|
2797
|
+
try {
|
|
2798
|
+
body = (await c.req.json());
|
|
2799
|
+
}
|
|
2800
|
+
catch {
|
|
2801
|
+
/* GET or no body */
|
|
2802
|
+
}
|
|
2803
|
+
const headers = {};
|
|
2804
|
+
c.req.raw.headers.forEach((v, k) => {
|
|
2805
|
+
headers[k] = v;
|
|
2806
|
+
});
|
|
2807
|
+
// Through the public handleRequest(), so a subclass override still
|
|
2808
|
+
// decides served requests; the Hono context rides along for onSwmlRequest.
|
|
2809
|
+
const [status, respHeaders, bodyStr] = await servedRequestContext.run(c, () => this.handleRequest(c.req.method, c.req.url, headers, body));
|
|
2810
|
+
// 307 routing redirect — real redirect status + Location, empty body.
|
|
2811
|
+
if (status === 307 && respHeaders['Location']) {
|
|
2812
|
+
return c.redirect(respHeaders['Location'], 307);
|
|
2813
|
+
}
|
|
2814
|
+
// Marshal any remaining headers (e.g. WWW-Authenticate on a 401) and emit
|
|
2815
|
+
// the body. The 200 SWML body is a JSON string; other statuses carry a JSON
|
|
2816
|
+
// error string — both are already serialized, so pass through with a JSON
|
|
2817
|
+
// content type and the exact status handleRequest chose.
|
|
2818
|
+
for (const [k, v] of Object.entries(respHeaders)) {
|
|
2819
|
+
c.header(k, v);
|
|
2820
|
+
}
|
|
2821
|
+
c.header('Content-Type', 'application/json');
|
|
2822
|
+
// The 307 redirect returned above; every remaining status (200 SWML, 401,
|
|
2823
|
+
// 4xx/5xx error JSON) carries a body, so it is a ContentfulStatusCode.
|
|
2824
|
+
return c.body(bodyStr, status);
|
|
2825
|
+
}
|
|
1913
2826
|
/**
|
|
1914
2827
|
* Get or lazily create the Hono HTTP application with all routes, middleware, auth, and CORS.
|
|
1915
2828
|
* @returns The configured Hono application instance.
|
|
1916
2829
|
*/
|
|
1917
2830
|
getApp() {
|
|
1918
|
-
|
|
2831
|
+
// Make sure subclass tools are registered before any route can dispatch
|
|
2832
|
+
// a SWAIG call (idempotent — see ensureToolsDefined).
|
|
2833
|
+
this.ensureToolsDefined();
|
|
2834
|
+
// Service's constructor eagerly initialised _app; AgentBase rebuilds it
|
|
2835
|
+
// here with its own middleware stack and route handlers on first call.
|
|
2836
|
+
if (this._appBuiltByAgent)
|
|
1919
2837
|
return this._app;
|
|
1920
|
-
|
|
2838
|
+
this._app = this.buildApp(this.route === '/' ? '' : this.route);
|
|
2839
|
+
this._appBuiltByAgent = true;
|
|
2840
|
+
return this._app;
|
|
2841
|
+
}
|
|
2842
|
+
/**
|
|
2843
|
+
* Build the Hono app serving this agent's routes under `basePath` ('' for
|
|
2844
|
+
* route-relative routes, as {@link asRouter} returns them).
|
|
2845
|
+
*
|
|
2846
|
+
* Paths are matched without regard to a trailing slash or repeated slashes
|
|
2847
|
+
* (`/agent/swaig/`, `/agent//swaig`), as the reference's router and
|
|
2848
|
+
* catch-all routes accept them; the signature check still covers the URL
|
|
2849
|
+
* as the request spelled it.
|
|
2850
|
+
*/
|
|
2851
|
+
buildApp(basePath) {
|
|
2852
|
+
// getPathNoStrict drops a trailing slash; repeated slashes are collapsed
|
|
2853
|
+
// too. (Hono ignores a custom getPath when `strict: false` is passed.)
|
|
2854
|
+
const app = new Hono({
|
|
2855
|
+
getPath: (req) => getPathNoStrict(req).replace(/\/{2,}/g, '/'),
|
|
2856
|
+
});
|
|
2857
|
+
// Each path with and without a trailing slash, so a host app that mounts
|
|
2858
|
+
// asRouter() with strict routing still serves `/swaig/` (as the
|
|
2859
|
+
// reference's router registers both).
|
|
2860
|
+
const withSlash = (path) => [path, `${path}/`];
|
|
1921
2861
|
// Security headers
|
|
1922
|
-
const requestTimeout = parseInt(process.env['SWML_REQUEST_TIMEOUT'] ?? '30000', 10);
|
|
1923
2862
|
const maxRequestSize = parseInt(process.env['SWML_MAX_REQUEST_SIZE'] ?? '1048576', 10);
|
|
2863
|
+
// The agent's header, CORS and CSRF middleware apply to the requests its
|
|
2864
|
+
// own routes serve (by method and path), so a mounted app (see mount())
|
|
2865
|
+
// keeps its own headers and CORS preflights, and so does another agent's
|
|
2866
|
+
// route or mount below this one's under AgentServer. (A mounted page
|
|
2867
|
+
// couldn't work under default-src 'none'.) Paths are compared relative
|
|
2868
|
+
// to where this app is mounted (routePath), so asRouter() under
|
|
2869
|
+
// AgentServer works the same.
|
|
2870
|
+
const agentRoutes = { byMethod: new Set(), paths: new Set() };
|
|
2871
|
+
AGENT_ROUTES.set(app, agentRoutes);
|
|
2872
|
+
const underMount = (c) => !ownsRoute(agentRoutes, c.req.method, relativePath(c.req.path, c.req.routePath));
|
|
1924
2873
|
app.use('*', async (c, next) => {
|
|
2874
|
+
// routePath names the handler after next(), so decide first.
|
|
2875
|
+
const mounted = underMount(c);
|
|
1925
2876
|
await next();
|
|
2877
|
+
if (mounted)
|
|
2878
|
+
return;
|
|
1926
2879
|
c.res.headers.set('X-Content-Type-Options', 'nosniff');
|
|
1927
2880
|
c.res.headers.set('X-Frame-Options', 'DENY');
|
|
1928
2881
|
c.res.headers.set('X-XSS-Protection', '1; mode=block');
|
|
@@ -1940,11 +2893,16 @@ export class AgentBase {
|
|
|
1940
2893
|
await next();
|
|
1941
2894
|
});
|
|
1942
2895
|
// Allowed hosts (configurable via env)
|
|
2896
|
+
// "*" allows every host, as the reference reads it.
|
|
1943
2897
|
const allowedHosts = process.env['SWML_ALLOWED_HOSTS'];
|
|
1944
|
-
|
|
1945
|
-
|
|
2898
|
+
const hostList = (allowedHosts ?? '')
|
|
2899
|
+
.split(',')
|
|
2900
|
+
.map((h) => h.trim().toLowerCase())
|
|
2901
|
+
.filter(Boolean);
|
|
2902
|
+
if (hostList.length > 0 && !hostList.includes('*')) {
|
|
2903
|
+
const hostSet = new Set(hostList);
|
|
1946
2904
|
app.use('*', async (c, next) => {
|
|
1947
|
-
const host = (c.req.header('host') ?? '').split(':')[0].toLowerCase();
|
|
2905
|
+
const host = (c.req.header('host') ?? '').split(':')[0].toLowerCase(); // split yields >=1 element
|
|
1948
2906
|
if (!hostSet.has(host)) {
|
|
1949
2907
|
return c.json({ error: 'Forbidden: host not allowed' }, 403);
|
|
1950
2908
|
}
|
|
@@ -1958,11 +2916,18 @@ export class AgentBase {
|
|
|
1958
2916
|
if (maxPerMinute > 0) {
|
|
1959
2917
|
const hits = new Map();
|
|
1960
2918
|
app.use('*', async (c, next) => {
|
|
2919
|
+
// The connection's own address, as the reference keys on
|
|
2920
|
+
// request.client.host; the forwarded headers only when trusted.
|
|
2921
|
+
// On a serverless platform, the address the platform reports.
|
|
2922
|
+
const env = c.env;
|
|
2923
|
+
const platformIp = env?.[_CLIENT_ADDRESS_ENV_KEY];
|
|
2924
|
+
const socketIp = env?.incoming?.socket?.remoteAddress ??
|
|
2925
|
+
(typeof platformIp === 'string' ? platformIp : 'unknown');
|
|
1961
2926
|
const ip = this._trustProxyHeaders
|
|
1962
|
-
? (c.req.header('x-forwarded-for')?.split(',')[0].trim()
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
:
|
|
2927
|
+
? (c.req.header('x-forwarded-for')?.split(',')[0].trim() ??
|
|
2928
|
+
c.req.header('x-real-ip') ??
|
|
2929
|
+
socketIp)
|
|
2930
|
+
: socketIp;
|
|
1966
2931
|
const now = Date.now();
|
|
1967
2932
|
let entry = hits.get(ip);
|
|
1968
2933
|
if (!entry || now >= entry.resetAt) {
|
|
@@ -1986,16 +2951,15 @@ export class AgentBase {
|
|
|
1986
2951
|
}
|
|
1987
2952
|
// CORS (configurable via env)
|
|
1988
2953
|
const corsOrigins = process.env['SWML_CORS_ORIGINS'];
|
|
1989
|
-
const corsOrigin = corsOrigins
|
|
2954
|
+
const corsOrigin = corsOriginsFromEnv(corsOrigins);
|
|
1990
2955
|
const corsCredentials = corsOrigin !== '*';
|
|
1991
|
-
|
|
2956
|
+
const corsMw = cors({ origin: corsOrigin, credentials: corsCredentials });
|
|
2957
|
+
app.use('*', (c, next) => (underMount(c) ? next() : corsMw(c, next)));
|
|
1992
2958
|
// CSRF protection (optional, gated by env)
|
|
1993
2959
|
if (process.env['SWML_CSRF_PROTECTION'] === 'true') {
|
|
1994
|
-
const allowedOrigins =
|
|
1995
|
-
? new Set(corsOrigins.split(',').map(o => o.trim().toLowerCase()))
|
|
1996
|
-
: null;
|
|
2960
|
+
const allowedOrigins = corsOrigin === '*' ? null : new Set(corsOrigin.map((o) => o.toLowerCase()));
|
|
1997
2961
|
app.use('*', async (c, next) => {
|
|
1998
|
-
if (c.req.method === 'POST') {
|
|
2962
|
+
if (c.req.method === 'POST' && !underMount(c)) {
|
|
1999
2963
|
const origin = c.req.header('origin');
|
|
2000
2964
|
if (origin && allowedOrigins && !allowedOrigins.has(origin.toLowerCase())) {
|
|
2001
2965
|
return c.json({ error: 'Origin not allowed' }, 403);
|
|
@@ -2004,66 +2968,65 @@ export class AgentBase {
|
|
|
2004
2968
|
await next();
|
|
2005
2969
|
});
|
|
2006
2970
|
}
|
|
2007
|
-
// Auth middleware
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
//
|
|
2971
|
+
// Auth middleware. The 401 challenge body must be the JSON envelope
|
|
2972
|
+
// {"error":"Unauthorized"} to match Python's auth challenge
|
|
2973
|
+
// (auth_mixin._send_lambda_auth_challenge / the primitive handleRequest 401);
|
|
2974
|
+
// Hono's default basicAuth returns a plain "Unauthorized" text body, which
|
|
2975
|
+
// diverges on the serverless dispatch path.
|
|
2976
|
+
const authMw = basicAuth({
|
|
2977
|
+
verifyUser: (username, password) => this.validateBasicAuth(username, password),
|
|
2978
|
+
invalidUserMessage: JSON.stringify({ error: 'Unauthorized' }),
|
|
2979
|
+
});
|
|
2980
|
+
// Webhook signature validation middleware — only mounted (and only on
|
|
2981
|
+
// POST routes) when a signing key is configured. Per
|
|
2982
|
+
// porting-sdk/webhooks.md, signed routes are POST / (SWML), POST /swaig,
|
|
2983
|
+
// and POST /post_prompt. GET / serves SWML to the platform's GET probe,
|
|
2984
|
+
// which is unsigned, so we don't apply the middleware to GET.
|
|
2985
|
+
const sigMw = this._signingKey !== null
|
|
2986
|
+
? webhookValidationMiddleware({
|
|
2987
|
+
signingKey: this._signingKey,
|
|
2988
|
+
trustProxy: this._webhookTrustProxy,
|
|
2989
|
+
})
|
|
2990
|
+
: null;
|
|
2991
|
+
// Root - returns SWML. Delegates the auth / routing-callback / dynamic-config
|
|
2992
|
+
// / render DECISION to handleRequest (the decomposed core), then marshals the
|
|
2993
|
+
// [status, headers, body] triple back — so serve()/asRouter() honor the
|
|
2994
|
+
// routing-callback 307 on the root path too, through the same core the
|
|
2995
|
+
// primitive path uses. Proxy detection stays in the thin adapter.
|
|
2012
2996
|
const handleSwml = async (c) => {
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
let body = {};
|
|
2016
|
-
try {
|
|
2017
|
-
body = await c.req.json();
|
|
2018
|
-
}
|
|
2019
|
-
catch { /* GET or no body */ }
|
|
2020
|
-
reqLog.debug('request_body_received', { body_size: JSON.stringify(body).length });
|
|
2021
|
-
this.detectProxyFromRequest(c);
|
|
2022
|
-
const callbackPath = body['callback_path'] ?? undefined;
|
|
2023
|
-
let swmlMods = undefined;
|
|
2024
|
-
try {
|
|
2025
|
-
swmlMods = await this.onSwmlRequest(body, callbackPath, c);
|
|
2026
|
-
if (swmlMods)
|
|
2027
|
-
reqLog.debug('on_swml_request_modifications_applied');
|
|
2028
|
-
}
|
|
2029
|
-
catch (err) {
|
|
2030
|
-
reqLog.error('error_in_on_swml_request', { error: err instanceof Error ? err.message : String(err) });
|
|
2031
|
-
}
|
|
2032
|
-
const callId = body['call_id'] || undefined;
|
|
2033
|
-
if (callId)
|
|
2034
|
-
reqLog = reqLog.bind({ call_id: callId });
|
|
2035
|
-
let agentToUse = this;
|
|
2036
|
-
if (this.dynamicConfigCallback) {
|
|
2037
|
-
agentToUse = this.createEphemeralCopy();
|
|
2038
|
-
const queryParams = {};
|
|
2039
|
-
const url = new URL(c.req.url);
|
|
2040
|
-
url.searchParams.forEach((v, k) => { queryParams[k] = v; });
|
|
2041
|
-
const rawHeaders = {};
|
|
2042
|
-
c.req.raw.headers.forEach((v, k) => { rawHeaders[k] = v; });
|
|
2043
|
-
const headers = filterSensitiveHeaders(rawHeaders);
|
|
2044
|
-
await this.dynamicConfigCallback(queryParams, body, headers, agentToUse);
|
|
2045
|
-
reqLog.debug('dynamic_config_complete');
|
|
2046
|
-
}
|
|
2047
|
-
const swml = agentToUse.renderSwml(callId, swmlMods || undefined);
|
|
2048
|
-
reqLog.debug('swml_rendered', { swml_size: swml.length });
|
|
2049
|
-
reqLog.info('request_successful');
|
|
2050
|
-
return c.json(JSON.parse(swml));
|
|
2997
|
+
this.log.bind({ endpoint: this.route }).debug('endpoint_called');
|
|
2998
|
+
return this.serveViaHandleRequest(c);
|
|
2051
2999
|
};
|
|
2052
3000
|
app.get(`${basePath}`, authMw, handleSwml);
|
|
2053
|
-
|
|
3001
|
+
if (sigMw) {
|
|
3002
|
+
app.post(`${basePath}`, authMw, sigMw, handleSwml);
|
|
3003
|
+
}
|
|
3004
|
+
else {
|
|
3005
|
+
app.post(`${basePath}`, authMw, handleSwml);
|
|
3006
|
+
}
|
|
2054
3007
|
if (basePath) {
|
|
2055
3008
|
app.get(`${basePath}/`, authMw, handleSwml);
|
|
2056
|
-
|
|
3009
|
+
if (sigMw) {
|
|
3010
|
+
app.post(`${basePath}/`, authMw, sigMw, handleSwml);
|
|
3011
|
+
}
|
|
3012
|
+
else {
|
|
3013
|
+
app.post(`${basePath}/`, authMw, handleSwml);
|
|
3014
|
+
}
|
|
2057
3015
|
}
|
|
2058
3016
|
// SWAIG function dispatcher
|
|
2059
3017
|
const handleSwaig = async (c) => {
|
|
2060
3018
|
let reqLog = this.log.bind({ endpoint: `${basePath}/swaig` });
|
|
2061
3019
|
reqLog.debug('endpoint_called');
|
|
3020
|
+
// Runtime fallback is the empty object (unchanged); the cast is
|
|
3021
|
+
// compile-time only — the backend always POSTs the full SWAIG payload,
|
|
3022
|
+
// and the parse-failure path below is rejected before any field is read.
|
|
2062
3023
|
let body = {};
|
|
2063
3024
|
try {
|
|
2064
3025
|
body = await c.req.json();
|
|
2065
3026
|
}
|
|
2066
|
-
catch {
|
|
3027
|
+
catch {
|
|
3028
|
+
/* empty */
|
|
3029
|
+
}
|
|
2067
3030
|
const fnName = body['function'];
|
|
2068
3031
|
if (!fnName)
|
|
2069
3032
|
return c.json({ error: 'Missing function name' }, 400);
|
|
@@ -2078,70 +3041,121 @@ export class AgentBase {
|
|
|
2078
3041
|
const callIdStr = body['call_id'] ?? '';
|
|
2079
3042
|
if (callIdStr)
|
|
2080
3043
|
reqLog = reqLog.bind({ call_id: callIdStr });
|
|
2081
|
-
|
|
3044
|
+
// The function runs on the agent the call's SWML came from: with a
|
|
3045
|
+
// dynamic config callback, the request's configured copy. So a tool the
|
|
3046
|
+
// callback registered or secured is found, and its token checked, here.
|
|
3047
|
+
const target = await this.perCallAgent(queryParamsOf(c.req.url), body, headersOf(c));
|
|
3048
|
+
const fn = target.toolRegistry.get(fnName);
|
|
2082
3049
|
if (!fn || !(fn instanceof SwaigFunction)) {
|
|
2083
3050
|
reqLog.warn('function_not_found', { requested: fnName });
|
|
2084
3051
|
return c.json({ error: `Unknown function: ${fnName}` }, 404);
|
|
2085
3052
|
}
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
const result = new FunctionResult('The security token for this function is missing or expired. This action cannot be completed.');
|
|
2093
|
-
return c.json(result.toDict());
|
|
2094
|
-
}
|
|
2095
|
-
if (!this.sessionManager.validateToken(callIdStr, fnName, token)) {
|
|
2096
|
-
reqLog.warn('token_invalid');
|
|
2097
|
-
const result = new FunctionResult('The security token for this function is invalid or expired. This action cannot be completed.');
|
|
2098
|
-
return c.json(result.toDict());
|
|
2099
|
-
}
|
|
2100
|
-
reqLog.debug('token_valid');
|
|
2101
|
-
}
|
|
2102
|
-
const rawArgs = body['argument'];
|
|
2103
|
-
const args = (rawArgs !== null && typeof rawArgs === 'object' && !Array.isArray(rawArgs))
|
|
2104
|
-
? rawArgs
|
|
2105
|
-
: {};
|
|
3053
|
+
const url = new URL(c.req.url);
|
|
3054
|
+
const token = url.searchParams.get('__token') ?? url.searchParams.get('token');
|
|
3055
|
+
const refusal = target.swaigTokenRefusal(fn, token, callIdStr, reqLog);
|
|
3056
|
+
if (refusal)
|
|
3057
|
+
return c.json(refusal);
|
|
3058
|
+
const args = this.extractSwaigArgs(body, reqLog);
|
|
2106
3059
|
reqLog.debug('executing_function', { args: JSON.stringify(args) });
|
|
2107
|
-
const hookResult = await
|
|
3060
|
+
const hookResult = await target.onFunctionCall(fnName, args, body);
|
|
2108
3061
|
// If onFunctionCall returned a result, use it (dispatch interception)
|
|
2109
3062
|
if (hookResult !== undefined && hookResult !== null) {
|
|
2110
3063
|
reqLog.info('function_intercepted_by_hook');
|
|
2111
3064
|
return c.json(hookResult);
|
|
2112
3065
|
}
|
|
2113
3066
|
try {
|
|
2114
|
-
const result = await fn.
|
|
3067
|
+
const result = await fn._executeAs(target, args, body, target._onError);
|
|
2115
3068
|
reqLog.info('function_executed_successfully');
|
|
2116
3069
|
reqLog.debug('function_result', { result_size: JSON.stringify(result).length });
|
|
2117
3070
|
return c.json(result);
|
|
2118
3071
|
}
|
|
2119
3072
|
catch (err) {
|
|
2120
|
-
reqLog.error('function_execution_error', {
|
|
3073
|
+
reqLog.error('function_execution_error', {
|
|
3074
|
+
error: err instanceof Error ? err.message : String(err),
|
|
3075
|
+
});
|
|
2121
3076
|
return c.json({ error: 'Function execution failed' }, 500);
|
|
2122
3077
|
}
|
|
2123
3078
|
};
|
|
2124
|
-
|
|
2125
|
-
|
|
3079
|
+
// A GET renders the SWML, like the agent's root (with ?call_id= for a
|
|
3080
|
+
// call's tokens); only a POST runs a function.
|
|
3081
|
+
const swaigPaths = withSlash(`${basePath}/swaig`);
|
|
3082
|
+
app.on('GET', swaigPaths, authMw, (c) => this.serveViaHandleRequest(c));
|
|
3083
|
+
if (sigMw) {
|
|
3084
|
+
app.on('POST', swaigPaths, authMw, sigMw, handleSwaig);
|
|
3085
|
+
}
|
|
3086
|
+
else {
|
|
3087
|
+
app.on('POST', swaigPaths, authMw, handleSwaig);
|
|
3088
|
+
}
|
|
2126
3089
|
// Post-prompt handler
|
|
2127
3090
|
const handlePostPrompt = async (c) => {
|
|
2128
3091
|
let reqLog = this.log.bind({ endpoint: `${basePath}/post_prompt` });
|
|
2129
3092
|
reqLog.debug('endpoint_called');
|
|
3093
|
+
// Runtime fallback is the empty object (unchanged); the cast is
|
|
3094
|
+
// compile-time only — the backend always POSTs the full post_prompt
|
|
3095
|
+
// payload, and the parse-failure path leaves an empty summary lookup.
|
|
2130
3096
|
let body = {};
|
|
2131
3097
|
try {
|
|
2132
3098
|
body = await c.req.json();
|
|
2133
3099
|
}
|
|
2134
|
-
catch {
|
|
2135
|
-
|
|
3100
|
+
catch {
|
|
3101
|
+
/* empty */
|
|
3102
|
+
}
|
|
3103
|
+
// A POST delivers a call's summary, so like a secure SWAIG function it
|
|
3104
|
+
// needs the token minted into the post-prompt URL for that call. The
|
|
3105
|
+
// call is the one the body names, or the URL's call_id when the body
|
|
3106
|
+
// names none; when they disagree the request is refused, so a token for
|
|
3107
|
+
// one call can't deliver another call's summary.
|
|
3108
|
+
const url = new URL(c.req.url);
|
|
3109
|
+
const queryCallId = url.searchParams.get('call_id') || undefined;
|
|
3110
|
+
const token = url.searchParams.get('__token') ?? url.searchParams.get('token');
|
|
3111
|
+
const rawBodyCallId = body['call_id'];
|
|
3112
|
+
const bodyCallId = typeof rawBodyCallId === 'string' && rawBodyCallId ? rawBodyCallId : undefined;
|
|
3113
|
+
if (queryCallId && bodyCallId && queryCallId !== bodyCallId) {
|
|
3114
|
+
reqLog.warn('call_id_mismatch');
|
|
3115
|
+
return c.json({ error: 'The call_id in the URL and the body differ' }, 400);
|
|
3116
|
+
}
|
|
3117
|
+
const callId = bodyCallId ?? queryCallId;
|
|
2136
3118
|
if (callId)
|
|
2137
3119
|
reqLog = reqLog.bind({ call_id: callId });
|
|
3120
|
+
if (!token) {
|
|
3121
|
+
reqLog.warn('token_missing');
|
|
3122
|
+
return c.json({ error: 'Invalid or missing token' }, 403);
|
|
3123
|
+
}
|
|
3124
|
+
if (!callId || !this.sessionManager.validateToken(callId, 'post_prompt', token)) {
|
|
3125
|
+
reqLog.warn('invalid_token');
|
|
3126
|
+
return c.json({ error: 'Invalid or missing token' }, 403);
|
|
3127
|
+
}
|
|
2138
3128
|
reqLog.info('post_prompt_received');
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
3129
|
+
// The summary goes to the agent the call ran on: with a dynamic config
|
|
3130
|
+
// callback, the request's configured copy.
|
|
3131
|
+
const target = await this.perCallAgent(queryParamsOf(c.req.url), body, headersOf(c));
|
|
3132
|
+
const summary = target.findSummary(body);
|
|
3133
|
+
let result;
|
|
3134
|
+
try {
|
|
3135
|
+
// onSummary is declared to return nothing, but an override may return
|
|
3136
|
+
// the conversation for a fetch_conversation request.
|
|
3137
|
+
result = await target.onSummary(summary, body);
|
|
3138
|
+
}
|
|
3139
|
+
catch (err) {
|
|
3140
|
+
reqLog.error('error_in_summary_handler', {
|
|
3141
|
+
error: err instanceof Error ? err.message : String(err),
|
|
3142
|
+
});
|
|
3143
|
+
}
|
|
3144
|
+
if (body['action'] === 'fetch_conversation' && result != null) {
|
|
3145
|
+
return c.json(result);
|
|
3146
|
+
}
|
|
3147
|
+
return c.json({ success: true });
|
|
2142
3148
|
};
|
|
2143
|
-
|
|
2144
|
-
|
|
3149
|
+
// A GET renders the SWML, like the agent's root; only a POST delivers a
|
|
3150
|
+
// summary.
|
|
3151
|
+
const postPromptPaths = withSlash(`${basePath}/post_prompt`);
|
|
3152
|
+
app.on('GET', postPromptPaths, authMw, (c) => this.serveViaHandleRequest(c));
|
|
3153
|
+
if (sigMw) {
|
|
3154
|
+
app.on('POST', postPromptPaths, authMw, sigMw, handlePostPrompt);
|
|
3155
|
+
}
|
|
3156
|
+
else {
|
|
3157
|
+
app.on('POST', postPromptPaths, authMw, handlePostPrompt);
|
|
3158
|
+
}
|
|
2145
3159
|
// Debug events handler
|
|
2146
3160
|
const handleDebugEvents = async (c) => {
|
|
2147
3161
|
const reqLog = this.log.bind({ endpoint: `${basePath}/debug_events` });
|
|
@@ -2150,21 +3164,29 @@ export class AgentBase {
|
|
|
2150
3164
|
try {
|
|
2151
3165
|
body = await c.req.json();
|
|
2152
3166
|
}
|
|
2153
|
-
catch {
|
|
3167
|
+
catch {
|
|
3168
|
+
/* empty */
|
|
3169
|
+
}
|
|
2154
3170
|
reqLog.debug('debug_event_received', body);
|
|
2155
3171
|
await this.onDebugEvent(body);
|
|
2156
3172
|
return c.json({ ok: true });
|
|
2157
3173
|
};
|
|
2158
3174
|
app.post(`${basePath}/debug_events`, authMw, handleDebugEvents);
|
|
2159
|
-
// MCP server endpoint (JSON-RPC 2.0)
|
|
3175
|
+
// MCP server endpoint (JSON-RPC 2.0). It runs the agent's tools, so it
|
|
3176
|
+
// takes the same basic auth as /swaig. MCP clients don't sign requests,
|
|
3177
|
+
// so there is no webhook signature check here.
|
|
2160
3178
|
if (this._mcpServerEnabled) {
|
|
2161
|
-
app.post(`${basePath}/mcp`, async (c) => {
|
|
2162
|
-
let body
|
|
3179
|
+
app.post(`${basePath}/mcp`, authMw, async (c) => {
|
|
3180
|
+
let body;
|
|
2163
3181
|
try {
|
|
2164
3182
|
body = await c.req.json();
|
|
2165
3183
|
}
|
|
2166
3184
|
catch {
|
|
2167
|
-
return c.json({
|
|
3185
|
+
return c.json({
|
|
3186
|
+
jsonrpc: '2.0',
|
|
3187
|
+
id: null,
|
|
3188
|
+
error: { code: -32700, message: 'Parse error' },
|
|
3189
|
+
});
|
|
2168
3190
|
}
|
|
2169
3191
|
const result = await this.handleMcpRequest(body);
|
|
2170
3192
|
return c.json(result);
|
|
@@ -2179,7 +3201,9 @@ export class AgentBase {
|
|
|
2179
3201
|
try {
|
|
2180
3202
|
body = await c.req.json();
|
|
2181
3203
|
}
|
|
2182
|
-
catch {
|
|
3204
|
+
catch {
|
|
3205
|
+
/* empty */
|
|
3206
|
+
}
|
|
2183
3207
|
const newPostPrompt = body['post_prompt'];
|
|
2184
3208
|
if (newPostPrompt !== undefined) {
|
|
2185
3209
|
this.setPostPrompt(newPostPrompt);
|
|
@@ -2198,55 +3222,98 @@ export class AgentBase {
|
|
|
2198
3222
|
try {
|
|
2199
3223
|
body = await c.req.json();
|
|
2200
3224
|
}
|
|
2201
|
-
catch {
|
|
3225
|
+
catch {
|
|
3226
|
+
/* empty */
|
|
3227
|
+
}
|
|
2202
3228
|
reqLog.info('check_for_input_received');
|
|
2203
3229
|
return c.json({ ok: true, received: body });
|
|
2204
3230
|
};
|
|
2205
3231
|
app.get(`${basePath}/check_for_input`, authMw, handleCheckForInput);
|
|
2206
3232
|
app.post(`${basePath}/check_for_input`, authMw, handleCheckForInput);
|
|
2207
3233
|
}
|
|
2208
|
-
// Routing callbacks (registered via registerRoutingCallback)
|
|
2209
|
-
|
|
3234
|
+
// Routing callbacks (registered via registerRoutingCallback). The served
|
|
3235
|
+
// path delegates to handleRequest, which runs the callback and returns a
|
|
3236
|
+
// real 307 (Location) on a redirect — NOT a 200 {action:redirect} — with the
|
|
3237
|
+
// same auth/render decision the primitive core makes. handleRequest resolves
|
|
3238
|
+
// the matching callback from the request URL via _callbackPathForUrl.
|
|
3239
|
+
for (const callbackPath of this._routingCallbacks.keys()) {
|
|
2210
3240
|
const fullPath = basePath ? `${basePath}${callbackPath}` : callbackPath;
|
|
2211
3241
|
const handleRouting = async (c) => {
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
let body = {};
|
|
2215
|
-
try {
|
|
2216
|
-
body = await c.req.json();
|
|
2217
|
-
}
|
|
2218
|
-
catch { /* GET or no body */ }
|
|
2219
|
-
try {
|
|
2220
|
-
const route = await callback(body);
|
|
2221
|
-
if (route) {
|
|
2222
|
-
reqLog.info('routing_callback_redirect', { route });
|
|
2223
|
-
return c.json({ action: 'redirect', route });
|
|
2224
|
-
}
|
|
2225
|
-
// No redirect — return SWML for this agent
|
|
2226
|
-
this.detectProxyFromRequest(c);
|
|
2227
|
-
const swml = this.renderSwml();
|
|
2228
|
-
return c.json(JSON.parse(swml));
|
|
2229
|
-
}
|
|
2230
|
-
catch (err) {
|
|
2231
|
-
reqLog.error('routing_callback_error', { error: err instanceof Error ? err.message : String(err) });
|
|
2232
|
-
return c.json({ error: 'Routing callback failed' }, 500);
|
|
2233
|
-
}
|
|
3242
|
+
this.log.bind({ endpoint: fullPath }).debug('routing_callback_called');
|
|
3243
|
+
return this.serveViaHandleRequest(c);
|
|
2234
3244
|
};
|
|
2235
|
-
|
|
2236
|
-
|
|
3245
|
+
// A routing-callback path renders SWML like the root, so a POST to it
|
|
3246
|
+
// needs a signature like the root when a signing key is set. A GET
|
|
3247
|
+
// (the platform's SWML probe) stays unsigned, as it is on the root.
|
|
3248
|
+
const callbackPaths = withSlash(fullPath);
|
|
3249
|
+
app.on('GET', callbackPaths, authMw, handleRouting);
|
|
3250
|
+
if (sigMw) {
|
|
3251
|
+
app.on('POST', callbackPaths, authMw, sigMw, handleRouting);
|
|
3252
|
+
}
|
|
3253
|
+
else {
|
|
3254
|
+
app.on('POST', callbackPaths, authMw, handleRouting);
|
|
3255
|
+
}
|
|
2237
3256
|
}
|
|
2238
3257
|
// Health / Ready
|
|
2239
3258
|
app.get(`${basePath}/health`, (c) => c.json({ status: 'ok' }));
|
|
2240
3259
|
app.get(`${basePath}/ready`, (c) => c.json({ status: 'ready' }));
|
|
2241
|
-
|
|
3260
|
+
// The agent's own paths, for the mount exemption above.
|
|
3261
|
+
for (const r of app.routes) {
|
|
3262
|
+
if (r.path.includes('*'))
|
|
3263
|
+
continue;
|
|
3264
|
+
const path = normalizePath(r.path);
|
|
3265
|
+
agentRoutes.byMethod.add(`${r.method.toUpperCase()} ${path}`);
|
|
3266
|
+
agentRoutes.paths.add(path);
|
|
3267
|
+
}
|
|
3268
|
+
// Mounted apps (see mount()), after the agent's own routes so those win.
|
|
3269
|
+
for (const m of this.mounts) {
|
|
3270
|
+
if (typeof m.app === 'function') {
|
|
3271
|
+
app.mount(m.prefix || '/', m.app);
|
|
3272
|
+
}
|
|
3273
|
+
else {
|
|
3274
|
+
app.route(m.prefix || '/', m.app);
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
2242
3277
|
return app;
|
|
2243
3278
|
}
|
|
3279
|
+
/** The route-relative app {@link asRouter} returns, built on first use. */
|
|
3280
|
+
_routerApp = null;
|
|
2244
3281
|
/**
|
|
2245
|
-
*
|
|
2246
|
-
*
|
|
3282
|
+
* Get a router to embed this agent's routes in a host web app.
|
|
3283
|
+
*
|
|
3284
|
+
* Returns a Hono sub-app with this agent's routes relative to its root
|
|
3285
|
+
* (`/`, `/swaig`, `/post_prompt`, plus any routing callbacks), for the host
|
|
3286
|
+
* to mount under the agent's route: `hostApp.route(agent.route,
|
|
3287
|
+
* agent.asRouter())`. This is the TypeScript realization of Python's
|
|
3288
|
+
* `as_router()`, which is route-relative the same way; the named
|
|
3289
|
+
* {@link HostAppRouter} type is the cross-port "embed my routes in a host
|
|
3290
|
+
* app" contract. {@link getApp} serves the same routes under the agent's
|
|
3291
|
+
* route.
|
|
3292
|
+
*
|
|
3293
|
+
* @returns A mountable Hono sub-app carrying this agent's routes.
|
|
2247
3294
|
*/
|
|
2248
3295
|
asRouter() {
|
|
2249
|
-
|
|
3296
|
+
this.ensureToolsDefined();
|
|
3297
|
+
this._routerApp ??= this.buildApp('');
|
|
3298
|
+
return this._routerApp;
|
|
3299
|
+
}
|
|
3300
|
+
/**
|
|
3301
|
+
* Whether a request path is served by an app added with {@link mount}
|
|
3302
|
+
* rather than by the agent's own routes, so the agent's security headers,
|
|
3303
|
+
* CORS and CSRF handling should leave it alone. Internal; AgentServer uses
|
|
3304
|
+
* it for the agents it serves.
|
|
3305
|
+
*
|
|
3306
|
+
* @param path - The path relative to the agent's route-relative router.
|
|
3307
|
+
* @param method - The request's method.
|
|
3308
|
+
*/
|
|
3309
|
+
_servedByMount(path, method = 'GET') {
|
|
3310
|
+
if (this.mounts.length === 0)
|
|
3311
|
+
return false;
|
|
3312
|
+
const routes = AGENT_ROUTES.get(this.asRouter());
|
|
3313
|
+
if (routes && ownsRoute(routes, method, path))
|
|
3314
|
+
return false;
|
|
3315
|
+
const normalized = normalizePath(path);
|
|
3316
|
+
return this.mounts.some((m) => m.prefix === '' || normalized === m.prefix || normalized.startsWith(`${m.prefix}/`));
|
|
2250
3317
|
}
|
|
2251
3318
|
/**
|
|
2252
3319
|
* Start the HTTP server and begin listening for requests.
|
|
@@ -2273,22 +3340,73 @@ export class AgentBase {
|
|
|
2273
3340
|
return;
|
|
2274
3341
|
const host = opts?.host ?? this.host;
|
|
2275
3342
|
const port = opts?.port ?? this.port;
|
|
2276
|
-
|
|
3343
|
+
// Serving HTTP itself, the agent is a server whatever the environment
|
|
3344
|
+
// says, so its webhook URLs are the host's (see getFullUrl).
|
|
3345
|
+
this._serving = true;
|
|
2277
3346
|
const app = this.getApp();
|
|
2278
|
-
|
|
3347
|
+
// HTTPS when SSL is configured (SWML_SSL_ENABLED with a certificate and
|
|
3348
|
+
// key, or the config file), as the reference's serve() passes them to
|
|
3349
|
+
// uvicorn; plain HTTP otherwise.
|
|
3350
|
+
const tls = this._servesTls();
|
|
3351
|
+
if (this.sslEnabled && !tls) {
|
|
3352
|
+
this.log.warn(`SSL is enabled but the certificate or key isn't found (${this.sslCertPath ?? 'no cert'}, ${this.sslKeyPath ?? 'no key'}); serving HTTP`);
|
|
3353
|
+
}
|
|
3354
|
+
const listenUrl = `${tls ? 'https' : 'http'}://${host}:${port}${this.route}`;
|
|
2279
3355
|
this.log.info(`Agent '${this.name}' running at ${listenUrl}`);
|
|
2280
3356
|
this.log.info(`Auth: ${this.basicAuthCreds[0]}:**** (source: ${this.basicAuthSource})`);
|
|
2281
3357
|
if (this._proxyUrlBase) {
|
|
2282
3358
|
this.log.info(`Proxy URL: ${redactUrl(this._proxyUrlBase)}`);
|
|
2283
3359
|
}
|
|
2284
|
-
|
|
3360
|
+
if (tls) {
|
|
3361
|
+
const { readFileSync } = await import('node:fs');
|
|
3362
|
+
const { createServer } = await import('node:https');
|
|
3363
|
+
const { getRequestListener } = await import('@hono/node-server');
|
|
3364
|
+
const server = createServer({
|
|
3365
|
+
cert: readFileSync(this.sslCertPath, 'utf-8'),
|
|
3366
|
+
key: readFileSync(this.sslKeyPath, 'utf-8'),
|
|
3367
|
+
}, getRequestListener(app.fetch));
|
|
3368
|
+
server.listen(port, host);
|
|
3369
|
+
this._server = server;
|
|
3370
|
+
}
|
|
3371
|
+
else {
|
|
3372
|
+
const { serve: honoServe } = await import('@hono/node-server');
|
|
3373
|
+
this._server = honoServe({
|
|
3374
|
+
fetch: app.fetch,
|
|
3375
|
+
port,
|
|
3376
|
+
hostname: host,
|
|
3377
|
+
});
|
|
3378
|
+
}
|
|
2285
3379
|
}
|
|
2286
3380
|
/**
|
|
2287
|
-
*
|
|
2288
|
-
*
|
|
2289
|
-
*
|
|
3381
|
+
* Smart entry point matching Python's `WebMixin.run()`: auto-detects the
|
|
3382
|
+
* execution environment and dispatches accordingly. When a serverless event
|
|
3383
|
+
* is supplied, or a serverless platform is detected from the environment
|
|
3384
|
+
* (`AWS_LAMBDA_FUNCTION_NAME`/`_HANDLER`, `FUNCTION_TARGET`,
|
|
3385
|
+
* `FUNCTIONS_WORKER_RUNTIME`, `GATEWAY_INTERFACE`), it dispatches to
|
|
3386
|
+
* {@link runServerless}; otherwise it starts the HTTP server via {@link serve}.
|
|
3387
|
+
* Cloud Run sets `K_SERVICE` but not `FUNCTION_TARGET`, so there it serves.
|
|
3388
|
+
*
|
|
3389
|
+
* For deterministic behavior, call {@link serve} (server) or
|
|
3390
|
+
* {@link runServerless} (serverless) directly.
|
|
3391
|
+
*
|
|
3392
|
+
* @param opts - Either server host/port overrides, or a serverless
|
|
3393
|
+
* `{ event, context, platform }` payload.
|
|
3394
|
+
* @returns `void` for server mode, or the serverless response object.
|
|
2290
3395
|
*/
|
|
2291
3396
|
async run(opts) {
|
|
3397
|
+
// Loaded by swaig-test: only the configuration is needed, never a request.
|
|
3398
|
+
if (process.env['SWAIG_CLI_MODE'] === 'true')
|
|
3399
|
+
return;
|
|
3400
|
+
const serverlessEnv = !!process.env['AWS_LAMBDA_FUNCTION_NAME'] ||
|
|
3401
|
+
!!process.env['_HANDLER'] ||
|
|
3402
|
+
// The Functions Framework sets FUNCTION_TARGET; K_SERVICE alone is Cloud
|
|
3403
|
+
// Run (or Cloud Shell), where the agent serves HTTP itself.
|
|
3404
|
+
!!process.env['FUNCTION_TARGET'] ||
|
|
3405
|
+
!!process.env['FUNCTIONS_WORKER_RUNTIME'] ||
|
|
3406
|
+
!!process.env['GATEWAY_INTERFACE'];
|
|
3407
|
+
if (opts?.event !== undefined || serverlessEnv) {
|
|
3408
|
+
return this.runServerless(opts?.event ?? {}, opts?.context, opts?.platform);
|
|
3409
|
+
}
|
|
2292
3410
|
return this.serve(opts);
|
|
2293
3411
|
}
|
|
2294
3412
|
/**
|
|
@@ -2296,8 +3414,8 @@ export class AgentBase {
|
|
|
2296
3414
|
*
|
|
2297
3415
|
* Matches Python `run(event, context)` when executed in a serverless environment. Python's
|
|
2298
3416
|
* `run()` auto-detects the platform via `get_execution_mode()` and dispatches accordingly;
|
|
2299
|
-
*
|
|
2300
|
-
*
|
|
3417
|
+
* `runServerless` is the **explicit** serverless path so callers can opt in deliberately
|
|
3418
|
+
* (the polymorphic {@link run} dispatches here when a serverless env/event is detected).
|
|
2301
3419
|
*
|
|
2302
3420
|
* Platform detection follows the same environment-variable heuristics as Python's
|
|
2303
3421
|
* `ServerlessMixin`: `AWS_LAMBDA_FUNCTION_NAME` → Lambda, `K_SERVICE` → GCF,
|
|
@@ -2318,8 +3436,16 @@ export class AgentBase {
|
|
|
2318
3436
|
const adapter = new ServerlessAdapter(platform ?? 'auto');
|
|
2319
3437
|
const app = this.getApp();
|
|
2320
3438
|
// Wrap Hono's fetch (which returns `Response | Promise<Response>`) into a plain
|
|
2321
|
-
// `Promise<Response
|
|
2322
|
-
|
|
3439
|
+
// `Promise<Response>`. The adapter passes an `env` carrying the URL the
|
|
3440
|
+
// platform was called on, for the webhook signature check; forward it.
|
|
3441
|
+
const fetchFn = (req, env) => Promise.resolve(app.fetch(req, env));
|
|
3442
|
+
// CGI has no event object — the request lives in the environment + stdin.
|
|
3443
|
+
// When dispatched in CGI mode with no explicit event, read the request from
|
|
3444
|
+
// the CGI environment and stdin, and write the CGI response to stdout, as a
|
|
3445
|
+
// CGI program must (mirrors Python serverless_mixin CGI mode).
|
|
3446
|
+
if (adapter.getPlatform() === 'cgi' && (event == null || Object.keys(event).length === 0)) {
|
|
3447
|
+
return adapter._runCgi({ fetch: fetchFn }, process.env);
|
|
3448
|
+
}
|
|
2323
3449
|
return adapter.handleRequest({ fetch: fetchFn }, event);
|
|
2324
3450
|
}
|
|
2325
3451
|
// ── Graceful shutdown ─────────────────────────────────────────────
|