@copilotkit/runtime 2.0.0-rc.6 → 2.0.0-rc.61
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 +29 -4
- 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 +17 -4
- 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 +202 -30
- 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 +202 -29
- 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 +23 -28
- package/dist/index.d.cts +14 -14
- package/dist/index.d.mts +14 -14
- package/dist/index.mjs +8 -8
- package/dist/internal/learned-skills.d.cts +1 -1
- package/dist/internal/learned-skills.d.mts +1 -1
- package/dist/node.cjs +2 -3
- package/dist/node.d.cts +3 -3
- package/dist/node.d.mts +3 -3
- package/dist/node.mjs +3 -3
- 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-cors.cjs.map +1 -1
- package/dist/runtime/core/fetch-cors.d.cts +2 -2
- package/dist/runtime/core/fetch-cors.d.cts.map +1 -1
- package/dist/runtime/core/fetch-cors.d.mts +2 -2
- package/dist/runtime/core/fetch-cors.d.mts.map +1 -1
- package/dist/runtime/core/fetch-cors.mjs.map +1 -1
- package/dist/runtime/core/fetch-handler.cjs +17 -14
- package/dist/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/runtime/core/fetch-handler.d.cts +22 -14
- package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/runtime/core/fetch-handler.d.mts +22 -14
- package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/runtime/core/fetch-handler.mjs +9 -5
- package/dist/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/runtime/core/hooks.cjs.map +1 -1
- package/dist/runtime/core/hooks.d.cts +5 -5
- package/dist/runtime/core/hooks.d.cts.map +1 -1
- package/dist/runtime/core/hooks.d.mts +5 -5
- package/dist/runtime/core/hooks.d.mts.map +1 -1
- package/dist/runtime/core/hooks.mjs.map +1 -1
- package/dist/runtime/core/learning.cjs.map +1 -1
- package/dist/runtime/core/learning.d.cts +9 -9
- package/dist/runtime/core/learning.d.cts.map +1 -1
- package/dist/runtime/core/learning.d.mts +8 -8
- package/dist/runtime/core/learning.d.mts.map +1 -1
- package/dist/runtime/core/learning.mjs.map +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 +26 -9
- package/dist/runtime/core/logger.d.cts.map +1 -1
- package/dist/runtime/core/logger.d.mts +26 -9
- 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.d.cts +3 -3
- package/dist/runtime/core/middleware.d.cts.map +1 -1
- package/dist/runtime/core/middleware.d.mts +3 -3
- package/dist/runtime/core/middleware.d.mts.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-error-reporter.cjs.map +1 -1
- package/dist/runtime/core/runtime-error-reporter.mjs.map +1 -1
- package/dist/runtime/core/runtime.cjs +44 -46
- package/dist/runtime/core/runtime.cjs.map +1 -1
- package/dist/runtime/core/runtime.d.cts +178 -91
- package/dist/runtime/core/runtime.d.cts.map +1 -1
- package/dist/runtime/core/runtime.d.mts +178 -91
- package/dist/runtime/core/runtime.d.mts.map +1 -1
- package/dist/runtime/core/runtime.mjs +42 -42
- 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 +4 -8
- package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.cts +4 -5
- package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.mts +4 -5
- 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 +7 -5
- package/dist/runtime/endpoints/node.cjs.map +1 -1
- package/dist/runtime/endpoints/node.d.cts +16 -16
- package/dist/runtime/endpoints/node.d.cts.map +1 -1
- package/dist/runtime/endpoints/node.d.mts +16 -16
- package/dist/runtime/endpoints/node.d.mts.map +1 -1
- package/dist/runtime/endpoints/node.mjs +9 -7
- 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 +68 -0
- package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.d.cts +27 -0
- package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.d.mts +27 -0
- package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.mjs +68 -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/a2ui-v09-actions.cjs +106 -0
- package/dist/runtime/generative-ui/a2ui-v09-actions.cjs.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-actions.mjs +106 -0
- package/dist/runtime/generative-ui/a2ui-v09-actions.mjs.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs +422 -0
- package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs +422 -0
- package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs +84 -0
- package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts +41 -0
- package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts +41 -0
- package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs +83 -0
- package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-operations.cjs +694 -0
- package/dist/runtime/generative-ui/a2ui-v09-operations.cjs.map +1 -0
- package/dist/runtime/generative-ui/a2ui-v09-operations.mjs +694 -0
- package/dist/runtime/generative-ui/a2ui-v09-operations.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/index.d.cts +1 -0
- package/dist/runtime/generative-ui/index.d.mts +1 -0
- 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 +24 -6
- package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.mjs +25 -7
- 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-debug-events.cjs.map +1 -1
- package/dist/runtime/handlers/handle-debug-events.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-learning.mjs.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-inspector-metadata.mjs.map +1 -1
- package/dist/runtime/handlers/handle-run.cjs +11 -16
- package/dist/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/runtime/handlers/handle-run.mjs +8 -12
- 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-trajectory-connect.cjs.map +1 -1
- package/dist/runtime/handlers/handle-trajectory-connect.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/handle-transcribe.mjs.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 +5 -4
- 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 +28 -23
- package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/memories.mjs +12 -6
- 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 +40 -31
- package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.mjs +18 -8
- package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.cjs +50 -46
- package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.mjs +47 -42
- 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/memory-policy.cjs.map +1 -1
- package/dist/runtime/handlers/shared/memory-policy.mjs.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 +4 -3
- 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 +4 -3
- 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 +13 -18
- package/dist/runtime/index.d.mts +13 -18
- 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 +30 -4
- package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.cts +25 -2
- package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.mts +25 -2
- package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/client.mjs +30 -3
- 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 +2 -2
- package/dist/runtime/node.d.mts +2 -2
- 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/dist/v2/index.d.cts +242 -0
- package/dist/v2/index.d.mts +242 -0
- package/dist/v2/node.d.cts +18 -0
- package/dist/v2/node.d.mts +18 -0
- package/package.json +84 -29
- 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
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_logger = require('../../core/logger.cjs');
|
|
2
2
|
const require_json_response = require('../shared/json-response.cjs');
|
|
3
3
|
const require_agent_utils = require('../shared/agent-utils.cjs');
|
|
4
|
-
let _copilotkit_shared = require("@copilotkit/shared");
|
|
5
4
|
|
|
6
5
|
//#region src/runtime/handlers/intelligence/thread-names.ts
|
|
7
6
|
const THREAD_NAME_SYSTEM_PROMPT = [
|
|
@@ -23,6 +22,7 @@ const MAX_TRANSCRIPT_MESSAGES = 8;
|
|
|
23
22
|
const MAX_TITLE_GENERATION_ATTEMPTS = 3;
|
|
24
23
|
const FALLBACK_THREAD_TITLE = "Untitled";
|
|
25
24
|
async function generateThreadNameForNewThread({ runtime, request, agentId, sourceInput, thread, userId }) {
|
|
25
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
26
26
|
if (!runtime.generateThreadNames || hasThreadName(thread.name)) return;
|
|
27
27
|
const prompt = buildThreadTitlePrompt(sourceInput.messages);
|
|
28
28
|
if (!prompt) return;
|
|
@@ -36,13 +36,13 @@ async function generateThreadNameForNewThread({ runtime, request, agentId, sourc
|
|
|
36
36
|
prompt
|
|
37
37
|
});
|
|
38
38
|
if (generatedTitle) break;
|
|
39
|
-
|
|
39
|
+
logger.warn({
|
|
40
40
|
agentId,
|
|
41
41
|
attempt,
|
|
42
42
|
threadId: thread.id
|
|
43
43
|
}, "Thread name generation returned an empty or invalid title");
|
|
44
44
|
} catch (error) {
|
|
45
|
-
|
|
45
|
+
logger.warn({
|
|
46
46
|
err: error,
|
|
47
47
|
agentId,
|
|
48
48
|
attempt,
|
|
@@ -58,9 +58,10 @@ async function generateThreadNameForNewThread({ runtime, request, agentId, sourc
|
|
|
58
58
|
}
|
|
59
59
|
async function runTitleGenerationAttempt(params) {
|
|
60
60
|
const { runtime, request, agentId, threadId, prompt } = params;
|
|
61
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
61
62
|
const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId, request);
|
|
62
63
|
if (require_json_response.isHandlerResponse(agent)) {
|
|
63
|
-
|
|
64
|
+
logger.warn({
|
|
64
65
|
agentId,
|
|
65
66
|
threadId
|
|
66
67
|
}, "Skipping thread naming because the agent could not be cloned");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-names.cjs","names":["cloneAgentForRequest","isHandlerResponse"],"sources":["../../../../src/runtime/handlers/intelligence/thread-names.ts"],"sourcesContent":["import type { Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkit/shared\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport type { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: {\n name:\n generatedTitle ?? deriveFallbackTitleFromMessages(sourceInput.messages),\n },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: globalThis.crypto.randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: globalThis.crypto.randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = globalThis.crypto.randomUUID();\n // Messages and state are picked up from the agent itself (set above);\n // RunAgentParameters no longer accepts them directly.\n const { newMessages } = await agent.runAgent({\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n return selectGeneratedTitleFromMessages(newMessages);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Conversation:\",\n transcript.join(\"\\n\"),\n 'Generate a short title for the conversation above. Return JSON only in this exact shape: {\"title\":\"...\"}. Do not answer the conversation.',\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n const jsonLike = isJsonLike(candidate);\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n } else if (jsonLike) {\n return null;\n }\n } catch {\n if (jsonLike) {\n return null;\n }\n }\n\n candidate = cleanupTitleText(candidate);\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction cleanupTitleText(text: string): string {\n return text\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction deriveFallbackTitleFromMessages(\n messages: Message[] | undefined,\n): string {\n for (const message of messages ?? []) {\n if (message.role !== \"user\") {\n continue;\n }\n\n const cleaned = cleanupTitleText(stringifyMessageContent(message.content));\n if (!cleaned) {\n continue;\n }\n\n let title = cleaned.split(/\\s+/).slice(0, MAX_TITLE_WORDS).join(\" \");\n if (title.length > MAX_TITLE_LENGTH) {\n title = title.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n return title || FALLBACK_THREAD_TITLE;\n }\n\n return FALLBACK_THREAD_TITLE;\n}\n\nfunction selectGeneratedTitleFromMessages(messages: Message[]): string | null {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message.role !== \"assistant\" || typeof message.content !== \"string\") {\n continue;\n }\n\n const title = normalizeGeneratedTitle(message.content);\n if (title) {\n return title;\n }\n }\n\n return null;\n}\n\nfunction isJsonLike(candidate: string): boolean {\n return (\n (candidate.startsWith(\"{\") && candidate.endsWith(\"}\")) ||\n (candidate.startsWith(\"[\") && candidate.endsWith(\"]\"))\n );\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵselectGeneratedTitleFromMessages =\n selectGeneratedTitleFromMessages;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"mappings":";;;;;;AAUA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;AAC1C,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3D,KAAI,CAAC,OACH;CAGF,IAAI,iBAAgC;AAEpC,MAAK,IAAI,UAAU,GAAG,WAAW,+BAA+B,UAC9D,KAAI;AACF,mBAAiB,MAAM,0BAA0B;GAC/C;GACA;GACA;GACA,UAAU,OAAO;GACjB;GACD,CAAC;AAEF,MAAI,eACF;AAGF,4BAAO,KACL;GAAE;GAAS;GAAS,UAAU,OAAO;GAAI,EACzC,4DACD;UACM,OAAO;AACd,4BAAO,KACL;GAAE,KAAK;GAAO;GAAS;GAAS,UAAU,OAAO;GAAI,EACrD,wCACD;;AAIL,OAAM,QAAQ,aAAa,aAAa;EACtC,UAAU,OAAO;EACjB;EACA;EACA,SAAS,EACP,MACE,kBAAkB,gCAAgC,YAAY,SAAS,EAC1E;EACF,CAAC;;AAGJ,eAAe,0BAA0B,QAMd;CACzB,MAAM,EAAE,SAAS,SAAS,SAAS,UAAU,WAAW;CACxD,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAIC,wCAAkB,MAAM,EAAE;AAC5B,4BAAO,KACL;GAAE;GAAS;GAAU,EACrB,+DACD;AACD,SAAO;;AAGT,8CAAyB;EACvB;EACA;EACA;EACA;EACD,CAAC;CAEF,MAAM,WAAsB,C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,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
|
|
1
|
+
{"version":3,"file":"thread-names.cjs","names":["getRuntimeLogger","cloneAgentForRequest","isHandlerResponse"],"sources":["../../../../src/runtime/handlers/intelligence/thread-names.ts"],"sourcesContent":["import type { Message, RunAgentInput } from \"@ag-ui/client\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport type { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotKitIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n const logger = getRuntimeLogger(runtime);\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: {\n name:\n generatedTitle ?? deriveFallbackTitleFromMessages(sourceInput.messages),\n },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotKitIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const logger = getRuntimeLogger(runtime);\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: globalThis.crypto.randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: globalThis.crypto.randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = globalThis.crypto.randomUUID();\n // Messages and state are picked up from the agent itself (set above);\n // RunAgentParameters no longer accepts them directly.\n const { newMessages } = await agent.runAgent({\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n return selectGeneratedTitleFromMessages(newMessages);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Conversation:\",\n transcript.join(\"\\n\"),\n 'Generate a short title for the conversation above. Return JSON only in this exact shape: {\"title\":\"...\"}. Do not answer the conversation.',\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n const jsonLike = isJsonLike(candidate);\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n } else if (jsonLike) {\n return null;\n }\n } catch {\n if (jsonLike) {\n return null;\n }\n }\n\n candidate = cleanupTitleText(candidate);\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction cleanupTitleText(text: string): string {\n return text\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction deriveFallbackTitleFromMessages(\n messages: Message[] | undefined,\n): string {\n for (const message of messages ?? []) {\n if (message.role !== \"user\") {\n continue;\n }\n\n const cleaned = cleanupTitleText(stringifyMessageContent(message.content));\n if (!cleaned) {\n continue;\n }\n\n let title = cleaned.split(/\\s+/).slice(0, MAX_TITLE_WORDS).join(\" \");\n if (title.length > MAX_TITLE_LENGTH) {\n title = title.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n return title || FALLBACK_THREAD_TITLE;\n }\n\n return FALLBACK_THREAD_TITLE;\n}\n\nfunction selectGeneratedTitleFromMessages(messages: Message[]): string | null {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message.role !== \"assistant\" || typeof message.content !== \"string\") {\n continue;\n }\n\n const title = normalizeGeneratedTitle(message.content);\n if (title) {\n return title;\n }\n }\n\n return null;\n}\n\nfunction isJsonLike(candidate: string): boolean {\n return (\n (candidate.startsWith(\"{\") && candidate.endsWith(\"}\")) ||\n (candidate.startsWith(\"[\") && candidate.endsWith(\"]\"))\n );\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵselectGeneratedTitleFromMessages =\n selectGeneratedTitleFromMessages;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"mappings":";;;;;AAUA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;CAC1C,MAAM,SAASA,gCAAiB,QAAQ;AACxC,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3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I,CACpB,MAAM;;AAGX,SAAS,gCACP,UACQ;AACR,MAAK,MAAM,WAAW,YAAY,EAAE,EAAE;AACpC,MAAI,QAAQ,SAAS,OACnB;EAGF,MAAM,UAAU,iBAAiB,wBAAwB,QAAQ,QAAQ,CAAC;AAC1E,MAAI,CAAC,QACH;EAGF,IAAI,QAAQ,QAAQ,MAAM,MAAM,CAAC,MAAM,GAAG,gBAAgB,CAAC,KAAK,IAAI;AACpE,MAAI,MAAM,SAAS,iBACjB,SAAQ,MAAM,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGjD,SAAO,SAAS;;AAGlB,QAAO;;AAGT,SAAS,iCAAiC,UAAoC;AAC5E,MAAK,IAAI,QAAQ,SAAS,SAAS,GAAG,SAAS,GAAG,SAAS;EACzD,MAAM,UAAU,SAAS;AACzB,MAAI,QAAQ,SAAS,eAAe,OAAO,QAAQ,YAAY,SAC7D;EAGF,MAAM,QAAQ,wBAAwB,QAAQ,QAAQ;AACtD,MAAI,MACF,QAAO;;AAIX,QAAO;;AAGT,SAAS,WAAW,WAA4B;AAC9C,QACG,UAAU,WAAW,IAAI,IAAI,UAAU,SAAS,IAAI,IACpD,UAAU,WAAW,IAAI,IAAI,UAAU,SAAS,IAAI;;AAIzD,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { getRuntimeLogger } from "../../core/logger.mjs";
|
|
1
2
|
import { isHandlerResponse } from "../shared/json-response.mjs";
|
|
2
3
|
import { cloneAgentForRequest, configureAgentForRequest } from "../shared/agent-utils.mjs";
|
|
3
|
-
import { logger } from "@copilotkit/shared";
|
|
4
4
|
|
|
5
5
|
//#region src/runtime/handlers/intelligence/thread-names.ts
|
|
6
6
|
const THREAD_NAME_SYSTEM_PROMPT = [
|
|
@@ -22,6 +22,7 @@ const MAX_TRANSCRIPT_MESSAGES = 8;
|
|
|
22
22
|
const MAX_TITLE_GENERATION_ATTEMPTS = 3;
|
|
23
23
|
const FALLBACK_THREAD_TITLE = "Untitled";
|
|
24
24
|
async function generateThreadNameForNewThread({ runtime, request, agentId, sourceInput, thread, userId }) {
|
|
25
|
+
const logger = getRuntimeLogger(runtime);
|
|
25
26
|
if (!runtime.generateThreadNames || hasThreadName(thread.name)) return;
|
|
26
27
|
const prompt = buildThreadTitlePrompt(sourceInput.messages);
|
|
27
28
|
if (!prompt) return;
|
|
@@ -57,6 +58,7 @@ async function generateThreadNameForNewThread({ runtime, request, agentId, sourc
|
|
|
57
58
|
}
|
|
58
59
|
async function runTitleGenerationAttempt(params) {
|
|
59
60
|
const { runtime, request, agentId, threadId, prompt } = params;
|
|
61
|
+
const logger = getRuntimeLogger(runtime);
|
|
60
62
|
const agent = await cloneAgentForRequest(runtime, agentId, request);
|
|
61
63
|
if (isHandlerResponse(agent)) {
|
|
62
64
|
logger.warn({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-names.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/thread-names.ts"],"sourcesContent":["import type { Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkit/shared\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport type { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: {\n name:\n generatedTitle ?? deriveFallbackTitleFromMessages(sourceInput.messages),\n },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: globalThis.crypto.randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: globalThis.crypto.randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = globalThis.crypto.randomUUID();\n // Messages and state are picked up from the agent itself (set above);\n // RunAgentParameters no longer accepts them directly.\n const { newMessages } = await agent.runAgent({\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n return selectGeneratedTitleFromMessages(newMessages);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Conversation:\",\n transcript.join(\"\\n\"),\n 'Generate a short title for the conversation above. Return JSON only in this exact shape: {\"title\":\"...\"}. Do not answer the conversation.',\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n const jsonLike = isJsonLike(candidate);\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n } else if (jsonLike) {\n return null;\n }\n } catch {\n if (jsonLike) {\n return null;\n }\n }\n\n candidate = cleanupTitleText(candidate);\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction cleanupTitleText(text: string): string {\n return text\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction deriveFallbackTitleFromMessages(\n messages: Message[] | undefined,\n): string {\n for (const message of messages ?? []) {\n if (message.role !== \"user\") {\n continue;\n }\n\n const cleaned = cleanupTitleText(stringifyMessageContent(message.content));\n if (!cleaned) {\n continue;\n }\n\n let title = cleaned.split(/\\s+/).slice(0, MAX_TITLE_WORDS).join(\" \");\n if (title.length > MAX_TITLE_LENGTH) {\n title = title.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n return title || FALLBACK_THREAD_TITLE;\n }\n\n return FALLBACK_THREAD_TITLE;\n}\n\nfunction selectGeneratedTitleFromMessages(messages: Message[]): string | null {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message.role !== \"assistant\" || typeof message.content !== \"string\") {\n continue;\n }\n\n const title = normalizeGeneratedTitle(message.content);\n if (title) {\n return title;\n }\n }\n\n return null;\n}\n\nfunction isJsonLike(candidate: string): boolean {\n return (\n (candidate.startsWith(\"{\") && candidate.endsWith(\"}\")) ||\n (candidate.startsWith(\"[\") && candidate.endsWith(\"]\"))\n );\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵselectGeneratedTitleFromMessages =\n selectGeneratedTitleFromMessages;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only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|
+
{"version":3,"file":"thread-names.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/thread-names.ts"],"sourcesContent":["import type { Message, RunAgentInput } from \"@ag-ui/client\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport type { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotKitIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n const logger = getRuntimeLogger(runtime);\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: {\n name:\n generatedTitle ?? deriveFallbackTitleFromMessages(sourceInput.messages),\n },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotKitIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const logger = getRuntimeLogger(runtime);\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: globalThis.crypto.randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: globalThis.crypto.randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = globalThis.crypto.randomUUID();\n // Messages and state are picked up from the agent itself (set above);\n // RunAgentParameters no longer accepts them directly.\n const { newMessages } = await agent.runAgent({\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n return selectGeneratedTitleFromMessages(newMessages);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Conversation:\",\n transcript.join(\"\\n\"),\n 'Generate a short title for the conversation above. Return JSON only in this exact shape: {\"title\":\"...\"}. Do not answer the conversation.',\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n const jsonLike = isJsonLike(candidate);\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n } else if (jsonLike) {\n return null;\n }\n } catch {\n if (jsonLike) {\n return null;\n }\n }\n\n candidate = cleanupTitleText(candidate);\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction cleanupTitleText(text: string): string {\n return text\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction deriveFallbackTitleFromMessages(\n messages: Message[] | undefined,\n): string {\n for (const message of messages ?? []) {\n if (message.role !== \"user\") {\n continue;\n }\n\n const cleaned = cleanupTitleText(stringifyMessageContent(message.content));\n if (!cleaned) {\n continue;\n }\n\n let title = cleaned.split(/\\s+/).slice(0, MAX_TITLE_WORDS).join(\" \");\n if (title.length > MAX_TITLE_LENGTH) {\n title = title.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n return title || FALLBACK_THREAD_TITLE;\n }\n\n return FALLBACK_THREAD_TITLE;\n}\n\nfunction selectGeneratedTitleFromMessages(messages: Message[]): string | null {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message.role !== \"assistant\" || typeof message.content !== \"string\") {\n continue;\n }\n\n const title = normalizeGeneratedTitle(message.content);\n if (title) {\n return title;\n }\n }\n\n return null;\n}\n\nfunction isJsonLike(candidate: string): boolean {\n return (\n (candidate.startsWith(\"{\") && candidate.endsWith(\"}\")) ||\n (candidate.startsWith(\"[\") && candidate.endsWith(\"]\"))\n );\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵselectGeneratedTitleFromMessages =\n selectGeneratedTitleFromMessages;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"mappings":";;;;;AAUA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;CAC1C,MAAM,SAAS,iBAAiB,QAAQ;AACxC,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3D,KAAI,CAAC,OACH;CAGF,IAAI,iBAAgC;AAEpC,MAAK,IAAI,UAAU,GAAG,WAAW,+BAA+B,UAC9D,KA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,SAAS,OACnB;EAGF,MAAM,UAAU,iBAAiB,wBAAwB,QAAQ,QAAQ,CAAC;AAC1E,MAAI,CAAC,QACH;EAGF,IAAI,QAAQ,QAAQ,MAAM,MAAM,CAAC,MAAM,GAAG,gBAAgB,CAAC,KAAK,IAAI;AACpE,MAAI,MAAM,SAAS,iBACjB,SAAQ,MAAM,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGjD,SAAO,SAAS;;AAGlB,QAAO;;AAGT,SAAS,iCAAiC,UAAoC;AAC5E,MAAK,IAAI,QAAQ,SAAS,SAAS,GAAG,SAAS,GAAG,SAAS;EACzD,MAAM,UAAU,SAAS;AACzB,MAAI,QAAQ,SAAS,eAAe,OAAO,QAAQ,YAAY,SAC7D;EAGF,MAAM,QAAQ,wBAAwB,QAAQ,QAAQ;AACtD,MAAI,MACF,QAAO;;AAIX,QAAO;;AAGT,SAAS,WAAW,WAA4B;AAC9C,QACG,UAAU,WAAW,IAAI,IAAI,UAAU,SAAS,IAAI,IACpD,UAAU,WAAW,IAAI,IAAI,UAAU,SAAS,IAAI;;AAIzD,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
|
|
@@ -1,28 +1,27 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_logger = require('../../core/logger.cjs');
|
|
2
2
|
const require_agent_runner = require('../../runner/agent-runner.cjs');
|
|
3
3
|
const require_json_response = require('../shared/json-response.cjs');
|
|
4
4
|
const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
|
|
5
5
|
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
6
6
|
const require_thread_access = require('../shared/thread-access.cjs');
|
|
7
|
-
const require_runtime
|
|
7
|
+
const require_runtime = require('../../core/runtime.cjs');
|
|
8
8
|
const require_platform_error = require('../shared/platform-error.cjs');
|
|
9
|
-
let _copilotkit_shared = require("@copilotkit/shared");
|
|
10
9
|
|
|
11
10
|
//#region src/runtime/handlers/intelligence/threads.ts
|
|
12
|
-
async function parseJsonBody(request) {
|
|
11
|
+
async function parseJsonBody(request, logger) {
|
|
13
12
|
try {
|
|
14
13
|
return await request.json();
|
|
15
14
|
} catch (error) {
|
|
16
|
-
|
|
15
|
+
logger.error({ err: error }, "Malformed JSON in request body");
|
|
17
16
|
return require_json_response.errorResponse("Invalid request body", 400);
|
|
18
17
|
}
|
|
19
18
|
}
|
|
20
19
|
function requireIntelligenceRuntime(runtime) {
|
|
21
|
-
if (!require_runtime
|
|
20
|
+
if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.", 422);
|
|
22
21
|
return runtime;
|
|
23
22
|
}
|
|
24
23
|
async function resolveThreadMutationContext(runtime, request) {
|
|
25
|
-
const body = await parseJsonBody(request);
|
|
24
|
+
const body = await parseJsonBody(request, require_logger.getRuntimeLogger(runtime));
|
|
26
25
|
if (require_json_response.isHandlerResponse(body)) return body;
|
|
27
26
|
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
28
27
|
runtime,
|
|
@@ -49,6 +48,7 @@ async function resolveThreadMutationContext(runtime, request) {
|
|
|
49
48
|
* for anything else (logged as an error).
|
|
50
49
|
*/
|
|
51
50
|
async function requireUserThread(runtime, threadId, userId, failure) {
|
|
51
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
52
52
|
let thread;
|
|
53
53
|
try {
|
|
54
54
|
thread = await runtime.intelligence.getThread({
|
|
@@ -57,24 +57,25 @@ async function requireUserThread(runtime, threadId, userId, failure) {
|
|
|
57
57
|
});
|
|
58
58
|
} catch (error) {
|
|
59
59
|
const status = require_intelligence_utils.getPlatformErrorStatus(error);
|
|
60
|
-
if (status !== void 0 && status >= 400 && status < 500 && status !== 401)
|
|
60
|
+
if (status !== void 0 && status >= 400 && status < 500 && status !== 401) logger.warn({
|
|
61
61
|
threadId,
|
|
62
62
|
status
|
|
63
63
|
}, "Thread not visible to the user");
|
|
64
|
-
else
|
|
64
|
+
else logger.error({
|
|
65
65
|
err: error,
|
|
66
66
|
threadId
|
|
67
67
|
}, "Error resolving thread");
|
|
68
68
|
return require_platform_error.platformErrorResponse(error, failure);
|
|
69
69
|
}
|
|
70
70
|
if (!thread || typeof thread.id !== "string" || !thread.id.trim()) {
|
|
71
|
-
|
|
71
|
+
logger.error({ threadId }, "Invalid thread response from getThread");
|
|
72
72
|
return require_json_response.errorResponse("Invalid thread response", 502);
|
|
73
73
|
}
|
|
74
74
|
return { threadId: thread.id };
|
|
75
75
|
}
|
|
76
76
|
async function handleListThreads({ runtime, request }) {
|
|
77
|
-
|
|
77
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
78
|
+
if (require_runtime.isIntelligenceRuntime(runtime)) try {
|
|
78
79
|
const url = new URL(request.url);
|
|
79
80
|
const agentId = url.searchParams.get("agentId");
|
|
80
81
|
const includeArchived = url.searchParams.get("includeArchived") === "true";
|
|
@@ -95,7 +96,7 @@ async function handleListThreads({ runtime, request }) {
|
|
|
95
96
|
});
|
|
96
97
|
return Response.json(data);
|
|
97
98
|
} catch (error) {
|
|
98
|
-
|
|
99
|
+
logger.error({ err: error }, "Error listing threads");
|
|
99
100
|
return require_json_response.errorResponse("Failed to list threads", 500);
|
|
100
101
|
}
|
|
101
102
|
if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
|
|
@@ -114,11 +115,11 @@ async function handleListThreads({ runtime, request }) {
|
|
|
114
115
|
nextCursor: null
|
|
115
116
|
});
|
|
116
117
|
} catch (error) {
|
|
117
|
-
|
|
118
|
+
logger.error({ err: error }, "Error listing threads");
|
|
118
119
|
return require_json_response.errorResponse("Failed to list threads", 500);
|
|
119
120
|
}
|
|
120
121
|
}
|
|
121
|
-
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in
|
|
122
|
+
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.", 422);
|
|
122
123
|
}
|
|
123
124
|
/**
|
|
124
125
|
* Clears the caller's in-memory thread history for the local-dev fallback.
|
|
@@ -133,6 +134,7 @@ async function handleListThreads({ runtime, request }) {
|
|
|
133
134
|
* client-side page load.
|
|
134
135
|
*/
|
|
135
136
|
async function handleClearThreads({ runtime, request }) {
|
|
137
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
136
138
|
if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
|
|
137
139
|
const ownerId = await require_thread_access.resolveLocalThreadOwner({
|
|
138
140
|
runtime,
|
|
@@ -143,13 +145,14 @@ async function handleClearThreads({ runtime, request }) {
|
|
|
143
145
|
try {
|
|
144
146
|
runtime.runner.clearThreads({ ownerId });
|
|
145
147
|
} catch (error) {
|
|
146
|
-
|
|
148
|
+
logger.error({ err: error }, "Error clearing threads");
|
|
147
149
|
return require_json_response.errorResponse("Failed to clear threads", 500);
|
|
148
150
|
}
|
|
149
151
|
}
|
|
150
152
|
return new Response(null, { status: 204 });
|
|
151
153
|
}
|
|
152
154
|
async function handleUpdateThread({ runtime, request, threadId }) {
|
|
155
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
153
156
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
154
157
|
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
155
158
|
try {
|
|
@@ -165,7 +168,7 @@ async function handleUpdateThread({ runtime, request, threadId }) {
|
|
|
165
168
|
});
|
|
166
169
|
return Response.json(thread);
|
|
167
170
|
} catch (error) {
|
|
168
|
-
|
|
171
|
+
logger.error({
|
|
169
172
|
err: error,
|
|
170
173
|
threadId
|
|
171
174
|
}, "Error updating thread");
|
|
@@ -173,6 +176,7 @@ async function handleUpdateThread({ runtime, request, threadId }) {
|
|
|
173
176
|
}
|
|
174
177
|
}
|
|
175
178
|
async function handleSubscribeToThreads({ runtime, request }) {
|
|
179
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
176
180
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
177
181
|
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
178
182
|
try {
|
|
@@ -184,11 +188,12 @@ async function handleSubscribeToThreads({ runtime, request }) {
|
|
|
184
188
|
const credentials = await intelligenceRuntime.intelligence.ɵsubscribeToThreads({ userId: user.id });
|
|
185
189
|
return Response.json({ joinToken: credentials.joinToken });
|
|
186
190
|
} catch (error) {
|
|
187
|
-
|
|
191
|
+
logger.error({ err: error }, "Error subscribing to threads");
|
|
188
192
|
return require_json_response.errorResponse("Failed to subscribe to threads", 500);
|
|
189
193
|
}
|
|
190
194
|
}
|
|
191
195
|
async function handleArchiveThread({ runtime, request, threadId }) {
|
|
196
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
192
197
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
193
198
|
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
194
199
|
try {
|
|
@@ -204,7 +209,7 @@ async function handleArchiveThread({ runtime, request, threadId }) {
|
|
|
204
209
|
archived: true
|
|
205
210
|
});
|
|
206
211
|
} catch (error) {
|
|
207
|
-
|
|
212
|
+
logger.error({
|
|
208
213
|
err: error,
|
|
209
214
|
threadId
|
|
210
215
|
}, "Error archiving thread");
|
|
@@ -212,6 +217,7 @@ async function handleArchiveThread({ runtime, request, threadId }) {
|
|
|
212
217
|
}
|
|
213
218
|
}
|
|
214
219
|
async function handleDeleteThread({ runtime, request, threadId }) {
|
|
220
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
215
221
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
216
222
|
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
217
223
|
try {
|
|
@@ -227,7 +233,7 @@ async function handleDeleteThread({ runtime, request, threadId }) {
|
|
|
227
233
|
deleted: true
|
|
228
234
|
});
|
|
229
235
|
} catch (error) {
|
|
230
|
-
|
|
236
|
+
logger.error({
|
|
231
237
|
err: error,
|
|
232
238
|
threadId
|
|
233
239
|
}, "Error deleting thread");
|
|
@@ -235,7 +241,8 @@ async function handleDeleteThread({ runtime, request, threadId }) {
|
|
|
235
241
|
}
|
|
236
242
|
}
|
|
237
243
|
async function handleGetThreadMessages({ runtime, request, threadId }) {
|
|
238
|
-
|
|
244
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
245
|
+
if (require_runtime.isIntelligenceRuntime(runtime)) try {
|
|
239
246
|
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
240
247
|
runtime,
|
|
241
248
|
request
|
|
@@ -247,7 +254,7 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
|
|
|
247
254
|
});
|
|
248
255
|
return Response.json(data);
|
|
249
256
|
} catch (error) {
|
|
250
|
-
|
|
257
|
+
logger.error({
|
|
251
258
|
err: error,
|
|
252
259
|
threadId
|
|
253
260
|
}, "Error fetching thread messages");
|
|
@@ -264,7 +271,7 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
|
|
|
264
271
|
try {
|
|
265
272
|
messages = runtime.runner.getThreadMessages(threadId, { ownerId });
|
|
266
273
|
} catch (error) {
|
|
267
|
-
|
|
274
|
+
logger.error({
|
|
268
275
|
err: error,
|
|
269
276
|
threadId
|
|
270
277
|
}, "Error fetching thread messages");
|
|
@@ -300,10 +307,11 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
|
|
|
300
307
|
});
|
|
301
308
|
return Response.json({ messages: mapped });
|
|
302
309
|
}
|
|
303
|
-
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in
|
|
310
|
+
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.", 422);
|
|
304
311
|
}
|
|
305
312
|
async function handleGetThreadEvents({ runtime, request, threadId }) {
|
|
306
|
-
|
|
313
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
314
|
+
if (require_runtime.isIntelligenceRuntime(runtime)) try {
|
|
307
315
|
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
308
316
|
runtime,
|
|
309
317
|
request
|
|
@@ -317,7 +325,7 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
|
|
|
317
325
|
});
|
|
318
326
|
return Response.json({ events: data.events });
|
|
319
327
|
} catch (error) {
|
|
320
|
-
|
|
328
|
+
logger.error({
|
|
321
329
|
err: error,
|
|
322
330
|
threadId
|
|
323
331
|
}, "Error fetching thread events");
|
|
@@ -334,17 +342,18 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
|
|
|
334
342
|
const events = runtime.runner.getThreadEvents(threadId, { ownerId });
|
|
335
343
|
return Response.json({ events });
|
|
336
344
|
} catch (error) {
|
|
337
|
-
|
|
345
|
+
logger.error({
|
|
338
346
|
err: error,
|
|
339
347
|
threadId
|
|
340
348
|
}, "Error fetching thread events");
|
|
341
349
|
return require_json_response.errorResponse("Failed to fetch thread events", 500);
|
|
342
350
|
}
|
|
343
351
|
}
|
|
344
|
-
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in
|
|
352
|
+
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.", 422);
|
|
345
353
|
}
|
|
346
354
|
async function handleGetThreadState({ runtime, request, threadId }) {
|
|
347
|
-
|
|
355
|
+
const logger = require_logger.getRuntimeLogger(runtime);
|
|
356
|
+
if (require_runtime.isIntelligenceRuntime(runtime)) try {
|
|
348
357
|
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
349
358
|
runtime,
|
|
350
359
|
request
|
|
@@ -359,7 +368,7 @@ async function handleGetThreadState({ runtime, request, threadId }) {
|
|
|
359
368
|
const state = data.kind === "snapshot" ? data.state : null;
|
|
360
369
|
return Response.json({ state });
|
|
361
370
|
} catch (error) {
|
|
362
|
-
|
|
371
|
+
logger.error({
|
|
363
372
|
err: error,
|
|
364
373
|
threadId
|
|
365
374
|
}, "Error fetching thread state");
|
|
@@ -376,14 +385,14 @@ async function handleGetThreadState({ runtime, request, threadId }) {
|
|
|
376
385
|
const state = runtime.runner.getThreadState(threadId, { ownerId });
|
|
377
386
|
return Response.json({ state });
|
|
378
387
|
} catch (error) {
|
|
379
|
-
|
|
388
|
+
logger.error({
|
|
380
389
|
err: error,
|
|
381
390
|
threadId
|
|
382
391
|
}, "Error fetching thread state");
|
|
383
392
|
return require_json_response.errorResponse("Failed to fetch thread state", 500);
|
|
384
393
|
}
|
|
385
394
|
}
|
|
386
|
-
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in
|
|
395
|
+
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.", 422);
|
|
387
396
|
}
|
|
388
397
|
|
|
389
398
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","getPlatformErrorStatus","platformErrorResponse","supportsLocalThreadEndpoints","resolveLocalThreadOwner"],"sources":["../../../../src/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;;AA+BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD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CAAE,QAAO;EACpC,MAAM,SAAS,MAAM,kBACnB,SACA,UACA,KAAK,IACL,+BACD;AACD,MAAIA,wCAAkB,OAAO,CAAE,QAAO;EAEtC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe;GACrD,UAAU,OAAO;GACjB,QAAQ,KAAK;GACd,CAAC;EAMF,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOI,6CAAsB,OAAO,+BAA+B;;AAIvE,KAAIC,kDAA6B,QAAQ,OAAO,EAAE;EAChD,MAAM,UAAU,MAAMC,8CAAwB;GAC5C;GACA;GACA,WAAW;GACZ,CAAC;AACF,MAAIN,wCAAkB,QAAQ,CAAE,QAAO;AACvC,MAAI;GACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,UAAU,EAAE,SAAS,CAAC;AAClE,UAAO,SAAS,KAAK,EAAE,OAAO,CAAC;WACxB,OAAO;AACd,6BAAO,MAAM;IAAE,KAAK;IAAO;IAAU,EAAE,8BAA8B;AACrE,UAAOF,oCAAc,gCAAgC,IAAI;;;AAI7D,QAAOA,oCACL,uJACA,IACD"}
|
|
1
|
+
{"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","getRuntimeLogger","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","getPlatformErrorStatus","platformErrorResponse","supportsLocalThreadEndpoints","resolveLocalThreadOwner"],"sources":["../../../../src/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotKitIntelligenceRuntimeLike,\n CopilotKitRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLogger } from \"../../core/logger\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n logger: CopilotKitRuntimeLogger,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotKitRuntimeLike,\n): CopilotKitIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotKitIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request, getRuntimeLogger(runtime));\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotKitIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n const logger = getRuntimeLogger(runtime);\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n case \"activity\":\n case \"developer\":\n case \"reasoning\":\n case \"system\":\n case \"user\":\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotKitRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AAgCA,eAAe,cACb,SACA,QAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC8C;AAC9C,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAOD,oCACL,0JACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,SAASE,gCAAiB,QAAQ,CAAC;AACpE,KAAIC,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAACE,6CAAkB,QAAQ,CAC7B,QAAOL,oCAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;;;;;;;;;;;;AAcH,eAAe,kBACb,SACA,UACA,QACA,SAC0C;CAC1C,MAAM,SAASE,gCAAiB,QAAQ;CACxC,IAAI;AACJ,KAAI;AACF,WAAS,MAAM,QAAQ,aAAa,UAAU;GAAE;GAAU;GAAQ,CAAC;UAC5D,OAAO;EACd,MAAM,SAASI,kDAAuB,MAAM;AAC5C,MACE,WAAW,UACX,UAAU,OACV,SAAS,OACT,WAAW,IAEX,QAAO,KAA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