@copilotkit/runtime 2.0.0-rc.4 → 2.0.0-rc.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -3
- package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -76
- package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
- package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
- package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
- package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
- package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
- package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
- package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
- package/dist/agent/ai-sdk.cjs +425 -0
- package/dist/agent/ai-sdk.cjs.map +1 -0
- package/dist/agent/ai-sdk.d.cts +119 -0
- package/dist/agent/ai-sdk.d.cts.map +1 -0
- package/dist/agent/ai-sdk.d.mts +119 -0
- package/dist/agent/ai-sdk.d.mts.map +1 -0
- package/dist/agent/ai-sdk.mjs +419 -0
- package/dist/agent/ai-sdk.mjs.map +1 -0
- package/dist/agent/classic-tools.cjs +185 -0
- package/dist/agent/classic-tools.cjs.map +1 -0
- package/dist/agent/classic-tools.mjs +183 -0
- package/dist/agent/classic-tools.mjs.map +1 -0
- package/dist/agent/converters/aisdk.cjs +16 -3
- package/dist/agent/converters/aisdk.cjs.map +1 -1
- package/dist/agent/converters/aisdk.d.cts.map +1 -1
- package/dist/agent/converters/aisdk.d.mts.map +1 -1
- package/dist/agent/converters/aisdk.mjs +18 -2
- package/dist/agent/converters/aisdk.mjs.map +1 -1
- package/dist/agent/converters/tanstack.cjs +201 -29
- package/dist/agent/converters/tanstack.cjs.map +1 -1
- package/dist/agent/converters/tanstack.d.cts +90 -6
- package/dist/agent/converters/tanstack.d.cts.map +1 -1
- package/dist/agent/converters/tanstack.d.mts +90 -6
- package/dist/agent/converters/tanstack.d.mts.map +1 -1
- package/dist/agent/converters/tanstack.mjs +201 -28
- package/dist/agent/converters/tanstack.mjs.map +1 -1
- package/dist/agent/learned-skills.cjs +15 -17
- package/dist/agent/learned-skills.cjs.map +1 -1
- package/dist/agent/learned-skills.d.cts +9 -3
- package/dist/agent/learned-skills.d.cts.map +1 -1
- package/dist/agent/learned-skills.d.mts +9 -3
- package/dist/agent/learned-skills.d.mts.map +1 -1
- package/dist/agent/learned-skills.mjs +15 -16
- package/dist/agent/learned-skills.mjs.map +1 -1
- package/dist/agent/model.cjs +42 -0
- package/dist/agent/model.cjs.map +1 -0
- package/dist/agent/model.d.cts +19 -0
- package/dist/agent/model.d.cts.map +1 -0
- package/dist/agent/model.d.mts +19 -0
- package/dist/agent/model.d.mts.map +1 -0
- package/dist/agent/model.mjs +41 -0
- package/dist/agent/model.mjs.map +1 -0
- package/dist/agent/state-delta.cjs +0 -1
- package/dist/agent/state-delta.cjs.map +1 -1
- package/dist/agent.cjs +558 -0
- package/dist/agent.cjs.map +1 -0
- package/dist/agent.d.cts +455 -0
- package/dist/agent.d.cts.map +1 -0
- package/dist/agent.d.mts +455 -0
- package/dist/agent.d.mts.map +1 -0
- package/dist/agent.mjs +551 -0
- package/dist/agent.mjs.map +1 -0
- package/dist/index.cjs +21 -27
- package/dist/index.d.cts +10 -11
- package/dist/index.d.mts +10 -11
- package/dist/index.mjs +5 -6
- package/dist/internal/learned-skills.d.cts +1 -1
- package/dist/internal/learned-skills.d.mts +1 -1
- package/dist/node.cjs +1 -2
- package/dist/node.d.cts +2 -2
- package/dist/node.d.mts +2 -2
- package/dist/node.mjs +2 -2
- package/dist/runtime/core/channel-manager.cjs +10 -2
- package/dist/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/runtime/core/channel-manager.d.cts +1 -1
- package/dist/runtime/core/channel-manager.d.mts +1 -1
- package/dist/runtime/core/channel-manager.mjs +10 -1
- package/dist/runtime/core/channel-manager.mjs.map +1 -1
- package/dist/runtime/core/debug-event-bus.cjs +4 -3
- package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
- package/dist/runtime/core/debug-event-bus.d.cts +5 -1
- package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
- package/dist/runtime/core/debug-event-bus.d.mts +4 -0
- package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
- package/dist/runtime/core/debug-event-bus.mjs +5 -3
- package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
- package/dist/runtime/core/fetch-handler.cjs +15 -12
- package/dist/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/runtime/core/fetch-handler.d.cts +8 -0
- package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/runtime/core/fetch-handler.d.mts +8 -0
- package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/runtime/core/fetch-handler.mjs +7 -3
- package/dist/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/runtime/core/learning.d.cts +1 -1
- package/dist/runtime/core/logger.cjs +105 -14
- package/dist/runtime/core/logger.cjs.map +1 -1
- package/dist/runtime/core/logger.d.cts +25 -8
- package/dist/runtime/core/logger.d.cts.map +1 -1
- package/dist/runtime/core/logger.d.mts +25 -8
- package/dist/runtime/core/logger.d.mts.map +1 -1
- package/dist/runtime/core/logger.mjs +105 -12
- package/dist/runtime/core/logger.mjs.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.cjs +3 -4
- package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
- package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
- package/dist/runtime/core/middleware.cjs +5 -5
- package/dist/runtime/core/middleware.cjs.map +1 -1
- package/dist/runtime/core/middleware.mjs +4 -3
- package/dist/runtime/core/middleware.mjs.map +1 -1
- package/dist/runtime/core/package-info.cjs +1 -1
- package/dist/runtime/core/package-info.mjs +1 -1
- package/dist/runtime/core/runtime.cjs +11 -10
- package/dist/runtime/core/runtime.cjs.map +1 -1
- package/dist/runtime/core/runtime.d.cts +22 -4
- package/dist/runtime/core/runtime.d.cts.map +1 -1
- package/dist/runtime/core/runtime.d.mts +22 -4
- package/dist/runtime/core/runtime.d.mts.map +1 -1
- package/dist/runtime/core/runtime.mjs +11 -9
- package/dist/runtime/core/runtime.mjs.map +1 -1
- package/dist/runtime/endpoints/auto-start-channels.cjs +3 -4
- package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
- package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
- package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.cjs +3 -7
- package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.cts +3 -4
- package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.mts +3 -4
- package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.mjs +3 -5
- package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
- package/dist/runtime/endpoints/node.cjs +4 -2
- package/dist/runtime/endpoints/node.cjs.map +1 -1
- package/dist/runtime/endpoints/node.d.cts.map +1 -1
- package/dist/runtime/endpoints/node.d.mts.map +1 -1
- package/dist/runtime/endpoints/node.mjs +4 -2
- package/dist/runtime/endpoints/node.mjs.map +1 -1
- package/dist/runtime/event-transforms/index.d.cts +4 -0
- package/dist/runtime/event-transforms/index.d.mts +4 -0
- package/dist/runtime/event-transforms/index.mjs +5 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.cjs +58 -0
- package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.d.cts +23 -0
- package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.d.mts +23 -0
- package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.mjs +58 -0
- package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
- package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
- package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
- package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
- package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.cjs +5 -1
- package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.mjs +5 -1
- package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/runtime/handlers/handle-connect.cjs +3 -8
- package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
- package/dist/runtime/handlers/handle-connect.mjs +3 -8
- package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
- package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
- package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
- package/dist/runtime/handlers/handle-run.cjs +11 -14
- package/dist/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/runtime/handlers/handle-run.mjs +8 -10
- package/dist/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/runtime/handlers/handle-stop.cjs +5 -5
- package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
- package/dist/runtime/handlers/handle-stop.mjs +2 -1
- package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
- package/dist/runtime/handlers/handle-suggest.cjs +6 -3
- package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
- package/dist/runtime/handlers/handle-suggest.mjs +6 -2
- package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
- package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
- package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/annotate.cjs +8 -8
- package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/annotate.mjs +4 -3
- package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
- package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
- package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/memories.cjs +27 -22
- package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/memories.mjs +11 -5
- package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/run.cjs +38 -30
- package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/run.mjs +37 -28
- package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -5
- package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
- package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.cjs +36 -27
- package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.mjs +13 -3
- package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.cjs +35 -34
- package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.mjs +29 -27
- package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
- package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +4 -3
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +4 -3
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
- package/dist/runtime/handlers/shared/sse-response.cjs +77 -78
- package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/runtime/handlers/shared/sse-response.mjs +77 -77
- package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.cjs +3 -2
- package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.mjs +3 -2
- package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
- package/dist/runtime/handlers/sse/connect.cjs +2 -0
- package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
- package/dist/runtime/handlers/sse/connect.mjs +2 -0
- package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
- package/dist/runtime/handlers/sse/run.cjs +5 -2
- package/dist/runtime/handlers/sse/run.cjs.map +1 -1
- package/dist/runtime/handlers/sse/run.mjs +5 -2
- package/dist/runtime/handlers/sse/run.mjs.map +1 -1
- package/dist/runtime/index.d.cts +9 -15
- package/dist/runtime/index.d.mts +9 -15
- package/dist/runtime/intelligence-platform/analytics-context.cjs +84 -0
- package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/analytics-context.mjs +83 -0
- package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/client.cjs +27 -1
- package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.cts +24 -1
- package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.mts +24 -1
- package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/client.mjs +27 -0
- package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
- package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
- package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
- package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
- package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +22 -19
- package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +22 -19
- package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/stop-run.cjs +50 -0
- package/dist/runtime/intelligence-platform/stop-run.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/stop-run.mjs +50 -0
- package/dist/runtime/intelligence-platform/stop-run.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -3
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
- package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
- package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
- package/dist/runtime/node.d.cts +1 -1
- package/dist/runtime/node.d.mts +1 -1
- package/dist/runtime/runner/agent-runner.cjs +0 -1
- package/dist/runtime/runner/agent-runner.cjs.map +1 -1
- package/dist/runtime/runner/agent-runner.d.cts +9 -0
- package/dist/runtime/runner/agent-runner.d.cts.map +1 -1
- package/dist/runtime/runner/agent-runner.d.mts +9 -0
- package/dist/runtime/runner/agent-runner.d.mts.map +1 -1
- package/dist/runtime/runner/agent-runner.mjs.map +1 -1
- package/dist/runtime/runner/in-memory.cjs +0 -1
- package/dist/runtime/runner/in-memory.cjs.map +1 -1
- package/dist/runtime/runner/index.d.cts +1 -1
- package/dist/runtime/runner/index.d.mts +1 -1
- package/dist/runtime/runner/index.mjs +1 -1
- package/dist/runtime/runner/intelligence.cjs +55 -9
- package/dist/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/runtime/runner/intelligence.d.cts +12 -1
- package/dist/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/runtime/runner/intelligence.d.mts +12 -1
- package/dist/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/runtime/runner/intelligence.mjs +56 -10
- package/dist/runtime/runner/intelligence.mjs.map +1 -1
- package/dist/runtime/telemetry/disclosure.cjs +2 -3
- package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
- package/dist/runtime/telemetry/disclosure.mjs +3 -3
- package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
- package/dist/runtime/telemetry/events.d.cts +1 -1
- package/dist/runtime/telemetry/events.d.mts +1 -1
- package/dist/runtime/telemetry/instance-created.cjs +33 -12
- package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
- package/dist/runtime/telemetry/instance-created.mjs +33 -12
- package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-client.cjs +0 -5
- package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-client.mjs +0 -4
- package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
- package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
- package/package.json +55 -30
- package/dist/_virtual/_rolldown/runtime.cjs +0 -29
- package/dist/agent/converters/index.d.mts +0 -2
- package/dist/agent/index.cjs +0 -1328
- package/dist/agent/index.cjs.map +0 -1
- package/dist/agent/index.d.cts +0 -467
- package/dist/agent/index.d.cts.map +0 -1
- package/dist/agent/index.d.mts +0 -468
- package/dist/agent/index.d.mts.map +0 -1
- package/dist/agent/index.mjs +0 -1318
- package/dist/agent/index.mjs.map +0 -1
- package/dist/agent/mcp-tool-names.cjs +0 -82
- package/dist/agent/mcp-tool-names.cjs.map +0 -1
- package/dist/agent/mcp-tool-names.mjs +0 -80
- package/dist/agent/mcp-tool-names.mjs.map +0 -1
- package/dist/agent/url-download.cjs.map +0 -1
- package/dist/agent/url-download.d.cts.map +0 -1
- package/dist/agent/url-download.d.mts.map +0 -1
- package/dist/agent/url-download.mjs.map +0 -1
- package/dist/runtime/index.d.cts.map +0 -1
- package/dist/runtime/index.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"url-download.mjs","names":["readBody"],"sources":["../../../src/agent/ai-sdk/url-download.ts"],"sourcesContent":["/**\n * Server-side download of URL attachments (image/file parts) for AI SDK\n * `streamText` calls, used as their `experimental_download`.\n *\n * The AI SDK downloads any URL attachment that the model cannot take as a URL\n * and puts the bytes into the prompt. The URL comes from the request, so the\n * default downloader lets a caller make the server fetch internal addresses.\n * The AI SDK's own check rejects literal private IPs and the names\n * `localhost`, `*.local` and `*.localhost`, but it compares the literal text\n * and never resolves DNS: a hostname that resolves to a private address, or a\n * spelling such as `localhost.`, gets through.\n *\n * This downloader:\n * - leaves `data:` URLs to the AI SDK, which decodes them without a fetch;\n * - accepts only http and https URLs without credentials;\n * - resolves the hostname and rejects any non-public address;\n * - connects only to the addresses it checked (no second DNS lookup);\n * - checks every redirect target the same way, and refuses https to http;\n * - limits the size and time of each download, and the number and total\n * size of the downloads for one model call;\n * - stops when the `signal` given to `createSafeUrlDownload` aborts, or when\n * another download of the same call fails.\n *\n * The client gets the same message whether a host did not resolve or resolved\n * to a non-public address, and the reason is only logged on the server. Two\n * residual signals are accepted: the time to fail can differ between the two\n * cases, and a DNS lookup that hangs (for example in an internal zone) ends\n * with the timeout message instead.\n */\nimport type * as DnsPromises from \"node:dns/promises\";\nimport type * as Http from \"node:http\";\nimport type { IncomingMessage } from \"node:http\";\nimport type * as Https from \"node:https\";\nimport type * as Net from \"node:net\";\nimport type { LookupAddress } from \"node:dns\";\nimport type { LookupFunction } from \"node:net\";\nimport { COPILOTKIT_VERSION } from \"@copilotkit/shared\";\nimport { DownloadError } from \"ai\";\nimport type { Experimental_DownloadFunction as DownloadFunction } from \"ai\";\n\n/** Options for the default, public-network-only URL downloader. */\nexport interface SafeUrlDownloadOptions {\n /**\n * Hostnames that may be downloaded. When omitted, any hostname is allowed.\n * Every resolved address must be public in both cases, and every redirect\n * target must match as well.\n *\n * - `cdn.example.com` matches exactly that host.\n * - `*.example.com` matches any subdomain (`a.example.com`,\n * `a.b.example.com`) but not `example.com` itself; list both if needed.\n *\n * Matching ignores case and a trailing dot. Unicode names match their\n * punycode form, and an IPv6 address may be given with or without\n * brackets. An entry with a scheme, port, path or user, and a wildcard over\n * an IP address (`*.1.2.3.4`), are rejected when the downloader is created.\n * An empty list refuses every server-side download; `data:` URLs and URLs\n * that the model takes directly are not downloaded, so they still pass.\n */\n allowedHosts?: string[];\n /** Largest response body to accept, in bytes (at least 1). Default: 20 MiB. */\n maxBytes?: number;\n /**\n * Time limit for one download, including redirects, in ms. From 1 to\n * 2147483647 (the largest delay `setTimeout` supports). Default: 30000.\n */\n timeoutMs?: number;\n /** Largest number of redirects to follow; 0 follows none. Default: 3. */\n maxRedirects?: number;\n /**\n * Largest number of distinct URLs to download for one model call (at\n * least 1); a URL that appears twice is downloaded once. The AI SDK\n * downloads the attachments of every user message again for each step of\n * a multi-step run. Default: 20.\n */\n maxDownloads?: number;\n /**\n * Largest number of bytes to download for one model call, over all its\n * URLs (at least 1). Default: 50 MiB.\n */\n maxTotalBytes?: number;\n}\n\n/** @internal Test seams. Not part of the public API. */\nexport interface UrlDownloadInternals {\n resolveHost?: (hostname: string) => Promise<LookupAddress[]>;\n /**\n * Replaces the address policy. It has the shape of the exported\n * {@link isPublicAddress}; an async answer is awaited.\n */\n isPublicAddress?: (address: string) => boolean | Promise<boolean>;\n /** CA certificates to trust for https instead of the default ones. */\n ca?: string;\n}\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_REDIRECTS = 3;\nconst DEFAULT_MAX_DOWNLOADS = 20;\nconst DEFAULT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;\n// One message for both cases, so that the error does not reveal whether an\n// internal name exists. The reason is logged on the server only. (A lookup\n// that hangs ends with the timeout message instead; see the file header.)\nconst HOST_REFUSED =\n \"The URL host is not a public address, or it could not be resolved.\";\n// For a network, TLS or response stream error. The cause, which can name a\n// resolved address, is only logged.\nconst DOWNLOAD_FAILED = \"The download failed.\";\nconst USER_AGENT = `CopilotKit-Runtime/${COPILOTKIT_VERSION}`;\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\ntype NodeModules = {\n dns: typeof DnsPromises;\n http: typeof Http;\n https: typeof Https;\n net: typeof Net;\n};\n\nlet nodeModules: Promise<NodeModules> | undefined;\n\ntype GetBuiltinModule = <T>(id: string) => T;\n\n// Loaded on first use so that importing the agent does not require Node\n// networking modules. Where they are not available (for example on an edge\n// runtime), downloads fail closed and the log says how to configure them.\n// `process.getBuiltinModule` (Node 20.16+) is used instead of `import(\"node:…\")`\n// so that edge bundlers (Workers, Vercel Edge) never see a Node specifier.\nfunction loadNodeModules(): Promise<NodeModules> {\n nodeModules ??= Promise.resolve()\n .then(() => {\n const load = (\n globalThis.process as\n | { getBuiltinModule?: GetBuiltinModule }\n | undefined\n )?.getBuiltinModule;\n if (!load) throw new Error(\"process.getBuiltinModule is not available\");\n return {\n dns: load<typeof DnsPromises>(\"node:dns/promises\"),\n http: load<typeof Http>(\"node:http\"),\n https: load<typeof Https>(\"node:https\"),\n net: load<typeof Net>(\"node:net\"),\n };\n })\n .catch((error: unknown) => {\n // Try again on the next download instead of failing forever.\n nodeModules = undefined;\n throw error;\n });\n return nodeModules;\n}\n\ntype AddressPolicy = (address: string) => boolean;\nlet defaultPolicy: AddressPolicy | undefined;\n\nfunction buildAddressPolicy(net: NodeModules[\"net\"]): AddressPolicy {\n const nonPublicV4 = new net.BlockList();\n for (const [address, prefix] of [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10], // Carrier-grade NAT.\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16], // Link-local, including cloud metadata.\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.88.99.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n ] as const) {\n nonPublicV4.addSubnet(address, prefix, \"ipv4\");\n }\n\n // Only global unicast IPv6 (2000::/3) is public. This also rejects ::1,\n // fc00::/7, fe80::/10, IPv4-mapped (::ffff:0:0/96) and NAT64 (64:ff9b::/96).\n const globalV6 = new net.BlockList();\n globalV6.addSubnet(\"2000::\", 3, \"ipv6\");\n const nonPublicV6 = new net.BlockList();\n for (const [address, prefix] of [\n // IANA special-purpose block, including Teredo (2001::/32). A few ranges\n // inside it are globally reachable (for example AS112, 2001:4:112::/48);\n // the whole /23 is refused on purpose, failing closed.\n [\"2001::\", 23],\n [\"2001:db8::\", 32], // Documentation.\n [\"2002::\", 16], // 6to4.\n [\"3fff::\", 20], // Documentation.\n ] as const) {\n nonPublicV6.addSubnet(address, prefix, \"ipv6\");\n }\n\n return (address) => {\n const family = net.isIP(address);\n if (family === 4) return !nonPublicV4.check(address, \"ipv4\");\n if (family !== 6 || address.includes(\"%\")) return false;\n return (\n globalV6.check(address, \"ipv6\") && !nonPublicV6.check(address, \"ipv6\")\n );\n };\n}\n\n/** Returns true only for a public unicast IPv4 or IPv6 address. */\nexport async function isPublicAddress(address: string): Promise<boolean> {\n const { net } = await loadNodeModules();\n defaultPolicy ??= buildAddressPolicy(net);\n return defaultPolicy(address);\n}\n\n/**\n * True when the server must not fetch this URL itself and returns `null` so\n * the AI SDK handles it: the provider takes the URL as-is, or it is a `data:`\n * URL, which the AI SDK decodes locally without any network request.\n */\nfunction leftToAiSdk({\n url,\n isUrlSupportedByModel,\n}: {\n url: URL;\n isUrlSupportedByModel: boolean;\n}): boolean {\n return isUrlSupportedByModel || url.protocol === \"data:\";\n}\n\n/** The URL without its query and fragment, which can hold credentials. */\nfunction urlForLog(url: URL | string): string {\n try {\n const parsed = new URL(String(url));\n return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** `text` with the query and fragment removed from every URL in it. */\nfunction redactUrls(text: string): string {\n return text.replace(\n /\\b([a-z][a-z0-9+.-]*:\\/\\/[^\\s?#\"'`<>]*)[?#][^\\s\"'`<>]*/gi,\n \"$1\",\n );\n}\n\n/**\n * Returns the error for a failed or refused download and logs it on the\n * server. `detail` goes only to the log: the client sees `message`, which\n * never holds the URL's query, a resolved address or a raw network error.\n * For a refused host, `message` is the same whether the name did not resolve\n * or resolved to a non-public address, so that it does not reveal internal\n * DNS names.\n */\nfunction refuse(\n url: URL | string,\n message: string,\n detail?: string,\n statusCode?: number,\n): DownloadError {\n console.warn(\n redactUrls(\n `[CopilotKit] URL download failed for ${urlForLog(url)}: ${message}${detail ? ` (${detail})` : \"\"}`,\n ),\n );\n return new DownloadError({ url: urlForLog(url), message, statusCode });\n}\n\n// Longest text logged for one value in an error description.\nconst MAX_LOGGED_FIELD_LENGTH = 2000;\n\nfunction truncateForLog(text: string): string {\n return text.length > MAX_LOGGED_FIELD_LENGTH\n ? `${text.slice(0, MAX_LOGGED_FIELD_LENGTH)}… (${text.length} characters)`\n : text;\n}\n\n/** Message, error code and causes of an error, for the server log. */\nfunction describeError(error: unknown, depth = 0): string {\n if (typeof error === \"string\") return error;\n if (!(error instanceof Error)) return truncateForLog(describeValue(error));\n const code = (error as { code?: unknown }).code;\n const text =\n typeof code === \"string\" && !error.message.includes(code)\n ? `${code}: ${error.message}`\n : error.message;\n return error.cause !== undefined && depth < 3\n ? `${text}; caused by ${describeError(error.cause, depth + 1)}`\n : text;\n}\n\n/**\n * A printable form of a configuration value for an error message. Unlike\n * `JSON.stringify`, it never throws (BigInt) and never gives `undefined`\n * (Symbol, function).\n */\nfunction describeValue(value: unknown): string {\n if (typeof value === \"bigint\") return `${value}n`;\n if (typeof value === \"function\") return \"a function\";\n try {\n const text = JSON.stringify(value);\n if (text !== undefined) return text;\n } catch {\n // Not serializable, for example a cycle or a nested BigInt.\n }\n try {\n return String(value);\n } catch {\n return Object.prototype.toString.call(value);\n }\n}\n\n/**\n * The form in which hostnames are compared: a URL hostname (lowercase ASCII,\n * IDNA as punycode, IPv6 in canonical form) without IPv6 brackets and without\n * one trailing dot.\n */\nfunction comparableHost(hostname: string): string {\n return hostname.replace(/^\\[(.*)\\]$/, \"$1\").replace(/\\.$/, \"\");\n}\n\n/**\n * Validates one `allowedHosts` entry and returns it in comparable form: an\n * exact host, or `*.` followed by a host suffix.\n */\nfunction normalizeAllowedHost(entry: unknown): string {\n const invalid = (reason: string) =>\n new Error(\n `createSafeUrlDownload.allowedHosts entry ${describeValue(entry)} is invalid: ${reason}`,\n );\n if (typeof entry !== \"string\" || entry === \"\") {\n throw invalid(\"it must be a non-empty hostname\");\n }\n if (/[\\s/?#@\\\\]/.test(entry)) {\n throw invalid(\"give only a hostname, without a scheme, path or user\");\n }\n const wildcard = entry.startsWith(\"*.\");\n const host = wildcard ? entry.slice(2) : entry;\n if (host === \"\" || host === \".\" || host.includes(\"*\")) {\n throw invalid('\"*\" is allowed only as a leading \"*.\" label');\n }\n // `host:port` (one \":\" and no brackets) or `[ipv6]:port`. An IPv6 address\n // without brackets always has at least two \":\".\n if (/^[^:[\\]]*:\\d*$/.test(host) || /^\\[.*\\]:\\d*$/.test(host)) {\n throw invalid(\"give only a hostname, without a port\");\n }\n const bare = host.replace(/^\\[(.*)\\]$/, \"$1\");\n // Any \":\" left belongs to an IPv6 address, which the URL parser needs in\n // brackets.\n const authority = bare.includes(\":\") ? `[${bare}]` : host;\n let parsed: URL;\n try {\n parsed = new URL(`http://${authority}/`);\n } catch {\n throw invalid(\"it is not a valid hostname\");\n }\n const normalized = comparableHost(parsed.hostname);\n // The URL parser turns a name whose last label is a number into an IPv4\n // address (`*.0.1` becomes `0.0.0.1`), and no hostname can end in one.\n if (\n wildcard &&\n (normalized.includes(\":\") || /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(normalized))\n ) {\n throw invalid(\"a wildcard needs a hostname suffix, not an IP address\");\n }\n return (wildcard ? \"*.\" : \"\") + normalized;\n}\n\nfunction normalizeAllowedHosts(entries: unknown): string[] | undefined {\n if (entries === undefined) return undefined;\n if (!Array.isArray(entries)) {\n throw new Error(\n \"createSafeUrlDownload.allowedHosts must be an array of hostnames\",\n );\n }\n return entries.map(normalizeAllowedHost);\n}\n\nfunction hostAllowed(hostname: string, allowedHosts?: string[]): boolean {\n if (!allowedHosts) return true;\n const host = comparableHost(hostname);\n return allowedHosts.some((pattern) =>\n pattern.startsWith(\"*.\")\n ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1\n : host === pattern,\n );\n}\n\nfunction checkUrl(url: URL, allowedHosts?: string[]): void {\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw refuse(url, \"Only http and https URLs can be downloaded.\");\n }\n if (url.username !== \"\" || url.password !== \"\") {\n throw refuse(url, \"URLs with credentials cannot be downloaded.\");\n }\n if (!hostAllowed(url.hostname, allowedHosts)) {\n throw refuse(url, \"The URL host is not in the allowed hosts list.\");\n }\n}\n\n/**\n * Waits for `work`, or rejects with the abort reason when `signal` aborts.\n * The handlers are attached to `work` first, so that a later rejection of\n * `work` is always handled: an unhandled rejection ends a Node process in\n * the default mode.\n */\nfunction withDeadline<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n work.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", onAbort);\n });\n if (signal.aborted) return onAbort();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nasync function requestPinned(\n modules: NodeModules,\n url: URL,\n addresses: LookupAddress[],\n signal: AbortSignal,\n ca: string | undefined,\n): Promise<IncomingMessage> {\n // Answer the socket's lookup with the checked addresses only, so a second\n // DNS answer (DNS rebinding) can never pick the destination.\n const lookup: LookupFunction = (_hostname, options, callback) => {\n const wanted = typeof options === \"number\" ? options : options?.family;\n const available =\n wanted === 4 || wanted === 6\n ? addresses.filter((a) => a.family === wanted)\n : addresses;\n if (available.length === 0) {\n callback(\n refuse(url, \"No checked address is available for this URL.\"),\n \"\",\n 4,\n );\n } else if (typeof options === \"object\" && options?.all) {\n callback(null, available);\n } else {\n callback(null, available[0]!.address, available[0]!.family);\n }\n };\n const isHttps = url.protocol === \"https:\";\n const transport = isHttps ? modules.https : modules.http;\n // A new agent per request: no pooled socket and no proxy can bypass the\n // pinned lookup.\n const agent = isHttps\n ? new modules.https.Agent({ keepAlive: false, maxCachedSessions: 0 })\n : new modules.http.Agent({ keepAlive: false });\n const hostname = url.hostname.replace(/^\\[|\\]$/g, \"\");\n\n return new Promise<IncomingMessage>((resolve, reject) => {\n const request = transport.request(\n {\n protocol: url.protocol,\n hostname,\n // SNI must not carry the trailing dot of a fully qualified name.\n servername:\n isHttps && modules.net.isIP(hostname) === 0\n ? hostname.replace(/\\.$/, \"\")\n : undefined,\n port: url.port || (isHttps ? 443 : 80),\n path: url.pathname + url.search,\n method: \"GET\",\n // Some hosts refuse a request without a User-Agent.\n headers: { \"accept-encoding\": \"identity\", \"user-agent\": USER_AGENT },\n lookup,\n agent,\n signal,\n ...(isHttps && ca !== undefined ? { ca } : {}),\n },\n (response) => {\n response.once(\"close\", () => agent.destroy());\n resolve(response);\n },\n );\n // `on`, not `once`: an error after the first one (for example from the\n // socket while it is torn down) must not go unhandled. Rejecting twice\n // is harmless.\n request.on(\"error\", (error) => {\n agent.destroy();\n reject(error);\n });\n request.once(\"upgrade\", (_response, socket) => {\n socket.destroy();\n agent.destroy();\n reject(refuse(url, \"Protocol upgrade refused.\"));\n });\n request.end();\n });\n}\n\n/**\n * Bytes still allowed for all the downloads of one model call, the current\n * one included. Shared by them and decreased as their bodies stream in.\n */\ntype ByteBudget = { remaining: number; readonly limit: number };\n\ntype ResolvedOptions = {\n allowedHosts: string[] | undefined;\n maxBytes: number;\n timeoutMs: number;\n maxRedirects: number;\n maxDownloads: number;\n maxTotalBytes: number;\n};\n\nasync function readBody(\n url: URL,\n response: IncomingMessage,\n maxBytes: number,\n budget: ByteBudget,\n): Promise<Uint8Array> {\n const tooLarge = () =>\n refuse(url, `The response is larger than the ${maxBytes}-byte limit.`);\n const overBudget = () =>\n refuse(\n url,\n `The downloads are larger than the ${budget.limit}-byte total limit.`,\n );\n const declared = Number(response.headers[\"content-length\"]);\n if (Number.isFinite(declared) && declared > maxBytes) throw tooLarge();\n if (Number.isFinite(declared) && declared > budget.remaining) {\n throw overBudget();\n }\n const encoding = response.headers[\"content-encoding\"];\n if (encoding && encoding !== \"identity\") {\n throw refuse(url, \"Compressed responses are not accepted.\");\n }\n const chunks: Buffer[] = [];\n let total = 0;\n for await (const chunk of response) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n total += buffer.byteLength;\n if (total > maxBytes) throw tooLarge();\n budget.remaining -= buffer.byteLength;\n if (budget.remaining < 0) throw overBudget();\n chunks.push(buffer);\n }\n return new Uint8Array(Buffer.concat(chunks, total));\n}\n\nasync function downloadOne(\n original: URL,\n options: ResolvedOptions,\n internals: UrlDownloadInternals,\n outer: AbortSignal,\n budget: ByteBudget,\n): Promise<{ data: Uint8Array; mediaType: string | undefined }> {\n const modules = await loadNodeModules().catch((error: unknown) => {\n throw refuse(\n original,\n \"URL download needs Node.js networking modules, which are not available here.\",\n `loading them failed: ${describeError(error)}. On a runtime without them, pass your own download function as experimental_download`,\n );\n });\n defaultPolicy ??= buildAddressPolicy(modules.net);\n const isPublic = internals.isPublicAddress ?? defaultPolicy;\n const resolveHost =\n internals.resolveHost ??\n ((hostname: string) =>\n modules.dns.lookup(hostname, { all: true, verbatim: true }));\n\n // The URL of the current hop, so that a timeout names the hop that hung.\n let url = original;\n const controller = new AbortController();\n const timer = setTimeout(\n () =>\n controller.abort(\n refuse(\n url,\n `The download timed out after ${options.timeoutMs} ms (timeoutMs).`,\n ),\n ),\n options.timeoutMs,\n );\n // The run was aborted, or another download in the same call failed.\n const onOuterAbort = () => controller.abort(outer.reason);\n if (outer.aborted) onOuterAbort();\n else outer.addEventListener(\"abort\", onOuterAbort, { once: true });\n const { signal } = controller;\n try {\n for (let hop = 0; ; hop++) {\n // An aborted download does nothing more, not even a DNS query for a\n // name that the request chose.\n signal.throwIfAborted();\n checkUrl(url, options.allowedHosts);\n const hostname = url.hostname.replace(/^\\[|\\]$/g, \"\");\n const literalFamily = modules.net.isIP(hostname);\n let addresses: LookupAddress[];\n try {\n signal.throwIfAborted();\n addresses = literalFamily\n ? [{ address: hostname, family: literalFamily }]\n : await withDeadline(resolveHost(hostname), signal);\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n throw refuse(\n url,\n HOST_REFUSED,\n `DNS lookup failed: ${describeError(error)}`,\n );\n }\n const verdicts = await Promise.all(\n addresses.map(\n async ({ address, family }) =>\n (family === 4 || family === 6) &&\n (await isPublic(address)) === true,\n ),\n );\n const rejected = addresses.filter((_address, i) => !verdicts[i]);\n if (addresses.length === 0 || rejected.length > 0) {\n throw refuse(\n url,\n HOST_REFUSED,\n addresses.length === 0\n ? \"DNS lookup returned no addresses\"\n : `non-public address: ${rejected.map((a) => a.address).join(\", \")}`,\n );\n }\n\n let response: IncomingMessage;\n try {\n response = await requestPinned(\n modules,\n url,\n addresses,\n signal,\n internals.ca,\n );\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n if (DownloadError.isInstance(error)) throw error;\n throw refuse(url, DOWNLOAD_FAILED, describeError(error));\n }\n try {\n const status = response.statusCode ?? 0;\n if (REDIRECT_STATUSES.has(status)) {\n if (hop >= options.maxRedirects) {\n throw refuse(\n url,\n `Too many redirects: the limit is ${options.maxRedirects} (maxRedirects).`,\n );\n }\n const location = response.headers.location;\n if (!location) throw refuse(url, \"Redirect without a location.\");\n let next: URL;\n try {\n next = new URL(location, url);\n } catch (error) {\n throw refuse(\n url,\n \"Redirect to an invalid URL.\",\n `Location ${JSON.stringify(location.slice(0, 200))}: ${describeError(error)}`,\n );\n }\n // Bytes fetched over plain http could be changed in transit.\n if (url.protocol === \"https:\" && next.protocol === \"http:\") {\n throw refuse(url, \"A redirect from https to http is refused.\");\n }\n url = next;\n continue;\n }\n if (status < 200 || status >= 300) {\n throw refuse(\n url,\n `The server answered with HTTP status ${status}.`,\n response.statusMessage,\n status,\n );\n }\n const data = await readBody(url, response, options.maxBytes, budget);\n const contentType = response.headers[\"content-type\"];\n return { data, mediaType: contentType || undefined };\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n if (DownloadError.isInstance(error)) throw error;\n throw refuse(url, DOWNLOAD_FAILED, describeError(error));\n } finally {\n response.destroy();\n }\n }\n } finally {\n clearTimeout(timer);\n outer.removeEventListener(\"abort\", onOuterAbort);\n controller.abort();\n }\n}\n\n// setTimeout clamps a longer delay to 1 ms, so a larger limit would end every\n// download at once.\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/** Returns `value` (or `fallback`) if it is an integer from `min` to `max`. */\nfunction integerOption(\n name: string,\n value: number | undefined,\n fallback: number,\n min: number,\n max = Number.MAX_SAFE_INTEGER,\n): number {\n const result = value ?? fallback;\n if (!Number.isSafeInteger(result) || result < min || result > max) {\n const range =\n max === Number.MAX_SAFE_INTEGER\n ? `an integer of at least ${min}`\n : `an integer from ${min} to ${max}`;\n throw new Error(\n `createSafeUrlDownload.${name} must be ${range}, got ${describeValue(value)}`,\n );\n }\n return result;\n}\n\n// Every option name, so that a mistyped name fails instead of being ignored:\n// a mistyped `allowedHosts` would otherwise allow every public host.\nconst OPTION_NAMES: Record<keyof SafeUrlDownloadOptions, true> = {\n allowedHosts: true,\n maxBytes: true,\n timeoutMs: true,\n maxRedirects: true,\n maxDownloads: true,\n maxTotalBytes: true,\n};\n\nfunction checkOptionsObject(options: unknown): asserts options is object {\n if (\n typeof options !== \"object\" ||\n options === null ||\n Array.isArray(options)\n ) {\n throw new Error(\n `createSafeUrlDownload options must be an object, got ${describeValue(options)}`,\n );\n }\n}\n\nfunction checkOptionNames(options: unknown): void {\n checkOptionsObject(options);\n for (const name of Object.keys(options)) {\n if (!Object.prototype.hasOwnProperty.call(OPTION_NAMES, name)) {\n throw new Error(\n `createSafeUrlDownload has an unknown option ${describeValue(name)}; the valid options are ${Object.keys(OPTION_NAMES).join(\", \")}`,\n );\n }\n }\n}\n\n/** A download function that can also be tied to a run's abort signal. */\nexport type GuardedUrlDownload = DownloadFunction & {\n /** The same download function, aborted when `signal` aborts. */\n forRun(signal: AbortSignal): DownloadFunction;\n};\n\n/** @internal Factory with test seams; use {@link createSafeUrlDownload}. */\nexport function createGuardedUrlDownload(\n options: SafeUrlDownloadOptions = {},\n internals: UrlDownloadInternals = {},\n): GuardedUrlDownload {\n checkOptionNames(options);\n const resolved: ResolvedOptions = {\n allowedHosts: normalizeAllowedHosts(options.allowedHosts),\n maxBytes: integerOption(\"maxBytes\", options.maxBytes, DEFAULT_MAX_BYTES, 1),\n timeoutMs: integerOption(\n \"timeoutMs\",\n options.timeoutMs,\n DEFAULT_TIMEOUT_MS,\n 1,\n MAX_TIMEOUT_MS,\n ),\n maxRedirects: integerOption(\n \"maxRedirects\",\n options.maxRedirects,\n DEFAULT_MAX_REDIRECTS,\n 0,\n ),\n maxDownloads: integerOption(\n \"maxDownloads\",\n options.maxDownloads,\n DEFAULT_MAX_DOWNLOADS,\n 1,\n ),\n maxTotalBytes: integerOption(\n \"maxTotalBytes\",\n options.maxTotalBytes,\n DEFAULT_MAX_TOTAL_BYTES,\n 1,\n ),\n };\n const downloadAll = async (\n requests: Parameters<DownloadFunction>[0],\n runSignal?: AbortSignal,\n ) => {\n // Aborted when the run aborts, or when one download fails, so that the\n // other downloads in this call stop as well.\n const batch = new AbortController();\n const onRunAbort = () => batch.abort(runSignal?.reason);\n if (runSignal?.aborted) onRunAbort();\n else runSignal?.addEventListener(\"abort\", onRunAbort, { once: true });\n try {\n // One download per distinct URL; duplicates share its result.\n const pending = new Map<string, URL>();\n for (const request of requests) {\n if (!leftToAiSdk(request)) pending.set(request.url.href, request.url);\n }\n if (pending.size > resolved.maxDownloads) {\n throw refuse(\n [...pending.values()][resolved.maxDownloads]!,\n `A model call can have at most ${resolved.maxDownloads} URL downloads; this one has ${pending.size}.`,\n );\n }\n const budget: ByteBudget = {\n remaining: resolved.maxTotalBytes,\n limit: resolved.maxTotalBytes,\n };\n const downloads = new Map(\n [...pending].map(([href, url]) => [\n href,\n downloadOne(url, resolved, internals, batch.signal, budget).catch(\n (error: unknown) => {\n batch.abort(error);\n throw error;\n },\n ),\n ]),\n );\n return await Promise.all(\n requests.map((request) =>\n leftToAiSdk(request) ? null : downloads.get(request.url.href)!,\n ),\n );\n } finally {\n runSignal?.removeEventListener(\"abort\", onRunAbort);\n batch.abort();\n }\n };\n return Object.assign(\n (requests: Parameters<DownloadFunction>[0]) => downloadAll(requests),\n {\n forRun:\n (signal: AbortSignal): DownloadFunction =>\n (requests) =>\n downloadAll(requests, signal),\n },\n );\n}\n\n/** Options for {@link createSafeUrlDownload}. */\nexport interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {\n /**\n * Stops every download of this function when it aborts, for example the\n * run's `ctx.abortSignal` in a `type: \"aisdk\"` factory. Without it, a\n * download that is running when the run is aborted goes on until it ends\n * or reaches `timeoutMs`.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Creates an AI SDK download function (`experimental_download`) that only\n * fetches public internet addresses. For `streamText` calls in a\n * `type: \"aisdk\"` factory. Create it in the factory with the run's abort\n * signal, so that an aborted run stops its downloads:\n *\n * ```ts\n * import { streamText } from \"ai\";\n * import { createSafeUrlDownload } from \"@copilotkit/runtime/agent/ai-sdk\";\n *\n * factory: (ctx) =>\n * streamText({\n * model,\n * messages,\n * abortSignal: ctx.abortSignal,\n * experimental_download: createSafeUrlDownload({ signal: ctx.abortSignal }),\n * }),\n * ```\n *\n * @param options - Host allow list, size, time and count limits, and the\n * abort `signal`. All are optional.\n * @throws Error when an option is invalid. It throws here, when the function\n * is created, not on the first download.\n */\nexport function createSafeUrlDownload(\n options: CreateSafeUrlDownloadOptions = {},\n) {\n checkOptionsObject(options);\n const { signal, ...downloadOptions } = options;\n if (signal !== undefined && !(signal instanceof AbortSignal)) {\n throw new Error(\n `createSafeUrlDownload signal must be an AbortSignal, got ${describeValue(signal)}`,\n );\n }\n const download = createGuardedUrlDownload(downloadOptions);\n // The public type is the plain AI SDK download function, without `forRun`.\n const runDownload: DownloadFunction = signal\n ? download.forRun(signal)\n : download;\n return runDownload;\n}\n"],"mappings":";;;;AA8FA,MAAM,oBAAoB,KAAK,OAAO;AACtC,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B,KAAK,OAAO;AAI5C,MAAM,eACJ;AAGF,MAAM,kBAAkB;AACxB,MAAM,aAAa,sBAAsB;AACzC,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;CAAI,CAAC;AAS5D,IAAI;AASJ,SAAS,kBAAwC;AAC/C,iBAAgB,QAAQ,SAAS,CAC9B,WAAW;EACV,MAAM,OACJ,WAAW,SAGV;AACH,MAAI,CAAC,KAAM,OA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mB;AAClB,UAAM,MAAM,MAAM;AAClB,UAAM;KAET,CACF,CAAC,CACH;AACD,UAAO,MAAM,QAAQ,IACnB,SAAS,KAAK,YACZ,YAAY,QAAQ,GAAG,OAAO,UAAU,IAAI,QAAQ,IAAI,KAAK,CAC9D,CACF;YACO;AACR,cAAW,oBAAoB,SAAS,WAAW;AACnD,SAAM,OAAO;;;AAGjB,QAAO,OAAO,QACX,aAA8C,YAAY,SAAS,EACpE,EACE,SACG,YACA,aACC,YAAY,UAAU,OAAO,EAClC,CACF;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCH,SAAgB,sBACd,UAAwC,EAAE,EAC1C;AACA,oBAAmB,QAAQ;CAC3B,MAAM,EAAE,QAAQ,GAAG,oBAAoB;AACvC,KAAI,WAAW,UAAa,EAAE,kBAAkB,aAC9C,OAAM,IAAI,MACR,4DAA4D,cAAc,OAAO,GAClF;CAEH,MAAM,WAAW,yBAAyB,gBAAgB;AAK1D,QAHsC,SAClC,SAAS,OAAO,OAAO,GACvB"}
|
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_url_download = require('./ai-sdk/url-download.cjs');
|
|
3
|
+
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
|
+
let zod = require("zod");
|
|
5
|
+
let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
|
|
6
|
+
let _cfworker_json_schema = require("@cfworker/json-schema");
|
|
7
|
+
let ai = require("ai");
|
|
8
|
+
|
|
9
|
+
//#region src/agent/ai-sdk/index.ts
|
|
10
|
+
/**
|
|
11
|
+
* `@copilotkit/runtime/agent/ai-sdk`: helpers for `type: "aisdk"` factories.
|
|
12
|
+
*
|
|
13
|
+
* This is the only runtime entry that imports `ai` at module scope. An app
|
|
14
|
+
* that imports it uses the AI SDK, so `ai` must be installed.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* A tool result or user part can name a provider file handle (`file` source).
|
|
18
|
+
* It is neither bytes nor a URL, and the AI SDK cannot send it to the
|
|
19
|
+
* provider, so the part is dropped with a warning.
|
|
20
|
+
*/
|
|
21
|
+
function warnDroppedFileSource(what) {
|
|
22
|
+
console.warn(`[CopilotKit] Dropping a ${what} that references a provider file handle: it is not a URL or inline data, so it cannot be sent to the model here.`);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The AI SDK output for an AG-UI tool message.
|
|
26
|
+
*
|
|
27
|
+
* A text-only result is one text output. A URL part becomes its URL as text.
|
|
28
|
+
* A result with inline media is a content list: the text entry first, when
|
|
29
|
+
* there is any, then each media part with its bytes and media type. A
|
|
30
|
+
* media-only result is media alone. A result whose parts were all dropped is
|
|
31
|
+
* the empty string, because AG-UI 1.0 requires every call to be answered.
|
|
32
|
+
*/
|
|
33
|
+
function toolResultOutput(content) {
|
|
34
|
+
if (typeof content === "string") return {
|
|
35
|
+
type: "text",
|
|
36
|
+
value: content
|
|
37
|
+
};
|
|
38
|
+
const segments = [];
|
|
39
|
+
const media = [];
|
|
40
|
+
let open = false;
|
|
41
|
+
for (const part of content) if (part.type === "text") {
|
|
42
|
+
if (open) segments[segments.length - 1] += part.text;
|
|
43
|
+
else segments.push(part.text);
|
|
44
|
+
open = true;
|
|
45
|
+
} else if (part.source.type === "file") warnDroppedFileSource(`${part.type} part in a tool result`);
|
|
46
|
+
else if (part.source.type === "url") {
|
|
47
|
+
segments.push(part.source.value);
|
|
48
|
+
open = false;
|
|
49
|
+
} else {
|
|
50
|
+
media.push({
|
|
51
|
+
type: "media",
|
|
52
|
+
data: part.source.value,
|
|
53
|
+
mediaType: part.source.mimeType
|
|
54
|
+
});
|
|
55
|
+
open = false;
|
|
56
|
+
}
|
|
57
|
+
const text = segments.join("\n");
|
|
58
|
+
if (media.length === 0) return {
|
|
59
|
+
type: "text",
|
|
60
|
+
value: text
|
|
61
|
+
};
|
|
62
|
+
return {
|
|
63
|
+
type: "content",
|
|
64
|
+
value: [...text.length > 0 ? [{
|
|
65
|
+
type: "text",
|
|
66
|
+
text
|
|
67
|
+
}] : [], ...media]
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** A URL from the request, or `null` (logged) when it does not parse. */
|
|
71
|
+
function parseContentUrl(value, what) {
|
|
72
|
+
try {
|
|
73
|
+
return new URL(value);
|
|
74
|
+
} catch {
|
|
75
|
+
console.error(`[CopilotKit] convertUserMessageContent: invalid URL "${value}" in ${what} part, skipping`);
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Converts AG-UI user message content to AI SDK user content: plain strings,
|
|
81
|
+
* modality parts (image, audio, video, document), and the legacy `binary`
|
|
82
|
+
* part.
|
|
83
|
+
*/
|
|
84
|
+
function convertUserMessageContent(content) {
|
|
85
|
+
if (!content) return "";
|
|
86
|
+
if (typeof content === "string") return content;
|
|
87
|
+
const parts = [];
|
|
88
|
+
for (const part of content) {
|
|
89
|
+
if (!part || typeof part !== "object" || !("type" in part)) continue;
|
|
90
|
+
switch (part.type) {
|
|
91
|
+
case "text":
|
|
92
|
+
if (part.text) parts.push({
|
|
93
|
+
type: "text",
|
|
94
|
+
text: part.text
|
|
95
|
+
});
|
|
96
|
+
break;
|
|
97
|
+
case "image": {
|
|
98
|
+
const { source } = part;
|
|
99
|
+
if (!source) break;
|
|
100
|
+
if (source.type === "data") parts.push({
|
|
101
|
+
type: "image",
|
|
102
|
+
image: source.value,
|
|
103
|
+
mediaType: source.mimeType
|
|
104
|
+
});
|
|
105
|
+
else if (source.type === "file") warnDroppedFileSource("image part");
|
|
106
|
+
else {
|
|
107
|
+
const url = parseContentUrl(source.value, "image");
|
|
108
|
+
if (url) parts.push({
|
|
109
|
+
type: "image",
|
|
110
|
+
image: url,
|
|
111
|
+
mediaType: source.mimeType
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
case "audio":
|
|
117
|
+
case "video":
|
|
118
|
+
case "document": {
|
|
119
|
+
const { source } = part;
|
|
120
|
+
if (!source) break;
|
|
121
|
+
if (source.type === "data") parts.push({
|
|
122
|
+
type: "file",
|
|
123
|
+
data: source.value,
|
|
124
|
+
mediaType: source.mimeType
|
|
125
|
+
});
|
|
126
|
+
else if (source.type === "file") warnDroppedFileSource(`${part.type} part`);
|
|
127
|
+
else {
|
|
128
|
+
const url = parseContentUrl(source.value, part.type);
|
|
129
|
+
if (url) parts.push({
|
|
130
|
+
type: "file",
|
|
131
|
+
data: url,
|
|
132
|
+
mediaType: source.mimeType ?? "application/octet-stream"
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
case "binary": {
|
|
138
|
+
const mimeType = part.mimeType ?? "application/octet-stream";
|
|
139
|
+
const isImage = mimeType.startsWith("image/");
|
|
140
|
+
const data = part.data ? part.data : part.url ? parseContentUrl(part.url, "binary") : null;
|
|
141
|
+
if (!data) break;
|
|
142
|
+
parts.push(isImage ? {
|
|
143
|
+
type: "image",
|
|
144
|
+
image: data,
|
|
145
|
+
mediaType: mimeType
|
|
146
|
+
} : {
|
|
147
|
+
type: "file",
|
|
148
|
+
data,
|
|
149
|
+
mediaType: mimeType
|
|
150
|
+
});
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
default: {
|
|
154
|
+
const unknownPart = part;
|
|
155
|
+
console.error(`[CopilotKit] convertUserMessageContent: unrecognized content part type "${unknownPart.type}", skipping`);
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return parts.length > 0 ? parts : "";
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Converts AG-UI messages to AI SDK `ModelMessage`s, for `streamText` calls in
|
|
164
|
+
* a `type: "aisdk"` factory.
|
|
165
|
+
*
|
|
166
|
+
* System and developer messages are dropped unless the matching option is on.
|
|
167
|
+
* Tool results keep their text and inline media.
|
|
168
|
+
*
|
|
169
|
+
* @param messages - The run's AG-UI messages, usually `ctx.input.messages`.
|
|
170
|
+
* @param options - Which system and developer messages to forward.
|
|
171
|
+
*
|
|
172
|
+
* ```ts
|
|
173
|
+
* streamText({ model, messages: convertMessagesToVercelAISDKMessages(ctx.input.messages) })
|
|
174
|
+
* ```
|
|
175
|
+
*/
|
|
176
|
+
function convertMessagesToVercelAISDKMessages(messages, options = {}) {
|
|
177
|
+
const result = [];
|
|
178
|
+
for (const message of messages) if (message.role === "system" && options.forwardSystemMessages) {
|
|
179
|
+
const systemMsg = {
|
|
180
|
+
role: "system",
|
|
181
|
+
content: message.content ?? ""
|
|
182
|
+
};
|
|
183
|
+
result.push(systemMsg);
|
|
184
|
+
} else if (message.role === "developer" && options.forwardDeveloperMessages) {
|
|
185
|
+
const systemMsg = {
|
|
186
|
+
role: "system",
|
|
187
|
+
content: message.content ?? ""
|
|
188
|
+
};
|
|
189
|
+
result.push(systemMsg);
|
|
190
|
+
} else if (message.role === "assistant") {
|
|
191
|
+
const parts = message.content ? [{
|
|
192
|
+
type: "text",
|
|
193
|
+
text: message.content
|
|
194
|
+
}] : [];
|
|
195
|
+
const toolCalls = message.toolCalls ?? [];
|
|
196
|
+
for (const toolCall of toolCalls) parts.push({
|
|
197
|
+
type: "tool-call",
|
|
198
|
+
toolCallId: toolCall.id,
|
|
199
|
+
toolName: toolCall.function.name,
|
|
200
|
+
input: (0, _copilotkit_shared.safeParseToolArgs)(toolCall.function.arguments),
|
|
201
|
+
...toolCall.encryptedValue ? { providerOptions: { google: { thoughtSignature: toolCall.encryptedValue } } } : {}
|
|
202
|
+
});
|
|
203
|
+
const assistantMsg = {
|
|
204
|
+
role: "assistant",
|
|
205
|
+
content: parts
|
|
206
|
+
};
|
|
207
|
+
result.push(assistantMsg);
|
|
208
|
+
} else if (message.role === "user") {
|
|
209
|
+
const userMsg = {
|
|
210
|
+
role: "user",
|
|
211
|
+
content: convertUserMessageContent(message.content)
|
|
212
|
+
};
|
|
213
|
+
result.push(userMsg);
|
|
214
|
+
} else if (message.role === "tool") {
|
|
215
|
+
const toolName = messages.flatMap((msg) => msg.role === "assistant" ? msg.toolCalls ?? [] : []).find((toolCall) => toolCall.id === message.toolCallId)?.function.name ?? "unknown";
|
|
216
|
+
const toolMsg = {
|
|
217
|
+
role: "tool",
|
|
218
|
+
content: [{
|
|
219
|
+
type: "tool-result",
|
|
220
|
+
toolCallId: message.toolCallId,
|
|
221
|
+
toolName,
|
|
222
|
+
output: toolResultOutput(message.content)
|
|
223
|
+
}]
|
|
224
|
+
};
|
|
225
|
+
result.push(toolMsg);
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Converts a JSON Schema to a Zod schema, for `type: "aisdk"` factories that
|
|
231
|
+
* need a Zod schema for an AG-UI tool.
|
|
232
|
+
*
|
|
233
|
+
* @param jsonSchema - The schema: objects, strings (with `enum`), numbers,
|
|
234
|
+
* integers, booleans, arrays, `null`, and `anyOf` / `oneOf` unions.
|
|
235
|
+
* @param required - When false, the result is `.optional()`.
|
|
236
|
+
* @throws Error for an array without `items` or a `type` it does not know.
|
|
237
|
+
*/
|
|
238
|
+
function convertJsonSchemaToZodSchema(jsonSchema, required) {
|
|
239
|
+
const describe = (schema) => jsonSchema.description ? schema.describe(jsonSchema.description) : schema;
|
|
240
|
+
if (jsonSchema.type === "null") {
|
|
241
|
+
const schema = describe(zod.z.null());
|
|
242
|
+
return required ? schema : schema.optional();
|
|
243
|
+
}
|
|
244
|
+
const unionVariants = jsonSchema.anyOf ?? jsonSchema.oneOf;
|
|
245
|
+
if (Array.isArray(unionVariants) && unionVariants.length > 0) {
|
|
246
|
+
if (unionVariants.length === 1) return convertJsonSchemaToZodSchema(unionVariants[0], required);
|
|
247
|
+
const variantSchemas = unionVariants.map((variant) => convertJsonSchemaToZodSchema(variant, true));
|
|
248
|
+
const schema = describe(zod.z.union(variantSchemas));
|
|
249
|
+
return required ? schema : schema.optional();
|
|
250
|
+
}
|
|
251
|
+
if (!jsonSchema.type) return required ? zod.z.object({}) : zod.z.object({}).optional();
|
|
252
|
+
if (jsonSchema.type === "object") {
|
|
253
|
+
const spec = {};
|
|
254
|
+
if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) return !required ? zod.z.object(spec).optional() : zod.z.object(spec);
|
|
255
|
+
const requiredKeys = new Set(jsonSchema.required ?? []);
|
|
256
|
+
for (const [key, value] of Object.entries(jsonSchema.properties)) spec[key] = convertJsonSchemaToZodSchema(value, requiredKeys.has(key));
|
|
257
|
+
const schema = describe(zod.z.object(spec));
|
|
258
|
+
return required ? schema : schema.optional();
|
|
259
|
+
} else if (jsonSchema.type === "string") {
|
|
260
|
+
if (jsonSchema.enum && jsonSchema.enum.length > 0) {
|
|
261
|
+
const schema = describe(zod.z.enum(jsonSchema.enum));
|
|
262
|
+
return required ? schema : schema.optional();
|
|
263
|
+
}
|
|
264
|
+
const schema = describe(zod.z.string());
|
|
265
|
+
return required ? schema : schema.optional();
|
|
266
|
+
} else if (jsonSchema.type === "number" || jsonSchema.type === "integer") {
|
|
267
|
+
const schema = describe(zod.z.number());
|
|
268
|
+
return required ? schema : schema.optional();
|
|
269
|
+
} else if (jsonSchema.type === "boolean") {
|
|
270
|
+
const schema = describe(zod.z.boolean());
|
|
271
|
+
return required ? schema : schema.optional();
|
|
272
|
+
} else if (jsonSchema.type === "array") {
|
|
273
|
+
if (!jsonSchema.items) throw new Error("Array type must have items property");
|
|
274
|
+
const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);
|
|
275
|
+
const schema = describe(zod.z.array(itemSchema));
|
|
276
|
+
return required ? schema : schema.optional();
|
|
277
|
+
}
|
|
278
|
+
console.error("Invalid JSON schema:", JSON.stringify(jsonSchema, null, 2));
|
|
279
|
+
throw new Error("Invalid JSON schema");
|
|
280
|
+
}
|
|
281
|
+
const JSON_SCHEMA_TYPES = [
|
|
282
|
+
"object",
|
|
283
|
+
"string",
|
|
284
|
+
"number",
|
|
285
|
+
"integer",
|
|
286
|
+
"boolean",
|
|
287
|
+
"array"
|
|
288
|
+
];
|
|
289
|
+
function isJsonSchema(obj) {
|
|
290
|
+
if (typeof obj !== "object" || obj === null) return false;
|
|
291
|
+
if (Object.keys(obj).length === 0) return true;
|
|
292
|
+
return "type" in obj && typeof obj.type === "string" && JSON_SCHEMA_TYPES.includes(obj.type);
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Converts AG-UI tools (the run's frontend tools, `ctx.input.tools`) to an AI
|
|
296
|
+
* SDK `ToolSet`, for `streamText` calls in a `type: "aisdk"` factory.
|
|
297
|
+
*
|
|
298
|
+
* The tools have no `execute`, so the AI SDK leaves their calls to the
|
|
299
|
+
* client. Their JSON Schema goes to the model unchanged, and the arguments
|
|
300
|
+
* are validated against it.
|
|
301
|
+
*
|
|
302
|
+
* @param tools - AG-UI tools whose `parameters` are JSON Schema objects.
|
|
303
|
+
* @throws Error when a tool's `parameters` is not a JSON Schema object.
|
|
304
|
+
*
|
|
305
|
+
* ```ts
|
|
306
|
+
* streamText({ model, tools: convertToolsToVercelAITools(ctx.input.tools) })
|
|
307
|
+
* ```
|
|
308
|
+
*/
|
|
309
|
+
function convertToolsToVercelAITools(tools) {
|
|
310
|
+
const result = {};
|
|
311
|
+
for (const tool of tools) {
|
|
312
|
+
if (!isJsonSchema(tool.parameters)) throw new Error(`Invalid JSON schema for tool ${tool.name}`);
|
|
313
|
+
const validator = new _cfworker_json_schema.Validator(tool.parameters, "7");
|
|
314
|
+
result[tool.name] = (0, ai.tool)({
|
|
315
|
+
description: tool.description,
|
|
316
|
+
inputSchema: (0, ai.jsonSchema)(tool.parameters, { validate: (value) => {
|
|
317
|
+
return validator.validate(value).valid ? {
|
|
318
|
+
success: true,
|
|
319
|
+
value
|
|
320
|
+
} : {
|
|
321
|
+
success: false,
|
|
322
|
+
error: /* @__PURE__ */ new Error(`Invalid arguments for tool ${tool.name}`)
|
|
323
|
+
};
|
|
324
|
+
} }),
|
|
325
|
+
...tool.name === _ag_ui_a2ui_middleware.RENDER_A2UI_TOOL.name ? { strict: false } : {}
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
return result;
|
|
329
|
+
}
|
|
330
|
+
/** Whether a TanStack `inputSchema` is a Standard Schema (Zod, Valibot, ArkType). */
|
|
331
|
+
function isStandardSchema(schema) {
|
|
332
|
+
return "~standard" in schema;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* The AI SDK input schema for a TanStack tool. No schema means no arguments.
|
|
336
|
+
* A Standard Schema also validates the input, so `execute` gets the parsed
|
|
337
|
+
* output (for example with Zod defaults applied), as in `chat()`.
|
|
338
|
+
*/
|
|
339
|
+
function toolInputSchema(name, schema) {
|
|
340
|
+
if (!schema) return (0, ai.jsonSchema)({
|
|
341
|
+
type: "object",
|
|
342
|
+
properties: {}
|
|
343
|
+
});
|
|
344
|
+
if (!isStandardSchema(schema)) return (0, ai.jsonSchema)(schema);
|
|
345
|
+
return (0, ai.jsonSchema)((0, _copilotkit_shared.schemaToJsonSchema)(schema), { validate: async (value) => {
|
|
346
|
+
const parsed = await schema["~standard"].validate(value);
|
|
347
|
+
if ("value" in parsed) return {
|
|
348
|
+
success: true,
|
|
349
|
+
value: parsed.value
|
|
350
|
+
};
|
|
351
|
+
const details = parsed.issues.map((issue) => issue.message).join("; ");
|
|
352
|
+
return {
|
|
353
|
+
success: false,
|
|
354
|
+
error: /* @__PURE__ */ new Error(`Invalid arguments for tool ${name}: ${details}`)
|
|
355
|
+
};
|
|
356
|
+
} });
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Converts TanStack AI tools to an AI SDK `ToolSet`, for `streamText` calls in
|
|
360
|
+
* a `type: "aisdk"` factory.
|
|
361
|
+
*
|
|
362
|
+
* - A tool with `execute` keeps it. The AI SDK runs it with the parsed input.
|
|
363
|
+
* - A tool without `execute` stays client-side: the AI SDK leaves its calls
|
|
364
|
+
* to the client.
|
|
365
|
+
* - `inputSchema` can be JSON Schema or a Standard Schema such as Zod.
|
|
366
|
+
*
|
|
367
|
+
* A typical use is the learned-skill tools of the run:
|
|
368
|
+
*
|
|
369
|
+
* ```ts
|
|
370
|
+
* import { streamText } from "ai";
|
|
371
|
+
* import { toAISDKTools } from "@copilotkit/runtime/agent/ai-sdk";
|
|
372
|
+
*
|
|
373
|
+
* factory: (ctx) =>
|
|
374
|
+
* streamText({
|
|
375
|
+
* model,
|
|
376
|
+
* system: ctx.learnedSkills.catalog,
|
|
377
|
+
* messages,
|
|
378
|
+
* tools: toAISDKTools(ctx.learnedSkills.tools),
|
|
379
|
+
* }),
|
|
380
|
+
* ```
|
|
381
|
+
*
|
|
382
|
+
* @param tools - TanStack server or client tools, as plain objects or from
|
|
383
|
+
* `toolDefinition()`.
|
|
384
|
+
* @throws Error when a Standard Schema cannot describe itself as JSON Schema.
|
|
385
|
+
*/
|
|
386
|
+
function toAISDKTools(tools) {
|
|
387
|
+
const result = {};
|
|
388
|
+
for (const tanstackTool of tools) {
|
|
389
|
+
const { execute } = tanstackTool;
|
|
390
|
+
result[tanstackTool.name] = (0, ai.tool)({
|
|
391
|
+
description: tanstackTool.description,
|
|
392
|
+
inputSchema: toolInputSchema(tanstackTool.name, tanstackTool.inputSchema),
|
|
393
|
+
...execute ? { execute: (input) => execute(input) } : {},
|
|
394
|
+
...tanstackTool.needsApproval ? { needsApproval: true } : {}
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
return result;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Converts tools made with `defineTool()` to an AI SDK `ToolSet`, for
|
|
401
|
+
* `streamText` calls in a `type: "aisdk"` factory.
|
|
402
|
+
*
|
|
403
|
+
* Each tool offers its JSON Schema to the model. Its `execute` validates the
|
|
404
|
+
* arguments with the tool's parameters schema and runs your `execute` with the
|
|
405
|
+
* parsed output. A tool without `execute` (an interrupt tool) stays
|
|
406
|
+
* client-side.
|
|
407
|
+
*
|
|
408
|
+
* @param tools - Tools from `defineTool()`.
|
|
409
|
+
*
|
|
410
|
+
* ```ts
|
|
411
|
+
* streamText({ model, tools: convertToolDefinitionsToVercelAITools([weatherTool]) })
|
|
412
|
+
* ```
|
|
413
|
+
*/
|
|
414
|
+
function convertToolDefinitionsToVercelAITools(tools) {
|
|
415
|
+
return toAISDKTools(tools);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
//#endregion
|
|
419
|
+
exports.convertJsonSchemaToZodSchema = convertJsonSchemaToZodSchema;
|
|
420
|
+
exports.convertMessagesToVercelAISDKMessages = convertMessagesToVercelAISDKMessages;
|
|
421
|
+
exports.convertToolDefinitionsToVercelAITools = convertToolDefinitionsToVercelAITools;
|
|
422
|
+
exports.convertToolsToVercelAITools = convertToolsToVercelAITools;
|
|
423
|
+
exports.createSafeUrlDownload = require_url_download.createSafeUrlDownload;
|
|
424
|
+
exports.toAISDKTools = toAISDKTools;
|
|
425
|
+
//# sourceMappingURL=ai-sdk.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ai-sdk.cjs","names":["z","Validator","RENDER_A2UI_TOOL"],"sources":["../../src/agent/ai-sdk/index.ts"],"sourcesContent":["/**\n * `@copilotkit/runtime/agent/ai-sdk`: helpers for `type: \"aisdk\"` factories.\n *\n * This is the only runtime entry that imports `ai` at module scope. An app\n * that imports it uses the AI SDK, so `ai` must be installed.\n */\nimport { RENDER_A2UI_TOOL } from \"@ag-ui/a2ui-middleware\";\nimport type {\n ContentPart,\n Message,\n RunAgentInput,\n ToolMessage,\n} from \"@ag-ui/client\";\nimport { Validator } from \"@cfworker/json-schema\";\nimport { safeParseToolArgs, schemaToJsonSchema } from \"@copilotkit/shared\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { AnyTool } from \"@tanstack/ai\";\nimport type {\n AssistantModelMessage,\n FilePart,\n ImagePart,\n ModelMessage,\n SystemModelMessage,\n TextPart,\n ToolCallPart,\n ToolModelMessage,\n ToolResultPart,\n ToolSet,\n UserModelMessage,\n} from \"ai\";\nimport { jsonSchema as aiJsonSchema, tool as createVercelAISDKTool } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolDefinition } from \"../index\";\n\nexport { createSafeUrlDownload } from \"./url-download\";\nexport type {\n CreateSafeUrlDownloadOptions,\n SafeUrlDownloadOptions,\n} from \"./url-download\";\n\n/**\n * A tool result or user part can name a provider file handle (`file` source).\n * It is neither bytes nor a URL, and the AI SDK cannot send it to the\n * provider, so the part is dropped with a warning.\n */\nfunction warnDroppedFileSource(what: string) {\n console.warn(\n `[CopilotKit] Dropping a ${what} that references a provider file handle: it is not a URL or inline data, so it cannot be sent to the model here.`,\n );\n}\n\n/**\n * The AI SDK output for an AG-UI tool message.\n *\n * A text-only result is one text output. A URL part becomes its URL as text.\n * A result with inline media is a content list: the text entry first, when\n * there is any, then each media part with its bytes and media type. A\n * media-only result is media alone. A result whose parts were all dropped is\n * the empty string, because AG-UI 1.0 requires every call to be answered.\n */\nfunction toolResultOutput(\n content: ToolMessage[\"content\"],\n): ToolResultPart[\"output\"] {\n if (typeof content === \"string\") return { type: \"text\", value: content };\n const segments: string[] = [];\n const media: Array<{ type: \"media\"; data: string; mediaType: string }> = [];\n let open = false; // whether the last segment is text still being appended to\n for (const part of content) {\n if (part.type === \"text\") {\n if (open) segments[segments.length - 1] += part.text;\n else segments.push(part.text);\n open = true;\n } else if (part.source.type === \"file\") {\n warnDroppedFileSource(`${part.type} part in a tool result`);\n } else if (part.source.type === \"url\") {\n segments.push(part.source.value);\n open = false;\n } else {\n media.push({\n type: \"media\",\n data: part.source.value,\n mediaType: part.source.mimeType,\n });\n open = false;\n }\n }\n const text = segments.join(\"\\n\");\n if (media.length === 0) return { type: \"text\", value: text };\n return {\n type: \"content\",\n value: [\n ...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n ...media,\n ],\n };\n}\n\ntype LegacyBinaryInputContent = {\n type: \"binary\";\n mimeType?: string;\n data?: string;\n url?: string;\n};\n\n/** A URL from the request, or `null` (logged) when it does not parse. */\nfunction parseContentUrl(value: string, what: string) {\n try {\n return new URL(value);\n } catch {\n console.error(\n `[CopilotKit] convertUserMessageContent: invalid URL \"${value}\" in ${what} part, skipping`,\n );\n return null;\n }\n}\n\n/**\n * Converts AG-UI user message content to AI SDK user content: plain strings,\n * modality parts (image, audio, video, document), and the legacy `binary`\n * part.\n */\nfunction convertUserMessageContent(\n content: string | Array<ContentPart | LegacyBinaryInputContent>,\n): string | Array<TextPart | ImagePart | FilePart> {\n if (!content) return \"\";\n if (typeof content === \"string\") return content;\n\n const parts: Array<TextPart | ImagePart | FilePart> = [];\n\n for (const part of content) {\n // The request body is not validated, so a part can be anything.\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) continue;\n\n switch (part.type) {\n case \"text\": {\n if (part.text) parts.push({ type: \"text\", text: part.text });\n break;\n }\n\n case \"image\": {\n const { source } = part;\n if (!source) break;\n if (source.type === \"data\") {\n parts.push({\n type: \"image\",\n image: source.value,\n mediaType: source.mimeType,\n });\n } else if (source.type === \"file\") {\n warnDroppedFileSource(\"image part\");\n } else {\n const url = parseContentUrl(source.value, \"image\");\n if (url) {\n parts.push({\n type: \"image\",\n image: url,\n mediaType: source.mimeType,\n });\n }\n }\n break;\n }\n\n case \"audio\":\n case \"video\":\n case \"document\": {\n const { source } = part;\n if (!source) break;\n if (source.type === \"data\") {\n parts.push({\n type: \"file\",\n data: source.value,\n mediaType: source.mimeType,\n });\n } else if (source.type === \"file\") {\n warnDroppedFileSource(`${part.type} part`);\n } else {\n const url = parseContentUrl(source.value, part.type);\n if (url) {\n parts.push({\n type: \"file\",\n data: url,\n mediaType: source.mimeType ?? \"application/octet-stream\",\n });\n }\n }\n break;\n }\n\n case \"binary\": {\n const mimeType = part.mimeType ?? \"application/octet-stream\";\n const isImage = mimeType.startsWith(\"image/\");\n const data = part.data\n ? part.data\n : part.url\n ? parseContentUrl(part.url, \"binary\")\n : null;\n if (!data) break;\n parts.push(\n isImage\n ? { type: \"image\", image: data, mediaType: mimeType }\n : { type: \"file\", data, mediaType: mimeType },\n );\n break;\n }\n\n default: {\n const unknownPart: { type: string } = part;\n console.error(\n `[CopilotKit] convertUserMessageContent: unrecognized content part type \"${unknownPart.type}\", skipping`,\n );\n break;\n }\n }\n }\n\n return parts.length > 0 ? parts : \"\";\n}\n\n/**\n * Options for {@link convertMessagesToVercelAISDKMessages}.\n */\nexport interface MessageConversionOptions {\n /** Send AG-UI `system` messages to the model as system messages. */\n forwardSystemMessages?: boolean;\n /** Send AG-UI `developer` messages to the model as system messages. */\n forwardDeveloperMessages?: boolean;\n}\n\n/**\n * Converts AG-UI messages to AI SDK `ModelMessage`s, for `streamText` calls in\n * a `type: \"aisdk\"` factory.\n *\n * System and developer messages are dropped unless the matching option is on.\n * Tool results keep their text and inline media.\n *\n * @param messages - The run's AG-UI messages, usually `ctx.input.messages`.\n * @param options - Which system and developer messages to forward.\n *\n * ```ts\n * streamText({ model, messages: convertMessagesToVercelAISDKMessages(ctx.input.messages) })\n * ```\n */\nexport function convertMessagesToVercelAISDKMessages(\n messages: Message[],\n options: MessageConversionOptions = {},\n) {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\" && options.forwardSystemMessages) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (\n message.role === \"developer\" &&\n options.forwardDeveloperMessages\n ) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content\n ? [{ type: \"text\", text: message.content }]\n : [];\n\n const toolCalls = message.toolCalls ?? [];\n for (const toolCall of toolCalls) {\n parts.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: safeParseToolArgs(toolCall.function.arguments),\n ...(toolCall.encryptedValue\n ? {\n providerOptions: {\n google: { thoughtSignature: toolCall.encryptedValue },\n },\n }\n : {}),\n });\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: convertUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n // The tool name comes from the assistant message that made the call.\n const toolName =\n messages\n .flatMap((msg) =>\n msg.role === \"assistant\" ? (msg.toolCalls ?? []) : [],\n )\n .find((toolCall) => toolCall.id === message.toolCallId)?.function\n .name ?? \"unknown\";\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [\n {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName,\n output: toolResultOutput(message.content),\n },\n ],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * The JSON Schema subset that {@link convertJsonSchemaToZodSchema} reads.\n */\ninterface JsonSchema {\n type?:\n | \"object\"\n | \"string\"\n | \"number\"\n | \"integer\"\n | \"boolean\"\n | \"array\"\n | \"null\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n enum?: string[];\n // Union combinators. A frontend tool authored with `z.discriminatedUnion`\n // (or any `z.union`) serializes to a node carrying `anyOf` / `oneOf` and\n // usually NO top-level `type`.\n anyOf?: JsonSchema[];\n oneOf?: JsonSchema[];\n}\n\n/**\n * Converts a JSON Schema to a Zod schema, for `type: \"aisdk\"` factories that\n * need a Zod schema for an AG-UI tool.\n *\n * @param jsonSchema - The schema: objects, strings (with `enum`), numbers,\n * integers, booleans, arrays, `null`, and `anyOf` / `oneOf` unions.\n * @param required - When false, the result is `.optional()`.\n * @throws Error for an array without `items` or a `type` it does not know.\n */\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: JsonSchema,\n required: boolean,\n): z.ZodSchema {\n // Zod 4 emits an empty `description` into JSON Schema; Zod 3's converters\n // dropped it. Only attach a description the JSON Schema actually had.\n const describe = <T extends z.ZodType>(schema: T): T =>\n jsonSchema.description ? schema.describe(jsonSchema.description) : schema;\n\n if (jsonSchema.type === \"null\") {\n const schema = describe(z.null());\n return required ? schema : schema.optional();\n }\n\n // Handle `anyOf` / `oneOf` unions (e.g. `z.discriminatedUnion` or `z.union`\n // on a frontend tool) as `z.union`. These nodes usually carry no top-level\n // `type`, so they MUST be handled before the empty-schema guard below.\n // Otherwise the union collapses to an empty object (`z.object({})`), the\n // reconstructed tool schema loses the union-typed field entirely, and the\n // model can never emit it. This is especially load-bearing for a union\n // nested inside array `items`, which OpenAI otherwise silently drops.\n const unionVariants = jsonSchema.anyOf ?? jsonSchema.oneOf;\n if (Array.isArray(unionVariants) && unionVariants.length > 0) {\n // A single-variant union is just that variant.\n if (unionVariants.length === 1) {\n return convertJsonSchemaToZodSchema(unionVariants[0], required);\n }\n const variantSchemas = unionVariants.map((variant) =>\n convertJsonSchemaToZodSchema(variant, true),\n );\n const schema = describe(\n z.union(variantSchemas as [z.ZodSchema, z.ZodSchema, ...z.ZodSchema[]]),\n );\n return required ? schema : schema.optional();\n }\n\n // Handle empty schemas {} (no input required) - treat as empty object\n if (!jsonSchema.type) {\n return required ? z.object({}) : z.object({}).optional();\n }\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n const requiredKeys = new Set(jsonSchema.required ?? []);\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, requiredKeys.has(key));\n }\n const schema = describe(z.object(spec));\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n const schema = describe(z.enum(jsonSchema.enum as [string, ...string[]]));\n return required ? schema : schema.optional();\n }\n const schema = describe(z.string());\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n const schema = describe(z.number());\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n const schema = describe(z.boolean());\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n const schema = describe(z.array(itemSchema));\n return required ? schema : schema.optional();\n }\n console.error(\"Invalid JSON schema:\", JSON.stringify(jsonSchema, null, 2));\n throw new Error(\"Invalid JSON schema\");\n}\n\nconst JSON_SCHEMA_TYPES = [\n \"object\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"array\",\n];\n\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n // Empty objects {} are valid JSON schemas (no input required)\n if (Object.keys(obj).length === 0) return true;\n return (\n \"type\" in obj &&\n typeof obj.type === \"string\" &&\n JSON_SCHEMA_TYPES.includes(obj.type)\n );\n}\n\n/**\n * Converts AG-UI tools (the run's frontend tools, `ctx.input.tools`) to an AI\n * SDK `ToolSet`, for `streamText` calls in a `type: \"aisdk\"` factory.\n *\n * The tools have no `execute`, so the AI SDK leaves their calls to the\n * client. Their JSON Schema goes to the model unchanged, and the arguments\n * are validated against it.\n *\n * @param tools - AG-UI tools whose `parameters` are JSON Schema objects.\n * @throws Error when a tool's `parameters` is not a JSON Schema object.\n *\n * ```ts\n * streamText({ model, tools: convertToolsToVercelAITools(ctx.input.tools) })\n * ```\n */\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]) {\n const result: ToolSet = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const validator = new Validator(tool.parameters, \"7\");\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n // AG-UI already supplies JSON Schema. A Zod round trip loses open object\n // fields (including A2UI components), references, and other constraints.\n inputSchema: aiJsonSchema(tool.parameters, {\n validate: (value) => {\n const validation = validator.validate(value);\n return validation.valid\n ? { success: true, value }\n : {\n success: false,\n error: new Error(`Invalid arguments for tool ${tool.name}`),\n };\n },\n }),\n // A2UI components require open objects. Other tools keep the provider's\n // existing strictness default instead of opting every tool out.\n ...(tool.name === RENDER_A2UI_TOOL.name ? { strict: false } : {}),\n });\n }\n\n return result;\n}\n\n/** Whether a TanStack `inputSchema` is a Standard Schema (Zod, Valibot, ArkType). */\nfunction isStandardSchema(\n schema: NonNullable<AnyTool[\"inputSchema\"]>,\n): schema is StandardSchemaV1 {\n return \"~standard\" in schema;\n}\n\n/**\n * The AI SDK input schema for a TanStack tool. No schema means no arguments.\n * A Standard Schema also validates the input, so `execute` gets the parsed\n * output (for example with Zod defaults applied), as in `chat()`.\n */\nfunction toolInputSchema(name: string, schema: AnyTool[\"inputSchema\"]) {\n if (!schema) return aiJsonSchema({ type: \"object\", properties: {} });\n if (!isStandardSchema(schema)) return aiJsonSchema(schema);\n return aiJsonSchema(schemaToJsonSchema(schema), {\n validate: async (value) => {\n const parsed = await schema[\"~standard\"].validate(value);\n if (\"value\" in parsed) return { success: true, value: parsed.value };\n const details = parsed.issues.map((issue) => issue.message).join(\"; \");\n return {\n success: false,\n error: new Error(`Invalid arguments for tool ${name}: ${details}`),\n };\n },\n });\n}\n\n/**\n * Converts TanStack AI tools to an AI SDK `ToolSet`, for `streamText` calls in\n * a `type: \"aisdk\"` factory.\n *\n * - A tool with `execute` keeps it. The AI SDK runs it with the parsed input.\n * - A tool without `execute` stays client-side: the AI SDK leaves its calls\n * to the client.\n * - `inputSchema` can be JSON Schema or a Standard Schema such as Zod.\n *\n * A typical use is the learned-skill tools of the run:\n *\n * ```ts\n * import { streamText } from \"ai\";\n * import { toAISDKTools } from \"@copilotkit/runtime/agent/ai-sdk\";\n *\n * factory: (ctx) =>\n * streamText({\n * model,\n * system: ctx.learnedSkills.catalog,\n * messages,\n * tools: toAISDKTools(ctx.learnedSkills.tools),\n * }),\n * ```\n *\n * @param tools - TanStack server or client tools, as plain objects or from\n * `toolDefinition()`.\n * @throws Error when a Standard Schema cannot describe itself as JSON Schema.\n */\nexport function toAISDKTools(tools: readonly AnyTool[]) {\n const result: ToolSet = {};\n\n for (const tanstackTool of tools) {\n const { execute } = tanstackTool;\n result[tanstackTool.name] = createVercelAISDKTool({\n description: tanstackTool.description,\n inputSchema: toolInputSchema(tanstackTool.name, tanstackTool.inputSchema),\n ...(execute ? { execute: (input: unknown) => execute(input) } : {}),\n ...(tanstackTool.needsApproval ? { needsApproval: true } : {}),\n });\n }\n\n return result;\n}\n\n/**\n * Converts tools made with `defineTool()` to an AI SDK `ToolSet`, for\n * `streamText` calls in a `type: \"aisdk\"` factory.\n *\n * Each tool offers its JSON Schema to the model. Its `execute` validates the\n * arguments with the tool's parameters schema and runs your `execute` with the\n * parsed output. A tool without `execute` (an interrupt tool) stays\n * client-side.\n *\n * @param tools - Tools from `defineTool()`.\n *\n * ```ts\n * streamText({ model, tools: convertToolDefinitionsToVercelAITools([weatherTool]) })\n * ```\n */\nexport function convertToolDefinitionsToVercelAITools(\n tools: readonly ToolDefinition[],\n) {\n return toAISDKTools(tools);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,sBAAsB,MAAc;AAC3C,SAAQ,KACN,2BAA2B,KAAK,kHACjC;;;;;;;;;;;AAYH,SAAS,iBACP,SAC0B;AAC1B,KAAI,OAAO,YAAY,SAAU,QAAO;EAAE,MAAM;EAAQ,OAAO;EAAS;CACxE,MAAM,WAAqB,EAAE;CAC7B,MAAM,QAAmE,EAAE;CAC3E,IAAI,OAAO;AACX,MAAK,MAAM,QAAQ,QACjB,KAAI,KAAK,SAAS,QAAQ;AACxB,MAAI,KAAM,UAAS,SAAS,SAAS,MAAM,KAAK;MAC3C,UAAS,KAAK,KAAK,KAAK;AAC7B,SAAO;YACE,KAAK,OAAO,SAAS,OAC9B,uBAAsB,GAAG,KAAK,KAAK,wBAAwB;U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