@copilotkit/runtime 2.0.0-next.1 → 2.0.0-rc.1
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/LICENSE +21 -0
- package/README.md +135 -1
- package/dist/_virtual/_rolldown/runtime.cjs +29 -0
- package/dist/_virtual/_rolldown/runtime.mjs +18 -0
- package/dist/agent/converters/aisdk.cjs +355 -0
- package/dist/agent/converters/aisdk.cjs.map +1 -0
- package/dist/agent/converters/aisdk.d.cts +22 -0
- package/dist/agent/converters/aisdk.d.cts.map +1 -0
- package/dist/agent/converters/aisdk.d.mts +22 -0
- package/dist/agent/converters/aisdk.d.mts.map +1 -0
- package/dist/agent/converters/aisdk.mjs +351 -0
- package/dist/agent/converters/aisdk.mjs.map +1 -0
- package/dist/agent/converters/index.d.mts +2 -0
- package/dist/agent/converters/tanstack.cjs +374 -0
- package/dist/agent/converters/tanstack.cjs.map +1 -0
- package/dist/agent/converters/tanstack.d.cts +83 -0
- package/dist/agent/converters/tanstack.d.cts.map +1 -0
- package/dist/agent/converters/tanstack.d.mts +83 -0
- package/dist/agent/converters/tanstack.d.mts.map +1 -0
- package/dist/agent/converters/tanstack.mjs +372 -0
- package/dist/agent/converters/tanstack.mjs.map +1 -0
- package/dist/agent/converters/usage.cjs +68 -0
- package/dist/agent/converters/usage.cjs.map +1 -0
- package/dist/agent/converters/usage.d.cts +19 -0
- package/dist/agent/converters/usage.d.cts.map +1 -0
- package/dist/agent/converters/usage.d.mts +19 -0
- package/dist/agent/converters/usage.d.mts.map +1 -0
- package/dist/agent/converters/usage.mjs +62 -0
- package/dist/agent/converters/usage.mjs.map +1 -0
- package/dist/agent/index.cjs +1328 -0
- package/dist/agent/index.cjs.map +1 -0
- package/dist/agent/index.d.cts +467 -0
- package/dist/agent/index.d.cts.map +1 -0
- package/dist/agent/index.d.mts +468 -0
- package/dist/agent/index.d.mts.map +1 -0
- package/dist/agent/index.mjs +1318 -0
- package/dist/agent/index.mjs.map +1 -0
- package/dist/agent/learned-skills.cjs +76 -0
- package/dist/agent/learned-skills.cjs.map +1 -0
- package/dist/agent/learned-skills.d.cts +15 -0
- package/dist/agent/learned-skills.d.cts.map +1 -0
- package/dist/agent/learned-skills.d.mts +15 -0
- package/dist/agent/learned-skills.d.mts.map +1 -0
- package/dist/agent/learned-skills.mjs +74 -0
- package/dist/agent/learned-skills.mjs.map +1 -0
- package/dist/agent/mcp-tool-names.cjs +82 -0
- package/dist/agent/mcp-tool-names.cjs.map +1 -0
- package/dist/agent/mcp-tool-names.mjs +80 -0
- package/dist/agent/mcp-tool-names.mjs.map +1 -0
- package/dist/agent/state-delta.cjs +321 -0
- package/dist/agent/state-delta.cjs.map +1 -0
- package/dist/agent/state-delta.mjs +320 -0
- package/dist/agent/state-delta.mjs.map +1 -0
- package/dist/agent/url-download.cjs +503 -0
- package/dist/agent/url-download.cjs.map +1 -0
- package/dist/agent/url-download.d.cts +79 -0
- package/dist/agent/url-download.d.cts.map +1 -0
- package/dist/agent/url-download.d.mts +79 -0
- package/dist/agent/url-download.d.mts.map +1 -0
- package/dist/agent/url-download.mjs +500 -0
- package/dist/agent/url-download.mjs.map +1 -0
- package/dist/index.cjs +75 -0
- package/dist/index.d.cts +24 -0
- package/dist/index.d.mts +24 -0
- package/dist/index.mjs +17 -5598
- package/dist/internal/learned-skills.cjs +21 -0
- package/dist/internal/learned-skills.d.cts +9 -0
- package/dist/internal/learned-skills.d.mts +9 -0
- package/dist/internal/learned-skills.mjs +9 -0
- package/dist/node.cjs +7 -0
- package/dist/node.d.cts +4 -0
- package/dist/node.d.mts +4 -0
- package/dist/node.mjs +4 -0
- package/dist/runtime/core/channel-activation-config.cjs +87 -0
- package/dist/runtime/core/channel-activation-config.cjs.map +1 -0
- package/dist/runtime/core/channel-activation-config.d.cts +39 -0
- package/dist/runtime/core/channel-activation-config.d.cts.map +1 -0
- package/dist/runtime/core/channel-activation-config.d.mts +39 -0
- package/dist/runtime/core/channel-activation-config.d.mts.map +1 -0
- package/dist/runtime/core/channel-activation-config.mjs +85 -0
- package/dist/runtime/core/channel-activation-config.mjs.map +1 -0
- package/dist/runtime/core/channel-manager.cjs +973 -0
- package/dist/runtime/core/channel-manager.cjs.map +1 -0
- package/dist/runtime/core/channel-manager.d.cts +166 -0
- package/dist/runtime/core/channel-manager.d.cts.map +1 -0
- package/dist/runtime/core/channel-manager.d.mts +167 -0
- package/dist/runtime/core/channel-manager.d.mts.map +1 -0
- package/dist/runtime/core/channel-manager.mjs +972 -0
- package/dist/runtime/core/channel-manager.mjs.map +1 -0
- package/dist/runtime/core/debug-event-bus.cjs +57 -0
- package/dist/runtime/core/debug-event-bus.cjs.map +1 -0
- package/dist/runtime/core/debug-event-bus.d.cts +18 -0
- package/dist/runtime/core/debug-event-bus.d.cts.map +1 -0
- package/dist/runtime/core/debug-event-bus.d.mts +18 -0
- package/dist/runtime/core/debug-event-bus.d.mts.map +1 -0
- package/dist/runtime/core/debug-event-bus.mjs +55 -0
- package/dist/runtime/core/debug-event-bus.mjs.map +1 -0
- package/dist/runtime/core/fetch-cors.cjs +71 -0
- package/dist/runtime/core/fetch-cors.cjs.map +1 -0
- package/dist/runtime/core/fetch-cors.d.cts +19 -0
- package/dist/runtime/core/fetch-cors.d.cts.map +1 -0
- package/dist/runtime/core/fetch-cors.d.mts +19 -0
- package/dist/runtime/core/fetch-cors.d.mts.map +1 -0
- package/dist/runtime/core/fetch-cors.mjs +69 -0
- package/dist/runtime/core/fetch-cors.mjs.map +1 -0
- package/dist/runtime/core/fetch-handler.cjs +539 -0
- package/dist/runtime/core/fetch-handler.cjs.map +1 -0
- package/dist/runtime/core/fetch-handler.d.cts +99 -0
- package/dist/runtime/core/fetch-handler.d.cts.map +1 -0
- package/dist/runtime/core/fetch-handler.d.mts +99 -0
- package/dist/runtime/core/fetch-handler.d.mts.map +1 -0
- package/dist/runtime/core/fetch-handler.mjs +538 -0
- package/dist/runtime/core/fetch-handler.mjs.map +1 -0
- package/dist/runtime/core/fetch-router.cjs +141 -0
- package/dist/runtime/core/fetch-router.cjs.map +1 -0
- package/dist/runtime/core/fetch-router.mjs +140 -0
- package/dist/runtime/core/fetch-router.mjs.map +1 -0
- package/dist/runtime/core/hooks.cjs +28 -0
- package/dist/runtime/core/hooks.cjs.map +1 -0
- package/dist/runtime/core/hooks.d.cts +121 -0
- package/dist/runtime/core/hooks.d.cts.map +1 -0
- package/dist/runtime/core/hooks.d.mts +121 -0
- package/dist/runtime/core/hooks.d.mts.map +1 -0
- package/dist/runtime/core/hooks.mjs +24 -0
- package/dist/runtime/core/hooks.mjs.map +1 -0
- package/dist/runtime/core/learning.cjs +61 -0
- package/dist/runtime/core/learning.cjs.map +1 -0
- package/dist/runtime/core/learning.d.cts +61 -0
- package/dist/runtime/core/learning.d.cts.map +1 -0
- package/dist/runtime/core/learning.d.mts +61 -0
- package/dist/runtime/core/learning.d.mts.map +1 -0
- package/dist/runtime/core/learning.mjs +56 -0
- package/dist/runtime/core/learning.mjs.map +1 -0
- package/dist/runtime/core/logger.cjs +21 -0
- package/dist/runtime/core/logger.cjs.map +1 -0
- package/dist/runtime/core/logger.d.cts +12 -0
- package/dist/runtime/core/logger.d.cts.map +1 -0
- package/dist/runtime/core/logger.d.mts +12 -0
- package/dist/runtime/core/logger.d.mts.map +1 -0
- package/dist/runtime/core/logger.mjs +18 -0
- package/dist/runtime/core/logger.mjs.map +1 -0
- package/dist/runtime/core/middleware-sse-parser.cjs +149 -0
- package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -0
- package/dist/runtime/core/middleware-sse-parser.d.cts +21 -0
- package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -0
- package/dist/runtime/core/middleware-sse-parser.d.mts +21 -0
- package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -0
- package/dist/runtime/core/middleware-sse-parser.mjs +148 -0
- package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -0
- package/dist/runtime/core/middleware.cjs +34 -0
- package/dist/runtime/core/middleware.cjs.map +1 -0
- package/dist/runtime/core/middleware.d.cts +31 -0
- package/dist/runtime/core/middleware.d.cts.map +1 -0
- package/dist/runtime/core/middleware.d.mts +31 -0
- package/dist/runtime/core/middleware.d.mts.map +1 -0
- package/dist/runtime/core/middleware.mjs +32 -0
- package/dist/runtime/core/middleware.mjs.map +1 -0
- package/dist/runtime/core/package-info.cjs +9 -0
- package/dist/runtime/core/package-info.cjs.map +1 -0
- package/dist/runtime/core/package-info.mjs +7 -0
- package/dist/runtime/core/package-info.mjs.map +1 -0
- package/dist/runtime/core/runtime-error-reporter.cjs +21 -0
- package/dist/runtime/core/runtime-error-reporter.cjs.map +1 -0
- package/dist/runtime/core/runtime-error-reporter.mjs +18 -0
- package/dist/runtime/core/runtime-error-reporter.mjs.map +1 -0
- package/dist/runtime/core/runtime.cjs +256 -0
- package/dist/runtime/core/runtime.cjs.map +1 -0
- package/dist/runtime/core/runtime.d.cts +481 -0
- package/dist/runtime/core/runtime.d.cts.map +1 -0
- package/dist/runtime/core/runtime.d.mts +481 -0
- package/dist/runtime/core/runtime.d.mts.map +1 -0
- package/dist/runtime/core/runtime.mjs +249 -0
- package/dist/runtime/core/runtime.mjs.map +1 -0
- package/dist/runtime/endpoints/auto-start-channels.cjs +46 -0
- package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -0
- package/dist/runtime/endpoints/auto-start-channels.mjs +45 -0
- package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -0
- package/dist/runtime/endpoints/node-fetch-handler.cjs +75 -0
- package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -0
- package/dist/runtime/endpoints/node-fetch-handler.d.cts +11 -0
- package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -0
- package/dist/runtime/endpoints/node-fetch-handler.d.mts +11 -0
- package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -0
- package/dist/runtime/endpoints/node-fetch-handler.mjs +73 -0
- package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -0
- package/dist/runtime/endpoints/node.cjs +16 -0
- package/dist/runtime/endpoints/node.cjs.map +1 -0
- package/dist/runtime/endpoints/node.d.cts +104 -0
- package/dist/runtime/endpoints/node.d.cts.map +1 -0
- package/dist/runtime/endpoints/node.d.mts +104 -0
- package/dist/runtime/endpoints/node.d.mts.map +1 -0
- package/dist/runtime/endpoints/node.mjs +16 -0
- package/dist/runtime/endpoints/node.mjs.map +1 -0
- package/dist/runtime/endpoints/single-route-helpers.cjs +130 -0
- package/dist/runtime/endpoints/single-route-helpers.cjs.map +1 -0
- package/dist/runtime/endpoints/single-route-helpers.mjs +125 -0
- package/dist/runtime/endpoints/single-route-helpers.mjs.map +1 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.cjs +393 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.d.cts +20 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.d.cts.map +1 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.d.mts +20 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.d.mts.map +1 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.mjs +392 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.mjs.map +1 -0
- package/dist/runtime/generative-ui/index.d.cts +2 -0
- package/dist/runtime/generative-ui/index.d.mts +2 -0
- package/dist/runtime/generative-ui/surface-writer.cjs +85 -0
- package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -0
- package/dist/runtime/generative-ui/surface-writer.d.cts +32 -0
- package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -0
- package/dist/runtime/generative-ui/surface-writer.d.mts +32 -0
- package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -0
- package/dist/runtime/generative-ui/surface-writer.mjs +84 -0
- package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -0
- package/dist/runtime/handlers/get-runtime-info.cjs +140 -0
- package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -0
- package/dist/runtime/handlers/get-runtime-info.mjs +140 -0
- package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -0
- package/dist/runtime/handlers/handle-connect.cjs +62 -0
- package/dist/runtime/handlers/handle-connect.cjs.map +1 -0
- package/dist/runtime/handlers/handle-connect.mjs +62 -0
- package/dist/runtime/handlers/handle-connect.mjs.map +1 -0
- package/dist/runtime/handlers/handle-debug-events.cjs +33 -0
- package/dist/runtime/handlers/handle-debug-events.cjs.map +1 -0
- package/dist/runtime/handlers/handle-debug-events.mjs +33 -0
- package/dist/runtime/handlers/handle-debug-events.mjs.map +1 -0
- package/dist/runtime/handlers/handle-inspector-learning.cjs +56 -0
- package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -0
- package/dist/runtime/handlers/handle-inspector-learning.mjs +55 -0
- package/dist/runtime/handlers/handle-inspector-learning.mjs.map +1 -0
- package/dist/runtime/handlers/handle-inspector-metadata.cjs +36 -0
- package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -0
- package/dist/runtime/handlers/handle-inspector-metadata.mjs +35 -0
- package/dist/runtime/handlers/handle-inspector-metadata.mjs.map +1 -0
- package/dist/runtime/handlers/handle-run.cjs +111 -0
- package/dist/runtime/handlers/handle-run.cjs.map +1 -0
- package/dist/runtime/handlers/handle-run.mjs +110 -0
- package/dist/runtime/handlers/handle-run.mjs.map +1 -0
- package/dist/runtime/handlers/handle-stop.cjs +102 -0
- package/dist/runtime/handlers/handle-stop.cjs.map +1 -0
- package/dist/runtime/handlers/handle-stop.mjs +101 -0
- package/dist/runtime/handlers/handle-stop.mjs.map +1 -0
- package/dist/runtime/handlers/handle-suggest.cjs +83 -0
- package/dist/runtime/handlers/handle-suggest.cjs.map +1 -0
- package/dist/runtime/handlers/handle-suggest.mjs +82 -0
- package/dist/runtime/handlers/handle-suggest.mjs.map +1 -0
- package/dist/runtime/handlers/handle-trajectory-connect.cjs +40 -0
- package/dist/runtime/handlers/handle-trajectory-connect.cjs.map +1 -0
- package/dist/runtime/handlers/handle-trajectory-connect.mjs +39 -0
- package/dist/runtime/handlers/handle-trajectory-connect.mjs.map +1 -0
- package/dist/runtime/handlers/handle-transcribe.cjs +112 -0
- package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -0
- package/dist/runtime/handlers/handle-transcribe.mjs +111 -0
- package/dist/runtime/handlers/handle-transcribe.mjs.map +1 -0
- package/dist/runtime/handlers/header-utils.cjs +185 -0
- package/dist/runtime/handlers/header-utils.cjs.map +1 -0
- package/dist/runtime/handlers/header-utils.d.cts +53 -0
- package/dist/runtime/handlers/header-utils.d.cts.map +1 -0
- package/dist/runtime/handlers/header-utils.d.mts +53 -0
- package/dist/runtime/handlers/header-utils.d.mts.map +1 -0
- package/dist/runtime/handlers/header-utils.mjs +183 -0
- package/dist/runtime/handlers/header-utils.mjs.map +1 -0
- package/dist/runtime/handlers/intelligence/annotate.cjs +83 -0
- package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -0
- package/dist/runtime/handlers/intelligence/annotate.mjs +82 -0
- package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -0
- package/dist/runtime/handlers/intelligence/connect.cjs +68 -0
- package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -0
- package/dist/runtime/handlers/intelligence/connect.mjs +68 -0
- package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -0
- package/dist/runtime/handlers/intelligence/memories.cjs +260 -0
- package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -0
- package/dist/runtime/handlers/intelligence/memories.mjs +254 -0
- package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -0
- package/dist/runtime/handlers/intelligence/run.cjs +283 -0
- package/dist/runtime/handlers/intelligence/run.cjs.map +1 -0
- package/dist/runtime/handlers/intelligence/run.mjs +282 -0
- package/dist/runtime/handlers/intelligence/run.mjs.map +1 -0
- package/dist/runtime/handlers/intelligence/thread-names.cjs +172 -0
- package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -0
- package/dist/runtime/handlers/intelligence/thread-names.mjs +171 -0
- package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -0
- package/dist/runtime/handlers/intelligence/threads.cjs +399 -0
- package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -0
- package/dist/runtime/handlers/intelligence/threads.mjs +390 -0
- package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -0
- package/dist/runtime/handlers/shared/agent-utils.cjs +267 -0
- package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -0
- package/dist/runtime/handlers/shared/agent-utils.mjs +262 -0
- package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -0
- package/dist/runtime/handlers/shared/cloud-telemetry.cjs +30 -0
- package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -0
- package/dist/runtime/handlers/shared/cloud-telemetry.mjs +29 -0
- package/dist/runtime/handlers/shared/cloud-telemetry.mjs.map +1 -0
- package/dist/runtime/handlers/shared/describe-endpoint.cjs +25 -0
- package/dist/runtime/handlers/shared/describe-endpoint.cjs.map +1 -0
- package/dist/runtime/handlers/shared/describe-endpoint.mjs +24 -0
- package/dist/runtime/handlers/shared/describe-endpoint.mjs.map +1 -0
- package/dist/runtime/handlers/shared/intelligence-utils.cjs +24 -0
- package/dist/runtime/handlers/shared/intelligence-utils.cjs.map +1 -0
- package/dist/runtime/handlers/shared/intelligence-utils.mjs +23 -0
- package/dist/runtime/handlers/shared/intelligence-utils.mjs.map +1 -0
- package/dist/runtime/handlers/shared/json-response.cjs +14 -0
- package/dist/runtime/handlers/shared/json-response.cjs.map +1 -0
- package/dist/runtime/handlers/shared/json-response.mjs +12 -0
- package/dist/runtime/handlers/shared/json-response.mjs.map +1 -0
- package/dist/runtime/handlers/shared/mcp-apps-servers.cjs +22 -0
- package/dist/runtime/handlers/shared/mcp-apps-servers.cjs.map +1 -0
- package/dist/runtime/handlers/shared/mcp-apps-servers.mjs +22 -0
- package/dist/runtime/handlers/shared/mcp-apps-servers.mjs.map +1 -0
- package/dist/runtime/handlers/shared/memory-policy.cjs +78 -0
- package/dist/runtime/handlers/shared/memory-policy.cjs.map +1 -0
- package/dist/runtime/handlers/shared/memory-policy.mjs +77 -0
- package/dist/runtime/handlers/shared/memory-policy.mjs.map +1 -0
- package/dist/runtime/handlers/shared/platform-error.cjs +39 -0
- package/dist/runtime/handlers/shared/platform-error.cjs.map +1 -0
- package/dist/runtime/handlers/shared/platform-error.mjs +39 -0
- package/dist/runtime/handlers/shared/platform-error.mjs.map +1 -0
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +50 -0
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -0
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +49 -0
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -0
- package/dist/runtime/handlers/shared/sse-keep-alive.cjs +68 -0
- package/dist/runtime/handlers/shared/sse-keep-alive.cjs.map +1 -0
- package/dist/runtime/handlers/shared/sse-keep-alive.mjs +66 -0
- package/dist/runtime/handlers/shared/sse-keep-alive.mjs.map +1 -0
- package/dist/runtime/handlers/shared/sse-response.cjs +237 -0
- package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -0
- package/dist/runtime/handlers/shared/sse-response.mjs +236 -0
- package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -0
- package/dist/runtime/handlers/shared/thread-access.cjs +137 -0
- package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -0
- package/dist/runtime/handlers/shared/thread-access.d.cts +28 -0
- package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -0
- package/dist/runtime/handlers/shared/thread-access.d.mts +28 -0
- package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -0
- package/dist/runtime/handlers/shared/thread-access.mjs +132 -0
- package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -0
- package/dist/runtime/handlers/sse/connect.cjs +23 -0
- package/dist/runtime/handlers/sse/connect.cjs.map +1 -0
- package/dist/runtime/handlers/sse/connect.mjs +23 -0
- package/dist/runtime/handlers/sse/connect.mjs.map +1 -0
- package/dist/runtime/handlers/sse/run.cjs +44 -0
- package/dist/runtime/handlers/sse/run.cjs.map +1 -0
- package/dist/runtime/handlers/sse/run.mjs +44 -0
- package/dist/runtime/handlers/sse/run.mjs.map +1 -0
- package/dist/runtime/index.d.cts +29 -0
- package/dist/runtime/index.d.cts.map +1 -0
- package/dist/runtime/index.d.mts +29 -0
- package/dist/runtime/index.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/client.cjs +1338 -0
- package/dist/runtime/intelligence-platform/client.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/client.d.cts +824 -0
- package/dist/runtime/intelligence-platform/client.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/client.d.mts +824 -0
- package/dist/runtime/intelligence-platform/client.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/client.mjs +1334 -0
- package/dist/runtime/intelligence-platform/client.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/experimental.d.cts +26 -0
- package/dist/runtime/intelligence-platform/experimental.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/experimental.d.mts +26 -0
- package/dist/runtime/intelligence-platform/experimental.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/index.d.cts +3 -0
- package/dist/runtime/intelligence-platform/index.d.mts +3 -0
- package/dist/runtime/intelligence-platform/learned-skills.cjs +95 -0
- package/dist/runtime/intelligence-platform/learned-skills.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/learned-skills.d.cts +43 -0
- package/dist/runtime/intelligence-platform/learned-skills.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/learned-skills.d.mts +43 -0
- package/dist/runtime/intelligence-platform/learned-skills.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/learned-skills.mjs +92 -0
- package/dist/runtime/intelligence-platform/learned-skills.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/learning-management.cjs +203 -0
- package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/learning-management.d.cts +111 -0
- package/dist/runtime/intelligence-platform/learning-management.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/learning-management.d.mts +111 -0
- package/dist/runtime/intelligence-platform/learning-management.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/learning-management.mjs +193 -0
- package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +131 -0
- package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +10 -0
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +10 -0
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +127 -0
- package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/config.cjs +65 -0
- package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/config.d.cts +47 -0
- package/dist/runtime/intelligence-platform/skill-registry/config.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/config.d.mts +47 -0
- package/dist/runtime/intelligence-platform/skill-registry/config.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/config.mjs +65 -0
- package/dist/runtime/intelligence-platform/skill-registry/config.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/errors.cjs +10 -0
- package/dist/runtime/intelligence-platform/skill-registry/errors.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/errors.d.cts +7 -0
- package/dist/runtime/intelligence-platform/skill-registry/errors.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/errors.d.mts +7 -0
- package/dist/runtime/intelligence-platform/skill-registry/errors.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/errors.mjs +10 -0
- package/dist/runtime/intelligence-platform/skill-registry/errors.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +7 -0
- package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +7 -0
- package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +247 -0
- package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts +36 -0
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts +36 -0
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +246 -0
- package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/skill-content.cjs +41 -0
- package/dist/runtime/intelligence-platform/skill-registry/skill-content.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/skill-content.d.cts +12 -0
- package/dist/runtime/intelligence-platform/skill-registry/skill-content.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/skill-content.d.mts +12 -0
- package/dist/runtime/intelligence-platform/skill-registry/skill-content.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/skill-content.mjs +38 -0
- package/dist/runtime/intelligence-platform/skill-registry/skill-content.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.cjs +92 -0
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.cts +27 -0
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.mts +27 -0
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.mjs +91 -0
- package/dist/runtime/intelligence-platform/skill-registry/snapshot.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +142 -0
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +141 -0
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/trajectories.cjs +95 -0
- package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/trajectories.d.cts +11 -0
- package/dist/runtime/intelligence-platform/trajectories.d.cts.map +1 -0
- package/dist/runtime/intelligence-platform/trajectories.d.mts +11 -0
- package/dist/runtime/intelligence-platform/trajectories.d.mts.map +1 -0
- package/dist/runtime/intelligence-platform/trajectories.mjs +91 -0
- package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -0
- package/dist/runtime/node.d.cts +2 -0
- package/dist/runtime/node.d.mts +2 -0
- package/dist/runtime/runner/agent-runner.cjs +82 -0
- package/dist/runtime/runner/agent-runner.cjs.map +1 -0
- package/dist/runtime/runner/agent-runner.d.cts +151 -0
- package/dist/runtime/runner/agent-runner.d.cts.map +1 -0
- package/dist/runtime/runner/agent-runner.d.mts +151 -0
- package/dist/runtime/runner/agent-runner.d.mts.map +1 -0
- package/dist/runtime/runner/agent-runner.mjs +73 -0
- package/dist/runtime/runner/agent-runner.mjs.map +1 -0
- package/dist/runtime/runner/in-memory.cjs +741 -0
- package/dist/runtime/runner/in-memory.cjs.map +1 -0
- package/dist/runtime/runner/in-memory.d.cts +427 -0
- package/dist/runtime/runner/in-memory.d.cts.map +1 -0
- package/dist/runtime/runner/in-memory.d.mts +427 -0
- package/dist/runtime/runner/in-memory.d.mts.map +1 -0
- package/dist/runtime/runner/in-memory.mjs +734 -0
- package/dist/runtime/runner/in-memory.mjs.map +1 -0
- package/dist/runtime/runner/index.d.cts +5 -0
- package/dist/runtime/runner/index.d.mts +5 -0
- package/dist/runtime/runner/index.mjs +6 -0
- package/dist/runtime/runner/intelligence.cjs +617 -0
- package/dist/runtime/runner/intelligence.cjs.map +1 -0
- package/dist/runtime/runner/intelligence.d.cts +104 -0
- package/dist/runtime/runner/intelligence.d.cts.map +1 -0
- package/dist/runtime/runner/intelligence.d.mts +104 -0
- package/dist/runtime/runner/intelligence.d.mts.map +1 -0
- package/dist/runtime/runner/intelligence.mjs +616 -0
- package/dist/runtime/runner/intelligence.mjs.map +1 -0
- package/dist/runtime/telemetry/disclosure.cjs +25 -0
- package/dist/runtime/telemetry/disclosure.cjs.map +1 -0
- package/dist/runtime/telemetry/disclosure.mjs +24 -0
- package/dist/runtime/telemetry/disclosure.mjs.map +1 -0
- package/dist/runtime/telemetry/events.d.cts +66 -0
- package/dist/runtime/telemetry/events.d.cts.map +1 -0
- package/dist/runtime/telemetry/events.d.mts +66 -0
- package/dist/runtime/telemetry/events.d.mts.map +1 -0
- package/dist/runtime/telemetry/instance-created.cjs +34 -0
- package/dist/runtime/telemetry/instance-created.cjs.map +1 -0
- package/dist/runtime/telemetry/instance-created.mjs +34 -0
- package/dist/runtime/telemetry/instance-created.mjs.map +1 -0
- package/dist/runtime/telemetry/telemetry-client.cjs +108 -0
- package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -0
- package/dist/runtime/telemetry/telemetry-client.d.cts +10 -0
- package/dist/runtime/telemetry/telemetry-client.d.cts.map +1 -0
- package/dist/runtime/telemetry/telemetry-client.d.mts +10 -0
- package/dist/runtime/telemetry/telemetry-client.d.mts.map +1 -0
- package/dist/runtime/telemetry/telemetry-client.mjs +107 -0
- package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -0
- package/dist/runtime/telemetry/telemetry-identity.cjs +12 -0
- package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -0
- package/dist/runtime/telemetry/telemetry-identity.mjs +11 -0
- package/dist/runtime/telemetry/telemetry-identity.mjs.map +1 -0
- package/dist/runtime/transcription-service/transcription-service.cjs +7 -0
- package/dist/runtime/transcription-service/transcription-service.cjs.map +1 -0
- package/dist/runtime/transcription-service/transcription-service.d.cts +14 -0
- package/dist/runtime/transcription-service/transcription-service.d.cts.map +1 -0
- package/dist/runtime/transcription-service/transcription-service.d.mts +14 -0
- package/dist/runtime/transcription-service/transcription-service.d.mts.map +1 -0
- package/dist/runtime/transcription-service/transcription-service.mjs +6 -0
- package/dist/runtime/transcription-service/transcription-service.mjs.map +1 -0
- package/package.json +104 -105
- package/.eslintrc.js +0 -7
- package/CHANGELOG.md +0 -2920
- package/__snapshots__/schema/schema.graphql +0 -371
- package/dist/index.d.ts +0 -1494
- package/dist/index.js +0 -5641
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/langgraph.d.ts +0 -284
- package/dist/langgraph.js +0 -211
- package/dist/langgraph.js.map +0 -1
- package/dist/langgraph.mjs +0 -206
- package/dist/langgraph.mjs.map +0 -1
- package/dist/v2/index.d.ts +0 -2
- package/dist/v2/index.js +0 -22
- package/dist/v2/index.js.map +0 -1
- package/dist/v2/index.mjs +0 -5
- package/dist/v2/index.mjs.map +0 -1
- package/jest.config.js +0 -10
- package/scripts/generate-gql-schema.ts +0 -13
- package/src/agents/langgraph/event-source.ts +0 -329
- package/src/agents/langgraph/events.ts +0 -377
- package/src/graphql/inputs/action.input.ts +0 -16
- package/src/graphql/inputs/agent-session.input.ts +0 -13
- package/src/graphql/inputs/agent-state.input.ts +0 -13
- package/src/graphql/inputs/cloud-guardrails.input.ts +0 -16
- package/src/graphql/inputs/cloud.input.ts +0 -8
- package/src/graphql/inputs/context-property.input.ts +0 -10
- package/src/graphql/inputs/copilot-context.input.ts +0 -10
- package/src/graphql/inputs/custom-property.input.ts +0 -15
- package/src/graphql/inputs/extensions.input.ts +0 -21
- package/src/graphql/inputs/forwarded-parameters.input.ts +0 -22
- package/src/graphql/inputs/frontend.input.ts +0 -14
- package/src/graphql/inputs/generate-copilot-response.input.ts +0 -59
- package/src/graphql/inputs/load-agent-state.input.ts +0 -10
- package/src/graphql/inputs/message.input.ts +0 -110
- package/src/graphql/inputs/meta-event.input.ts +0 -18
- package/src/graphql/message-conversion/agui-to-gql.test.ts +0 -1263
- package/src/graphql/message-conversion/agui-to-gql.ts +0 -333
- package/src/graphql/message-conversion/gql-to-agui.test.ts +0 -1580
- package/src/graphql/message-conversion/gql-to-agui.ts +0 -278
- package/src/graphql/message-conversion/index.ts +0 -2
- package/src/graphql/message-conversion/roundtrip-conversion.test.ts +0 -526
- package/src/graphql/resolvers/copilot.resolver.ts +0 -708
- package/src/graphql/resolvers/state.resolver.ts +0 -27
- package/src/graphql/types/agents-response.type.ts +0 -19
- package/src/graphql/types/base/index.ts +0 -10
- package/src/graphql/types/converted/index.ts +0 -176
- package/src/graphql/types/copilot-response.type.ts +0 -138
- package/src/graphql/types/enums.ts +0 -38
- package/src/graphql/types/extensions-response.type.ts +0 -23
- package/src/graphql/types/guardrails-result.type.ts +0 -20
- package/src/graphql/types/load-agent-state-response.type.ts +0 -17
- package/src/graphql/types/message-status.type.ts +0 -42
- package/src/graphql/types/meta-events.type.ts +0 -71
- package/src/graphql/types/response-status.type.ts +0 -66
- package/src/index.ts +0 -4
- package/src/langgraph.ts +0 -1
- package/src/lib/cloud/index.ts +0 -4
- package/src/lib/error-messages.ts +0 -200
- package/src/lib/index.ts +0 -52
- package/src/lib/integrations/index.ts +0 -6
- package/src/lib/integrations/nest/index.ts +0 -14
- package/src/lib/integrations/nextjs/app-router.ts +0 -38
- package/src/lib/integrations/nextjs/pages-router.ts +0 -39
- package/src/lib/integrations/node-express/index.ts +0 -14
- package/src/lib/integrations/node-http/index.ts +0 -143
- package/src/lib/integrations/node-http/request-handler.ts +0 -111
- package/src/lib/integrations/shared.ts +0 -161
- package/src/lib/logger.ts +0 -28
- package/src/lib/observability.ts +0 -160
- package/src/lib/runtime/__tests__/copilot-runtime-error.test.ts +0 -169
- package/src/lib/runtime/__tests__/mcp-tools-utils.test.ts +0 -464
- package/src/lib/runtime/agent-integrations/langgraph/agent.ts +0 -209
- package/src/lib/runtime/agent-integrations/langgraph/consts.ts +0 -34
- package/src/lib/runtime/agent-integrations/langgraph/index.ts +0 -2
- package/src/lib/runtime/copilot-runtime.ts +0 -710
- package/src/lib/runtime/mcp-tools-utils.ts +0 -254
- package/src/lib/runtime/retry-utils.ts +0 -96
- package/src/lib/runtime/telemetry-agent-runner.ts +0 -139
- package/src/lib/runtime/types.ts +0 -49
- package/src/lib/runtime/utils.ts +0 -87
- package/src/lib/streaming.ts +0 -202
- package/src/lib/telemetry-client.ts +0 -64
- package/src/service-adapters/anthropic/anthropic-adapter.ts +0 -452
- package/src/service-adapters/anthropic/utils.ts +0 -152
- package/src/service-adapters/bedrock/bedrock-adapter.ts +0 -73
- package/src/service-adapters/conversion.ts +0 -67
- package/src/service-adapters/empty/empty-adapter.ts +0 -38
- package/src/service-adapters/events.ts +0 -294
- package/src/service-adapters/experimental/ollama/ollama-adapter.ts +0 -84
- package/src/service-adapters/google/google-genai-adapter.test.ts +0 -104
- package/src/service-adapters/google/google-genai-adapter.ts +0 -88
- package/src/service-adapters/groq/groq-adapter.ts +0 -203
- package/src/service-adapters/index.ts +0 -18
- package/src/service-adapters/langchain/langchain-adapter.ts +0 -111
- package/src/service-adapters/langchain/langserve.ts +0 -88
- package/src/service-adapters/langchain/types.ts +0 -14
- package/src/service-adapters/langchain/utils.ts +0 -313
- package/src/service-adapters/openai/openai-adapter.ts +0 -283
- package/src/service-adapters/openai/openai-assistant-adapter.ts +0 -344
- package/src/service-adapters/openai/utils.ts +0 -199
- package/src/service-adapters/service-adapter.ts +0 -41
- package/src/service-adapters/shared/error-utils.ts +0 -61
- package/src/service-adapters/shared/index.ts +0 -1
- package/src/service-adapters/unify/unify-adapter.ts +0 -151
- package/src/utils/failed-response-status-reasons.ts +0 -70
- package/src/utils/index.ts +0 -1
- package/src/v2/index.ts +0 -3
- package/tests/global.d.ts +0 -13
- package/tests/service-adapters/anthropic/allowlist-approach.test.ts +0 -226
- package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +0 -389
- package/tests/service-adapters/openai/allowlist-approach.test.ts +0 -238
- package/tests/service-adapters/openai/openai-adapter.test.ts +0 -301
- package/tests/setup.jest.ts +0 -21
- package/tests/tsconfig.json +0 -10
- package/tsconfig.json +0 -13
- package/tsup.config.ts +0 -20
- package/typedoc.json +0 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveLocalThreadOwner","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../src/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { isHandlerResponse } from "./shared/json-response.mjs";
|
|
2
|
+
import { getPlatformErrorStatus } from "./shared/intelligence-utils.mjs";
|
|
3
|
+
import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs";
|
|
4
|
+
import { resolveLocalThreadOwner } from "./shared/thread-access.mjs";
|
|
5
|
+
import { isIntelligenceRuntime, resolveAgents } from "../core/runtime.mjs";
|
|
6
|
+
import { EventType } from "@ag-ui/client";
|
|
7
|
+
|
|
8
|
+
//#region src/runtime/handlers/handle-stop.ts
|
|
9
|
+
/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */
|
|
10
|
+
async function parseStopScope(request) {
|
|
11
|
+
try {
|
|
12
|
+
const raw = await request.text();
|
|
13
|
+
const body = raw.trim() ? JSON.parse(raw) : {};
|
|
14
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) return Response.json({ error: "Invalid stop request" }, { status: 400 });
|
|
15
|
+
if (Object.keys(body).some((key) => key !== "runId")) return Response.json({ error: "Invalid stop request" }, { status: 400 });
|
|
16
|
+
if (!("runId" in body)) return {};
|
|
17
|
+
if (typeof body.runId !== "string" || !body.runId.trim()) return Response.json({ error: "Invalid runId" }, { status: 400 });
|
|
18
|
+
return { runId: body.runId };
|
|
19
|
+
} catch {
|
|
20
|
+
return Response.json({ error: "Invalid stop request" }, { status: 400 });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Stop an active run after applying the runtime's application identity policy. */
|
|
24
|
+
async function handleStopAgent({ runtime, request, agentId, threadId }) {
|
|
25
|
+
try {
|
|
26
|
+
const scope = await parseStopScope(request.clone());
|
|
27
|
+
if (isHandlerResponse(scope)) return scope;
|
|
28
|
+
const { runId } = scope;
|
|
29
|
+
let stopThreadId = threadId;
|
|
30
|
+
let ownerId;
|
|
31
|
+
if (!isIntelligenceRuntime(runtime)) {
|
|
32
|
+
const owner = await resolveLocalThreadOwner({
|
|
33
|
+
runtime,
|
|
34
|
+
request,
|
|
35
|
+
operation: "stop"
|
|
36
|
+
});
|
|
37
|
+
if (isHandlerResponse(owner)) return owner;
|
|
38
|
+
ownerId = owner;
|
|
39
|
+
} else {
|
|
40
|
+
const user = await resolveIntelligenceUser({
|
|
41
|
+
runtime,
|
|
42
|
+
request
|
|
43
|
+
});
|
|
44
|
+
if (isHandlerResponse(user)) return user;
|
|
45
|
+
try {
|
|
46
|
+
const thread = await runtime.intelligence.getThread({
|
|
47
|
+
threadId,
|
|
48
|
+
userId: user.id
|
|
49
|
+
});
|
|
50
|
+
if (!thread || typeof thread.id !== "string" || !thread.id.trim()) return Response.json({ error: "Invalid thread response" }, { status: 502 });
|
|
51
|
+
if (thread.agentId !== void 0 && thread.agentId !== agentId) return Response.json({ error: "Thread access denied" }, { status: 403 });
|
|
52
|
+
stopThreadId = thread.id;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
const status = getPlatformErrorStatus(error);
|
|
55
|
+
return Response.json({ error: "Thread access denied" }, { status: status && status >= 400 && status < 500 ? status : 502 });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (!(await resolveAgents(runtime.agents, request))[agentId]) return new Response(JSON.stringify({
|
|
59
|
+
error: "Agent not found",
|
|
60
|
+
message: `Agent '${agentId}' does not exist`
|
|
61
|
+
}), {
|
|
62
|
+
status: 404,
|
|
63
|
+
headers: { "Content-Type": "application/json" }
|
|
64
|
+
});
|
|
65
|
+
if (!await runtime.runner.stop({
|
|
66
|
+
threadId: stopThreadId,
|
|
67
|
+
...runId === void 0 ? {} : { runId },
|
|
68
|
+
...ownerId === void 0 ? {} : { ownerId }
|
|
69
|
+
})) return new Response(JSON.stringify({
|
|
70
|
+
stopped: false,
|
|
71
|
+
message: runId === void 0 ? `No active run for thread '${threadId}'.` : `Run '${runId}' is not the active run for thread '${threadId}'.`
|
|
72
|
+
}), {
|
|
73
|
+
status: 200,
|
|
74
|
+
headers: { "Content-Type": "application/json" }
|
|
75
|
+
});
|
|
76
|
+
return new Response(JSON.stringify({
|
|
77
|
+
stopped: true,
|
|
78
|
+
interrupt: {
|
|
79
|
+
type: EventType.RUN_ERROR,
|
|
80
|
+
message: "Run stopped by user",
|
|
81
|
+
code: "STOPPED"
|
|
82
|
+
}
|
|
83
|
+
}), {
|
|
84
|
+
status: 200,
|
|
85
|
+
headers: { "Content-Type": "application/json" }
|
|
86
|
+
});
|
|
87
|
+
} catch (error) {
|
|
88
|
+
console.error("Error stopping agent run:", error);
|
|
89
|
+
return new Response(JSON.stringify({
|
|
90
|
+
error: "Failed to stop agent",
|
|
91
|
+
message: error instanceof Error ? error.message : "Unknown error"
|
|
92
|
+
}), {
|
|
93
|
+
status: 500,
|
|
94
|
+
headers: { "Content-Type": "application/json" }
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
//#endregion
|
|
100
|
+
export { handleStopAgent };
|
|
101
|
+
//# sourceMappingURL=handle-stop.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-stop.mjs","names":[],"sources":["../../../src/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,OAAO;SACtB;AACN,SAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;AAK5E,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;EAIF,MAAM,QAAQ,MAAM,eAAe,QAAQ,OAAO,CAAC;AACnD,MAAI,kBAAkB,MAAM,CAAE,QAAO;EACrC,MAAM,EAAE,UAAU;EAClB,IAAI,eAAe;EACnB,IAAI;AACJ,MAAI,CAAC,sBAAsB,QAAQ,EAAE;GAEnC,MAAM,QAAQ,MAAM,wBAAwB;IAC1C;IACA;IACA,WAAW;IACZ,CAAC;AACF,OAAI,kBAAkB,MAAM,CAAE,QAAO;AACrC,aAAU;SACL;GACL,MAAM,OAAO,MAAM,wBAAwB;IAAE;IAAS;IAAS,CAAC;AAChE,OAAI,kBAAkB,KAAK,CAAE,QAAO;AACpC,OAAI;IACF,MAAM,SAAS,MAAM,QAAQ,aAAa,UAAU;KAClD;KACA,QAAQ,KAAK;KACd,CAAC;AACF,QAAI,CAAC,UAAU,OAAO,OAAO,OAAO,YAAY,CAAC,OAAO,GAAG,MAAM,CAC/D,QAAO,SAAS,KACd,EAAE,OAAO,2BAA2B,EACpC,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAI,OAAO,YAAY,UAAa,OAAO,YAAY,QACrD,QAAO,SAAS,KACd,EAAE,OAAO,wBAAwB,EACjC,EAAE,QAAQ,KAAK,CAChB;AAEH,mBAAe,OAAO;YACf,OAAO;IACd,MAAM,SAAS,uBAAuB,MAAM;AAC5C,WAAO,SAAS,KACd,EAAE,OAAO,wBAAwB,EACjC,EAAE,QAAQ,UAAU,UAAU,OAAO,SAAS,MAAM,SAAS,KAAK,CACnE;;;AAKL,MAAI,EAFW,MAAM,cAAc,QAAQ,QAAQ,QAAQ,EAE/C,SACV,QAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,UAAU,QAAQ;GAC5B,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AASH,MAAI,CANY,MAAM,QAAQ,OAAO,KAAK;GACxC,UAAU;GACV,GAAI,UAAU,SAAY,EAAE,GAAG,EAAE,OAAO;GACxC,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SACE,UAAU,SACN,6BAA6B,SAAS,MACtC,QAAQ,MAAM,sCAAsC,SAAS;GACpE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAM,UAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
2
|
+
const require_header_utils = require('./header-utils.cjs');
|
|
3
|
+
const require_agent_utils = require('./shared/agent-utils.cjs');
|
|
4
|
+
const require_sse_response = require('./shared/sse-response.cjs');
|
|
5
|
+
let _copilotkit_shared = require("@copilotkit/shared");
|
|
6
|
+
let rxjs = require("rxjs");
|
|
7
|
+
|
|
8
|
+
//#region src/runtime/handlers/handle-suggest.ts
|
|
9
|
+
/**
|
|
10
|
+
* Stateless suggestion run.
|
|
11
|
+
*
|
|
12
|
+
* Executes the provider agent **directly** and streams its AG-UI events back as
|
|
13
|
+
* SSE — the same wire format as `/agent/:id/run`, so the client consumes it with
|
|
14
|
+
* the stock `HttpAgent` transport and chips fill in as the provider emits them.
|
|
15
|
+
* It deliberately does not go through `runtime.runner`: the runner's
|
|
16
|
+
* `run()` writes to a module-level store keyed by threadId (backing the SSE
|
|
17
|
+
* runtime's local thread endpoints), which would leak the throwaway suggestion
|
|
18
|
+
* thread. This handler runs the agent's event pipeline **without** that
|
|
19
|
+
* persistence — no thread, lock, gateway, name-gen, or run telemetry — so
|
|
20
|
+
* dynamic suggestions are side-effect-free in every runtime mode.
|
|
21
|
+
*
|
|
22
|
+
* The only per-request configuration it applies is forwarding the request's
|
|
23
|
+
* allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does
|
|
24
|
+
* **not** attach any request middleware — no A2UI, no MCPApps, no
|
|
25
|
+
* OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**
|
|
26
|
+
* (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the
|
|
27
|
+
* request body; this handler does not set tool choice itself and relies on it
|
|
28
|
+
* being present in the incoming `input`. Given that forced tool choice, any
|
|
29
|
+
* middleware-injected tools are dead weight, and MCPApps setup can incur a
|
|
30
|
+
* `listTools` network round-trip per suggestion under `available: "always"` — a
|
|
31
|
+
* side effect this path must never pay.
|
|
32
|
+
*
|
|
33
|
+
* When the client aborts the HTTP request (via its `AbortController`), the
|
|
34
|
+
* server-side run is cancelled best-effort so an aborted suggestion does not
|
|
35
|
+
* keep running a provider call to completion.
|
|
36
|
+
*
|
|
37
|
+
* @param params - The runtime, request, and resolved agent id.
|
|
38
|
+
* @returns A `text/event-stream` `Response` of the provider agent's AG-UI events
|
|
39
|
+
* on success, or the resolution `Response` (e.g. 404/400) when agent/body
|
|
40
|
+
* resolution fails before streaming begins.
|
|
41
|
+
*/
|
|
42
|
+
async function handleSuggestAgent({ runtime, request, agentId }) {
|
|
43
|
+
const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId, request);
|
|
44
|
+
if (agent instanceof Response) return agent;
|
|
45
|
+
agent.agentId = agentId;
|
|
46
|
+
const input = await require_agent_utils.parseRunRequest(request);
|
|
47
|
+
if (input instanceof Response) return input;
|
|
48
|
+
const headerCarryingAgent = agent;
|
|
49
|
+
headerCarryingAgent.headers = require_header_utils.mergeForwardableHeaders(headerCarryingAgent.headers, request, runtime.forwardHeadersPolicy ?? require_header_utils.resolveForwardHeadersPolicy(void 0));
|
|
50
|
+
agent.setMessages(input.messages);
|
|
51
|
+
agent.setState(input.state);
|
|
52
|
+
agent.threadId = input.threadId;
|
|
53
|
+
return require_sse_response.createSseEventResponse({
|
|
54
|
+
request,
|
|
55
|
+
agentId,
|
|
56
|
+
captureTelemetry: false,
|
|
57
|
+
keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
|
|
58
|
+
observableFactory: () => new rxjs.Observable((subscriber) => {
|
|
59
|
+
const finalizer = (0, _copilotkit_shared.createRunEventFinalizer)();
|
|
60
|
+
let settled = false;
|
|
61
|
+
agent.runAgent(input, { onEvent: ({ event }) => {
|
|
62
|
+
finalizer.observe(event);
|
|
63
|
+
subscriber.next(event);
|
|
64
|
+
} }).then(() => {
|
|
65
|
+
for (const event of finalizer.finalize({ stopRequested: false })) subscriber.next(event);
|
|
66
|
+
settled = true;
|
|
67
|
+
subscriber.complete();
|
|
68
|
+
}).catch((error) => {
|
|
69
|
+
settled = true;
|
|
70
|
+
subscriber.error(error);
|
|
71
|
+
});
|
|
72
|
+
return () => {
|
|
73
|
+
if (!settled && typeof agent.abortRun === "function") try {
|
|
74
|
+
agent.abortRun();
|
|
75
|
+
} catch {}
|
|
76
|
+
};
|
|
77
|
+
})
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
//#endregion
|
|
82
|
+
exports.handleSuggestAgent = handleSuggestAgent;
|
|
83
|
+
//# sourceMappingURL=handle-suggest.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAIC,iBAAuB,eAAe;GAMxC,MAAM,6DAAqC;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { mergeForwardableHeaders, resolveForwardHeadersPolicy } from "./header-utils.mjs";
|
|
2
|
+
import { cloneAgentForRequest, parseRunRequest } from "./shared/agent-utils.mjs";
|
|
3
|
+
import { createSseEventResponse } from "./shared/sse-response.mjs";
|
|
4
|
+
import { createRunEventFinalizer } from "@copilotkit/shared";
|
|
5
|
+
import { Observable } from "rxjs";
|
|
6
|
+
|
|
7
|
+
//#region src/runtime/handlers/handle-suggest.ts
|
|
8
|
+
/**
|
|
9
|
+
* Stateless suggestion run.
|
|
10
|
+
*
|
|
11
|
+
* Executes the provider agent **directly** and streams its AG-UI events back as
|
|
12
|
+
* SSE — the same wire format as `/agent/:id/run`, so the client consumes it with
|
|
13
|
+
* the stock `HttpAgent` transport and chips fill in as the provider emits them.
|
|
14
|
+
* It deliberately does not go through `runtime.runner`: the runner's
|
|
15
|
+
* `run()` writes to a module-level store keyed by threadId (backing the SSE
|
|
16
|
+
* runtime's local thread endpoints), which would leak the throwaway suggestion
|
|
17
|
+
* thread. This handler runs the agent's event pipeline **without** that
|
|
18
|
+
* persistence — no thread, lock, gateway, name-gen, or run telemetry — so
|
|
19
|
+
* dynamic suggestions are side-effect-free in every runtime mode.
|
|
20
|
+
*
|
|
21
|
+
* The only per-request configuration it applies is forwarding the request's
|
|
22
|
+
* allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does
|
|
23
|
+
* **not** attach any request middleware — no A2UI, no MCPApps, no
|
|
24
|
+
* OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**
|
|
25
|
+
* (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the
|
|
26
|
+
* request body; this handler does not set tool choice itself and relies on it
|
|
27
|
+
* being present in the incoming `input`. Given that forced tool choice, any
|
|
28
|
+
* middleware-injected tools are dead weight, and MCPApps setup can incur a
|
|
29
|
+
* `listTools` network round-trip per suggestion under `available: "always"` — a
|
|
30
|
+
* side effect this path must never pay.
|
|
31
|
+
*
|
|
32
|
+
* When the client aborts the HTTP request (via its `AbortController`), the
|
|
33
|
+
* server-side run is cancelled best-effort so an aborted suggestion does not
|
|
34
|
+
* keep running a provider call to completion.
|
|
35
|
+
*
|
|
36
|
+
* @param params - The runtime, request, and resolved agent id.
|
|
37
|
+
* @returns A `text/event-stream` `Response` of the provider agent's AG-UI events
|
|
38
|
+
* on success, or the resolution `Response` (e.g. 404/400) when agent/body
|
|
39
|
+
* resolution fails before streaming begins.
|
|
40
|
+
*/
|
|
41
|
+
async function handleSuggestAgent({ runtime, request, agentId }) {
|
|
42
|
+
const agent = await cloneAgentForRequest(runtime, agentId, request);
|
|
43
|
+
if (agent instanceof Response) return agent;
|
|
44
|
+
agent.agentId = agentId;
|
|
45
|
+
const input = await parseRunRequest(request);
|
|
46
|
+
if (input instanceof Response) return input;
|
|
47
|
+
const headerCarryingAgent = agent;
|
|
48
|
+
headerCarryingAgent.headers = mergeForwardableHeaders(headerCarryingAgent.headers, request, runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(void 0));
|
|
49
|
+
agent.setMessages(input.messages);
|
|
50
|
+
agent.setState(input.state);
|
|
51
|
+
agent.threadId = input.threadId;
|
|
52
|
+
return createSseEventResponse({
|
|
53
|
+
request,
|
|
54
|
+
agentId,
|
|
55
|
+
captureTelemetry: false,
|
|
56
|
+
keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
|
|
57
|
+
observableFactory: () => new Observable((subscriber) => {
|
|
58
|
+
const finalizer = createRunEventFinalizer();
|
|
59
|
+
let settled = false;
|
|
60
|
+
agent.runAgent(input, { onEvent: ({ event }) => {
|
|
61
|
+
finalizer.observe(event);
|
|
62
|
+
subscriber.next(event);
|
|
63
|
+
} }).then(() => {
|
|
64
|
+
for (const event of finalizer.finalize({ stopRequested: false })) subscriber.next(event);
|
|
65
|
+
settled = true;
|
|
66
|
+
subscriber.complete();
|
|
67
|
+
}).catch((error) => {
|
|
68
|
+
settled = true;
|
|
69
|
+
subscriber.error(error);
|
|
70
|
+
});
|
|
71
|
+
return () => {
|
|
72
|
+
if (!settled && typeof agent.abortRun === "function") try {
|
|
73
|
+
agent.abortRun();
|
|
74
|
+
} catch {}
|
|
75
|
+
};
|
|
76
|
+
})
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
//#endregion
|
|
81
|
+
export { handleSuggestAgent };
|
|
82
|
+
//# sourceMappingURL=handle-suggest.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-suggest.mjs","names":[],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAM,gBAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAU,wBAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwB,4BAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAO,uBAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAI,YAAuB,eAAe;GAMxC,MAAM,YAAY,yBAAyB;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const require_trajectories = require('../intelligence-platform/trajectories.cjs');
|
|
2
|
+
const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
|
|
3
|
+
const require_runtime = require('../core/runtime.cjs');
|
|
4
|
+
|
|
5
|
+
//#region src/runtime/handlers/handle-trajectory-connect.ts
|
|
6
|
+
function trajectoryErrorResponse(code, message, status) {
|
|
7
|
+
return Response.json({
|
|
8
|
+
code,
|
|
9
|
+
message
|
|
10
|
+
}, {
|
|
11
|
+
status,
|
|
12
|
+
headers: { "Cache-Control": "no-store" }
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
async function handleTrajectoryConnect({ runtime, request, trajectoryId }) {
|
|
16
|
+
if (!require_trajectories.isValidTrajectoryId(trajectoryId)) return trajectoryErrorResponse("INVALID_REQUEST", "A valid trajectoryId is required", 400);
|
|
17
|
+
if (!require_runtime.isIntelligenceRuntime(runtime)) return trajectoryErrorResponse("INTELLIGENCE_RUNTIME_REQUIRED", "Trajectory capture requires an Intelligence runtime", 503);
|
|
18
|
+
if (!runtime.identifyUser) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
|
|
19
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
20
|
+
runtime,
|
|
21
|
+
request
|
|
22
|
+
});
|
|
23
|
+
if (user instanceof Response) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
|
|
24
|
+
try {
|
|
25
|
+
const grant = await runtime.intelligence.ɵconnectTrajectory({
|
|
26
|
+
trajectoryId,
|
|
27
|
+
user,
|
|
28
|
+
signal: request.signal
|
|
29
|
+
});
|
|
30
|
+
return Response.json(grant, { headers: { "Cache-Control": "no-store" } });
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (error instanceof require_trajectories.TrajectoryConnectionError) return trajectoryErrorResponse(error.code, error.message, error.status);
|
|
33
|
+
return trajectoryErrorResponse("CONNECTION_FAILED", "Could not connect to Intelligence", 502);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
exports.handleTrajectoryConnect = handleTrajectoryConnect;
|
|
39
|
+
exports.trajectoryErrorResponse = trajectoryErrorResponse;
|
|
40
|
+
//# sourceMappingURL=handle-trajectory-connect.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-trajectory-connect.cjs","names":["isValidTrajectoryId","isIntelligenceRuntime","resolveIntelligenceUser","TrajectoryConnectionError"],"sources":["../../../src/runtime/handlers/handle-trajectory-connect.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport {\n isValidTrajectoryId,\n TrajectoryConnectionError,\n} from \"../intelligence-platform/trajectories\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\n\nexport function trajectoryErrorResponse(\n code: string,\n message: string,\n status: number,\n): Response {\n return Response.json(\n { code, message },\n { status, headers: { \"Cache-Control\": \"no-store\" } },\n );\n}\n\nexport async function handleTrajectoryConnect({\n runtime,\n request,\n trajectoryId,\n}: {\n runtime: CopilotRuntimeLike;\n request: Request;\n trajectoryId: string;\n}): Promise<Response> {\n if (!isValidTrajectoryId(trajectoryId)) {\n return trajectoryErrorResponse(\n \"INVALID_REQUEST\",\n \"A valid trajectoryId is required\",\n 400,\n );\n }\n if (!isIntelligenceRuntime(runtime)) {\n return trajectoryErrorResponse(\n \"INTELLIGENCE_RUNTIME_REQUIRED\",\n \"Trajectory capture requires an Intelligence runtime\",\n 503,\n );\n }\n if (!runtime.identifyUser) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n if (user instanceof Response) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n\n try {\n const grant = await runtime.intelligence.ɵconnectTrajectory({\n trajectoryId,\n user,\n signal: request.signal,\n });\n return Response.json(grant, {\n headers: { \"Cache-Control\": \"no-store\" },\n });\n } catch (error) {\n if (error instanceof TrajectoryConnectionError) {\n return trajectoryErrorResponse(error.code, error.message, error.status);\n }\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n}\n"],"mappings":";;;;;AAQA,SAAgB,wBACd,MACA,SACA,QACU;AACV,QAAO,SAAS,KACd;EAAE;EAAM;EAAS,EACjB;EAAE;EAAQ,SAAS,EAAE,iBAAiB,YAAY;EAAE,CACrD;;AAGH,eAAsB,wBAAwB,EAC5C,SACA,SACA,gBAKoB;AACpB,KAAI,CAACA,yCAAoB,aAAa,CACpC,QAAO,wBACL,mBACA,oCACA,IACD;AAEH,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAO,wBACL,iCACA,uDACA,IACD;AAEH,KAAI,CAAC,QAAQ,aACX,QAAO,wBACL,qBACA,kDACA,IACD;CAEH,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,gBAAgB,SAClB,QAAO,wBACL,qBACA,kDACA,IACD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,aAAa,mBAAmB;GAC1D;GACA;GACA,QAAQ,QAAQ;GACjB,CAAC;AACF,SAAO,SAAS,KAAK,OAAO,EAC1B,SAAS,EAAE,iBAAiB,YAAY,EACzC,CAAC;UACK,OAAO;AACd,MAAI,iBAAiBC,+CACnB,QAAO,wBAAwB,MAAM,MAAM,MAAM,SAAS,MAAM,OAAO;AAEzE,SAAO,wBACL,qBACA,qCACA,IACD"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { TrajectoryConnectionError, isValidTrajectoryId } from "../intelligence-platform/trajectories.mjs";
|
|
2
|
+
import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs";
|
|
3
|
+
import { isIntelligenceRuntime } from "../core/runtime.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/runtime/handlers/handle-trajectory-connect.ts
|
|
6
|
+
function trajectoryErrorResponse(code, message, status) {
|
|
7
|
+
return Response.json({
|
|
8
|
+
code,
|
|
9
|
+
message
|
|
10
|
+
}, {
|
|
11
|
+
status,
|
|
12
|
+
headers: { "Cache-Control": "no-store" }
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
async function handleTrajectoryConnect({ runtime, request, trajectoryId }) {
|
|
16
|
+
if (!isValidTrajectoryId(trajectoryId)) return trajectoryErrorResponse("INVALID_REQUEST", "A valid trajectoryId is required", 400);
|
|
17
|
+
if (!isIntelligenceRuntime(runtime)) return trajectoryErrorResponse("INTELLIGENCE_RUNTIME_REQUIRED", "Trajectory capture requires an Intelligence runtime", 503);
|
|
18
|
+
if (!runtime.identifyUser) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
|
|
19
|
+
const user = await resolveIntelligenceUser({
|
|
20
|
+
runtime,
|
|
21
|
+
request
|
|
22
|
+
});
|
|
23
|
+
if (user instanceof Response) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
|
|
24
|
+
try {
|
|
25
|
+
const grant = await runtime.intelligence.ɵconnectTrajectory({
|
|
26
|
+
trajectoryId,
|
|
27
|
+
user,
|
|
28
|
+
signal: request.signal
|
|
29
|
+
});
|
|
30
|
+
return Response.json(grant, { headers: { "Cache-Control": "no-store" } });
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (error instanceof TrajectoryConnectionError) return trajectoryErrorResponse(error.code, error.message, error.status);
|
|
33
|
+
return trajectoryErrorResponse("CONNECTION_FAILED", "Could not connect to Intelligence", 502);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
export { handleTrajectoryConnect, trajectoryErrorResponse };
|
|
39
|
+
//# sourceMappingURL=handle-trajectory-connect.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-trajectory-connect.mjs","names":[],"sources":["../../../src/runtime/handlers/handle-trajectory-connect.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport {\n isValidTrajectoryId,\n TrajectoryConnectionError,\n} from \"../intelligence-platform/trajectories\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\n\nexport function trajectoryErrorResponse(\n code: string,\n message: string,\n status: number,\n): Response {\n return Response.json(\n { code, message },\n { status, headers: { \"Cache-Control\": \"no-store\" } },\n );\n}\n\nexport async function handleTrajectoryConnect({\n runtime,\n request,\n trajectoryId,\n}: {\n runtime: CopilotRuntimeLike;\n request: Request;\n trajectoryId: string;\n}): Promise<Response> {\n if (!isValidTrajectoryId(trajectoryId)) {\n return trajectoryErrorResponse(\n \"INVALID_REQUEST\",\n \"A valid trajectoryId is required\",\n 400,\n );\n }\n if (!isIntelligenceRuntime(runtime)) {\n return trajectoryErrorResponse(\n \"INTELLIGENCE_RUNTIME_REQUIRED\",\n \"Trajectory capture requires an Intelligence runtime\",\n 503,\n );\n }\n if (!runtime.identifyUser) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n if (user instanceof Response) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n\n try {\n const grant = await runtime.intelligence.ɵconnectTrajectory({\n trajectoryId,\n user,\n signal: request.signal,\n });\n return Response.json(grant, {\n headers: { \"Cache-Control\": \"no-store\" },\n });\n } catch (error) {\n if (error instanceof TrajectoryConnectionError) {\n return trajectoryErrorResponse(error.code, error.message, error.status);\n }\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n}\n"],"mappings":";;;;;AAQA,SAAgB,wBACd,MACA,SACA,QACU;AACV,QAAO,SAAS,KACd;EAAE;EAAM;EAAS,EACjB;EAAE;EAAQ,SAAS,EAAE,iBAAiB,YAAY;EAAE,CACrD;;AAGH,eAAsB,wBAAwB,EAC5C,SACA,SACA,gBAKoB;AACpB,KAAI,CAAC,oBAAoB,aAAa,CACpC,QAAO,wBACL,mBACA,oCACA,IACD;AAEH,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,wBACL,iCACA,uDACA,IACD;AAEH,KAAI,CAAC,QAAQ,aACX,QAAO,wBACL,qBACA,kDACA,IACD;CAEH,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,gBAAgB,SAClB,QAAO,wBACL,qBACA,kDACA,IACD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,aAAa,mBAAmB;GAC1D;GACA;GACA,QAAQ,QAAQ;GACjB,CAAC;AACF,SAAO,SAAS,KAAK,OAAO,EAC1B,SAAS,EAAE,iBAAiB,YAAY,EACzC,CAAC;UACK,OAAO;AACd,MAAI,iBAAiB,0BACnB,QAAO,wBAAwB,MAAM,MAAM,MAAM,SAAS,MAAM,OAAO;AAEzE,SAAO,wBACL,qBACA,qCACA,IACD"}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
2
|
+
let _copilotkit_shared = require("@copilotkit/shared");
|
|
3
|
+
|
|
4
|
+
//#region src/runtime/handlers/handle-transcribe.ts
|
|
5
|
+
/**
|
|
6
|
+
* HTTP status codes for transcription error codes
|
|
7
|
+
*/
|
|
8
|
+
const ERROR_STATUS_CODES = {
|
|
9
|
+
[_copilotkit_shared.TranscriptionErrorCode.SERVICE_NOT_CONFIGURED]: 503,
|
|
10
|
+
[_copilotkit_shared.TranscriptionErrorCode.INVALID_AUDIO_FORMAT]: 400,
|
|
11
|
+
[_copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_LONG]: 400,
|
|
12
|
+
[_copilotkit_shared.TranscriptionErrorCode.AUDIO_TOO_SHORT]: 400,
|
|
13
|
+
[_copilotkit_shared.TranscriptionErrorCode.RATE_LIMITED]: 429,
|
|
14
|
+
[_copilotkit_shared.TranscriptionErrorCode.AUTH_FAILED]: 401,
|
|
15
|
+
[_copilotkit_shared.TranscriptionErrorCode.PROVIDER_ERROR]: 500,
|
|
16
|
+
[_copilotkit_shared.TranscriptionErrorCode.NETWORK_ERROR]: 502,
|
|
17
|
+
[_copilotkit_shared.TranscriptionErrorCode.INVALID_REQUEST]: 400
|
|
18
|
+
};
|
|
19
|
+
const VALID_AUDIO_TYPES = [
|
|
20
|
+
"audio/mpeg",
|
|
21
|
+
"audio/mp3",
|
|
22
|
+
"audio/mp4",
|
|
23
|
+
"audio/wav",
|
|
24
|
+
"audio/webm",
|
|
25
|
+
"audio/ogg",
|
|
26
|
+
"audio/flac",
|
|
27
|
+
"audio/aac"
|
|
28
|
+
];
|
|
29
|
+
function isValidAudioType(type) {
|
|
30
|
+
const baseType = type.split(";")[0]?.trim() ?? "";
|
|
31
|
+
return VALID_AUDIO_TYPES.includes(baseType) || baseType === "" || baseType === "application/octet-stream";
|
|
32
|
+
}
|
|
33
|
+
function createErrorResponse(errorResponse) {
|
|
34
|
+
const status = ERROR_STATUS_CODES[errorResponse.error] ?? 500;
|
|
35
|
+
return new Response(JSON.stringify(errorResponse), {
|
|
36
|
+
status,
|
|
37
|
+
headers: { "Content-Type": "application/json" }
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
function base64ToFile(base64, mimeType, filename) {
|
|
41
|
+
const base64Data = base64.includes(",") ? base64.split(",")[1] ?? base64 : base64;
|
|
42
|
+
const binaryString = atob(base64Data);
|
|
43
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
44
|
+
for (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);
|
|
45
|
+
return new File([bytes], filename, { type: mimeType });
|
|
46
|
+
}
|
|
47
|
+
async function extractAudioFromFormData(request) {
|
|
48
|
+
let audioFile = (await request.formData()).get("audio");
|
|
49
|
+
if (!audioFile || !(audioFile instanceof File)) return { error: createErrorResponse(_copilotkit_shared.TranscriptionErrors.invalidRequest("No audio file found in form data. Please include an 'audio' field.")) };
|
|
50
|
+
if (!isValidAudioType(audioFile.type)) return { error: createErrorResponse(_copilotkit_shared.TranscriptionErrors.invalidAudioFormat(audioFile.type, VALID_AUDIO_TYPES)) };
|
|
51
|
+
if (!audioFile.type || audioFile.type === "application/octet-stream") audioFile = new File([audioFile], audioFile.name || "recording.webm", { type: "audio/webm" });
|
|
52
|
+
return { file: audioFile };
|
|
53
|
+
}
|
|
54
|
+
async function extractAudioFromJson(request) {
|
|
55
|
+
let body;
|
|
56
|
+
try {
|
|
57
|
+
body = await request.json();
|
|
58
|
+
} catch {
|
|
59
|
+
return { error: createErrorResponse(_copilotkit_shared.TranscriptionErrors.invalidRequest("Request body must be valid JSON")) };
|
|
60
|
+
}
|
|
61
|
+
if (!body.audio || typeof body.audio !== "string") return { error: createErrorResponse(_copilotkit_shared.TranscriptionErrors.invalidRequest("Request must include 'audio' field with base64-encoded audio data")) };
|
|
62
|
+
if (!body.mimeType || typeof body.mimeType !== "string") return { error: createErrorResponse(_copilotkit_shared.TranscriptionErrors.invalidRequest("Request must include 'mimeType' field (e.g., 'audio/webm')")) };
|
|
63
|
+
if (!isValidAudioType(body.mimeType)) return { error: createErrorResponse(_copilotkit_shared.TranscriptionErrors.invalidAudioFormat(body.mimeType, VALID_AUDIO_TYPES)) };
|
|
64
|
+
try {
|
|
65
|
+
const filename = body.filename || "recording.webm";
|
|
66
|
+
return { file: base64ToFile(body.audio, body.mimeType, filename) };
|
|
67
|
+
} catch {
|
|
68
|
+
return { error: createErrorResponse(_copilotkit_shared.TranscriptionErrors.invalidRequest("Failed to decode base64 audio data")) };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Categorize provider errors into appropriate transcription error responses.
|
|
73
|
+
*/
|
|
74
|
+
function categorizeProviderError(error) {
|
|
75
|
+
const message = error instanceof Error ? error.message : "Unknown error occurred";
|
|
76
|
+
const errorStr = String(error).toLowerCase();
|
|
77
|
+
if (errorStr.includes("rate") || errorStr.includes("429") || errorStr.includes("too many")) return _copilotkit_shared.TranscriptionErrors.rateLimited();
|
|
78
|
+
if (errorStr.includes("auth") || errorStr.includes("401") || errorStr.includes("api key") || errorStr.includes("unauthorized")) return _copilotkit_shared.TranscriptionErrors.authFailed();
|
|
79
|
+
if (errorStr.includes("too long") || errorStr.includes("duration") || errorStr.includes("length")) return _copilotkit_shared.TranscriptionErrors.audioTooLong();
|
|
80
|
+
return _copilotkit_shared.TranscriptionErrors.providerError(message);
|
|
81
|
+
}
|
|
82
|
+
async function handleTranscribe({ runtime, request }) {
|
|
83
|
+
try {
|
|
84
|
+
if (!runtime.transcriptionService) return createErrorResponse(_copilotkit_shared.TranscriptionErrors.serviceNotConfigured());
|
|
85
|
+
const contentType = request.headers.get("content-type") || "";
|
|
86
|
+
let extractResult;
|
|
87
|
+
if (contentType.includes("multipart/form-data")) extractResult = await extractAudioFromFormData(request);
|
|
88
|
+
else if (contentType.includes("application/json")) extractResult = await extractAudioFromJson(request);
|
|
89
|
+
else return createErrorResponse(_copilotkit_shared.TranscriptionErrors.invalidRequest("Request must be multipart/form-data or application/json with base64 audio"));
|
|
90
|
+
if ("error" in extractResult) return extractResult.error;
|
|
91
|
+
const audioFile = extractResult.file;
|
|
92
|
+
const transcription = await runtime.transcriptionService.transcribeFile({
|
|
93
|
+
audioFile,
|
|
94
|
+
mimeType: audioFile.type,
|
|
95
|
+
size: audioFile.size
|
|
96
|
+
});
|
|
97
|
+
return new Response(JSON.stringify({
|
|
98
|
+
text: transcription,
|
|
99
|
+
size: audioFile.size,
|
|
100
|
+
type: audioFile.type
|
|
101
|
+
}), {
|
|
102
|
+
status: 200,
|
|
103
|
+
headers: { "Content-Type": "application/json" }
|
|
104
|
+
});
|
|
105
|
+
} catch (error) {
|
|
106
|
+
return createErrorResponse(categorizeProviderError(error));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
//#endregion
|
|
111
|
+
exports.handleTranscribe = handleTranscribe;
|
|
112
|
+
//# sourceMappingURL=handle-transcribe.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle-transcribe.cjs","names":["TranscriptionErrorCode","TranscriptionErrors"],"sources":["../../../src/runtime/handlers/handle-transcribe.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n} from \"@copilotkit/shared\";\nimport type { TranscriptionErrorResponse } from \"@copilotkit/shared\";\n\n/**\n * HTTP status codes for transcription error codes\n */\nconst ERROR_STATUS_CODES: Record<TranscriptionErrorCode, number> = {\n [TranscriptionErrorCode.SERVICE_NOT_CONFIGURED]: 503,\n [TranscriptionErrorCode.INVALID_AUDIO_FORMAT]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_LONG]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_SHORT]: 400,\n [TranscriptionErrorCode.RATE_LIMITED]: 429,\n [TranscriptionErrorCode.AUTH_FAILED]: 401,\n [TranscriptionErrorCode.PROVIDER_ERROR]: 500,\n [TranscriptionErrorCode.NETWORK_ERROR]: 502,\n [TranscriptionErrorCode.INVALID_REQUEST]: 400,\n};\n\ninterface HandleTranscribeParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface Base64AudioInput {\n audio: string; // base64-encoded audio data\n mimeType: string;\n filename?: string;\n}\n\nconst VALID_AUDIO_TYPES = [\n \"audio/mpeg\",\n \"audio/mp3\",\n \"audio/mp4\",\n \"audio/wav\",\n \"audio/webm\",\n \"audio/ogg\",\n \"audio/flac\",\n \"audio/aac\",\n];\n\nfunction isValidAudioType(type: string): boolean {\n // Extract base MIME type (before semicolon) to handle types like \"audio/webm; codecs=opus\"\n const baseType = type.split(\";\")[0]?.trim() ?? \"\";\n return (\n VALID_AUDIO_TYPES.includes(baseType) ||\n baseType === \"\" ||\n baseType === \"application/octet-stream\"\n );\n}\n\nfunction createErrorResponse(\n errorResponse: TranscriptionErrorResponse,\n): Response {\n const status = ERROR_STATUS_CODES[errorResponse.error] ?? 500;\n return new Response(JSON.stringify(errorResponse), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction base64ToFile(\n base64: string,\n mimeType: string,\n filename: string,\n): File {\n // Remove data URL prefix if present (e.g., \"data:audio/webm;base64,\")\n const base64Data = base64.includes(\",\")\n ? (base64.split(\",\")[1] ?? base64)\n : base64;\n\n // Decode base64 to binary\n const binaryString = atob(base64Data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n\n // Create File object\n return new File([bytes], filename, { type: mimeType });\n}\n\nasync function extractAudioFromFormData(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n const formData = await request.formData();\n let audioFile = formData.get(\"audio\") as File | null;\n\n if (!audioFile || !(audioFile instanceof File)) {\n const err = TranscriptionErrors.invalidRequest(\n \"No audio file found in form data. Please include an 'audio' field.\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(audioFile.type)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n audioFile.type,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n // Browser MediaRecorder Blobs often arrive at the server with their\n // `type` field empty (and `application/octet-stream` is also accepted by\n // isValidAudioType for compatibility). OpenAI Whisper rejects files\n // without a recognizable MIME / extension with a 502 \"Invalid file\n // format\" — even though the bytes themselves are valid WebM Opus.\n // Stamp `audio/webm` (the standard MediaRecorder default in Chromium /\n // Firefox / Safari) so Whisper can pick the right decoder.\n if (!audioFile.type || audioFile.type === \"application/octet-stream\") {\n audioFile = new File([audioFile], audioFile.name || \"recording.webm\", {\n type: \"audio/webm\",\n });\n }\n\n return { file: audioFile };\n}\n\nasync function extractAudioFromJson(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n let body: Base64AudioInput;\n\n try {\n body = await request.json();\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Request body must be valid JSON\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.audio || typeof body.audio !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'audio' field with base64-encoded audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.mimeType || typeof body.mimeType !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'mimeType' field (e.g., 'audio/webm')\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(body.mimeType)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n body.mimeType,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n try {\n const filename = body.filename || \"recording.webm\";\n const file = base64ToFile(body.audio, body.mimeType, filename);\n return { file };\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Failed to decode base64 audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n}\n\n/**\n * Categorize provider errors into appropriate transcription error responses.\n */\nfunction categorizeProviderError(error: unknown): TranscriptionErrorResponse {\n const message =\n error instanceof Error ? error.message : \"Unknown error occurred\";\n const errorStr = String(error).toLowerCase();\n\n // Check for rate limiting\n if (\n errorStr.includes(\"rate\") ||\n errorStr.includes(\"429\") ||\n errorStr.includes(\"too many\")\n ) {\n return TranscriptionErrors.rateLimited();\n }\n\n // Check for auth errors\n if (\n errorStr.includes(\"auth\") ||\n errorStr.includes(\"401\") ||\n errorStr.includes(\"api key\") ||\n errorStr.includes(\"unauthorized\")\n ) {\n return TranscriptionErrors.authFailed();\n }\n\n // Check for audio too long\n if (\n errorStr.includes(\"too long\") ||\n errorStr.includes(\"duration\") ||\n errorStr.includes(\"length\")\n ) {\n return TranscriptionErrors.audioTooLong();\n }\n\n // Default to provider error\n return TranscriptionErrors.providerError(message);\n}\n\nexport async function handleTranscribe({\n runtime,\n request,\n}: HandleTranscribeParameters) {\n try {\n // Check if transcription service is configured\n if (!runtime.transcriptionService) {\n const err = TranscriptionErrors.serviceNotConfigured();\n return createErrorResponse(err);\n }\n\n // Determine input type based on content-type header\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n let extractResult: { file: File } | { error: Response };\n\n if (contentType.includes(\"multipart/form-data\")) {\n // Handle multipart/form-data (REST mode)\n extractResult = await extractAudioFromFormData(request);\n } else if (contentType.includes(\"application/json\")) {\n // Handle JSON with base64 audio (single-endpoint mode)\n extractResult = await extractAudioFromJson(request);\n } else {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must be multipart/form-data or application/json with base64 audio\",\n );\n return createErrorResponse(err);\n }\n\n // Check for extraction errors\n if (\"error\" in extractResult) {\n return extractResult.error;\n }\n\n const audioFile = extractResult.file;\n\n // Transcribe the audio file\n const transcription = await runtime.transcriptionService.transcribeFile({\n audioFile,\n mimeType: audioFile.type,\n size: audioFile.size,\n });\n\n return new Response(\n JSON.stringify({\n text: transcription,\n size: audioFile.size,\n type: audioFile.type,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n // Categorize the error for better client-side handling\n return createErrorResponse(categorizeProviderError(error));\n }\n}\n"],"mappings":"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"}
|