@signalwire/sdk 2.0.5 → 3.6.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 +821 -0
- package/LICENSE +21 -0
- package/README.md +163 -68
- package/dist/AGENTS.md +13 -0
- package/dist/AgentBase.d.ts +510 -126
- package/dist/AgentBase.js +1581 -455
- 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 +186 -45
- package/dist/DataMap.js +210 -52
- package/dist/DataMap.js.map +1 -1
- package/dist/FunctionResult.d.ts +309 -83
- package/dist/FunctionResult.js +483 -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 +12 -1
- package/dist/POM/PromptObjectModel.js +25 -9
- package/dist/POM/PromptObjectModel.js.map +1 -1
- 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 +18 -0
- package/dist/PomBuilder.js +53 -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 +22 -1
- package/dist/PromptManager.js +28 -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 +169 -59
- package/dist/SWMLService.js +456 -129
- 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 +49 -9
- package/dist/SecurityUtils.js +153 -51
- package/dist/SecurityUtils.js.map +1 -1
- package/dist/SemanticGate.d.ts +183 -0
- package/dist/SemanticGate.js +533 -0
- package/dist/SemanticGate.js.map +1 -0
- 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 +139 -7
- package/dist/SwaigFunction.js +170 -22
- 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 +92 -33
- 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 -371
- 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 +920 -0
- package/dist/cli/tsdocs/topics.js.map +1 -0
- package/dist/index.d.ts +49 -68
- package/dist/index.js +45 -73
- 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 +44 -17
- package/dist/relay/RelayClient.js +175 -65
- 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 +73 -42
- 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 +5 -2
- package/dist/rest/callHandler.js +4 -1
- package/dist/rest/callHandler.js.map +1 -1
- package/dist/rest/index.d.ts +18 -77
- package/dist/rest/index.js +47 -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 -327
- package/dist/rest/namespaces/fabric.js +14 -439
- 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 +8 -196
- package/dist/rest/namespaces/phone-numbers.js +8 -230
- 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 +111 -21
- 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 +22 -11
- package/dist/skills/SkillRegistry.js +47 -17
- 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 +18 -6
- 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 +21 -22
- 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 +42 -4
- package/dist/skills/builtin/spider.js +277 -104
- 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 +38 -30
- 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 +294 -100
- 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 +14 -13
- 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 +59 -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 +3641 -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 +1207 -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 +1986 -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 +85 -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,24 +4,200 @@
|
|
|
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';
|
|
14
17
|
import { SWMLService } from './SWMLService.js';
|
|
15
18
|
import { ConfigLoader } from './ConfigLoader.js';
|
|
16
|
-
import { SwaigFunction } from './SwaigFunction.js';
|
|
19
|
+
import { SwaigFunction, normalizeParameters, } from './SwaigFunction.js';
|
|
20
|
+
import { _checkGatedFunction } from './SemanticGate.js';
|
|
17
21
|
import { inferSchema, createTypedHandlerWrapper } from './TypeInference.js';
|
|
18
22
|
import { FunctionResult } from './FunctionResult.js';
|
|
19
|
-
import { ContextBuilder } from './ContextBuilder.js';
|
|
20
|
-
import { getLogger, suppressAllLogs } from './Logger.js';
|
|
21
|
-
import { safeAssign, filterSensitiveHeaders, redactUrl, isValidHostname } from './SecurityUtils.js';
|
|
23
|
+
import { Context as ConversationContext, ContextBuilder, GatherInfo, GatherQuestion, Step, } from './ContextBuilder.js';
|
|
24
|
+
import { getExecutionMode, getLogger, suppressAllLogs } from './Logger.js';
|
|
25
|
+
import { safeAssign, filterSensitiveHeaders, redactUrl, isValidHostname, corsOriginsFromEnv, } from './SecurityUtils.js';
|
|
22
26
|
import { SkillManager } from './skills/SkillManager.js';
|
|
23
27
|
import { SkillRegistry } from './skills/SkillRegistry.js';
|
|
24
|
-
import { ServerlessAdapter } from './ServerlessAdapter.js';
|
|
28
|
+
import { ServerlessAdapter, } from './ServerlessAdapter.js';
|
|
29
|
+
import { webhookValidationMiddleware } from './WebhookMiddleware.js';
|
|
30
|
+
import { _CLIENT_ADDRESS_ENV_KEY, _PLATFORM_BASE_ENV_KEY } from './ServerlessAdapter.js';
|
|
31
|
+
/** A URL's query parameters as a plain object (the last value of a repeated key wins). */
|
|
32
|
+
function queryParamsOf(url) {
|
|
33
|
+
const params = {};
|
|
34
|
+
try {
|
|
35
|
+
new URL(url, 'http://localhost').searchParams.forEach((v, k) => {
|
|
36
|
+
params[k] = v;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
/* not a URL: no query params */
|
|
41
|
+
}
|
|
42
|
+
return params;
|
|
43
|
+
}
|
|
44
|
+
/** A Hono request's headers as a plain object with lower-case names. */
|
|
45
|
+
function headersOf(c) {
|
|
46
|
+
const headers = {};
|
|
47
|
+
c.req.raw.headers.forEach((v, k) => {
|
|
48
|
+
headers[k] = v;
|
|
49
|
+
});
|
|
50
|
+
return headers;
|
|
51
|
+
}
|
|
52
|
+
/** The Hono context of the served request being handled, for onSwmlRequest. */
|
|
53
|
+
const servedRequestContext = new AsyncLocalStorage();
|
|
54
|
+
/** Compare two strings in constant time, whatever their lengths. */
|
|
55
|
+
function constantTimeEqual(a, b) {
|
|
56
|
+
const digest = (v) => createHash('sha256').update(v, 'utf8').digest();
|
|
57
|
+
return timingSafeEqual(digest(a), digest(b));
|
|
58
|
+
}
|
|
59
|
+
/** SDK classes whose instances a per-request copy duplicates field by field. */
|
|
60
|
+
const CLONEABLE_CLASSES = new Set([
|
|
61
|
+
// A tool: its settings are copied, its handler (a function) is shared, so a
|
|
62
|
+
// callback that changes a tool changes it for that request only.
|
|
63
|
+
SwaigFunction,
|
|
64
|
+
ContextBuilder,
|
|
65
|
+
ConversationContext,
|
|
66
|
+
Step,
|
|
67
|
+
GatherInfo,
|
|
68
|
+
GatherQuestion,
|
|
69
|
+
]);
|
|
70
|
+
/**
|
|
71
|
+
* Deep-copy agent configuration for a per-request copy. Arrays, Maps, Sets,
|
|
72
|
+
* Dates, plain objects and the contexts classes (a ContextBuilder and its
|
|
73
|
+
* contexts, steps and gather questions) are copied. Anything else (a URL, a
|
|
74
|
+
* RegExp, a class with private fields, a function) is shared as is: it can't
|
|
75
|
+
* be rebuilt field by field, since its state lives in internal slots.
|
|
76
|
+
* `memo` maps originals to their copies, so shared references stay shared
|
|
77
|
+
* and a reference to the agent can be redirected to the copy.
|
|
78
|
+
*/
|
|
79
|
+
function deepCloneState(value, memo) {
|
|
80
|
+
if (value === null || typeof value !== 'object')
|
|
81
|
+
return value;
|
|
82
|
+
const obj = value;
|
|
83
|
+
if (memo.has(obj))
|
|
84
|
+
return memo.get(obj);
|
|
85
|
+
if (obj instanceof Date)
|
|
86
|
+
return new Date(obj.getTime());
|
|
87
|
+
if (Array.isArray(obj)) {
|
|
88
|
+
const out = [];
|
|
89
|
+
memo.set(obj, out);
|
|
90
|
+
for (const item of obj)
|
|
91
|
+
out.push(deepCloneState(item, memo));
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
if (obj instanceof Map) {
|
|
95
|
+
const out = new Map();
|
|
96
|
+
memo.set(obj, out);
|
|
97
|
+
for (const [k, v] of obj)
|
|
98
|
+
out.set(deepCloneState(k, memo), deepCloneState(v, memo));
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
if (obj instanceof Set) {
|
|
102
|
+
const out = new Set();
|
|
103
|
+
memo.set(obj, out);
|
|
104
|
+
for (const v of obj)
|
|
105
|
+
out.add(deepCloneState(v, memo));
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
const proto = Object.getPrototypeOf(obj);
|
|
109
|
+
const plain = proto === null || proto === Object.prototype;
|
|
110
|
+
if (!plain && !CLONEABLE_CLASSES.has(proto?.constructor))
|
|
111
|
+
return value;
|
|
112
|
+
const out = Object.create(proto);
|
|
113
|
+
memo.set(obj, out);
|
|
114
|
+
for (const key of Reflect.ownKeys(obj)) {
|
|
115
|
+
const desc = Object.getOwnPropertyDescriptor(obj, key);
|
|
116
|
+
if ('value' in desc)
|
|
117
|
+
desc.value = deepCloneState(desc.value, memo);
|
|
118
|
+
Object.defineProperty(out, key, desc);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* The base URL a serverless platform serves the function on, built from the
|
|
124
|
+
* platform's environment as the reference's `get_full_url` builds it, or null
|
|
125
|
+
* in server mode. `FUNCTION_URL` (Google Cloud) and `AZURE_FUNCTION_URL`,
|
|
126
|
+
* which swaig-test's platform flags set, are used when present.
|
|
127
|
+
*/
|
|
128
|
+
function serverlessBaseUrl() {
|
|
129
|
+
const env = process.env;
|
|
130
|
+
switch (getExecutionMode()) {
|
|
131
|
+
case 'cgi': {
|
|
132
|
+
const protocol = env['HTTPS'] === 'on' ? 'https' : 'http';
|
|
133
|
+
const host = env['HTTP_HOST'] || env['SERVER_NAME'] || 'localhost';
|
|
134
|
+
return `${protocol}://${host}${env['SCRIPT_NAME'] ?? ''}`.replace(/\/+$/, '');
|
|
135
|
+
}
|
|
136
|
+
case 'lambda': {
|
|
137
|
+
if (env['AWS_LAMBDA_FUNCTION_URL'])
|
|
138
|
+
return env['AWS_LAMBDA_FUNCTION_URL'].replace(/\/+$/, '');
|
|
139
|
+
const region = env['AWS_REGION'] || 'us-east-1';
|
|
140
|
+
const fn = env['AWS_LAMBDA_FUNCTION_NAME'] || 'unknown';
|
|
141
|
+
return `https://${fn}.lambda-url.${region}.on.aws`;
|
|
142
|
+
}
|
|
143
|
+
case 'google_cloud_function': {
|
|
144
|
+
if (env['FUNCTION_URL'])
|
|
145
|
+
return env['FUNCTION_URL'].replace(/\/+$/, '');
|
|
146
|
+
// K_SERVICE and GOOGLE_CLOUD_PROJECT are also set on Cloud Run and in
|
|
147
|
+
// Cloud Shell; the functions framework sets FUNCTION_TARGET.
|
|
148
|
+
if (!env['FUNCTION_TARGET'])
|
|
149
|
+
return null;
|
|
150
|
+
const project = env['GOOGLE_CLOUD_PROJECT'] || env['GCP_PROJECT'];
|
|
151
|
+
const region = env['FUNCTION_REGION'] || env['GOOGLE_CLOUD_REGION'] || 'us-central1';
|
|
152
|
+
const service = env['K_SERVICE'] || env['FUNCTION_TARGET'] || 'unknown';
|
|
153
|
+
return project
|
|
154
|
+
? `https://${region}-${project}.cloudfunctions.net/${service}`
|
|
155
|
+
: 'https://localhost:8080';
|
|
156
|
+
}
|
|
157
|
+
case 'azure_function': {
|
|
158
|
+
if (env['AZURE_FUNCTION_URL'])
|
|
159
|
+
return env['AZURE_FUNCTION_URL'].replace(/\/+$/, '');
|
|
160
|
+
const app = env['WEBSITE_SITE_NAME'] || env['AZURE_FUNCTIONS_APP_NAME'];
|
|
161
|
+
const fn = env['AZURE_FUNCTION_NAME'] || 'unknown';
|
|
162
|
+
return app
|
|
163
|
+
? `https://${app}.azurewebsites.net/api/${fn}`
|
|
164
|
+
: `https://localhost:7071/api/${fn}`;
|
|
165
|
+
}
|
|
166
|
+
default:
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** The agent's own routes in each app buildApp() makes, normalized. */
|
|
171
|
+
const AGENT_ROUTES = new WeakMap();
|
|
172
|
+
/**
|
|
173
|
+
* Whether the agent's own routes serve a request. HEAD counts as GET, and an
|
|
174
|
+
* OPTIONS preflight counts for a path the agent serves by any method.
|
|
175
|
+
*/
|
|
176
|
+
function ownsRoute(routes, method, path) {
|
|
177
|
+
const p = normalizePath(path);
|
|
178
|
+
const m = method.toUpperCase() === 'HEAD' ? 'GET' : method.toUpperCase();
|
|
179
|
+
if (m === 'OPTIONS')
|
|
180
|
+
return routes.paths.has(p);
|
|
181
|
+
return routes.byMethod.has(`${m} ${p}`) || routes.byMethod.has(`ALL ${p}`);
|
|
182
|
+
}
|
|
183
|
+
/** A path with repeated slashes collapsed and no trailing slash, as routing matches it. */
|
|
184
|
+
function normalizePath(path) {
|
|
185
|
+
return path.replace(/\/{2,}/g, '/').replace(/(.)\/$/, '$1') || '/';
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* A request path relative to where the app handling it is mounted: a
|
|
189
|
+
* middleware registered as `*` reports `routePath` `/agent/*` when its app is
|
|
190
|
+
* mounted at `/agent`, and `*` or `/*` at the root.
|
|
191
|
+
*/
|
|
192
|
+
function relativePath(path, routePath) {
|
|
193
|
+
const base = normalizePath(routePath.replace(/\/?\*$/, '') || '/');
|
|
194
|
+
const normalized = normalizePath(path);
|
|
195
|
+
if (base === '/')
|
|
196
|
+
return normalized;
|
|
197
|
+
if (normalized === base)
|
|
198
|
+
return '/';
|
|
199
|
+
return normalized.startsWith(`${base}/`) ? normalized.slice(base.length) : normalized;
|
|
200
|
+
}
|
|
25
201
|
/**
|
|
26
202
|
* Core agent class that composes an HTTP server, prompt management, session handling,
|
|
27
203
|
* SWAIG tool registry, and 5-phase SWML rendering into a single deployable unit.
|
|
@@ -106,6 +282,7 @@ export class AgentBase extends SWMLService {
|
|
|
106
282
|
// AI config
|
|
107
283
|
hints = [];
|
|
108
284
|
languages = [];
|
|
285
|
+
multilingual = {};
|
|
109
286
|
pronounce = [];
|
|
110
287
|
params = {};
|
|
111
288
|
globalData = {};
|
|
@@ -119,13 +296,22 @@ export class AgentBase extends SWMLService {
|
|
|
119
296
|
postAnswerVerbs = [];
|
|
120
297
|
postAiVerbs = [];
|
|
121
298
|
// Dynamic config
|
|
122
|
-
|
|
299
|
+
/** Per-request configuration callbacks, run in order on each request's copy. */
|
|
300
|
+
perCallConfigs = [];
|
|
301
|
+
/** Set once serve() runs an HTTP server; getFullUrl then ignores serverless environments. */
|
|
302
|
+
_serving = false;
|
|
303
|
+
/** Handlers registered with {@link onCallEnd}. */
|
|
304
|
+
callEndHandlers = [];
|
|
305
|
+
/** Apps and routers added with {@link mount}, replayed on every app build. */
|
|
306
|
+
mounts = [];
|
|
123
307
|
swaigQueryParams = {};
|
|
124
308
|
// Webhook URL overrides
|
|
125
309
|
webHookUrlOverride = null;
|
|
126
310
|
postPromptUrlOverride = null;
|
|
127
311
|
// Contexts
|
|
128
312
|
contextsBuilder = null;
|
|
313
|
+
/** Contexts given as a plain object, rendered as they are. */
|
|
314
|
+
_rawContexts = null;
|
|
129
315
|
// MCP
|
|
130
316
|
_mcpServers = [];
|
|
131
317
|
_mcpServerEnabled = false;
|
|
@@ -145,14 +331,48 @@ export class AgentBase extends SWMLService {
|
|
|
145
331
|
/** Structured logger instance for this agent. Override the inherited
|
|
146
332
|
* SWMLService logger with an AgentBase-tagged one. */
|
|
147
333
|
log = getLogger('AgentBase');
|
|
148
|
-
// Skills
|
|
149
|
-
|
|
334
|
+
// Skills. The manager takes `this` as its public back-reference (the
|
|
335
|
+
// reference's `SkillManager(agent)`); a field initializer runs after `super()`
|
|
336
|
+
// so `this` is already bound.
|
|
337
|
+
_skillManager = new SkillManager(this);
|
|
150
338
|
// New constructor params (P1 gaps)
|
|
151
339
|
_enablePostPromptOverride = false;
|
|
152
340
|
_checkForInputOverride = false;
|
|
153
341
|
_schemaValidation = true;
|
|
154
342
|
_configFile = null;
|
|
155
343
|
_schemaPath = null;
|
|
344
|
+
/**
|
|
345
|
+
* Resolved SignalWire Signing Key. Source of truth for the
|
|
346
|
+
* webhook-validation middleware mounted on POST /, /swaig, /post_prompt.
|
|
347
|
+
* Resolved from constructor opts, falling back to
|
|
348
|
+
* ``SIGNALWIRE_SIGNING_KEY``. When ``null``, signature validation is
|
|
349
|
+
* disabled.
|
|
350
|
+
*
|
|
351
|
+
* NEVER logged. NEVER serialized. Not included in any SWML/SWAIG render or
|
|
352
|
+
* state dump.
|
|
353
|
+
*
|
|
354
|
+
* READABLE, matching the reference's public `self.signing_key`
|
|
355
|
+
* (`core/agent_base.py:253`) and java's `getSigningKey()`. The value came FROM the
|
|
356
|
+
* caller (an explicit `signingKey` option or `SIGNALWIRE_SIGNING_KEY`), so a
|
|
357
|
+
* caller who supplied it must be able to read back which key the agent resolved —
|
|
358
|
+
* the same posture as `getBasicAuthCredentials()`, which already returns the auth
|
|
359
|
+
* secret. Withholding it hides configuration from its own owner without hiding it
|
|
360
|
+
* from anything else (the process already holds it).
|
|
361
|
+
*/
|
|
362
|
+
_signingKey = null;
|
|
363
|
+
/**
|
|
364
|
+
* The resolved SignalWire Signing Key, or `null` when signature validation is
|
|
365
|
+
* disabled — the reference's public `self.signing_key`.
|
|
366
|
+
*
|
|
367
|
+
* Read-only: the resolution order (explicit option → `SIGNALWIRE_SIGNING_KEY` →
|
|
368
|
+
* `null`) runs once at construction and the middleware is mounted against it, so a
|
|
369
|
+
* post-construction write would not take effect.
|
|
370
|
+
*/
|
|
371
|
+
get signingKey() {
|
|
372
|
+
return this._signingKey;
|
|
373
|
+
}
|
|
374
|
+
/** Whether to honor X-Forwarded-* headers when reconstructing the URL. */
|
|
375
|
+
_webhookTrustProxy = false;
|
|
156
376
|
// _routingCallbacks and _app are inherited from SWMLService.
|
|
157
377
|
// AgentBase rebuilds _app in getApp() with its own middleware stack and
|
|
158
378
|
// route handlers, overwriting the parent-init Hono instance. The flag
|
|
@@ -173,19 +393,18 @@ export class AgentBase extends SWMLService {
|
|
|
173
393
|
if (opts.configFile) {
|
|
174
394
|
try {
|
|
175
395
|
const loader = new ConfigLoader(opts.configFile);
|
|
176
|
-
serviceConfig =
|
|
396
|
+
serviceConfig = loader.get('service') ?? {};
|
|
177
397
|
}
|
|
178
398
|
catch {
|
|
179
399
|
// Config file not found or invalid — continue with constructor args
|
|
180
400
|
}
|
|
181
401
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
const
|
|
188
|
-
const resolvedHost = hostArg !== '0.0.0.0' ? hostArg : (serviceConfig['host'] ?? hostArg);
|
|
402
|
+
// Constructor arguments take precedence: the config file fills in only an
|
|
403
|
+
// argument the caller left out. `name` is required, so it always wins.
|
|
404
|
+
const resolvedName = opts.name;
|
|
405
|
+
const resolvedRoute = (opts.route ?? serviceConfig['route'] ?? '/').replace(/\/+$/, '') ||
|
|
406
|
+
'/';
|
|
407
|
+
const resolvedHost = opts.host ?? serviceConfig['host'] ?? '0.0.0.0';
|
|
189
408
|
const configPort = serviceConfig['port'];
|
|
190
409
|
const parsedPort = opts.port ?? configPort ?? parseInt(process.env['PORT'] ?? '3000', 10);
|
|
191
410
|
if (isNaN(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
|
|
@@ -216,45 +435,64 @@ export class AgentBase extends SWMLService {
|
|
|
216
435
|
this._checkForInputOverride = opts.checkForInputOverride ?? false;
|
|
217
436
|
this._schemaValidation = opts.schemaValidation ?? true;
|
|
218
437
|
this._schemaPath = opts.schemaPath ?? null;
|
|
438
|
+
// Before any warning below, so suppressLogs silences the constructor too.
|
|
219
439
|
if (opts.suppressLogs) {
|
|
220
440
|
suppressAllLogs(true);
|
|
221
441
|
}
|
|
222
|
-
|
|
223
|
-
|
|
442
|
+
// Webhook signing key: explicit option > SIGNALWIRE_SIGNING_KEY env > null.
|
|
443
|
+
// Per porting-sdk/webhooks.md: when null, validation is disabled and we
|
|
444
|
+
// log a prominent one-shot warning so operators don't ship an unsigned
|
|
445
|
+
// production agent by accident.
|
|
446
|
+
const explicitKey = typeof opts.signingKey === 'string' && opts.signingKey.length > 0 ? opts.signingKey : null;
|
|
447
|
+
const envKey = process.env['SIGNALWIRE_SIGNING_KEY'];
|
|
448
|
+
this._signingKey =
|
|
449
|
+
explicitKey ?? (typeof envKey === 'string' && envKey.length > 0 ? envKey : null);
|
|
450
|
+
this._webhookTrustProxy = opts.webhookTrustProxy ?? false;
|
|
451
|
+
if (this._signingKey === null) {
|
|
452
|
+
// Exact warning text mandated by porting-sdk/webhooks.md so all ports
|
|
453
|
+
// emit the same operator-facing message.
|
|
454
|
+
this.log.warn('[signalwire] webhook signature validation is disabled — set signingKey or SIGNALWIRE_SIGNING_KEY to enable');
|
|
455
|
+
}
|
|
456
|
+
this._promptManager = new PromptManager(opts.usePom ?? true, this);
|
|
457
|
+
// A shared secret (option, then SIGNALWIRE_SWAIG_SECRET) lets tokens minted
|
|
458
|
+
// by one process validate on another replica or after a restart.
|
|
459
|
+
this.sessionManager = new SessionManager(opts.tokenExpirySecs ?? 3600, opts.swaigSecret || process.env['SIGNALWIRE_SWAIG_SECRET'] || undefined);
|
|
224
460
|
// swmlBuilder is inherited from SWMLService (initialized via super()).
|
|
225
461
|
// Setup auth — populate the legacy basicAuthCreds/basicAuthSource
|
|
226
462
|
// mirrors so AgentBase callers that read them still work.
|
|
227
463
|
// SWMLService's authCredentials (set in super()) is the source of truth
|
|
228
464
|
// for HTTP-level enforcement.
|
|
465
|
+
// Resolution order: constructor > config file > environment > generated.
|
|
466
|
+
// SecurityConfig (built by SWMLService from the config file and the
|
|
467
|
+
// environment) applies the middle two and records which supplied it.
|
|
468
|
+
const configured = opts.basicAuth ? null : this.security.getBasicAuth();
|
|
229
469
|
if (opts.basicAuth) {
|
|
230
470
|
this.basicAuthCreds = opts.basicAuth;
|
|
231
471
|
this.basicAuthSource = 'provided';
|
|
232
472
|
}
|
|
473
|
+
else if (configured) {
|
|
474
|
+
this.basicAuthCreds = configured;
|
|
475
|
+
this.basicAuthSource = this.security.basicAuthSource ?? 'environment';
|
|
476
|
+
}
|
|
233
477
|
else {
|
|
234
478
|
const envUser = process.env['SWML_BASIC_AUTH_USER'];
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
this
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
`password that exists only in this process; external callers will ` +
|
|
253
|
-
`get HTTP 401 unless they read the value from this process's env. ` +
|
|
254
|
-
`To fix, set SWML_BASIC_AUTH_USER and SWML_BASIC_AUTH_PASSWORD in ` +
|
|
255
|
-
`your .env, or pass { basicAuth: [user, pass] } to the agent ` +
|
|
256
|
-
`constructor.`);
|
|
257
|
-
}
|
|
479
|
+
// No password in the config file or SWML_BASIC_AUTH_PASSWORD, and
|
|
480
|
+
// the caller did not pass basicAuth. Fall back to a random
|
|
481
|
+
// password that exists only in this process; warn loudly so
|
|
482
|
+
// external callers (tests, RPC clients, MCP) know why they are
|
|
483
|
+
// getting HTTP 401.
|
|
484
|
+
const username = envUser || this.name;
|
|
485
|
+
this.basicAuthCreds = [username, randomBytes(16).toString('hex')];
|
|
486
|
+
this.basicAuthSource = 'generated';
|
|
487
|
+
this.log.warn(`basic_auth_password_autogenerated: username="${username}". ` +
|
|
488
|
+
`No SWML_BASIC_AUTH_PASSWORD found in environment and no basicAuth ` +
|
|
489
|
+
`passed to the agent constructor. The SDK generated a random ` +
|
|
490
|
+
`password that exists only in this process; external callers will ` +
|
|
491
|
+
`get HTTP 401 unless this process hands it to them ` +
|
|
492
|
+
`(getBasicAuthCredentials()). ` +
|
|
493
|
+
`To fix, set SWML_BASIC_AUTH_USER and SWML_BASIC_AUTH_PASSWORD in ` +
|
|
494
|
+
`your .env, or pass { basicAuth: [user, pass] } to the agent ` +
|
|
495
|
+
`constructor.`);
|
|
258
496
|
}
|
|
259
497
|
// Apply static PROMPT_SECTIONS from the class if defined
|
|
260
498
|
const ctor = this.constructor;
|
|
@@ -269,14 +507,55 @@ export class AgentBase extends SWMLService {
|
|
|
269
507
|
* Each entry is applied via promptAddSection() in the constructor.
|
|
270
508
|
*/
|
|
271
509
|
static PROMPT_SECTIONS;
|
|
510
|
+
/** Guards {@link ensureToolsDefined} so `defineTools()` runs at most once. */
|
|
511
|
+
_toolsDefined = false;
|
|
272
512
|
/**
|
|
273
|
-
* Lifecycle
|
|
274
|
-
*
|
|
275
|
-
*
|
|
513
|
+
* Lifecycle hook for subclasses to register their SWAIG tools. Override it
|
|
514
|
+
* and call `this.defineTool(...)` inside.
|
|
515
|
+
*
|
|
516
|
+
* You do **not** need to call this yourself — the base class invokes it
|
|
517
|
+
* automatically (exactly once) the first time tools are needed: on
|
|
518
|
+
* {@link renderSwml}, {@link getTools}, {@link serve}/{@link run}, or SWAIG
|
|
519
|
+
* dispatch. It runs lazily rather than from the base constructor because in
|
|
520
|
+
* JS/TS `super()` runs *before* a subclass's field initializers, so a
|
|
521
|
+
* base-constructor call would see `undefined` fields. Deferring to first use
|
|
522
|
+
* guarantees all subclass fields are initialized.
|
|
523
|
+
*
|
|
524
|
+
* Calling `this.defineTools()` manually (the old convention) still works and
|
|
525
|
+
* is safe — the call is idempotent, so it will not double-register tools.
|
|
276
526
|
*/
|
|
277
527
|
defineTools() {
|
|
278
528
|
// Default no-op — subclasses override
|
|
279
529
|
}
|
|
530
|
+
/**
|
|
531
|
+
* Run {@link defineTools} exactly once. Idempotent: safe to call from any
|
|
532
|
+
* tool-consumption entry point and from a subclass constructor. This is how
|
|
533
|
+
* `defineTools()` gets auto-invoked without falling into the JS field-init
|
|
534
|
+
* ordering trap (see {@link defineTools}).
|
|
535
|
+
*/
|
|
536
|
+
ensureToolsDefined() {
|
|
537
|
+
if (this._toolsDefined)
|
|
538
|
+
return;
|
|
539
|
+
this._toolsDefined = true;
|
|
540
|
+
this.defineTools();
|
|
541
|
+
}
|
|
542
|
+
/** Agent-level SWAIG error hook; see {@link onError}. */
|
|
543
|
+
_onError;
|
|
544
|
+
/**
|
|
545
|
+
* Register an agent-level error hook invoked when any SWAIG tool handler
|
|
546
|
+
* throws. It runs after a tool's own `onError` (if any) and lets you report
|
|
547
|
+
* failures (Sentry/Datadog/logging) and optionally control the user-facing
|
|
548
|
+
* response — return a {@link FunctionResult} to override it, or nothing to
|
|
549
|
+
* fall back to the default message. The error is always contained, so a
|
|
550
|
+
* thrown handler never breaks the live call.
|
|
551
|
+
*
|
|
552
|
+
* @param handler - The error hook, or `undefined` to clear it.
|
|
553
|
+
* @returns `this`, for chaining.
|
|
554
|
+
*/
|
|
555
|
+
onError(handler) {
|
|
556
|
+
this._onError = handler;
|
|
557
|
+
return this;
|
|
558
|
+
}
|
|
280
559
|
/**
|
|
281
560
|
* Public access to the list of registered tools.
|
|
282
561
|
*
|
|
@@ -286,6 +565,7 @@ export class AgentBase extends SWMLService {
|
|
|
286
565
|
* @returns Array of all registered SwaigFunction instances.
|
|
287
566
|
*/
|
|
288
567
|
getTools() {
|
|
568
|
+
this.ensureToolsDefined();
|
|
289
569
|
const tools = [];
|
|
290
570
|
for (const [, fn] of this.toolRegistry) {
|
|
291
571
|
if (fn instanceof SwaigFunction)
|
|
@@ -306,7 +586,7 @@ export class AgentBase extends SWMLService {
|
|
|
306
586
|
/**
|
|
307
587
|
* Public accessor for the agent's POM as a {@link PromptObjectModel} instance.
|
|
308
588
|
*
|
|
309
|
-
* Python
|
|
589
|
+
* Python equivalent: ``agent.pom`` instance attribute (agent_base.py line 209)
|
|
310
590
|
* is a ``signalwire.pom.pom.PromptObjectModel`` when ``use_pom=True``,
|
|
311
591
|
* or ``None`` otherwise. This getter returns the equivalent TypeScript
|
|
312
592
|
* ``PromptObjectModel`` instance — callers can use ``addSection``,
|
|
@@ -484,17 +764,20 @@ export class AgentBase extends SWMLService {
|
|
|
484
764
|
}
|
|
485
765
|
return this;
|
|
486
766
|
}
|
|
487
|
-
// ── Contexts ────────────────────────────────────────────────────────
|
|
488
|
-
/**
|
|
489
|
-
* Define or replace the contexts configuration for the AI verb.
|
|
490
|
-
* @param contexts - An existing ContextBuilder instance or a plain object; a new ContextBuilder is created if omitted.
|
|
491
|
-
* @returns The active ContextBuilder for further configuration.
|
|
492
|
-
*/
|
|
493
767
|
defineContexts(contexts) {
|
|
768
|
+
if (contexts !== undefined && !(contexts instanceof ContextBuilder)) {
|
|
769
|
+
if (contexts === null || typeof contexts !== 'object' || Array.isArray(contexts)) {
|
|
770
|
+
throw new TypeError('contexts must be an object or a ContextBuilder');
|
|
771
|
+
}
|
|
772
|
+
this._rawContexts = contexts;
|
|
773
|
+
this.contextsBuilder = null;
|
|
774
|
+
return this;
|
|
775
|
+
}
|
|
776
|
+
this._rawContexts = null;
|
|
494
777
|
if (contexts instanceof ContextBuilder) {
|
|
495
778
|
this.contextsBuilder = contexts;
|
|
496
779
|
}
|
|
497
|
-
else {
|
|
780
|
+
else if (!this.contextsBuilder) {
|
|
498
781
|
this.contextsBuilder = new ContextBuilder();
|
|
499
782
|
}
|
|
500
783
|
// Attach agent reference so ContextBuilder.validate() can check
|
|
@@ -515,6 +798,7 @@ export class AgentBase extends SWMLService {
|
|
|
515
798
|
if (this.contextsBuilder) {
|
|
516
799
|
this.contextsBuilder.reset();
|
|
517
800
|
}
|
|
801
|
+
this._rawContexts = null;
|
|
518
802
|
return this;
|
|
519
803
|
}
|
|
520
804
|
/**
|
|
@@ -528,7 +812,7 @@ export class AgentBase extends SWMLService {
|
|
|
528
812
|
*/
|
|
529
813
|
getContexts() {
|
|
530
814
|
if (!this.contextsBuilder)
|
|
531
|
-
return
|
|
815
|
+
return this._rawContexts;
|
|
532
816
|
return this.contextsBuilder.toDict();
|
|
533
817
|
}
|
|
534
818
|
// ── AI config methods ───────────────────────────────────────────────
|
|
@@ -570,6 +854,10 @@ export class AgentBase extends SWMLService {
|
|
|
570
854
|
/**
|
|
571
855
|
* Add a supported language to the AI configuration.
|
|
572
856
|
* @param config - Language configuration including name, code, voice, and optional fillers.
|
|
857
|
+
* `params` may be set to attach engine-specific tuning (voice stability,
|
|
858
|
+
* similarity boost, model knobs, etc.); only emitted into SWML when
|
|
859
|
+
* non-empty so existing entries stay byte-identical when no params are
|
|
860
|
+
* passed (Python ai_config_mixin.py `add_language`).
|
|
573
861
|
* @returns This agent instance for chaining.
|
|
574
862
|
*/
|
|
575
863
|
addLanguage(config) {
|
|
@@ -581,12 +869,39 @@ export class AgentBase extends SWMLService {
|
|
|
581
869
|
lang['voice'] = config.voice;
|
|
582
870
|
if (config.engine)
|
|
583
871
|
lang['engine'] = config.engine;
|
|
584
|
-
if (config.
|
|
585
|
-
lang['
|
|
872
|
+
if (config.model)
|
|
873
|
+
lang['model'] = config.model;
|
|
874
|
+
// Fillers as the reference emits them: speech_fillers and function_fillers
|
|
875
|
+
// when both are given, and one given alone as the older `fillers` list.
|
|
876
|
+
// The object forms this SDK once took are flattened into lists.
|
|
877
|
+
const flatten = (value) => {
|
|
878
|
+
if (Array.isArray(value))
|
|
879
|
+
return value.filter((v) => typeof v === 'string');
|
|
880
|
+
if (value && typeof value === 'object')
|
|
881
|
+
return Object.values(value).flatMap(flatten);
|
|
882
|
+
return [];
|
|
883
|
+
};
|
|
884
|
+
const legacyFillers = config.fillers && !Array.isArray(config.fillers);
|
|
885
|
+
const speech = config.speechFillers ?? (config.fillers ? flatten(config.fillers) : undefined);
|
|
886
|
+
const fn = config.functionFillers ? flatten(config.functionFillers) : undefined;
|
|
887
|
+
if (legacyFillers || (config.functionFillers && !Array.isArray(config.functionFillers))) {
|
|
888
|
+
this.log.warn('addLanguage(): fillers keyed by category, and functionFillers keyed by function, are ' +
|
|
889
|
+
'flattened into lists; pass speechFillers and functionFillers as string arrays');
|
|
890
|
+
}
|
|
891
|
+
if (speech?.length && fn?.length) {
|
|
892
|
+
lang['speech_fillers'] = speech;
|
|
893
|
+
lang['function_fillers'] = fn;
|
|
894
|
+
}
|
|
895
|
+
else if (speech?.length || fn?.length) {
|
|
896
|
+
lang['fillers'] = speech?.length ? speech : fn;
|
|
897
|
+
}
|
|
586
898
|
if (config.speechModel)
|
|
587
899
|
lang['speech_model'] = config.speechModel;
|
|
588
|
-
|
|
589
|
-
|
|
900
|
+
// Per-language params — only emit the key when non-empty (Python equivalent:
|
|
901
|
+
// `if params: language["params"] = params`).
|
|
902
|
+
if (config.params && Object.keys(config.params).length > 0) {
|
|
903
|
+
lang['params'] = config.params;
|
|
904
|
+
}
|
|
590
905
|
this.languages.push(lang);
|
|
591
906
|
return this;
|
|
592
907
|
}
|
|
@@ -601,6 +916,69 @@ export class AgentBase extends SWMLService {
|
|
|
601
916
|
this.addLanguage(l);
|
|
602
917
|
return this;
|
|
603
918
|
}
|
|
919
|
+
/**
|
|
920
|
+
* Configure ASR-driven multilingual mode (Mode B).
|
|
921
|
+
*
|
|
922
|
+
* Emits a top-level `multilingual` object on the AI verb. The recognizer runs
|
|
923
|
+
* in code-switching mode and the agent answers in whatever language the caller
|
|
924
|
+
* actually spoke — the model does not pick the language. Mutually exclusive
|
|
925
|
+
* with {@link setLanguages}; if both are set the server uses `multilingual` and
|
|
926
|
+
* ignores `languages`.
|
|
927
|
+
*
|
|
928
|
+
* @param config - The multilingual config object (languages, allowed,
|
|
929
|
+
* start_language, min_switch_words, fillers, etc.).
|
|
930
|
+
* @returns This agent instance for chaining.
|
|
931
|
+
*/
|
|
932
|
+
setMultilingual(config) {
|
|
933
|
+
if (config && typeof config === 'object') {
|
|
934
|
+
this.multilingual = config;
|
|
935
|
+
}
|
|
936
|
+
return this;
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* Set (or replace) the per-language `params` dict on an already-added
|
|
940
|
+
* language. Useful when language entries are built up via {@link addLanguage}
|
|
941
|
+
* first and engine-specific tuning is added later (e.g., from a config
|
|
942
|
+
* loader).
|
|
943
|
+
*
|
|
944
|
+
* Python equivalent: `set_language_params(code, params)`. Passing an empty
|
|
945
|
+
* object removes the `params` key entirely. Unknown codes are a no-op.
|
|
946
|
+
*
|
|
947
|
+
* @param code - Language code as previously passed to {@link addLanguage} (e.g. `"en-US"`).
|
|
948
|
+
* @param params - Engine-specific params dict to attach. Empty object removes the key.
|
|
949
|
+
* @returns This agent instance for chaining.
|
|
950
|
+
*/
|
|
951
|
+
setLanguageParams(code, params) {
|
|
952
|
+
for (const language of this.languages) {
|
|
953
|
+
if (language['code'] === code) {
|
|
954
|
+
if (params && Object.keys(params).length > 0) {
|
|
955
|
+
language['params'] = params;
|
|
956
|
+
}
|
|
957
|
+
else {
|
|
958
|
+
delete language['params'];
|
|
959
|
+
}
|
|
960
|
+
break;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return this;
|
|
964
|
+
}
|
|
965
|
+
/**
|
|
966
|
+
* Read the per-language `params` dict for a previously-added language.
|
|
967
|
+
*
|
|
968
|
+
* Python equivalent: `get_language_params(code)`. Returns `undefined` if the
|
|
969
|
+
* code is unknown or the language has no params set — no exception path.
|
|
970
|
+
*
|
|
971
|
+
* @param code - Language code as previously passed to {@link addLanguage}.
|
|
972
|
+
* @returns The params dict if set, `undefined` otherwise (including when the code is unknown).
|
|
973
|
+
*/
|
|
974
|
+
getLanguageParams(code) {
|
|
975
|
+
for (const language of this.languages) {
|
|
976
|
+
if (language['code'] === code) {
|
|
977
|
+
return language['params'];
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
return undefined;
|
|
981
|
+
}
|
|
604
982
|
/**
|
|
605
983
|
* Add a pronunciation override rule for the TTS engine.
|
|
606
984
|
* @param rule - Pronunciation rule specifying the text to replace and its substitute.
|
|
@@ -645,31 +1023,107 @@ export class AgentBase extends SWMLService {
|
|
|
645
1023
|
return this;
|
|
646
1024
|
}
|
|
647
1025
|
/**
|
|
648
|
-
*
|
|
649
|
-
*
|
|
650
|
-
*
|
|
651
|
-
*
|
|
652
|
-
*
|
|
1026
|
+
* Set how the call checks its functions' semantic gates (see
|
|
1027
|
+
* {@link SemanticGate}).
|
|
1028
|
+
*
|
|
1029
|
+
* Each option left out leaves its current setting as it is; the platform's
|
|
1030
|
+
* default applies to a setting that was never set.
|
|
1031
|
+
* @param opts - The gate settings.
|
|
1032
|
+
* @param opts.enabled - `false` dispatches gated functions without checking
|
|
1033
|
+
* their gates. Default `true`. Sent as `semantic_gates_enabled`.
|
|
1034
|
+
* @param opts.timeoutMs - The time one check may take, 500 to 10000
|
|
1035
|
+
* milliseconds, preparing the request and any retry included. A check that
|
|
1036
|
+
* runs out blocks the call. Default 2500. Sent as
|
|
1037
|
+
* `semantic_gate_timeout_ms`.
|
|
1038
|
+
* @param opts.history - How many recent dialogue entries the decision model
|
|
1039
|
+
* sees, 0 to 100. Default 20. Sent as `semantic_gate_history`.
|
|
1040
|
+
* @returns This agent instance for chaining.
|
|
1041
|
+
* @throws {Error} When a value has the wrong type or is out of range.
|
|
1042
|
+
*/
|
|
1043
|
+
setSemanticGates(opts = {}) {
|
|
1044
|
+
// Check every value before setting any, so a refused call changes nothing
|
|
1045
|
+
const { enabled, timeoutMs, history } = opts;
|
|
1046
|
+
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
|
1047
|
+
throw new Error(`enabled must be a boolean, got ${JSON.stringify(enabled)}`);
|
|
1048
|
+
}
|
|
1049
|
+
const ranges = [
|
|
1050
|
+
['semantic_gate_timeout_ms', 'timeout_ms', timeoutMs, 500, 10000],
|
|
1051
|
+
['semantic_gate_history', 'history', history, 0, 100],
|
|
1052
|
+
];
|
|
1053
|
+
for (const [, name, value, low, high] of ranges) {
|
|
1054
|
+
if (value === undefined)
|
|
1055
|
+
continue;
|
|
1056
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < low || value > high) {
|
|
1057
|
+
throw new Error(`${name} must be an integer from ${low} to ${high}, got ${JSON.stringify(value)}`);
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
if (enabled !== undefined)
|
|
1061
|
+
this.params['semantic_gates_enabled'] = enabled;
|
|
1062
|
+
for (const [param, , value] of ranges) {
|
|
1063
|
+
if (value !== undefined)
|
|
1064
|
+
this.params[param] = value;
|
|
1065
|
+
}
|
|
1066
|
+
return this;
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* **MERGES** `data` into the global_data object passed into the AI
|
|
1070
|
+
* configuration. **Despite the name, this does NOT replace** the existing
|
|
1071
|
+
* object — existing keys are preserved and incoming keys overwrite only on
|
|
1072
|
+
* collision (it calls `.update()`-style merge, matching Python
|
|
1073
|
+
* `set_global_data`). This is intentional: skills and other callers each
|
|
1074
|
+
* contribute keys via {@link updateGlobalData}, and a replacing
|
|
1075
|
+
* `setGlobalData` would silently clobber their contributions.
|
|
653
1076
|
*
|
|
654
|
-
*
|
|
655
|
-
*
|
|
1077
|
+
* - To **add/override** keys while keeping the rest: this method or the
|
|
1078
|
+
* identical {@link updateGlobalData}.
|
|
1079
|
+
* - To **fully replace** global_data (clearing every prior key, including
|
|
1080
|
+
* skill-contributed ones): use {@link replaceGlobalData}.
|
|
656
1081
|
*
|
|
657
1082
|
* @param data - Key-value pairs to merge into global data.
|
|
658
1083
|
* @returns This agent instance for chaining.
|
|
1084
|
+
* @see updateGlobalData - explicit merge alias.
|
|
1085
|
+
* @see replaceGlobalData - true replace semantics.
|
|
659
1086
|
*/
|
|
660
1087
|
setGlobalData(data) {
|
|
661
1088
|
safeAssign(this.globalData, data);
|
|
662
1089
|
return this;
|
|
663
1090
|
}
|
|
664
1091
|
/**
|
|
665
|
-
* Merge additional entries into the existing global_data object.
|
|
1092
|
+
* Merge additional entries into the existing global_data object. Identical in
|
|
1093
|
+
* behavior to {@link setGlobalData} (both merge); use this name when the
|
|
1094
|
+
* intent is explicitly "add to" rather than "set". Skills register their
|
|
1095
|
+
* global data through this path.
|
|
1096
|
+
*
|
|
666
1097
|
* @param data - Key-value pairs to merge into global data.
|
|
667
1098
|
* @returns This agent instance for chaining.
|
|
1099
|
+
* @see replaceGlobalData - to clear prior keys instead of merging.
|
|
668
1100
|
*/
|
|
669
1101
|
updateGlobalData(data) {
|
|
670
1102
|
safeAssign(this.globalData, data);
|
|
671
1103
|
return this;
|
|
672
1104
|
}
|
|
1105
|
+
/**
|
|
1106
|
+
* **REPLACES** the entire global_data object: every previously-set key
|
|
1107
|
+
* (including skill-contributed keys) is cleared, and `data` becomes the new
|
|
1108
|
+
* global_data. Use this when you genuinely want a fresh object — the
|
|
1109
|
+
* unambiguous counterpart to the merging {@link setGlobalData} /
|
|
1110
|
+
* {@link updateGlobalData}.
|
|
1111
|
+
*
|
|
1112
|
+
* A shallow copy of `data` is stored, so later mutations of the caller's
|
|
1113
|
+
* object do not leak into the agent.
|
|
1114
|
+
*
|
|
1115
|
+
* TS-native addition: Python's reference SDK has no replace path (its
|
|
1116
|
+
* `set_global_data` only merges), so this has no Python counterpart — see
|
|
1117
|
+
* `PORT_ADDITIONS.md`.
|
|
1118
|
+
*
|
|
1119
|
+
* @param data - The new global_data object (replaces all prior keys).
|
|
1120
|
+
* @returns This agent instance for chaining.
|
|
1121
|
+
* @see setGlobalData - the merging counterpart (does NOT clear prior keys).
|
|
1122
|
+
*/
|
|
1123
|
+
replaceGlobalData(data) {
|
|
1124
|
+
this.globalData = { ...data };
|
|
1125
|
+
return this;
|
|
1126
|
+
}
|
|
673
1127
|
/**
|
|
674
1128
|
* Set the list of native SWAIG function names (built-in platform functions).
|
|
675
1129
|
* @param funcs - Array of native function names.
|
|
@@ -841,6 +1295,31 @@ export class AgentBase extends SWMLService {
|
|
|
841
1295
|
enableSipRouting(autoMap = true, path = '/sip') {
|
|
842
1296
|
this._sipRoutingEnabled = true;
|
|
843
1297
|
this._sipRoute = path;
|
|
1298
|
+
// Register a routing callback at `path` that extracts the SIP username from
|
|
1299
|
+
// the request body and consults this agent's registered usernames. Mirrors
|
|
1300
|
+
// Python `enable_sip_routing` (core/agent_base.py:708-753): the callback is
|
|
1301
|
+
// what makes `_sipUsernames` CONSULTED rather than stored-but-unconsulted.
|
|
1302
|
+
//
|
|
1303
|
+
// Framework-free `(body, headers)` shape; only the body is inspected. When
|
|
1304
|
+
// the username is registered with THIS agent the callback returns null so
|
|
1305
|
+
// the agent serves its own SWML (no redirect — it already handles that
|
|
1306
|
+
// username). An unregistered username also returns null, letting an
|
|
1307
|
+
// enclosing AgentServer's server-level callback (registered at the same
|
|
1308
|
+
// path, checked first) decide the cross-agent redirect.
|
|
1309
|
+
const sipRoutingCallback = (body) => {
|
|
1310
|
+
const sipUsername = AgentBase.extractSipUsername(body);
|
|
1311
|
+
if (sipUsername) {
|
|
1312
|
+
this.log.info(`sip_username_extracted username=${sipUsername}`);
|
|
1313
|
+
if (this._sipUsernames && this._sipUsernames.has(sipUsername.toLowerCase())) {
|
|
1314
|
+
this.log.info(`sip_username_matched username=${sipUsername}`);
|
|
1315
|
+
// Handled by this agent; no redirect needed.
|
|
1316
|
+
return null;
|
|
1317
|
+
}
|
|
1318
|
+
this.log.info(`sip_username_not_matched username=${sipUsername}`);
|
|
1319
|
+
}
|
|
1320
|
+
return null;
|
|
1321
|
+
};
|
|
1322
|
+
this.registerRoutingCallback(sipRoutingCallback, path);
|
|
844
1323
|
if (autoMap) {
|
|
845
1324
|
this._sipAutoMap = true;
|
|
846
1325
|
this.autoMapSipUsernames();
|
|
@@ -897,8 +1376,8 @@ export class AgentBase extends SWMLService {
|
|
|
897
1376
|
*
|
|
898
1377
|
* When called, the endpoint at `path` will invoke `callback` with the parsed
|
|
899
1378
|
* request body. If `callback` returns a non-empty route string the server
|
|
900
|
-
* responds with `
|
|
901
|
-
* request to the right agent. If `callback` returns `null` / `undefined` the
|
|
1379
|
+
* responds with a `307` redirect to it (`Location: <route>`), so the
|
|
1380
|
+
* request goes to the right agent. If `callback` returns `null` / `undefined` the
|
|
902
1381
|
* agent's own SWML is returned instead (normal processing).
|
|
903
1382
|
*
|
|
904
1383
|
* Mirrors Python `swml_service.register_routing_callback` /
|
|
@@ -920,6 +1399,7 @@ export class AgentBase extends SWMLService {
|
|
|
920
1399
|
// _app is non-nullable on the parent (SWMLService); rebuild fresh.
|
|
921
1400
|
this._app = new Hono();
|
|
922
1401
|
this._appBuiltByAgent = false;
|
|
1402
|
+
this._routerApp = null;
|
|
923
1403
|
return this;
|
|
924
1404
|
}
|
|
925
1405
|
/**
|
|
@@ -931,14 +1411,21 @@ export class AgentBase extends SWMLService {
|
|
|
931
1411
|
const call = requestBody?.['call'];
|
|
932
1412
|
const callTo = call?.['to'];
|
|
933
1413
|
if (callTo) {
|
|
934
|
-
|
|
935
|
-
if (
|
|
936
|
-
uri =
|
|
1414
|
+
// SIP/SIPS URIs: strip the scheme, then the username is the part before '@'.
|
|
1415
|
+
if (callTo.startsWith('sip:') || callTo.startsWith('sips:')) {
|
|
1416
|
+
const uri = callTo.replace(/^sips?:/, '');
|
|
1417
|
+
const atIdx = uri.indexOf('@');
|
|
1418
|
+
if (atIdx > 0)
|
|
1419
|
+
return uri.substring(0, atIdx);
|
|
1420
|
+
return uri;
|
|
937
1421
|
}
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
1422
|
+
// TEL URIs ("tel:+1234567890") — strip the scheme (parity with
|
|
1423
|
+
// SWMLService.extractSipUsername / Python swml_service.extract_sip_username).
|
|
1424
|
+
if (callTo.startsWith('tel:')) {
|
|
1425
|
+
return callTo.substring(4);
|
|
1426
|
+
}
|
|
1427
|
+
// Otherwise return the whole 'to' field.
|
|
1428
|
+
return callTo;
|
|
942
1429
|
}
|
|
943
1430
|
return null;
|
|
944
1431
|
}
|
|
@@ -964,6 +1451,8 @@ export class AgentBase extends SWMLService {
|
|
|
964
1451
|
/**
|
|
965
1452
|
* Expose this agent's tools as an MCP server endpoint at /mcp.
|
|
966
1453
|
* Adds a JSON-RPC 2.0 endpoint that MCP clients (Claude Desktop, other agents) can connect to.
|
|
1454
|
+
* The endpoint requires the agent's basic auth credentials, and lists and
|
|
1455
|
+
* calls only the tools the agent runs itself (not DataMap or external webhook tools).
|
|
967
1456
|
* @returns This agent instance for chaining
|
|
968
1457
|
*/
|
|
969
1458
|
enableMcpServer() {
|
|
@@ -978,30 +1467,24 @@ export class AgentBase extends SWMLService {
|
|
|
978
1467
|
getMcpServers() {
|
|
979
1468
|
return [...this._mcpServers];
|
|
980
1469
|
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Whether the /mcp endpoint may list and call this tool: only tools this
|
|
1472
|
+
* agent runs itself. DataMap tools run on SignalWire and external webhook
|
|
1473
|
+
* tools run on another server, so neither has a handler here.
|
|
1474
|
+
*/
|
|
1475
|
+
isMcpCallable(fn) {
|
|
1476
|
+
return fn instanceof SwaigFunction && !fn.isExternal;
|
|
1477
|
+
}
|
|
981
1478
|
/** Build MCP tool list from registered tools. */
|
|
982
1479
|
buildMcpToolList() {
|
|
983
1480
|
const tools = [];
|
|
984
1481
|
for (const [name, fn] of this.toolRegistry) {
|
|
985
|
-
if (fn
|
|
1482
|
+
if (this.isMcpCallable(fn)) {
|
|
986
1483
|
const tool = {
|
|
987
1484
|
name,
|
|
988
1485
|
description: fn.description || name,
|
|
989
1486
|
};
|
|
990
|
-
|
|
991
|
-
if ('type' in fn.parameters && 'properties' in fn.parameters) {
|
|
992
|
-
tool['inputSchema'] = fn.parameters;
|
|
993
|
-
}
|
|
994
|
-
else {
|
|
995
|
-
tool['inputSchema'] = {
|
|
996
|
-
type: 'object',
|
|
997
|
-
properties: fn.parameters,
|
|
998
|
-
...(fn.required.length ? { required: fn.required } : {}),
|
|
999
|
-
};
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
else {
|
|
1003
|
-
tool['inputSchema'] = { type: 'object', properties: {} };
|
|
1004
|
-
}
|
|
1487
|
+
tool['inputSchema'] = normalizeParameters(fn.parameters, fn.required);
|
|
1005
1488
|
tools.push(tool);
|
|
1006
1489
|
}
|
|
1007
1490
|
}
|
|
@@ -1014,12 +1497,17 @@ export class AgentBase extends SWMLService {
|
|
|
1014
1497
|
const reqId = body['id'] ?? null;
|
|
1015
1498
|
const params = body['params'] || {};
|
|
1016
1499
|
if (jsonrpc !== '2.0') {
|
|
1017
|
-
return {
|
|
1500
|
+
return {
|
|
1501
|
+
jsonrpc: '2.0',
|
|
1502
|
+
id: reqId,
|
|
1503
|
+
error: { code: -32600, message: 'Invalid JSON-RPC version' },
|
|
1504
|
+
};
|
|
1018
1505
|
}
|
|
1019
1506
|
// Initialize handshake
|
|
1020
1507
|
if (method === 'initialize') {
|
|
1021
1508
|
return {
|
|
1022
|
-
jsonrpc: '2.0',
|
|
1509
|
+
jsonrpc: '2.0',
|
|
1510
|
+
id: reqId,
|
|
1023
1511
|
result: {
|
|
1024
1512
|
protocolVersion: '2025-06-18',
|
|
1025
1513
|
capabilities: { tools: {} },
|
|
@@ -1040,22 +1528,36 @@ export class AgentBase extends SWMLService {
|
|
|
1040
1528
|
const toolName = params['name'] || '';
|
|
1041
1529
|
const args = params['arguments'] || {};
|
|
1042
1530
|
const fn = this.toolRegistry.get(toolName);
|
|
1043
|
-
if (!
|
|
1044
|
-
return {
|
|
1531
|
+
if (!this.isMcpCallable(fn)) {
|
|
1532
|
+
return {
|
|
1533
|
+
jsonrpc: '2.0',
|
|
1534
|
+
id: reqId,
|
|
1535
|
+
error: { code: -32602, message: `Unknown tool: ${toolName}` },
|
|
1536
|
+
};
|
|
1045
1537
|
}
|
|
1046
1538
|
try {
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
const
|
|
1539
|
+
// MCP bridge synthesizes a minimal SWAIG payload — only the fields the
|
|
1540
|
+
// handler path needs. Runtime shape unchanged; cast is compile-time only.
|
|
1541
|
+
const rawData = {
|
|
1542
|
+
function: toolName,
|
|
1543
|
+
argument: { parsed: [args] },
|
|
1544
|
+
};
|
|
1545
|
+
const resultDict = await fn._executeAs(this, args, rawData, this._onError);
|
|
1546
|
+
// MCP content is text: a structured { tool_result, tool_prompt }
|
|
1547
|
+
// response goes as its JSON.
|
|
1548
|
+
const response = resultDict['response'] ?? '';
|
|
1549
|
+
const responseText = typeof response === 'string' ? response : JSON.stringify(response);
|
|
1050
1550
|
return {
|
|
1051
|
-
jsonrpc: '2.0',
|
|
1551
|
+
jsonrpc: '2.0',
|
|
1552
|
+
id: reqId,
|
|
1052
1553
|
result: { content: [{ type: 'text', text: responseText }], isError: false },
|
|
1053
1554
|
};
|
|
1054
1555
|
}
|
|
1055
1556
|
catch (e) {
|
|
1056
1557
|
const msg = e instanceof Error ? e.message : String(e);
|
|
1057
1558
|
return {
|
|
1058
|
-
jsonrpc: '2.0',
|
|
1559
|
+
jsonrpc: '2.0',
|
|
1560
|
+
id: reqId,
|
|
1059
1561
|
result: { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true },
|
|
1060
1562
|
};
|
|
1061
1563
|
}
|
|
@@ -1064,83 +1566,18 @@ export class AgentBase extends SWMLService {
|
|
|
1064
1566
|
if (method === 'ping') {
|
|
1065
1567
|
return { jsonrpc: '2.0', id: reqId, result: {} };
|
|
1066
1568
|
}
|
|
1067
|
-
return {
|
|
1569
|
+
return {
|
|
1570
|
+
jsonrpc: '2.0',
|
|
1571
|
+
id: reqId,
|
|
1572
|
+
error: { code: -32601, message: `Method not found: ${method}` },
|
|
1573
|
+
};
|
|
1068
1574
|
}
|
|
1069
1575
|
// ── Tools ───────────────────────────────────────────────────────────
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
* A SWAIG function is **exactly the same concept** as a "tool" in
|
|
1076
|
-
* native OpenAI / Anthropic tool calling. On every LLM turn, the SDK
|
|
1077
|
-
* renders each registered SWAIG function into the OpenAI tool schema:
|
|
1078
|
-
*
|
|
1079
|
-
* ```json
|
|
1080
|
-
* {
|
|
1081
|
-
* "type": "function",
|
|
1082
|
-
* "function": {
|
|
1083
|
-
* "name": "your_name_here",
|
|
1084
|
-
* "description": "your description text",
|
|
1085
|
-
* "parameters": { /* your JSON schema *\/ }
|
|
1086
|
-
* }
|
|
1087
|
-
* }
|
|
1088
|
-
* ```
|
|
1089
|
-
*
|
|
1090
|
-
* That schema goes to the model in the same API call that produces
|
|
1091
|
-
* the next assistant message. The model reads:
|
|
1092
|
-
*
|
|
1093
|
-
* - the **function `description`** to decide WHEN to call this tool
|
|
1094
|
-
* - each **parameter `description`** (inside the JSON schema) to
|
|
1095
|
-
* decide HOW to fill in each argument
|
|
1096
|
-
*
|
|
1097
|
-
* This means **descriptions are prompt engineering**, not developer
|
|
1098
|
-
* comments. A vague description is the #1 cause of "the model has the
|
|
1099
|
-
* right tool but doesn't call it" failures.
|
|
1100
|
-
*
|
|
1101
|
-
* ### Bad vs good descriptions
|
|
1102
|
-
*
|
|
1103
|
-
* ```text
|
|
1104
|
-
* BAD : description: 'Lookup function'
|
|
1105
|
-
* GOOD: description: 'Look up a customer's account details by account
|
|
1106
|
-
* number. Use this BEFORE quoting any account-specific info
|
|
1107
|
-
* (balance, plan, status). Do not use for general product
|
|
1108
|
-
* questions.'
|
|
1109
|
-
*
|
|
1110
|
-
* BAD : parameters: { id: { type: 'string', description: 'the id' } }
|
|
1111
|
-
* GOOD: parameters: { account_number: { type: 'string', description:
|
|
1112
|
-
* 'The customer's 8-digit account number, no dashes or spaces.
|
|
1113
|
-
* Ask the user if they don't provide it.' } }
|
|
1114
|
-
* ```
|
|
1115
|
-
*
|
|
1116
|
-
* ### Tool count matters
|
|
1117
|
-
*
|
|
1118
|
-
* LLM tool selection accuracy degrades past ~7-8 simultaneously-active
|
|
1119
|
-
* tools per call. Use Step.setFunctions() to partition tools across
|
|
1120
|
-
* steps so only the relevant subset is active at any moment.
|
|
1121
|
-
*
|
|
1122
|
-
* @param opts - Tool definition including name, description, parameter
|
|
1123
|
-
* schema, and handler callback. `description` and per-parameter
|
|
1124
|
-
* `description` strings are LLM-facing prompt engineering.
|
|
1125
|
-
* @returns This agent instance for chaining.
|
|
1126
|
-
*/
|
|
1127
|
-
defineTool(opts) {
|
|
1128
|
-
const fn = new SwaigFunction({
|
|
1129
|
-
name: opts.name,
|
|
1130
|
-
description: opts.description,
|
|
1131
|
-
parameters: opts.parameters,
|
|
1132
|
-
handler: opts.handler,
|
|
1133
|
-
secure: opts.secure,
|
|
1134
|
-
fillers: opts.fillers,
|
|
1135
|
-
waitFile: opts.waitFile,
|
|
1136
|
-
waitFileLoops: opts.waitFileLoops,
|
|
1137
|
-
required: opts.required,
|
|
1138
|
-
webhookUrl: opts.webhookUrl,
|
|
1139
|
-
extraFields: opts.extraFields,
|
|
1140
|
-
});
|
|
1141
|
-
this.toolRegistry.set(opts.name, fn);
|
|
1142
|
-
return this;
|
|
1143
|
-
}
|
|
1576
|
+
//
|
|
1577
|
+
// `defineTool<P, R>(...)` is inherited from SWMLService — one generic
|
|
1578
|
+
// definition serves both classes. With a flat inline `parameters` map it
|
|
1579
|
+
// infers the handler's `args` precisely (args.phone: string, enum→literal
|
|
1580
|
+
// union, required vs optional); wrapped/loose schemas keep open-record args.
|
|
1144
1581
|
/**
|
|
1145
1582
|
* Register a SWAIG tool with a typed handler that receives named parameters
|
|
1146
1583
|
* instead of the standard `(args, rawData)` convention.
|
|
@@ -1184,6 +1621,8 @@ export class AgentBase extends SWMLService {
|
|
|
1184
1621
|
waitFileLoops: opts.waitFileLoops,
|
|
1185
1622
|
required,
|
|
1186
1623
|
isTypedHandler: true,
|
|
1624
|
+
gates: opts.gates,
|
|
1625
|
+
gateFillers: opts.gateFillers,
|
|
1187
1626
|
});
|
|
1188
1627
|
this.toolRegistry.set(opts.name, fn);
|
|
1189
1628
|
return this;
|
|
@@ -1322,31 +1761,52 @@ export class AgentBase extends SWMLService {
|
|
|
1322
1761
|
* @returns This agent instance for chaining.
|
|
1323
1762
|
*/
|
|
1324
1763
|
async addSkill(skill) {
|
|
1764
|
+
// On a per-request copy, a skill it inherited from the agent is already
|
|
1765
|
+
// loaded, with its tools, prompts, hints and data: nothing to add.
|
|
1766
|
+
if (this._skillManager._inherits(skill))
|
|
1767
|
+
return this;
|
|
1325
1768
|
skill.setAgent(this);
|
|
1326
1769
|
await this._skillManager.addSkill(skill);
|
|
1327
|
-
// Register skill tools
|
|
1770
|
+
// Register skill tools. As in Python's SkillBase.define_tool
|
|
1771
|
+
// (skill_base.py:59-79), swaig_fields are define_tool arguments with the
|
|
1772
|
+
// tool's own fields winning: `secure` sets whether the tool needs a token,
|
|
1773
|
+
// and the other keys go into the SWAIG definition.
|
|
1774
|
+
const { secure: skillSecure, ...skillExtraFields } = skill.swaigFields;
|
|
1328
1775
|
for (const toolDef of skill.getTools()) {
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
}
|
|
1344
|
-
// Propagate is_hangup_hook so the SignalWire platform auto-fires this
|
|
1345
|
-
// tool on call hangup (Python equivalent: is_hangup_hook=True in define_tool).
|
|
1346
|
-
if (toolDef.isHangupHook) {
|
|
1347
|
-
fn.extraFields['is_hangup_hook'] = true;
|
|
1348
|
-
}
|
|
1776
|
+
// Skill-level swaigFields are the base and the tool's own fields win —
|
|
1777
|
+
// Python skill_base.py:70-73 (swaig_fields base, explicit kwargs win) and
|
|
1778
|
+
// SkillBase.defineTool() ({...swaigDefaults, ...toolDef}). They are merged
|
|
1779
|
+
// before the function is built, so the result is what's checked: a
|
|
1780
|
+
// skill's default gates never replace a tool's own.
|
|
1781
|
+
const extraFields = {};
|
|
1782
|
+
safeAssign(extraFields, skillExtraFields);
|
|
1783
|
+
// A tool may carry its own extra fields (getTools() can return
|
|
1784
|
+
// SwaigFunctionOptions); they win over the skill's defaults.
|
|
1785
|
+
const ownExtraFields = toolDef.extraFields;
|
|
1786
|
+
if (ownExtraFields)
|
|
1787
|
+
safeAssign(extraFields, ownExtraFields);
|
|
1788
|
+
if (toolDef.wait_for_fillers !== undefined) {
|
|
1789
|
+
extraFields['wait_for_fillers'] = toolDef.wait_for_fillers;
|
|
1349
1790
|
}
|
|
1791
|
+
if (toolDef.skip_fillers !== undefined) {
|
|
1792
|
+
extraFields['skip_fillers'] = toolDef.skip_fillers;
|
|
1793
|
+
}
|
|
1794
|
+
// Propagate is_hangup_hook so the SignalWire platform auto-fires this
|
|
1795
|
+
// tool on call hangup (Python equivalent: is_hangup_hook=True in define_tool).
|
|
1796
|
+
if (toolDef.isHangupHook) {
|
|
1797
|
+
extraFields['is_hangup_hook'] = true;
|
|
1798
|
+
}
|
|
1799
|
+
if (toolDef.gates !== undefined)
|
|
1800
|
+
extraFields['gates'] = toolDef.gates;
|
|
1801
|
+
if (toolDef.gate_fillers !== undefined)
|
|
1802
|
+
extraFields['gate_fillers'] = toolDef.gate_fillers;
|
|
1803
|
+
this.defineTool({
|
|
1804
|
+
...toolDef,
|
|
1805
|
+
...(toolDef.secure === undefined && typeof skillSecure === 'boolean'
|
|
1806
|
+
? { secure: skillSecure }
|
|
1807
|
+
: {}),
|
|
1808
|
+
extraFields,
|
|
1809
|
+
});
|
|
1350
1810
|
}
|
|
1351
1811
|
// Register DataMap-style tools — skills that build their own SWAIG JSON
|
|
1352
1812
|
// (e.g. DataSphereServerless) return them via getDataMapTools().
|
|
@@ -1376,6 +1836,13 @@ export class AgentBase extends SWMLService {
|
|
|
1376
1836
|
* name via the SkillManager registry. Throws a `ValueError`-equivalent if the
|
|
1377
1837
|
* skill name is not found in the registry.
|
|
1378
1838
|
*
|
|
1839
|
+
* Accepts a typed {@link SkillNameOrString}: one of the built-in
|
|
1840
|
+
* {@link SkillName} values (autocompleted) or any other string for custom
|
|
1841
|
+
* and third-party skills. Because any string is accepted, a misspelled name
|
|
1842
|
+
* compiles, and this rejects at runtime because it isn't registered. The value is
|
|
1843
|
+
* forwarded to the registry unchanged — the typing is erased at runtime, so
|
|
1844
|
+
* this matches Python's bare-`str` `add_skill(skill_name, params)`.
|
|
1845
|
+
*
|
|
1379
1846
|
* @param skillName - The name the skill was registered under in the SkillRegistry.
|
|
1380
1847
|
* @param params - Optional configuration parameters forwarded to the skill factory.
|
|
1381
1848
|
* @returns This agent instance for chaining.
|
|
@@ -1405,6 +1872,11 @@ export class AgentBase extends SWMLService {
|
|
|
1405
1872
|
}
|
|
1406
1873
|
/**
|
|
1407
1874
|
* Check whether a skill with the given name is registered.
|
|
1875
|
+
*
|
|
1876
|
+
* Accepts a typed {@link SkillNameOrString} so built-in names autocomplete;
|
|
1877
|
+
* any other string is accepted too (custom skills, matching Python's
|
|
1878
|
+
* bare-`str` `has_skill`), so a misspelled name compiles and returns false.
|
|
1879
|
+
*
|
|
1408
1880
|
* @param skillName - The skill name to check.
|
|
1409
1881
|
* @returns True if a skill with that name exists.
|
|
1410
1882
|
*/
|
|
@@ -1412,11 +1884,11 @@ export class AgentBase extends SWMLService {
|
|
|
1412
1884
|
return this._skillManager.hasSkill(skillName);
|
|
1413
1885
|
}
|
|
1414
1886
|
/**
|
|
1415
|
-
* Remove a skill by its name (Python
|
|
1887
|
+
* Remove a skill by its name (matches the Python SDK).
|
|
1416
1888
|
*
|
|
1417
1889
|
* Python's `remove_skill(skill_name)` removes by skill name.
|
|
1418
1890
|
* The existing `removeSkill(instanceId)` removes by instance ID.
|
|
1419
|
-
* This method provides name-based removal
|
|
1891
|
+
* This method provides name-based removal to match the Python SDK.
|
|
1420
1892
|
*
|
|
1421
1893
|
* @param skillName - The skill name to remove.
|
|
1422
1894
|
* @returns True if a skill with that name was found and removed.
|
|
@@ -1430,13 +1902,42 @@ export class AgentBase extends SWMLService {
|
|
|
1430
1902
|
}
|
|
1431
1903
|
return false;
|
|
1432
1904
|
}
|
|
1905
|
+
/**
|
|
1906
|
+
* A tool handler that calls `fn` with the agent running the call: with a
|
|
1907
|
+
* dynamic config callback, the request's configured copy (so the handler
|
|
1908
|
+
* sees what the callback configured), otherwise this agent. For handlers
|
|
1909
|
+
* that read the agent's own state; the SDK's prefabs register theirs this
|
|
1910
|
+
* way. A plain handler gets the same agent as its third argument.
|
|
1911
|
+
* @internal
|
|
1912
|
+
*/
|
|
1913
|
+
_onCallAgent(fn) {
|
|
1914
|
+
return (args, rawData, agent) => fn(agent ?? this, args, rawData);
|
|
1915
|
+
}
|
|
1433
1916
|
// ── Dynamic config ──────────────────────────────────────────────────
|
|
1434
1917
|
/**
|
|
1435
|
-
* Set a callback
|
|
1436
|
-
*
|
|
1437
|
-
*
|
|
1438
|
-
*
|
|
1439
|
-
*
|
|
1918
|
+
* Set a callback that configures a per-request copy of this agent.
|
|
1919
|
+
*
|
|
1920
|
+
* On each request that renders SWML, runs a SWAIG function or delivers a
|
|
1921
|
+
* summary, the SDK makes a copy of this agent, calls the callback with the
|
|
1922
|
+
* request's query parameters, body and headers (credential-bearing headers
|
|
1923
|
+
* removed) and the copy, and handles the request with the copy. Tool
|
|
1924
|
+
* handlers get the copy as their third argument, and `onSummary` runs on it.
|
|
1925
|
+
*
|
|
1926
|
+
* The copy has its own prompt, tools, skills list, hints, languages,
|
|
1927
|
+
* pronunciations, params, global data, function includes, LLM params,
|
|
1928
|
+
* fillers, call-flow verbs, SWAIG query params, native functions, MCP
|
|
1929
|
+
* servers, SIP usernames, routing callbacks and contexts, so changing any of
|
|
1930
|
+
* them with the agent's methods affects only this request. Anything else is
|
|
1931
|
+
* shared with this agent and every request in flight: a field a subclass
|
|
1932
|
+
* adds, a skill instance, or an object inside the configuration that isn't
|
|
1933
|
+
* plain data (a `URL`, a class instance). Assigning a new value to such a
|
|
1934
|
+
* field on the copy is safe; mutating a shared object in place is not.
|
|
1935
|
+
*
|
|
1936
|
+
* A handler that captured this agent (an arrow function, or a method passed
|
|
1937
|
+
* with `.bind(this)`) still sees this agent, not the copy: read per-call
|
|
1938
|
+
* configuration from the handler's third argument. A subclass's JavaScript
|
|
1939
|
+
* `#private` fields aren't on the copy, so its methods that read them
|
|
1940
|
+
* throw there; use TypeScript `private` fields.
|
|
1440
1941
|
*
|
|
1441
1942
|
* @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)` where
|
|
1442
1943
|
* `agent` is the ephemeral `AgentBase` copy to mutate. May be async.
|
|
@@ -1453,7 +1954,133 @@ export class AgentBase extends SWMLService {
|
|
|
1453
1954
|
* ```
|
|
1454
1955
|
*/
|
|
1455
1956
|
setDynamicConfigCallback(cb) {
|
|
1456
|
-
|
|
1957
|
+
// Replaces the whole chain, including callbacks from addPerCallConfig.
|
|
1958
|
+
this.perCallConfigs = [cb];
|
|
1959
|
+
return this;
|
|
1960
|
+
}
|
|
1961
|
+
/**
|
|
1962
|
+
* Register a per-request configuration callback, keeping any already set.
|
|
1963
|
+
*
|
|
1964
|
+
* Same signature and contract as {@link setDynamicConfigCallback}, except
|
|
1965
|
+
* that callbacks accumulate instead of replacing each other. They run in
|
|
1966
|
+
* registration order on the same per-request copy, so a later one sees what
|
|
1967
|
+
* an earlier one configured. This is the composable form: a base class and a
|
|
1968
|
+
* subclass, or an agent and a helper, can each register what they own
|
|
1969
|
+
* without knowing about each other. `setDynamicConfigCallback` replaces
|
|
1970
|
+
* every callback registered so far.
|
|
1971
|
+
*
|
|
1972
|
+
* @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)`,
|
|
1973
|
+
* where `agent` is the per-request copy. Configure that, never the agent
|
|
1974
|
+
* itself, or the configuration leaks across callers. May be async.
|
|
1975
|
+
* @returns This agent instance for chaining.
|
|
1976
|
+
*/
|
|
1977
|
+
addPerCallConfig(cb) {
|
|
1978
|
+
// Rebind rather than push: a per-request copy shares this array.
|
|
1979
|
+
this.perCallConfigs = [...this.perCallConfigs, cb];
|
|
1980
|
+
return this;
|
|
1981
|
+
}
|
|
1982
|
+
/**
|
|
1983
|
+
* Register a handler that runs when the call ends, with the transcript.
|
|
1984
|
+
*
|
|
1985
|
+
* Handlers run in registration order with `(callLog, rawData)`: the
|
|
1986
|
+
* conversation as the platform recorded it, and the whole SWAIG request
|
|
1987
|
+
* (with `global_data` and `call_id`). This wraps the platform's reserved
|
|
1988
|
+
* `hangup_hook` function, which fires on hangup and is never offered to the
|
|
1989
|
+
* model, so it can't be called early or skipped.
|
|
1990
|
+
*
|
|
1991
|
+
* Registering a handler also turns on the `swaig_post_conversation`
|
|
1992
|
+
* parameter: without it the hook still fires, but carries no transcript,
|
|
1993
|
+
* and the handler gets an empty list with nothing to say why. If that
|
|
1994
|
+
* parameter is explicitly `false`, it's left alone and a warning is logged.
|
|
1995
|
+
*
|
|
1996
|
+
* A handler's return value is ignored (the call is over), and an exception
|
|
1997
|
+
* is logged, not raised, so a failing handler doesn't stop the others.
|
|
1998
|
+
*
|
|
1999
|
+
* @param handler - Called with `(callLog, rawData)`; may be async.
|
|
2000
|
+
* @returns The handler.
|
|
2001
|
+
*
|
|
2002
|
+
* @example
|
|
2003
|
+
* ```ts
|
|
2004
|
+
* agent.onCallEnd((callLog, rawData) => {
|
|
2005
|
+
* archive(rawData.global_data?.['conversation_id'], callLog);
|
|
2006
|
+
* });
|
|
2007
|
+
* ```
|
|
2008
|
+
*/
|
|
2009
|
+
onCallEnd(handler) {
|
|
2010
|
+
const first = this.callEndHandlers.length === 0;
|
|
2011
|
+
// Rebind rather than push: a per-request copy shares this array.
|
|
2012
|
+
this.callEndHandlers = [...this.callEndHandlers, handler];
|
|
2013
|
+
if (first)
|
|
2014
|
+
this.ensureCallEndHook();
|
|
2015
|
+
return handler;
|
|
2016
|
+
}
|
|
2017
|
+
/** Register the reserved hangup_hook tool once, and turn on its transcript. */
|
|
2018
|
+
ensureCallEndHook() {
|
|
2019
|
+
if (this.params['swaig_post_conversation'] === false) {
|
|
2020
|
+
this.log.warn('[signalwire] onCallEnd handlers are registered but swaig_post_conversation is explicitly false -- they will receive an empty call_log');
|
|
2021
|
+
}
|
|
2022
|
+
else if (!('swaig_post_conversation' in this.params)) {
|
|
2023
|
+
this.params['swaig_post_conversation'] = true;
|
|
2024
|
+
}
|
|
2025
|
+
this.defineTool({
|
|
2026
|
+
name: 'hangup_hook',
|
|
2027
|
+
description: 'Internal: fires when the call ends.',
|
|
2028
|
+
parameters: {},
|
|
2029
|
+
handler: async (_args, rawData, running) => {
|
|
2030
|
+
const raw = (rawData ?? {});
|
|
2031
|
+
// Both spellings are seen, depending on the engine; an empty log
|
|
2032
|
+
// counts as absent, so the other spelling is tried.
|
|
2033
|
+
const log = (v) => Array.isArray(v) && v.length > 0 ? v : null;
|
|
2034
|
+
const callLog = log(raw['call_log']) ?? log(raw['raw_call_log']) ?? [];
|
|
2035
|
+
// The handlers of the agent running the call: a per-call copy may
|
|
2036
|
+
// have added its own.
|
|
2037
|
+
const agent = running instanceof AgentBase ? running : this;
|
|
2038
|
+
for (const callback of agent.callEndHandlers) {
|
|
2039
|
+
// Each handler is isolated, so one failure doesn't stop the others.
|
|
2040
|
+
try {
|
|
2041
|
+
await callback(callLog, rawData);
|
|
2042
|
+
}
|
|
2043
|
+
catch (err) {
|
|
2044
|
+
this.log.error('call_end_handler_failed', {
|
|
2045
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2046
|
+
});
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
return new FunctionResult('');
|
|
2050
|
+
},
|
|
2051
|
+
});
|
|
2052
|
+
}
|
|
2053
|
+
/**
|
|
2054
|
+
* Mount an extra Hono app, or a fetch handler, alongside this agent's routes.
|
|
2055
|
+
*
|
|
2056
|
+
* Use this instead of adding routes to {@link getApp}'s app by hand: the
|
|
2057
|
+
* agent rebuilds its app when its routes change (a routing callback, say),
|
|
2058
|
+
* and a mount is replayed on every build. A mounted app answers its own
|
|
2059
|
+
* CORS preflights (the agent's CORS and CSRF middleware don't apply to it),
|
|
2060
|
+
* sets its own security headers, and isn't behind the agent's basic auth.
|
|
2061
|
+
* Mount before calling `serve()`.
|
|
2062
|
+
*
|
|
2063
|
+
* @param appOrRouter - A Hono app (its routes are added under `prefix`) or a
|
|
2064
|
+
* fetch handler `(request) => Response` (mounted at `prefix`, which it
|
|
2065
|
+
* doesn't see).
|
|
2066
|
+
* @param opts - `prefix`: the path to mount at, from the host root (a
|
|
2067
|
+
* trailing slash is dropped; default the root). `name`: accepted so
|
|
2068
|
+
* code written for the Python SDK works; it has no effect here.
|
|
2069
|
+
* @returns This agent instance for chaining.
|
|
2070
|
+
*
|
|
2071
|
+
* @example
|
|
2072
|
+
* ```ts
|
|
2073
|
+
* agent.mount(gateway.router(), { prefix: '/chat' });
|
|
2074
|
+
* ```
|
|
2075
|
+
*/
|
|
2076
|
+
mount(appOrRouter, opts = {}) {
|
|
2077
|
+
// opts.name is accepted but unused; the Python SDK names an ASGI mount with it.
|
|
2078
|
+
const clean = (opts.prefix ?? '').replace(/\/+$/, '');
|
|
2079
|
+
this.mounts = [...this.mounts, { app: appOrRouter, prefix: clean }];
|
|
2080
|
+
// Rebuild the apps on next use, with the mount.
|
|
2081
|
+
this._appBuiltByAgent = false;
|
|
2082
|
+
this._routerApp = null;
|
|
2083
|
+
this.log.info('agent_route_mounted', { prefix: clean || '/' });
|
|
1457
2084
|
return this;
|
|
1458
2085
|
}
|
|
1459
2086
|
/**
|
|
@@ -1525,6 +2152,7 @@ export class AgentBase extends SWMLService {
|
|
|
1525
2152
|
const hostMatch = forwarded.match(/host=([^;,\s]+)/i);
|
|
1526
2153
|
const protoMatch = forwarded.match(/proto=([^;,\s]+)/i);
|
|
1527
2154
|
if (hostMatch && isValidHostname(hostMatch[1])) {
|
|
2155
|
+
// capture group 1 is present on any successful match
|
|
1528
2156
|
const proto = protoMatch ? protoMatch[1] : 'https';
|
|
1529
2157
|
const url = `${proto}://${hostMatch[1]}`;
|
|
1530
2158
|
if (this._proxyDebug)
|
|
@@ -1585,15 +2213,47 @@ export class AgentBase extends SWMLService {
|
|
|
1585
2213
|
base += this.route;
|
|
1586
2214
|
return base;
|
|
1587
2215
|
}
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
2216
|
+
// Serverless: the URL the platform serves the function on, from its
|
|
2217
|
+
// environment, as the reference builds it. Not once serve() runs an HTTP
|
|
2218
|
+
// server: a server on Cloud Run also has K_SERVICE set.
|
|
2219
|
+
const platformBase = this._serving ? null : serverlessBaseUrl();
|
|
2220
|
+
if (platformBase) {
|
|
2221
|
+
let base = includeAuth ? this.insertAuth(platformBase) : platformBase;
|
|
2222
|
+
if (this.route && this.route !== '/' && !base.endsWith(this.route)) {
|
|
2223
|
+
base = `${base}/${this.route.replace(/^\/+/, '')}`;
|
|
2224
|
+
}
|
|
2225
|
+
return base;
|
|
2226
|
+
}
|
|
2227
|
+
// An agent that serves HTTPS itself (SSL configured, as serve() checks)
|
|
2228
|
+
// gives https URLs, on the SSL domain when one is set, as the reference's
|
|
2229
|
+
// _get_base_url does.
|
|
2230
|
+
const tls = this._servesTls();
|
|
2231
|
+
const protocol = this._enforceHttps || tls ? 'https' : 'http';
|
|
2232
|
+
let base;
|
|
2233
|
+
if (tls && this.domain) {
|
|
2234
|
+
base = `${protocol}://${this.domain}${this.port === 443 ? '' : `:${this.port}`}`;
|
|
2235
|
+
}
|
|
2236
|
+
else {
|
|
2237
|
+
const hostPart = this.host === '0.0.0.0' ? 'localhost' : this.host;
|
|
2238
|
+
base = `${protocol}://${hostPart}:${this.port}`;
|
|
2239
|
+
}
|
|
1591
2240
|
if (includeAuth)
|
|
1592
2241
|
base = this.insertAuth(base);
|
|
1593
2242
|
if (this.route && this.route !== '/')
|
|
1594
2243
|
base += this.route;
|
|
1595
2244
|
return base;
|
|
1596
2245
|
}
|
|
2246
|
+
/**
|
|
2247
|
+
* Whether serve() serves HTTPS: SSL enabled with a certificate and key that
|
|
2248
|
+
* exist. getFullUrl() uses the same check, so the webhook URLs match.
|
|
2249
|
+
*/
|
|
2250
|
+
_servesTls() {
|
|
2251
|
+
return !!(this.sslEnabled &&
|
|
2252
|
+
this.sslCertPath &&
|
|
2253
|
+
this.sslKeyPath &&
|
|
2254
|
+
existsSync(this.sslCertPath) &&
|
|
2255
|
+
existsSync(this.sslKeyPath));
|
|
2256
|
+
}
|
|
1597
2257
|
insertAuth(baseUrl) {
|
|
1598
2258
|
const [user, pass] = this.basicAuthCreds;
|
|
1599
2259
|
if (!user || !pass)
|
|
@@ -1605,7 +2265,9 @@ export class AgentBase extends SWMLService {
|
|
|
1605
2265
|
const params = { ...extraParams };
|
|
1606
2266
|
const entries = Object.entries(params).filter(([, v]) => v);
|
|
1607
2267
|
if (entries.length) {
|
|
1608
|
-
url +=
|
|
2268
|
+
url +=
|
|
2269
|
+
'?' +
|
|
2270
|
+
entries.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
|
|
1609
2271
|
}
|
|
1610
2272
|
return url;
|
|
1611
2273
|
}
|
|
@@ -1614,7 +2276,7 @@ export class AgentBase extends SWMLService {
|
|
|
1614
2276
|
* Lifecycle hook called when a post-prompt summary is received. Override in subclasses.
|
|
1615
2277
|
*
|
|
1616
2278
|
* Invoked once at the end of a call when the AI has produced a structured summary
|
|
1617
|
-
* (configured via `setPostPrompt()`
|
|
2279
|
+
* (configured via `setPostPrompt()`). Use this hook to persist
|
|
1618
2280
|
* call data, notify other systems, or trigger follow-up workflows.
|
|
1619
2281
|
*
|
|
1620
2282
|
* @param _summary - Parsed summary object (JSON when the post-prompt requests
|
|
@@ -1622,6 +2284,12 @@ export class AgentBase extends SWMLService {
|
|
|
1622
2284
|
* @param _rawData - Full raw post-prompt payload received from the platform,
|
|
1623
2285
|
* including call metadata, conversation history, and the summary text.
|
|
1624
2286
|
*
|
|
2287
|
+
* With a dynamic config callback set, this runs on the request's configured
|
|
2288
|
+
* copy of the agent. For a request whose `action` is `fetch_conversation`,
|
|
2289
|
+
* an override may return the conversation (for example
|
|
2290
|
+
* `{ conversation_summary: '...' }`); the post-prompt endpoint sends that
|
|
2291
|
+
* back instead of `{ success: true }`.
|
|
2292
|
+
*
|
|
1625
2293
|
* @example
|
|
1626
2294
|
* ```ts
|
|
1627
2295
|
* class MyAgent extends AgentBase {
|
|
@@ -1676,6 +2344,127 @@ export class AgentBase extends SWMLService {
|
|
|
1676
2344
|
onSwmlRequest(_rawData, _callbackPath, _context) {
|
|
1677
2345
|
// Default no-op
|
|
1678
2346
|
}
|
|
2347
|
+
/**
|
|
2348
|
+
* Framework-free request-dispatch core for AgentBase.
|
|
2349
|
+
*
|
|
2350
|
+
* Overrides {@link SWMLService.handleRequest} so the primitive dispatch surface
|
|
2351
|
+
* renders SWML via AgentBase's {@link renderSwml} (mirroring the Hono root path)
|
|
2352
|
+
* instead of the base `renderDocument`. Performs basic-auth, the routing-callback
|
|
2353
|
+
* check `(body, headers)`, and `onSwmlRequest` modification over plain
|
|
2354
|
+
* primitives, returning a `[status, headers, bodyString]` triple with the
|
|
2355
|
+
* 401-auth and 307-redirect behavior preserved. Mirrors Python's
|
|
2356
|
+
* `AgentBase.handle_request(method, url, headers, body)`.
|
|
2357
|
+
*
|
|
2358
|
+
* @param method HTTP method, e.g. `"GET"` or `"POST"`.
|
|
2359
|
+
* @param url The full request URL.
|
|
2360
|
+
* @param headers Request headers as a plain dict.
|
|
2361
|
+
* @param body The already-parsed JSON body for POST requests, or `undefined`.
|
|
2362
|
+
* @returns A `[statusCode, responseHeaders, bodyString]` triple.
|
|
2363
|
+
*/
|
|
2364
|
+
async handleRequest(method, url, headers, body) {
|
|
2365
|
+
// The Hono context of a served request (see serveViaHandleRequest), which
|
|
2366
|
+
// onSwmlRequest receives as its third argument; undefined on the
|
|
2367
|
+
// primitive path.
|
|
2368
|
+
const context = servedRequestContext.getStore();
|
|
2369
|
+
const parsedBody = body ?? {};
|
|
2370
|
+
const callbackPath = this._callbackPathForUrl(url);
|
|
2371
|
+
// Auth. A served request (context set) has passed the route's basic-auth
|
|
2372
|
+
// middleware already, which every route that serves through here has, so
|
|
2373
|
+
// validateBasicAuth() isn't run twice; a direct call is checked here.
|
|
2374
|
+
if (!context && !(await this.checkAgentBasicAuth(headers))) {
|
|
2375
|
+
return [401, { 'WWW-Authenticate': 'Basic' }, JSON.stringify({ error: 'Unauthorized' })];
|
|
2376
|
+
}
|
|
2377
|
+
// call_id: from the body for POST, from the `call_id` query parameter for
|
|
2378
|
+
// GET. The GET form is how a caller outside SignalWire fetches the SWML (and
|
|
2379
|
+
// so the per-function `__token`s) for a known call.
|
|
2380
|
+
let callId;
|
|
2381
|
+
if (method === 'GET') {
|
|
2382
|
+
try {
|
|
2383
|
+
callId = new URL(url, 'http://localhost').searchParams.get('call_id') ?? undefined;
|
|
2384
|
+
}
|
|
2385
|
+
catch {
|
|
2386
|
+
callId = undefined;
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
if (method === 'POST' && Object.keys(parsedBody).length > 0) {
|
|
2390
|
+
callId = parsedBody['call_id'] ?? undefined;
|
|
2391
|
+
if (!callId && parsedBody['call'] && typeof parsedBody['call'] === 'object') {
|
|
2392
|
+
callId = parsedBody['call']['call_id'];
|
|
2393
|
+
}
|
|
2394
|
+
// Routing callback: (body, headers) -> route | null.
|
|
2395
|
+
if (callbackPath && this._routingCallbacks.has(callbackPath)) {
|
|
2396
|
+
const callbackFn = this._routingCallbacks.get(callbackPath);
|
|
2397
|
+
try {
|
|
2398
|
+
const route = await callbackFn(parsedBody, headers);
|
|
2399
|
+
if (route != null) {
|
|
2400
|
+
this.log.info(`routing_request route=${route}`);
|
|
2401
|
+
return [307, { Location: route }, ''];
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
catch (err) {
|
|
2405
|
+
this.log.error(`error_in_routing_callback error=${err instanceof Error ? err.message : String(err)}`);
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
// Subclass modification hook, with the Hono context on the served path.
|
|
2410
|
+
let modifications = undefined;
|
|
2411
|
+
try {
|
|
2412
|
+
modifications = await this.onSwmlRequest(parsedBody, callbackPath ?? undefined, context);
|
|
2413
|
+
}
|
|
2414
|
+
catch (err) {
|
|
2415
|
+
this.log.error(`error_in_request_modifier error=${err instanceof Error ? err.message : String(err)}`);
|
|
2416
|
+
}
|
|
2417
|
+
// Per-request dynamic config: render from the configured copy, so the Hono
|
|
2418
|
+
// and primitive paths produce identical SWML.
|
|
2419
|
+
const agentToUse = await this.perCallAgent(queryParamsOf(url), parsedBody, headers);
|
|
2420
|
+
const swml = agentToUse.renderSwml(callId, modifications || undefined);
|
|
2421
|
+
return [200, {}, swml];
|
|
2422
|
+
}
|
|
2423
|
+
/**
|
|
2424
|
+
* The agent a request runs on: this agent, or, when a dynamic config
|
|
2425
|
+
* callback is set, a per-request copy that the callback configured from the
|
|
2426
|
+
* request's query parameters, body and headers (credential-bearing headers
|
|
2427
|
+
* removed). Rendering SWML, running a SWAIG function and delivering a
|
|
2428
|
+
* summary all use it, so a tool the callback registers or secures is the one
|
|
2429
|
+
* that runs, and is checked, when the call invokes it. Mirrors the
|
|
2430
|
+
* reference's `_per_call_agent`.
|
|
2431
|
+
*/
|
|
2432
|
+
async perCallAgent(queryParams, body, headers) {
|
|
2433
|
+
if (this.perCallConfigs.length === 0)
|
|
2434
|
+
return this;
|
|
2435
|
+
const copy = this.createEphemeralCopy();
|
|
2436
|
+
const safeHeaders = filterSensitiveHeaders(headers);
|
|
2437
|
+
try {
|
|
2438
|
+
for (const cb of this.perCallConfigs) {
|
|
2439
|
+
await cb(queryParams, body, safeHeaders, copy);
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
catch (err) {
|
|
2443
|
+
this.log.error(`dynamic_config_error error=${err instanceof Error ? err.message : String(err)}`);
|
|
2444
|
+
}
|
|
2445
|
+
return copy;
|
|
2446
|
+
}
|
|
2447
|
+
/** Validate basic-auth from a plain headers dict (the primitive analog of
|
|
2448
|
+
* the Hono `basicAuth` middleware), through {@link validateBasicAuth}. */
|
|
2449
|
+
async checkAgentBasicAuth(headers) {
|
|
2450
|
+
const [user, pass] = this.basicAuthCreds;
|
|
2451
|
+
if (!user || !pass)
|
|
2452
|
+
return true;
|
|
2453
|
+
const authHeader = headers['authorization'] ?? headers['Authorization'];
|
|
2454
|
+
if (!authHeader || !authHeader.startsWith('Basic '))
|
|
2455
|
+
return false;
|
|
2456
|
+
let decoded;
|
|
2457
|
+
try {
|
|
2458
|
+
decoded = Buffer.from(authHeader.slice(6), 'base64').toString('utf-8');
|
|
2459
|
+
}
|
|
2460
|
+
catch {
|
|
2461
|
+
return false;
|
|
2462
|
+
}
|
|
2463
|
+
const idx = decoded.indexOf(':');
|
|
2464
|
+
if (idx < 0)
|
|
2465
|
+
return false;
|
|
2466
|
+
return await this.validateBasicAuth(decoded.slice(0, idx), decoded.slice(idx + 1));
|
|
2467
|
+
}
|
|
1679
2468
|
/**
|
|
1680
2469
|
* Lifecycle hook called when a debug event webhook is received. Override in subclasses.
|
|
1681
2470
|
* @param _event - The debug event payload.
|
|
@@ -1684,13 +2473,20 @@ export class AgentBase extends SWMLService {
|
|
|
1684
2473
|
// Default no-op
|
|
1685
2474
|
}
|
|
1686
2475
|
/**
|
|
1687
|
-
*
|
|
1688
|
-
*
|
|
1689
|
-
*
|
|
2476
|
+
* Check a request's basic-auth credentials. Every route that requires
|
|
2477
|
+
* basic auth calls it. The default compares them with the agent's
|
|
2478
|
+
* credentials in constant time; override it to check credentials another
|
|
2479
|
+
* way, as the Python SDK's `validate_basic_auth` allows. An override
|
|
2480
|
+
* replaces the comparison, so call `super.validateBasicAuth()` to keep it.
|
|
2481
|
+
* @param username - The username from the request.
|
|
2482
|
+
* @param password - The password from the request.
|
|
1690
2483
|
* @returns True if the credentials are valid; false to reject the request.
|
|
1691
2484
|
*/
|
|
1692
|
-
validateBasicAuth(
|
|
1693
|
-
|
|
2485
|
+
validateBasicAuth(username, password) {
|
|
2486
|
+
const [user, pass] = this.basicAuthCreds;
|
|
2487
|
+
if (!user || !pass)
|
|
2488
|
+
return false;
|
|
2489
|
+
return constantTimeEqual(username, user) && constantTimeEqual(password, pass);
|
|
1694
2490
|
}
|
|
1695
2491
|
/**
|
|
1696
2492
|
* Hook called before each SWAIG function execution. Override in subclasses.
|
|
@@ -1699,7 +2495,7 @@ export class AgentBase extends SWMLService {
|
|
|
1699
2495
|
* — it retrieves and executes the function, returning the result. In TypeScript,
|
|
1700
2496
|
* `fn.execute()` is called separately after this hook. However, if this method
|
|
1701
2497
|
* returns a non-void value, it is used as the result and the default execution
|
|
1702
|
-
* is skipped, enabling dispatch interception
|
|
2498
|
+
* is skipped, enabling dispatch interception matching the Python SDK.
|
|
1703
2499
|
*
|
|
1704
2500
|
* @param _name - Name of the function about to execute.
|
|
1705
2501
|
* @param _args - Parsed arguments for the function.
|
|
@@ -1710,6 +2506,84 @@ export class AgentBase extends SWMLService {
|
|
|
1710
2506
|
onFunctionCall(_name, _args, _rawData) {
|
|
1711
2507
|
// Default no-op
|
|
1712
2508
|
}
|
|
2509
|
+
/**
|
|
2510
|
+
* Extract the tool-call arguments from a SWAIG request body.
|
|
2511
|
+
*
|
|
2512
|
+
* The real platform (mod_openai) POSTs a tool call with the args nested under
|
|
2513
|
+
* the platform envelope `{"argument": {"parsed": [{...args...}], "raw": "..."}}`
|
|
2514
|
+
* — NOT flat. Reading `body.argument` directly hands the handler the WHOLE
|
|
2515
|
+
* envelope (`{parsed, raw}`) instead of the args, so a real platform call
|
|
2516
|
+
* arrives with EMPTY args. This unwraps `argument.parsed[0]` first, falls back
|
|
2517
|
+
* to parsing `argument.raw` JSON, and finally accepts the flat
|
|
2518
|
+
* `{"arguments": {...}}` shape some external integrations send — matching the
|
|
2519
|
+
* Python reference (`core/swml_service.py:836-851`).
|
|
2520
|
+
*
|
|
2521
|
+
* @param body - The parsed SWAIG request body.
|
|
2522
|
+
* @param reqLog - Request-scoped logger for the raw-parse-error path.
|
|
2523
|
+
* @returns The extracted argument object (empty object when none present).
|
|
2524
|
+
*/
|
|
2525
|
+
/**
|
|
2526
|
+
* Check a SWAIG request's token before a function runs.
|
|
2527
|
+
*
|
|
2528
|
+
* A secure function runs only with a valid token minted for that function
|
|
2529
|
+
* and call. The token is in the `web_hook_url` the agent rendered, so a
|
|
2530
|
+
* request without one didn't come from that SWML: a missing token, or a
|
|
2531
|
+
* missing `call_id`, is refused like a wrong token. A non-secure function
|
|
2532
|
+
* runs without a token.
|
|
2533
|
+
*
|
|
2534
|
+
* @returns The SWAIG response to send instead of running the function, or
|
|
2535
|
+
* `null` when the function may run.
|
|
2536
|
+
*/
|
|
2537
|
+
swaigTokenRefusal(fn, token, callId, reqLog) {
|
|
2538
|
+
if (!fn.secure)
|
|
2539
|
+
return null;
|
|
2540
|
+
if (!token) {
|
|
2541
|
+
reqLog.warn('token_missing');
|
|
2542
|
+
}
|
|
2543
|
+
else if (!callId) {
|
|
2544
|
+
reqLog.warn('token_rejected_no_call_id');
|
|
2545
|
+
}
|
|
2546
|
+
else if (this.sessionManager.validateToken(callId, fn.name, token)) {
|
|
2547
|
+
reqLog.debug('token_valid');
|
|
2548
|
+
return null;
|
|
2549
|
+
}
|
|
2550
|
+
else {
|
|
2551
|
+
reqLog.warn('token_invalid');
|
|
2552
|
+
}
|
|
2553
|
+
// The reference's exact wording: the refusal is part of the SWAIG wire contract.
|
|
2554
|
+
return new FunctionResult("I'm sorry, the security token for this function is invalid or expired. I cannot execute this action.").toDict();
|
|
2555
|
+
}
|
|
2556
|
+
extractSwaigArgs(body, reqLog) {
|
|
2557
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
2558
|
+
const argument = body['argument'];
|
|
2559
|
+
if (isPlainObject(argument)) {
|
|
2560
|
+
// Platform-nested shape: argument.parsed[0] holds the real args.
|
|
2561
|
+
const parsed = argument['parsed'];
|
|
2562
|
+
if (Array.isArray(parsed) && parsed.length > 0 && isPlainObject(parsed[0])) {
|
|
2563
|
+
return parsed[0];
|
|
2564
|
+
}
|
|
2565
|
+
// Fallback: argument.raw is a JSON string of the args.
|
|
2566
|
+
const raw = argument['raw'];
|
|
2567
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
2568
|
+
try {
|
|
2569
|
+
const decoded = JSON.parse(raw);
|
|
2570
|
+
if (isPlainObject(decoded))
|
|
2571
|
+
return decoded;
|
|
2572
|
+
}
|
|
2573
|
+
catch (e) {
|
|
2574
|
+
reqLog.error('error_parsing_raw_arguments', {
|
|
2575
|
+
error: e instanceof Error ? e.message : String(e),
|
|
2576
|
+
});
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
return {};
|
|
2580
|
+
}
|
|
2581
|
+
// Flat shape used by some external integrations: {"arguments": {...}}.
|
|
2582
|
+
const flat = body['arguments'];
|
|
2583
|
+
if (isPlainObject(flat))
|
|
2584
|
+
return flat;
|
|
2585
|
+
return {};
|
|
2586
|
+
}
|
|
1713
2587
|
// ── 5-phase SWML rendering ─────────────────────────────────────────
|
|
1714
2588
|
/**
|
|
1715
2589
|
* Render the complete SWML document by assembling all 5 phases: pre-answer, answer,
|
|
@@ -1722,6 +2596,7 @@ export class AgentBase extends SWMLService {
|
|
|
1722
2596
|
* @returns The rendered SWML document as a JSON string.
|
|
1723
2597
|
*/
|
|
1724
2598
|
renderSwml(callId, modifications) {
|
|
2599
|
+
this.ensureToolsDefined();
|
|
1725
2600
|
this.swmlBuilder.reset();
|
|
1726
2601
|
const prompt = this.getPrompt();
|
|
1727
2602
|
const postPrompt = this.getPostPrompt();
|
|
@@ -1751,11 +2626,7 @@ export class AgentBase extends SWMLService {
|
|
|
1751
2626
|
const entry = {
|
|
1752
2627
|
function: name,
|
|
1753
2628
|
description: fn.description,
|
|
1754
|
-
parameters: fn.parameters
|
|
1755
|
-
? ('type' in fn.parameters && 'properties' in fn.parameters
|
|
1756
|
-
? fn.parameters
|
|
1757
|
-
: { type: 'object', properties: fn.parameters, ...(fn.required.length ? { required: fn.required } : {}) })
|
|
1758
|
-
: { type: 'object', properties: {} },
|
|
2629
|
+
parameters: normalizeParameters(fn.parameters, fn.required),
|
|
1759
2630
|
};
|
|
1760
2631
|
if (fn.fillers && Object.keys(fn.fillers).length)
|
|
1761
2632
|
entry['fillers'] = fn.fillers;
|
|
@@ -1773,11 +2644,16 @@ export class AgentBase extends SWMLService {
|
|
|
1773
2644
|
entry['web_hook_url'] = this.buildWebhookUrl('swaig', urlParams);
|
|
1774
2645
|
}
|
|
1775
2646
|
safeAssign(entry, fn.extraFields);
|
|
2647
|
+
// Gates are checked once more as sent: under the name the entry carries,
|
|
2648
|
+
// with its URL or the defaults' URL (the platform drops a gated
|
|
2649
|
+
// function it can't register).
|
|
2650
|
+
_checkGatedFunction(entry, defaultWebhookUrl);
|
|
1776
2651
|
functions.push(entry);
|
|
1777
2652
|
}
|
|
1778
2653
|
else {
|
|
1779
2654
|
// Raw dict (DataMap) - use as-is
|
|
1780
2655
|
const entry = { ...fn, function: name };
|
|
2656
|
+
_checkGatedFunction(entry, defaultWebhookUrl);
|
|
1781
2657
|
functions.push(entry);
|
|
1782
2658
|
}
|
|
1783
2659
|
}
|
|
@@ -1807,35 +2683,45 @@ export class AgentBase extends SWMLService {
|
|
|
1807
2683
|
this.swmlBuilder.addVerb(verb, config);
|
|
1808
2684
|
}
|
|
1809
2685
|
// ── PHASE 2: Answer verb ──
|
|
2686
|
+
// Internally-assembled trusted verb — skip the schema pass (its shape is
|
|
2687
|
+
// fixed by the builder, and revalidating it on every render would pay the
|
|
2688
|
+
// full-schema Ajv compile cost on the hot path). User-supplied verbs below
|
|
2689
|
+
// still validate.
|
|
1810
2690
|
if (this.autoAnswer) {
|
|
1811
|
-
this.swmlBuilder.addVerb('answer', this.answerConfig);
|
|
2691
|
+
this.swmlBuilder.addVerb('answer', this.answerConfig, { skipValidation: true });
|
|
1812
2692
|
}
|
|
1813
2693
|
// ── PHASE 3: Post-answer verbs ──
|
|
1814
2694
|
if (this._recordCall) {
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
stereo: this.recordStereo,
|
|
1818
|
-
});
|
|
2695
|
+
// Internally-assembled trusted verb — skip the schema pass (see PHASE 2).
|
|
2696
|
+
this.swmlBuilder.addVerb('record_call', { format: this.recordFormat, stereo: this.recordStereo }, { skipValidation: true });
|
|
1819
2697
|
}
|
|
1820
2698
|
for (const [verb, config] of this.postAnswerVerbs) {
|
|
1821
2699
|
this.swmlBuilder.addVerb(verb, config);
|
|
1822
2700
|
}
|
|
1823
2701
|
// ── PHASE 4: AI verb ──
|
|
1824
2702
|
const aiConfig = {};
|
|
1825
|
-
// Prompt
|
|
1826
|
-
if
|
|
1827
|
-
|
|
1828
|
-
|
|
2703
|
+
// Prompt. Mirror Python (agent_base.py: `prompt_is_pom = isinstance(prompt, list)`;
|
|
2704
|
+
// ai_config = {"prompt": {"text" if not prompt_is_pom else "pom": prompt}}):
|
|
2705
|
+
// when the agent is in POM mode with at least one section AND no raw prompt
|
|
2706
|
+
// string was set, the prompt renders as a structured `pom` array, not `text`.
|
|
2707
|
+
// A raw prompt string (getRawPrompt) always wins, matching PromptManager.getPrompt.
|
|
2708
|
+
const promptPom = this.getRawPrompt() === null ? this.getPromptPom() : null;
|
|
2709
|
+
const buildPromptObj = (fallbackText) => {
|
|
2710
|
+
const obj = promptPom ? { pom: promptPom } : { text: fallbackText };
|
|
1829
2711
|
if (Object.keys(this.promptLlmParams).length)
|
|
1830
|
-
Object.assign(
|
|
2712
|
+
Object.assign(obj, this.promptLlmParams);
|
|
2713
|
+
return obj;
|
|
2714
|
+
};
|
|
2715
|
+
const contextsDict = this.contextsBuilder?.toDict() ?? this._rawContexts;
|
|
2716
|
+
if (contextsDict) {
|
|
2717
|
+
// Contexts live inside the prompt (`ai.prompt.contexts`), where the
|
|
2718
|
+
// platform reads them and the reference SDK renders them.
|
|
2719
|
+
const promptObj = buildPromptObj(prompt || `You are ${this.name}, a helpful AI assistant.`);
|
|
2720
|
+
promptObj['contexts'] = contextsDict;
|
|
1831
2721
|
aiConfig['prompt'] = promptObj;
|
|
1832
|
-
aiConfig['contexts'] = contextsDict;
|
|
1833
2722
|
}
|
|
1834
2723
|
else {
|
|
1835
|
-
|
|
1836
|
-
if (Object.keys(this.promptLlmParams).length)
|
|
1837
|
-
Object.assign(promptObj, this.promptLlmParams);
|
|
1838
|
-
aiConfig['prompt'] = promptObj;
|
|
2724
|
+
aiConfig['prompt'] = buildPromptObj(prompt);
|
|
1839
2725
|
}
|
|
1840
2726
|
// Post-prompt
|
|
1841
2727
|
if (postPrompt) {
|
|
@@ -1854,6 +2740,9 @@ export class AgentBase extends SWMLService {
|
|
|
1854
2740
|
aiConfig['hints'] = this.hints;
|
|
1855
2741
|
if (this.languages.length)
|
|
1856
2742
|
aiConfig['languages'] = this.languages;
|
|
2743
|
+
// ASR-driven multilingual mode: a top-level `multilingual` object on the AI verb.
|
|
2744
|
+
if (Object.keys(this.multilingual).length)
|
|
2745
|
+
aiConfig['multilingual'] = this.multilingual;
|
|
1857
2746
|
if (this.pronounce.length)
|
|
1858
2747
|
aiConfig['pronounce'] = this.pronounce;
|
|
1859
2748
|
if (Object.keys(this.params).length)
|
|
@@ -1865,7 +2754,7 @@ export class AgentBase extends SWMLService {
|
|
|
1865
2754
|
aiConfig['debug_webhook_url'] = this.buildWebhookUrl('debug_events');
|
|
1866
2755
|
aiConfig['debug_webhook_level'] = this.debugEventsLevel;
|
|
1867
2756
|
}
|
|
1868
|
-
// Apply modifications from onSwmlRequest (Python
|
|
2757
|
+
// Apply modifications from onSwmlRequest (Python equivalent: merge into AI verb config).
|
|
1869
2758
|
// global_data is deep-merged; all other keys override AI config fields directly.
|
|
1870
2759
|
if (modifications && typeof modifications === 'object') {
|
|
1871
2760
|
if (modifications['global_data'] && typeof modifications['global_data'] === 'object') {
|
|
@@ -1880,110 +2769,175 @@ export class AgentBase extends SWMLService {
|
|
|
1880
2769
|
}
|
|
1881
2770
|
}
|
|
1882
2771
|
}
|
|
1883
|
-
|
|
2772
|
+
// The assembled ai verb may legitimately carry real SWML the bundled schema
|
|
2773
|
+
// does not yet model (multilingual, SWAIG.mcp_servers, per-language
|
|
2774
|
+
// engine/model/fillers, debug_webhook_url). It is built from typed builder
|
|
2775
|
+
// inputs, not raw user config, so skip the closed-schema check here; the
|
|
2776
|
+
// strict-render contract governs direct addVerb input, not trusted assembly.
|
|
2777
|
+
this.swmlBuilder.addVerb('ai', aiConfig, { skipValidation: true });
|
|
1884
2778
|
// ── PHASE 5: Post-AI verbs ──
|
|
1885
2779
|
for (const [verb, config] of this.postAiVerbs) {
|
|
1886
2780
|
this.swmlBuilder.addVerb(verb, config);
|
|
1887
2781
|
}
|
|
1888
|
-
return this.swmlBuilder.
|
|
2782
|
+
return this.swmlBuilder.render();
|
|
1889
2783
|
}
|
|
1890
2784
|
// ── Ephemeral copy for dynamic config ───────────────────────────────
|
|
1891
2785
|
createEphemeralCopy() {
|
|
1892
2786
|
const copy = Object.create(Object.getPrototypeOf(this));
|
|
1893
2787
|
Object.assign(copy, this);
|
|
1894
|
-
//
|
|
1895
|
-
|
|
1896
|
-
//
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
const
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
copy.
|
|
1907
|
-
copy.
|
|
1908
|
-
copy.
|
|
1909
|
-
copy.
|
|
1910
|
-
copy.
|
|
1911
|
-
copy.
|
|
1912
|
-
copy.
|
|
1913
|
-
|
|
1914
|
-
copy.
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
if (fn instanceof SwaigFunction) {
|
|
1938
|
-
if (Object.keys(skill.swaigFields).length > 0) {
|
|
1939
|
-
safeAssign(fn.extraFields, skill.swaigFields);
|
|
1940
|
-
}
|
|
1941
|
-
if (toolDef.wait_for_fillers !== undefined) {
|
|
1942
|
-
fn.extraFields['wait_for_fillers'] = toolDef.wait_for_fillers;
|
|
1943
|
-
}
|
|
1944
|
-
if (toolDef.skip_fillers !== undefined) {
|
|
1945
|
-
fn.extraFields['skip_fillers'] = toolDef.skip_fillers;
|
|
1946
|
-
}
|
|
1947
|
-
if (toolDef.isHangupHook) {
|
|
1948
|
-
fn.extraFields['is_hangup_hook'] = true;
|
|
1949
|
-
}
|
|
1950
|
-
}
|
|
1951
|
-
}
|
|
1952
|
-
for (const dmFn of skill.getDataMapTools()) {
|
|
1953
|
-
copy.registerSwaigFunction(dmFn);
|
|
1954
|
-
}
|
|
1955
|
-
for (const section of skill.getPromptSections()) {
|
|
1956
|
-
copy.promptAddSection(section.title, section);
|
|
1957
|
-
}
|
|
1958
|
-
const hints = skill.getHints();
|
|
1959
|
-
if (hints.length)
|
|
1960
|
-
copy.addHints(hints);
|
|
1961
|
-
const globalData = skill.getGlobalData();
|
|
1962
|
-
if (Object.keys(globalData).length)
|
|
1963
|
-
copy.updateGlobalData(globalData);
|
|
1964
|
-
}
|
|
1965
|
-
catch (e) {
|
|
1966
|
-
this.log.warn(`Failed to replay skill '${entry.skillName}' in ephemeral copy: ${e}`);
|
|
1967
|
-
}
|
|
1968
|
-
}
|
|
2788
|
+
// Every field starts as a reference to this agent's. The configuration a
|
|
2789
|
+
// per-request callback can change is then replaced with independent
|
|
2790
|
+
// copies, so a callback's changes stay on this request: without that, one
|
|
2791
|
+
// caller's query params, MCP servers or context edits would reach every
|
|
2792
|
+
// later call. References to this agent inside the copied state (the
|
|
2793
|
+
// contexts builder's back-reference) are redirected to the copy.
|
|
2794
|
+
const memo = new Map([[this, copy]]);
|
|
2795
|
+
const clone = (value) => deepCloneState(value, memo);
|
|
2796
|
+
// The copy's own prompt state, with the POM sections copied rather than
|
|
2797
|
+
// rendered to text, so it still emits a structured prompt and a callback
|
|
2798
|
+
// can add sections to it. The back-reference points at the COPY, not
|
|
2799
|
+
// `this` (the clone-drops-configuration defect class).
|
|
2800
|
+
copy._promptManager = this._promptManager._copyFor(copy);
|
|
2801
|
+
copy.toolRegistry = clone(this.toolRegistry);
|
|
2802
|
+
copy.hints = clone(this.hints);
|
|
2803
|
+
copy.languages = clone(this.languages);
|
|
2804
|
+
copy.multilingual = clone(this.multilingual);
|
|
2805
|
+
copy.pronounce = clone(this.pronounce);
|
|
2806
|
+
copy.params = clone(this.params);
|
|
2807
|
+
copy.globalData = clone(this.globalData);
|
|
2808
|
+
copy.functionIncludes = clone(this.functionIncludes);
|
|
2809
|
+
copy.promptLlmParams = clone(this.promptLlmParams);
|
|
2810
|
+
copy.postPromptLlmParams = clone(this.postPromptLlmParams);
|
|
2811
|
+
copy.internalFillers = clone(this.internalFillers);
|
|
2812
|
+
copy.preAnswerVerbs = clone(this.preAnswerVerbs);
|
|
2813
|
+
copy.answerConfig = clone(this.answerConfig);
|
|
2814
|
+
copy.postAnswerVerbs = clone(this.postAnswerVerbs);
|
|
2815
|
+
copy.postAiVerbs = clone(this.postAiVerbs);
|
|
2816
|
+
copy.swaigQueryParams = clone(this.swaigQueryParams);
|
|
2817
|
+
copy._nativeFunctions = clone(this._nativeFunctions);
|
|
2818
|
+
copy._mcpServers = clone(this._mcpServers);
|
|
2819
|
+
copy._sipUsernames = this._sipUsernames ? new Map(this._sipUsernames) : null;
|
|
2820
|
+
copy._routingCallbacks = new Map(this._routingCallbacks);
|
|
2821
|
+
copy.contextsBuilder = clone(this.contextsBuilder);
|
|
2822
|
+
copy._rawContexts = clone(this._rawContexts);
|
|
2823
|
+
// Back-reference points at the COPY, not `this` (see _promptManager above).
|
|
2824
|
+
copy.swmlBuilder = new SwmlBuilder({ service: copy, ...this._builderSchemaOptions });
|
|
2825
|
+
// The copy starts with the skills this agent loaded. Their tools, hints,
|
|
2826
|
+
// prompt sections and global data are already in the state copied above,
|
|
2827
|
+
// so they aren't set up again: running every skill's setup() on every
|
|
2828
|
+
// request was slow, and left the copy's skill list empty until it finished.
|
|
2829
|
+
copy._skillManager = new SkillManager(copy);
|
|
2830
|
+
copy._skillManager._inheritFrom(this._skillManager);
|
|
1969
2831
|
return copy;
|
|
1970
2832
|
}
|
|
1971
2833
|
// ── Hono HTTP app ───────────────────────────────────────────────────
|
|
2834
|
+
/**
|
|
2835
|
+
* Thin Hono adapter over the decomposed {@link handleRequest} core. Extracts
|
|
2836
|
+
* `(method, url, headers, body)` primitives from the Hono `Context`, delegates
|
|
2837
|
+
* the auth / routing-callback / render DECISION to `handleRequest`, and
|
|
2838
|
+
* marshals the returned `[status, headers, body]` triple back into a Hono
|
|
2839
|
+
* `Response` — including the routing-callback **307** (`Location`) and the
|
|
2840
|
+
* **401** (`WWW-Authenticate`). This is what routes serve()/asRouter() through
|
|
2841
|
+
* the same core the primitive path uses, instead of a parallel inline
|
|
2842
|
+
* auth/render/redirect path (mirrors the rust/dotnet/php served path).
|
|
2843
|
+
*
|
|
2844
|
+
* Proxy detection stays here as framework plumbing (it needs the raw request);
|
|
2845
|
+
* everything else comes from `handleRequest`.
|
|
2846
|
+
*/
|
|
2847
|
+
// Call it only from a route behind the basic-auth middleware: handleRequest()
|
|
2848
|
+
// skips its own credential check for a served request.
|
|
2849
|
+
async serveViaHandleRequest(c) {
|
|
2850
|
+
this.detectProxyFromRequest(c);
|
|
2851
|
+
// A serverless adapter passes the base URL the platform was called on
|
|
2852
|
+
// (Azure's /api/<function>, say), so the SWML's webhook URLs point back
|
|
2853
|
+
// there. SWML_PROXY_URL_BASE still wins.
|
|
2854
|
+
const platformBase = c.env?.[_PLATFORM_BASE_ENV_KEY];
|
|
2855
|
+
if (typeof platformBase === 'string' && platformBase && !this._proxyUrlBaseFromEnv) {
|
|
2856
|
+
this._proxyUrlBase = platformBase.replace(/\/+$/, '');
|
|
2857
|
+
}
|
|
2858
|
+
let body = null;
|
|
2859
|
+
try {
|
|
2860
|
+
body = (await c.req.json());
|
|
2861
|
+
}
|
|
2862
|
+
catch {
|
|
2863
|
+
/* GET or no body */
|
|
2864
|
+
}
|
|
2865
|
+
const headers = {};
|
|
2866
|
+
c.req.raw.headers.forEach((v, k) => {
|
|
2867
|
+
headers[k] = v;
|
|
2868
|
+
});
|
|
2869
|
+
// Through the public handleRequest(), so a subclass override still
|
|
2870
|
+
// decides served requests; the Hono context rides along for onSwmlRequest.
|
|
2871
|
+
const [status, respHeaders, bodyStr] = await servedRequestContext.run(c, () => this.handleRequest(c.req.method, c.req.url, headers, body));
|
|
2872
|
+
// 307 routing redirect — real redirect status + Location, empty body.
|
|
2873
|
+
if (status === 307 && respHeaders['Location']) {
|
|
2874
|
+
return c.redirect(respHeaders['Location'], 307);
|
|
2875
|
+
}
|
|
2876
|
+
// Marshal any remaining headers (e.g. WWW-Authenticate on a 401) and emit
|
|
2877
|
+
// the body. The 200 SWML body is a JSON string; other statuses carry a JSON
|
|
2878
|
+
// error string — both are already serialized, so pass through with a JSON
|
|
2879
|
+
// content type and the exact status handleRequest chose.
|
|
2880
|
+
for (const [k, v] of Object.entries(respHeaders)) {
|
|
2881
|
+
c.header(k, v);
|
|
2882
|
+
}
|
|
2883
|
+
c.header('Content-Type', 'application/json');
|
|
2884
|
+
// The 307 redirect returned above; every remaining status (200 SWML, 401,
|
|
2885
|
+
// 4xx/5xx error JSON) carries a body, so it is a ContentfulStatusCode.
|
|
2886
|
+
return c.body(bodyStr, status);
|
|
2887
|
+
}
|
|
1972
2888
|
/**
|
|
1973
2889
|
* Get or lazily create the Hono HTTP application with all routes, middleware, auth, and CORS.
|
|
1974
2890
|
* @returns The configured Hono application instance.
|
|
1975
2891
|
*/
|
|
1976
2892
|
getApp() {
|
|
2893
|
+
// Make sure subclass tools are registered before any route can dispatch
|
|
2894
|
+
// a SWAIG call (idempotent — see ensureToolsDefined).
|
|
2895
|
+
this.ensureToolsDefined();
|
|
1977
2896
|
// Service's constructor eagerly initialised _app; AgentBase rebuilds it
|
|
1978
2897
|
// here with its own middleware stack and route handlers on first call.
|
|
1979
2898
|
if (this._appBuiltByAgent)
|
|
1980
2899
|
return this._app;
|
|
1981
|
-
|
|
2900
|
+
this._app = this.buildApp(this.route === '/' ? '' : this.route);
|
|
2901
|
+
this._appBuiltByAgent = true;
|
|
2902
|
+
return this._app;
|
|
2903
|
+
}
|
|
2904
|
+
/**
|
|
2905
|
+
* Build the Hono app serving this agent's routes under `basePath` ('' for
|
|
2906
|
+
* route-relative routes, as {@link asRouter} returns them).
|
|
2907
|
+
*
|
|
2908
|
+
* Paths are matched without regard to a trailing slash or repeated slashes
|
|
2909
|
+
* (`/agent/swaig/`, `/agent//swaig`), as the reference's router and
|
|
2910
|
+
* catch-all routes accept them; the signature check still covers the URL
|
|
2911
|
+
* as the request spelled it.
|
|
2912
|
+
*/
|
|
2913
|
+
buildApp(basePath) {
|
|
2914
|
+
// getPathNoStrict drops a trailing slash; repeated slashes are collapsed
|
|
2915
|
+
// too. (Hono ignores a custom getPath when `strict: false` is passed.)
|
|
2916
|
+
const app = new Hono({
|
|
2917
|
+
getPath: (req) => getPathNoStrict(req).replace(/\/{2,}/g, '/'),
|
|
2918
|
+
});
|
|
2919
|
+
// Each path with and without a trailing slash, so a host app that mounts
|
|
2920
|
+
// asRouter() with strict routing still serves `/swaig/` (as the
|
|
2921
|
+
// reference's router registers both).
|
|
2922
|
+
const withSlash = (path) => [path, `${path}/`];
|
|
1982
2923
|
// Security headers
|
|
1983
|
-
const requestTimeout = parseInt(process.env['SWML_REQUEST_TIMEOUT'] ?? '30000', 10);
|
|
1984
2924
|
const maxRequestSize = parseInt(process.env['SWML_MAX_REQUEST_SIZE'] ?? '1048576', 10);
|
|
2925
|
+
// The agent's header, CORS and CSRF middleware apply to the requests its
|
|
2926
|
+
// own routes serve (by method and path), so a mounted app (see mount())
|
|
2927
|
+
// keeps its own headers and CORS preflights, and so does another agent's
|
|
2928
|
+
// route or mount below this one's under AgentServer. (A mounted page
|
|
2929
|
+
// couldn't work under default-src 'none'.) Paths are compared relative
|
|
2930
|
+
// to where this app is mounted (routePath), so asRouter() under
|
|
2931
|
+
// AgentServer works the same.
|
|
2932
|
+
const agentRoutes = { byMethod: new Set(), paths: new Set() };
|
|
2933
|
+
AGENT_ROUTES.set(app, agentRoutes);
|
|
2934
|
+
const underMount = (c) => !ownsRoute(agentRoutes, c.req.method, relativePath(c.req.path, c.req.routePath));
|
|
1985
2935
|
app.use('*', async (c, next) => {
|
|
2936
|
+
// routePath names the handler after next(), so decide first.
|
|
2937
|
+
const mounted = underMount(c);
|
|
1986
2938
|
await next();
|
|
2939
|
+
if (mounted)
|
|
2940
|
+
return;
|
|
1987
2941
|
c.res.headers.set('X-Content-Type-Options', 'nosniff');
|
|
1988
2942
|
c.res.headers.set('X-Frame-Options', 'DENY');
|
|
1989
2943
|
c.res.headers.set('X-XSS-Protection', '1; mode=block');
|
|
@@ -2001,11 +2955,16 @@ export class AgentBase extends SWMLService {
|
|
|
2001
2955
|
await next();
|
|
2002
2956
|
});
|
|
2003
2957
|
// Allowed hosts (configurable via env)
|
|
2958
|
+
// "*" allows every host, as the reference reads it.
|
|
2004
2959
|
const allowedHosts = process.env['SWML_ALLOWED_HOSTS'];
|
|
2005
|
-
|
|
2006
|
-
|
|
2960
|
+
const hostList = (allowedHosts ?? '')
|
|
2961
|
+
.split(',')
|
|
2962
|
+
.map((h) => h.trim().toLowerCase())
|
|
2963
|
+
.filter(Boolean);
|
|
2964
|
+
if (hostList.length > 0 && !hostList.includes('*')) {
|
|
2965
|
+
const hostSet = new Set(hostList);
|
|
2007
2966
|
app.use('*', async (c, next) => {
|
|
2008
|
-
const host = (c.req.header('host') ?? '').split(':')[0].toLowerCase();
|
|
2967
|
+
const host = (c.req.header('host') ?? '').split(':')[0].toLowerCase(); // split yields >=1 element
|
|
2009
2968
|
if (!hostSet.has(host)) {
|
|
2010
2969
|
return c.json({ error: 'Forbidden: host not allowed' }, 403);
|
|
2011
2970
|
}
|
|
@@ -2019,11 +2978,18 @@ export class AgentBase extends SWMLService {
|
|
|
2019
2978
|
if (maxPerMinute > 0) {
|
|
2020
2979
|
const hits = new Map();
|
|
2021
2980
|
app.use('*', async (c, next) => {
|
|
2981
|
+
// The connection's own address, as the reference keys on
|
|
2982
|
+
// request.client.host; the forwarded headers only when trusted.
|
|
2983
|
+
// On a serverless platform, the address the platform reports.
|
|
2984
|
+
const env = c.env;
|
|
2985
|
+
const platformIp = env?.[_CLIENT_ADDRESS_ENV_KEY];
|
|
2986
|
+
const socketIp = env?.incoming?.socket?.remoteAddress ??
|
|
2987
|
+
(typeof platformIp === 'string' ? platformIp : 'unknown');
|
|
2022
2988
|
const ip = this._trustProxyHeaders
|
|
2023
|
-
? (c.req.header('x-forwarded-for')?.split(',')[0].trim()
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
:
|
|
2989
|
+
? (c.req.header('x-forwarded-for')?.split(',')[0].trim() ??
|
|
2990
|
+
c.req.header('x-real-ip') ??
|
|
2991
|
+
socketIp)
|
|
2992
|
+
: socketIp;
|
|
2027
2993
|
const now = Date.now();
|
|
2028
2994
|
let entry = hits.get(ip);
|
|
2029
2995
|
if (!entry || now >= entry.resetAt) {
|
|
@@ -2047,16 +3013,15 @@ export class AgentBase extends SWMLService {
|
|
|
2047
3013
|
}
|
|
2048
3014
|
// CORS (configurable via env)
|
|
2049
3015
|
const corsOrigins = process.env['SWML_CORS_ORIGINS'];
|
|
2050
|
-
const corsOrigin = corsOrigins
|
|
3016
|
+
const corsOrigin = corsOriginsFromEnv(corsOrigins);
|
|
2051
3017
|
const corsCredentials = corsOrigin !== '*';
|
|
2052
|
-
|
|
3018
|
+
const corsMw = cors({ origin: corsOrigin, credentials: corsCredentials });
|
|
3019
|
+
app.use('*', (c, next) => (underMount(c) ? next() : corsMw(c, next)));
|
|
2053
3020
|
// CSRF protection (optional, gated by env)
|
|
2054
3021
|
if (process.env['SWML_CSRF_PROTECTION'] === 'true') {
|
|
2055
|
-
const allowedOrigins =
|
|
2056
|
-
? new Set(corsOrigins.split(',').map(o => o.trim().toLowerCase()))
|
|
2057
|
-
: null;
|
|
3022
|
+
const allowedOrigins = corsOrigin === '*' ? null : new Set(corsOrigin.map((o) => o.toLowerCase()));
|
|
2058
3023
|
app.use('*', async (c, next) => {
|
|
2059
|
-
if (c.req.method === 'POST') {
|
|
3024
|
+
if (c.req.method === 'POST' && !underMount(c)) {
|
|
2060
3025
|
const origin = c.req.header('origin');
|
|
2061
3026
|
if (origin && allowedOrigins && !allowedOrigins.has(origin.toLowerCase())) {
|
|
2062
3027
|
return c.json({ error: 'Origin not allowed' }, 403);
|
|
@@ -2065,66 +3030,65 @@ export class AgentBase extends SWMLService {
|
|
|
2065
3030
|
await next();
|
|
2066
3031
|
});
|
|
2067
3032
|
}
|
|
2068
|
-
// Auth middleware
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
//
|
|
3033
|
+
// Auth middleware. The 401 challenge body must be the JSON envelope
|
|
3034
|
+
// {"error":"Unauthorized"} to match Python's auth challenge
|
|
3035
|
+
// (auth_mixin._send_lambda_auth_challenge / the primitive handleRequest 401);
|
|
3036
|
+
// Hono's default basicAuth returns a plain "Unauthorized" text body, which
|
|
3037
|
+
// diverges on the serverless dispatch path.
|
|
3038
|
+
const authMw = basicAuth({
|
|
3039
|
+
verifyUser: (username, password) => this.validateBasicAuth(username, password),
|
|
3040
|
+
invalidUserMessage: JSON.stringify({ error: 'Unauthorized' }),
|
|
3041
|
+
});
|
|
3042
|
+
// Webhook signature validation middleware — only mounted (and only on
|
|
3043
|
+
// POST routes) when a signing key is configured. Per
|
|
3044
|
+
// porting-sdk/webhooks.md, signed routes are POST / (SWML), POST /swaig,
|
|
3045
|
+
// and POST /post_prompt. GET / serves SWML to the platform's GET probe,
|
|
3046
|
+
// which is unsigned, so we don't apply the middleware to GET.
|
|
3047
|
+
const sigMw = this._signingKey !== null
|
|
3048
|
+
? webhookValidationMiddleware({
|
|
3049
|
+
signingKey: this._signingKey,
|
|
3050
|
+
trustProxy: this._webhookTrustProxy,
|
|
3051
|
+
})
|
|
3052
|
+
: null;
|
|
3053
|
+
// Root - returns SWML. Delegates the auth / routing-callback / dynamic-config
|
|
3054
|
+
// / render DECISION to handleRequest (the decomposed core), then marshals the
|
|
3055
|
+
// [status, headers, body] triple back — so serve()/asRouter() honor the
|
|
3056
|
+
// routing-callback 307 on the root path too, through the same core the
|
|
3057
|
+
// primitive path uses. Proxy detection stays in the thin adapter.
|
|
2073
3058
|
const handleSwml = async (c) => {
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
let body = {};
|
|
2077
|
-
try {
|
|
2078
|
-
body = await c.req.json();
|
|
2079
|
-
}
|
|
2080
|
-
catch { /* GET or no body */ }
|
|
2081
|
-
reqLog.debug('request_body_received', { body_size: JSON.stringify(body).length });
|
|
2082
|
-
this.detectProxyFromRequest(c);
|
|
2083
|
-
const callbackPath = body['callback_path'] ?? undefined;
|
|
2084
|
-
let swmlMods = undefined;
|
|
2085
|
-
try {
|
|
2086
|
-
swmlMods = await this.onSwmlRequest(body, callbackPath, c);
|
|
2087
|
-
if (swmlMods)
|
|
2088
|
-
reqLog.debug('on_swml_request_modifications_applied');
|
|
2089
|
-
}
|
|
2090
|
-
catch (err) {
|
|
2091
|
-
reqLog.error('error_in_on_swml_request', { error: err instanceof Error ? err.message : String(err) });
|
|
2092
|
-
}
|
|
2093
|
-
const callId = body['call_id'] || undefined;
|
|
2094
|
-
if (callId)
|
|
2095
|
-
reqLog = reqLog.bind({ call_id: callId });
|
|
2096
|
-
let agentToUse = this;
|
|
2097
|
-
if (this.dynamicConfigCallback) {
|
|
2098
|
-
agentToUse = this.createEphemeralCopy();
|
|
2099
|
-
const queryParams = {};
|
|
2100
|
-
const url = new URL(c.req.url);
|
|
2101
|
-
url.searchParams.forEach((v, k) => { queryParams[k] = v; });
|
|
2102
|
-
const rawHeaders = {};
|
|
2103
|
-
c.req.raw.headers.forEach((v, k) => { rawHeaders[k] = v; });
|
|
2104
|
-
const headers = filterSensitiveHeaders(rawHeaders);
|
|
2105
|
-
await this.dynamicConfigCallback(queryParams, body, headers, agentToUse);
|
|
2106
|
-
reqLog.debug('dynamic_config_complete');
|
|
2107
|
-
}
|
|
2108
|
-
const swml = agentToUse.renderSwml(callId, swmlMods || undefined);
|
|
2109
|
-
reqLog.debug('swml_rendered', { swml_size: swml.length });
|
|
2110
|
-
reqLog.info('request_successful');
|
|
2111
|
-
return c.json(JSON.parse(swml));
|
|
3059
|
+
this.log.bind({ endpoint: this.route }).debug('endpoint_called');
|
|
3060
|
+
return this.serveViaHandleRequest(c);
|
|
2112
3061
|
};
|
|
2113
3062
|
app.get(`${basePath}`, authMw, handleSwml);
|
|
2114
|
-
|
|
3063
|
+
if (sigMw) {
|
|
3064
|
+
app.post(`${basePath}`, authMw, sigMw, handleSwml);
|
|
3065
|
+
}
|
|
3066
|
+
else {
|
|
3067
|
+
app.post(`${basePath}`, authMw, handleSwml);
|
|
3068
|
+
}
|
|
2115
3069
|
if (basePath) {
|
|
2116
3070
|
app.get(`${basePath}/`, authMw, handleSwml);
|
|
2117
|
-
|
|
3071
|
+
if (sigMw) {
|
|
3072
|
+
app.post(`${basePath}/`, authMw, sigMw, handleSwml);
|
|
3073
|
+
}
|
|
3074
|
+
else {
|
|
3075
|
+
app.post(`${basePath}/`, authMw, handleSwml);
|
|
3076
|
+
}
|
|
2118
3077
|
}
|
|
2119
3078
|
// SWAIG function dispatcher
|
|
2120
3079
|
const handleSwaig = async (c) => {
|
|
2121
3080
|
let reqLog = this.log.bind({ endpoint: `${basePath}/swaig` });
|
|
2122
3081
|
reqLog.debug('endpoint_called');
|
|
3082
|
+
// Runtime fallback is the empty object (unchanged); the cast is
|
|
3083
|
+
// compile-time only — the backend always POSTs the full SWAIG payload,
|
|
3084
|
+
// and the parse-failure path below is rejected before any field is read.
|
|
2123
3085
|
let body = {};
|
|
2124
3086
|
try {
|
|
2125
3087
|
body = await c.req.json();
|
|
2126
3088
|
}
|
|
2127
|
-
catch {
|
|
3089
|
+
catch {
|
|
3090
|
+
/* empty */
|
|
3091
|
+
}
|
|
2128
3092
|
const fnName = body['function'];
|
|
2129
3093
|
if (!fnName)
|
|
2130
3094
|
return c.json({ error: 'Missing function name' }, 400);
|
|
@@ -2139,70 +3103,121 @@ export class AgentBase extends SWMLService {
|
|
|
2139
3103
|
const callIdStr = body['call_id'] ?? '';
|
|
2140
3104
|
if (callIdStr)
|
|
2141
3105
|
reqLog = reqLog.bind({ call_id: callIdStr });
|
|
2142
|
-
|
|
3106
|
+
// The function runs on the agent the call's SWML came from: with a
|
|
3107
|
+
// dynamic config callback, the request's configured copy. So a tool the
|
|
3108
|
+
// callback registered or secured is found, and its token checked, here.
|
|
3109
|
+
const target = await this.perCallAgent(queryParamsOf(c.req.url), body, headersOf(c));
|
|
3110
|
+
const fn = target.toolRegistry.get(fnName);
|
|
2143
3111
|
if (!fn || !(fn instanceof SwaigFunction)) {
|
|
2144
3112
|
reqLog.warn('function_not_found', { requested: fnName });
|
|
2145
3113
|
return c.json({ error: `Unknown function: ${fnName}` }, 404);
|
|
2146
3114
|
}
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
const result = new FunctionResult('The security token for this function is missing or expired. This action cannot be completed.');
|
|
2154
|
-
return c.json(result.toDict());
|
|
2155
|
-
}
|
|
2156
|
-
if (!this.sessionManager.validateToken(callIdStr, fnName, token)) {
|
|
2157
|
-
reqLog.warn('token_invalid');
|
|
2158
|
-
const result = new FunctionResult('The security token for this function is invalid or expired. This action cannot be completed.');
|
|
2159
|
-
return c.json(result.toDict());
|
|
2160
|
-
}
|
|
2161
|
-
reqLog.debug('token_valid');
|
|
2162
|
-
}
|
|
2163
|
-
const rawArgs = body['argument'];
|
|
2164
|
-
const args = (rawArgs !== null && typeof rawArgs === 'object' && !Array.isArray(rawArgs))
|
|
2165
|
-
? rawArgs
|
|
2166
|
-
: {};
|
|
3115
|
+
const url = new URL(c.req.url);
|
|
3116
|
+
const token = url.searchParams.get('__token') ?? url.searchParams.get('token');
|
|
3117
|
+
const refusal = target.swaigTokenRefusal(fn, token, callIdStr, reqLog);
|
|
3118
|
+
if (refusal)
|
|
3119
|
+
return c.json(refusal);
|
|
3120
|
+
const args = this.extractSwaigArgs(body, reqLog);
|
|
2167
3121
|
reqLog.debug('executing_function', { args: JSON.stringify(args) });
|
|
2168
|
-
const hookResult = await
|
|
3122
|
+
const hookResult = await target.onFunctionCall(fnName, args, body);
|
|
2169
3123
|
// If onFunctionCall returned a result, use it (dispatch interception)
|
|
2170
3124
|
if (hookResult !== undefined && hookResult !== null) {
|
|
2171
3125
|
reqLog.info('function_intercepted_by_hook');
|
|
2172
3126
|
return c.json(hookResult);
|
|
2173
3127
|
}
|
|
2174
3128
|
try {
|
|
2175
|
-
const result = await fn.
|
|
3129
|
+
const result = await fn._executeAs(target, args, body, target._onError);
|
|
2176
3130
|
reqLog.info('function_executed_successfully');
|
|
2177
3131
|
reqLog.debug('function_result', { result_size: JSON.stringify(result).length });
|
|
2178
3132
|
return c.json(result);
|
|
2179
3133
|
}
|
|
2180
3134
|
catch (err) {
|
|
2181
|
-
reqLog.error('function_execution_error', {
|
|
3135
|
+
reqLog.error('function_execution_error', {
|
|
3136
|
+
error: err instanceof Error ? err.message : String(err),
|
|
3137
|
+
});
|
|
2182
3138
|
return c.json({ error: 'Function execution failed' }, 500);
|
|
2183
3139
|
}
|
|
2184
3140
|
};
|
|
2185
|
-
|
|
2186
|
-
|
|
3141
|
+
// A GET renders the SWML, like the agent's root (with ?call_id= for a
|
|
3142
|
+
// call's tokens); only a POST runs a function.
|
|
3143
|
+
const swaigPaths = withSlash(`${basePath}/swaig`);
|
|
3144
|
+
app.on('GET', swaigPaths, authMw, (c) => this.serveViaHandleRequest(c));
|
|
3145
|
+
if (sigMw) {
|
|
3146
|
+
app.on('POST', swaigPaths, authMw, sigMw, handleSwaig);
|
|
3147
|
+
}
|
|
3148
|
+
else {
|
|
3149
|
+
app.on('POST', swaigPaths, authMw, handleSwaig);
|
|
3150
|
+
}
|
|
2187
3151
|
// Post-prompt handler
|
|
2188
3152
|
const handlePostPrompt = async (c) => {
|
|
2189
3153
|
let reqLog = this.log.bind({ endpoint: `${basePath}/post_prompt` });
|
|
2190
3154
|
reqLog.debug('endpoint_called');
|
|
3155
|
+
// Runtime fallback is the empty object (unchanged); the cast is
|
|
3156
|
+
// compile-time only — the backend always POSTs the full post_prompt
|
|
3157
|
+
// payload, and the parse-failure path leaves an empty summary lookup.
|
|
2191
3158
|
let body = {};
|
|
2192
3159
|
try {
|
|
2193
3160
|
body = await c.req.json();
|
|
2194
3161
|
}
|
|
2195
|
-
catch {
|
|
2196
|
-
|
|
3162
|
+
catch {
|
|
3163
|
+
/* empty */
|
|
3164
|
+
}
|
|
3165
|
+
// A POST delivers a call's summary, so like a secure SWAIG function it
|
|
3166
|
+
// needs the token minted into the post-prompt URL for that call. The
|
|
3167
|
+
// call is the one the body names, or the URL's call_id when the body
|
|
3168
|
+
// names none; when they disagree the request is refused, so a token for
|
|
3169
|
+
// one call can't deliver another call's summary.
|
|
3170
|
+
const url = new URL(c.req.url);
|
|
3171
|
+
const queryCallId = url.searchParams.get('call_id') || undefined;
|
|
3172
|
+
const token = url.searchParams.get('__token') ?? url.searchParams.get('token');
|
|
3173
|
+
const rawBodyCallId = body['call_id'];
|
|
3174
|
+
const bodyCallId = typeof rawBodyCallId === 'string' && rawBodyCallId ? rawBodyCallId : undefined;
|
|
3175
|
+
if (queryCallId && bodyCallId && queryCallId !== bodyCallId) {
|
|
3176
|
+
reqLog.warn('call_id_mismatch');
|
|
3177
|
+
return c.json({ error: 'The call_id in the URL and the body differ' }, 400);
|
|
3178
|
+
}
|
|
3179
|
+
const callId = bodyCallId ?? queryCallId;
|
|
2197
3180
|
if (callId)
|
|
2198
3181
|
reqLog = reqLog.bind({ call_id: callId });
|
|
3182
|
+
if (!token) {
|
|
3183
|
+
reqLog.warn('token_missing');
|
|
3184
|
+
return c.json({ error: 'Invalid or missing token' }, 403);
|
|
3185
|
+
}
|
|
3186
|
+
if (!callId || !this.sessionManager.validateToken(callId, 'post_prompt', token)) {
|
|
3187
|
+
reqLog.warn('invalid_token');
|
|
3188
|
+
return c.json({ error: 'Invalid or missing token' }, 403);
|
|
3189
|
+
}
|
|
2199
3190
|
reqLog.info('post_prompt_received');
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
3191
|
+
// The summary goes to the agent the call ran on: with a dynamic config
|
|
3192
|
+
// callback, the request's configured copy.
|
|
3193
|
+
const target = await this.perCallAgent(queryParamsOf(c.req.url), body, headersOf(c));
|
|
3194
|
+
const summary = target.findSummary(body);
|
|
3195
|
+
let result;
|
|
3196
|
+
try {
|
|
3197
|
+
// onSummary is declared to return nothing, but an override may return
|
|
3198
|
+
// the conversation for a fetch_conversation request.
|
|
3199
|
+
result = await target.onSummary(summary, body);
|
|
3200
|
+
}
|
|
3201
|
+
catch (err) {
|
|
3202
|
+
reqLog.error('error_in_summary_handler', {
|
|
3203
|
+
error: err instanceof Error ? err.message : String(err),
|
|
3204
|
+
});
|
|
3205
|
+
}
|
|
3206
|
+
if (body['action'] === 'fetch_conversation' && result != null) {
|
|
3207
|
+
return c.json(result);
|
|
3208
|
+
}
|
|
3209
|
+
return c.json({ success: true });
|
|
2203
3210
|
};
|
|
2204
|
-
|
|
2205
|
-
|
|
3211
|
+
// A GET renders the SWML, like the agent's root; only a POST delivers a
|
|
3212
|
+
// summary.
|
|
3213
|
+
const postPromptPaths = withSlash(`${basePath}/post_prompt`);
|
|
3214
|
+
app.on('GET', postPromptPaths, authMw, (c) => this.serveViaHandleRequest(c));
|
|
3215
|
+
if (sigMw) {
|
|
3216
|
+
app.on('POST', postPromptPaths, authMw, sigMw, handlePostPrompt);
|
|
3217
|
+
}
|
|
3218
|
+
else {
|
|
3219
|
+
app.on('POST', postPromptPaths, authMw, handlePostPrompt);
|
|
3220
|
+
}
|
|
2206
3221
|
// Debug events handler
|
|
2207
3222
|
const handleDebugEvents = async (c) => {
|
|
2208
3223
|
const reqLog = this.log.bind({ endpoint: `${basePath}/debug_events` });
|
|
@@ -2211,21 +3226,29 @@ export class AgentBase extends SWMLService {
|
|
|
2211
3226
|
try {
|
|
2212
3227
|
body = await c.req.json();
|
|
2213
3228
|
}
|
|
2214
|
-
catch {
|
|
3229
|
+
catch {
|
|
3230
|
+
/* empty */
|
|
3231
|
+
}
|
|
2215
3232
|
reqLog.debug('debug_event_received', body);
|
|
2216
3233
|
await this.onDebugEvent(body);
|
|
2217
3234
|
return c.json({ ok: true });
|
|
2218
3235
|
};
|
|
2219
3236
|
app.post(`${basePath}/debug_events`, authMw, handleDebugEvents);
|
|
2220
|
-
// MCP server endpoint (JSON-RPC 2.0)
|
|
3237
|
+
// MCP server endpoint (JSON-RPC 2.0). It runs the agent's tools, so it
|
|
3238
|
+
// takes the same basic auth as /swaig. MCP clients don't sign requests,
|
|
3239
|
+
// so there is no webhook signature check here.
|
|
2221
3240
|
if (this._mcpServerEnabled) {
|
|
2222
|
-
app.post(`${basePath}/mcp`, async (c) => {
|
|
2223
|
-
let body
|
|
3241
|
+
app.post(`${basePath}/mcp`, authMw, async (c) => {
|
|
3242
|
+
let body;
|
|
2224
3243
|
try {
|
|
2225
3244
|
body = await c.req.json();
|
|
2226
3245
|
}
|
|
2227
3246
|
catch {
|
|
2228
|
-
return c.json({
|
|
3247
|
+
return c.json({
|
|
3248
|
+
jsonrpc: '2.0',
|
|
3249
|
+
id: null,
|
|
3250
|
+
error: { code: -32700, message: 'Parse error' },
|
|
3251
|
+
});
|
|
2229
3252
|
}
|
|
2230
3253
|
const result = await this.handleMcpRequest(body);
|
|
2231
3254
|
return c.json(result);
|
|
@@ -2240,7 +3263,9 @@ export class AgentBase extends SWMLService {
|
|
|
2240
3263
|
try {
|
|
2241
3264
|
body = await c.req.json();
|
|
2242
3265
|
}
|
|
2243
|
-
catch {
|
|
3266
|
+
catch {
|
|
3267
|
+
/* empty */
|
|
3268
|
+
}
|
|
2244
3269
|
const newPostPrompt = body['post_prompt'];
|
|
2245
3270
|
if (newPostPrompt !== undefined) {
|
|
2246
3271
|
this.setPostPrompt(newPostPrompt);
|
|
@@ -2259,56 +3284,98 @@ export class AgentBase extends SWMLService {
|
|
|
2259
3284
|
try {
|
|
2260
3285
|
body = await c.req.json();
|
|
2261
3286
|
}
|
|
2262
|
-
catch {
|
|
3287
|
+
catch {
|
|
3288
|
+
/* empty */
|
|
3289
|
+
}
|
|
2263
3290
|
reqLog.info('check_for_input_received');
|
|
2264
3291
|
return c.json({ ok: true, received: body });
|
|
2265
3292
|
};
|
|
2266
3293
|
app.get(`${basePath}/check_for_input`, authMw, handleCheckForInput);
|
|
2267
3294
|
app.post(`${basePath}/check_for_input`, authMw, handleCheckForInput);
|
|
2268
3295
|
}
|
|
2269
|
-
// Routing callbacks (registered via registerRoutingCallback)
|
|
2270
|
-
|
|
3296
|
+
// Routing callbacks (registered via registerRoutingCallback). The served
|
|
3297
|
+
// path delegates to handleRequest, which runs the callback and returns a
|
|
3298
|
+
// real 307 (Location) on a redirect — NOT a 200 {action:redirect} — with the
|
|
3299
|
+
// same auth/render decision the primitive core makes. handleRequest resolves
|
|
3300
|
+
// the matching callback from the request URL via _callbackPathForUrl.
|
|
3301
|
+
for (const callbackPath of this._routingCallbacks.keys()) {
|
|
2271
3302
|
const fullPath = basePath ? `${basePath}${callbackPath}` : callbackPath;
|
|
2272
3303
|
const handleRouting = async (c) => {
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
let body = {};
|
|
2276
|
-
try {
|
|
2277
|
-
body = await c.req.json();
|
|
2278
|
-
}
|
|
2279
|
-
catch { /* GET or no body */ }
|
|
2280
|
-
try {
|
|
2281
|
-
const route = await callback(body);
|
|
2282
|
-
if (route) {
|
|
2283
|
-
reqLog.info('routing_callback_redirect', { route });
|
|
2284
|
-
return c.json({ action: 'redirect', route });
|
|
2285
|
-
}
|
|
2286
|
-
// No redirect — return SWML for this agent
|
|
2287
|
-
this.detectProxyFromRequest(c);
|
|
2288
|
-
const swml = this.renderSwml();
|
|
2289
|
-
return c.json(JSON.parse(swml));
|
|
2290
|
-
}
|
|
2291
|
-
catch (err) {
|
|
2292
|
-
reqLog.error('routing_callback_error', { error: err instanceof Error ? err.message : String(err) });
|
|
2293
|
-
return c.json({ error: 'Routing callback failed' }, 500);
|
|
2294
|
-
}
|
|
3304
|
+
this.log.bind({ endpoint: fullPath }).debug('routing_callback_called');
|
|
3305
|
+
return this.serveViaHandleRequest(c);
|
|
2295
3306
|
};
|
|
2296
|
-
|
|
2297
|
-
|
|
3307
|
+
// A routing-callback path renders SWML like the root, so a POST to it
|
|
3308
|
+
// needs a signature like the root when a signing key is set. A GET
|
|
3309
|
+
// (the platform's SWML probe) stays unsigned, as it is on the root.
|
|
3310
|
+
const callbackPaths = withSlash(fullPath);
|
|
3311
|
+
app.on('GET', callbackPaths, authMw, handleRouting);
|
|
3312
|
+
if (sigMw) {
|
|
3313
|
+
app.on('POST', callbackPaths, authMw, sigMw, handleRouting);
|
|
3314
|
+
}
|
|
3315
|
+
else {
|
|
3316
|
+
app.on('POST', callbackPaths, authMw, handleRouting);
|
|
3317
|
+
}
|
|
2298
3318
|
}
|
|
2299
3319
|
// Health / Ready
|
|
2300
3320
|
app.get(`${basePath}/health`, (c) => c.json({ status: 'ok' }));
|
|
2301
3321
|
app.get(`${basePath}/ready`, (c) => c.json({ status: 'ready' }));
|
|
2302
|
-
|
|
2303
|
-
|
|
3322
|
+
// The agent's own paths, for the mount exemption above.
|
|
3323
|
+
for (const r of app.routes) {
|
|
3324
|
+
if (r.path.includes('*'))
|
|
3325
|
+
continue;
|
|
3326
|
+
const path = normalizePath(r.path);
|
|
3327
|
+
agentRoutes.byMethod.add(`${r.method.toUpperCase()} ${path}`);
|
|
3328
|
+
agentRoutes.paths.add(path);
|
|
3329
|
+
}
|
|
3330
|
+
// Mounted apps (see mount()), after the agent's own routes so those win.
|
|
3331
|
+
for (const m of this.mounts) {
|
|
3332
|
+
if (typeof m.app === 'function') {
|
|
3333
|
+
app.mount(m.prefix || '/', m.app);
|
|
3334
|
+
}
|
|
3335
|
+
else {
|
|
3336
|
+
app.route(m.prefix || '/', m.app);
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
2304
3339
|
return app;
|
|
2305
3340
|
}
|
|
3341
|
+
/** The route-relative app {@link asRouter} returns, built on first use. */
|
|
3342
|
+
_routerApp = null;
|
|
2306
3343
|
/**
|
|
2307
|
-
*
|
|
2308
|
-
*
|
|
3344
|
+
* Get a router to embed this agent's routes in a host web app.
|
|
3345
|
+
*
|
|
3346
|
+
* Returns a Hono sub-app with this agent's routes relative to its root
|
|
3347
|
+
* (`/`, `/swaig`, `/post_prompt`, plus any routing callbacks), for the host
|
|
3348
|
+
* to mount under the agent's route: `hostApp.route(agent.route,
|
|
3349
|
+
* agent.asRouter())`. This is the TypeScript realization of Python's
|
|
3350
|
+
* `as_router()`, which is route-relative the same way; the named
|
|
3351
|
+
* {@link HostAppRouter} type is the cross-port "embed my routes in a host
|
|
3352
|
+
* app" contract. {@link getApp} serves the same routes under the agent's
|
|
3353
|
+
* route.
|
|
3354
|
+
*
|
|
3355
|
+
* @returns A mountable Hono sub-app carrying this agent's routes.
|
|
2309
3356
|
*/
|
|
2310
3357
|
asRouter() {
|
|
2311
|
-
|
|
3358
|
+
this.ensureToolsDefined();
|
|
3359
|
+
this._routerApp ??= this.buildApp('');
|
|
3360
|
+
return this._routerApp;
|
|
3361
|
+
}
|
|
3362
|
+
/**
|
|
3363
|
+
* Whether a request path is served by an app added with {@link mount}
|
|
3364
|
+
* rather than by the agent's own routes, so the agent's security headers,
|
|
3365
|
+
* CORS and CSRF handling should leave it alone. Internal; AgentServer uses
|
|
3366
|
+
* it for the agents it serves.
|
|
3367
|
+
*
|
|
3368
|
+
* @param path - The path relative to the agent's route-relative router.
|
|
3369
|
+
* @param method - The request's method.
|
|
3370
|
+
*/
|
|
3371
|
+
_servedByMount(path, method = 'GET') {
|
|
3372
|
+
if (this.mounts.length === 0)
|
|
3373
|
+
return false;
|
|
3374
|
+
const routes = AGENT_ROUTES.get(this.asRouter());
|
|
3375
|
+
if (routes && ownsRoute(routes, method, path))
|
|
3376
|
+
return false;
|
|
3377
|
+
const normalized = normalizePath(path);
|
|
3378
|
+
return this.mounts.some((m) => m.prefix === '' || normalized === m.prefix || normalized.startsWith(`${m.prefix}/`));
|
|
2312
3379
|
}
|
|
2313
3380
|
/**
|
|
2314
3381
|
* Start the HTTP server and begin listening for requests.
|
|
@@ -2335,22 +3402,73 @@ export class AgentBase extends SWMLService {
|
|
|
2335
3402
|
return;
|
|
2336
3403
|
const host = opts?.host ?? this.host;
|
|
2337
3404
|
const port = opts?.port ?? this.port;
|
|
2338
|
-
|
|
3405
|
+
// Serving HTTP itself, the agent is a server whatever the environment
|
|
3406
|
+
// says, so its webhook URLs are the host's (see getFullUrl).
|
|
3407
|
+
this._serving = true;
|
|
2339
3408
|
const app = this.getApp();
|
|
2340
|
-
|
|
3409
|
+
// HTTPS when SSL is configured (SWML_SSL_ENABLED with a certificate and
|
|
3410
|
+
// key, or the config file), as the reference's serve() passes them to
|
|
3411
|
+
// uvicorn; plain HTTP otherwise.
|
|
3412
|
+
const tls = this._servesTls();
|
|
3413
|
+
if (this.sslEnabled && !tls) {
|
|
3414
|
+
this.log.warn(`SSL is enabled but the certificate or key isn't found (${this.sslCertPath ?? 'no cert'}, ${this.sslKeyPath ?? 'no key'}); serving HTTP`);
|
|
3415
|
+
}
|
|
3416
|
+
const listenUrl = `${tls ? 'https' : 'http'}://${host}:${port}${this.route}`;
|
|
2341
3417
|
this.log.info(`Agent '${this.name}' running at ${listenUrl}`);
|
|
2342
3418
|
this.log.info(`Auth: ${this.basicAuthCreds[0]}:**** (source: ${this.basicAuthSource})`);
|
|
2343
3419
|
if (this._proxyUrlBase) {
|
|
2344
3420
|
this.log.info(`Proxy URL: ${redactUrl(this._proxyUrlBase)}`);
|
|
2345
3421
|
}
|
|
2346
|
-
|
|
3422
|
+
if (tls) {
|
|
3423
|
+
const { readFileSync } = await import('node:fs');
|
|
3424
|
+
const { createServer } = await import('node:https');
|
|
3425
|
+
const { getRequestListener } = await import('@hono/node-server');
|
|
3426
|
+
const server = createServer({
|
|
3427
|
+
cert: readFileSync(this.sslCertPath, 'utf-8'),
|
|
3428
|
+
key: readFileSync(this.sslKeyPath, 'utf-8'),
|
|
3429
|
+
}, getRequestListener(app.fetch));
|
|
3430
|
+
server.listen(port, host);
|
|
3431
|
+
this._server = server;
|
|
3432
|
+
}
|
|
3433
|
+
else {
|
|
3434
|
+
const { serve: honoServe } = await import('@hono/node-server');
|
|
3435
|
+
this._server = honoServe({
|
|
3436
|
+
fetch: app.fetch,
|
|
3437
|
+
port,
|
|
3438
|
+
hostname: host,
|
|
3439
|
+
});
|
|
3440
|
+
}
|
|
2347
3441
|
}
|
|
2348
3442
|
/**
|
|
2349
|
-
*
|
|
2350
|
-
*
|
|
2351
|
-
*
|
|
3443
|
+
* Smart entry point matching Python's `WebMixin.run()`: auto-detects the
|
|
3444
|
+
* execution environment and dispatches accordingly. When a serverless event
|
|
3445
|
+
* is supplied, or a serverless platform is detected from the environment
|
|
3446
|
+
* (`AWS_LAMBDA_FUNCTION_NAME`/`_HANDLER`, `FUNCTION_TARGET`,
|
|
3447
|
+
* `FUNCTIONS_WORKER_RUNTIME`, `GATEWAY_INTERFACE`), it dispatches to
|
|
3448
|
+
* {@link runServerless}; otherwise it starts the HTTP server via {@link serve}.
|
|
3449
|
+
* Cloud Run sets `K_SERVICE` but not `FUNCTION_TARGET`, so there it serves.
|
|
3450
|
+
*
|
|
3451
|
+
* For deterministic behavior, call {@link serve} (server) or
|
|
3452
|
+
* {@link runServerless} (serverless) directly.
|
|
3453
|
+
*
|
|
3454
|
+
* @param opts - Either server host/port overrides, or a serverless
|
|
3455
|
+
* `{ event, context, platform }` payload.
|
|
3456
|
+
* @returns `void` for server mode, or the serverless response object.
|
|
2352
3457
|
*/
|
|
2353
3458
|
async run(opts) {
|
|
3459
|
+
// Loaded by swaig-test: only the configuration is needed, never a request.
|
|
3460
|
+
if (process.env['SWAIG_CLI_MODE'] === 'true')
|
|
3461
|
+
return;
|
|
3462
|
+
const serverlessEnv = !!process.env['AWS_LAMBDA_FUNCTION_NAME'] ||
|
|
3463
|
+
!!process.env['_HANDLER'] ||
|
|
3464
|
+
// The Functions Framework sets FUNCTION_TARGET; K_SERVICE alone is Cloud
|
|
3465
|
+
// Run (or Cloud Shell), where the agent serves HTTP itself.
|
|
3466
|
+
!!process.env['FUNCTION_TARGET'] ||
|
|
3467
|
+
!!process.env['FUNCTIONS_WORKER_RUNTIME'] ||
|
|
3468
|
+
!!process.env['GATEWAY_INTERFACE'];
|
|
3469
|
+
if (opts?.event !== undefined || serverlessEnv) {
|
|
3470
|
+
return this.runServerless(opts?.event ?? {}, opts?.context, opts?.platform);
|
|
3471
|
+
}
|
|
2354
3472
|
return this.serve(opts);
|
|
2355
3473
|
}
|
|
2356
3474
|
/**
|
|
@@ -2358,8 +3476,8 @@ export class AgentBase extends SWMLService {
|
|
|
2358
3476
|
*
|
|
2359
3477
|
* Matches Python `run(event, context)` when executed in a serverless environment. Python's
|
|
2360
3478
|
* `run()` auto-detects the platform via `get_execution_mode()` and dispatches accordingly;
|
|
2361
|
-
*
|
|
2362
|
-
*
|
|
3479
|
+
* `runServerless` is the **explicit** serverless path so callers can opt in deliberately
|
|
3480
|
+
* (the polymorphic {@link run} dispatches here when a serverless env/event is detected).
|
|
2363
3481
|
*
|
|
2364
3482
|
* Platform detection follows the same environment-variable heuristics as Python's
|
|
2365
3483
|
* `ServerlessMixin`: `AWS_LAMBDA_FUNCTION_NAME` → Lambda, `K_SERVICE` → GCF,
|
|
@@ -2380,8 +3498,16 @@ export class AgentBase extends SWMLService {
|
|
|
2380
3498
|
const adapter = new ServerlessAdapter(platform ?? 'auto');
|
|
2381
3499
|
const app = this.getApp();
|
|
2382
3500
|
// Wrap Hono's fetch (which returns `Response | Promise<Response>`) into a plain
|
|
2383
|
-
// `Promise<Response
|
|
2384
|
-
|
|
3501
|
+
// `Promise<Response>`. The adapter passes an `env` carrying the URL the
|
|
3502
|
+
// platform was called on, for the webhook signature check; forward it.
|
|
3503
|
+
const fetchFn = (req, env) => Promise.resolve(app.fetch(req, env));
|
|
3504
|
+
// CGI has no event object — the request lives in the environment + stdin.
|
|
3505
|
+
// When dispatched in CGI mode with no explicit event, read the request from
|
|
3506
|
+
// the CGI environment and stdin, and write the CGI response to stdout, as a
|
|
3507
|
+
// CGI program must (mirrors Python serverless_mixin CGI mode).
|
|
3508
|
+
if (adapter.getPlatform() === 'cgi' && (event == null || Object.keys(event).length === 0)) {
|
|
3509
|
+
return adapter._runCgi({ fetch: fetchFn }, process.env);
|
|
3510
|
+
}
|
|
2385
3511
|
return adapter.handleRequest({ fetch: fetchFn }, event);
|
|
2386
3512
|
}
|
|
2387
3513
|
// ── Graceful shutdown ─────────────────────────────────────────────
|