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