@copilotkit/runtime 2.0.0-rc.4 → 2.0.0-rc.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -3
- package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -76
- package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
- package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
- package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
- package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
- package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
- package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
- package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
- package/dist/agent/ai-sdk.cjs +425 -0
- package/dist/agent/ai-sdk.cjs.map +1 -0
- package/dist/agent/ai-sdk.d.cts +119 -0
- package/dist/agent/ai-sdk.d.cts.map +1 -0
- package/dist/agent/ai-sdk.d.mts +119 -0
- package/dist/agent/ai-sdk.d.mts.map +1 -0
- package/dist/agent/ai-sdk.mjs +419 -0
- package/dist/agent/ai-sdk.mjs.map +1 -0
- package/dist/agent/classic-tools.cjs +185 -0
- package/dist/agent/classic-tools.cjs.map +1 -0
- package/dist/agent/classic-tools.mjs +183 -0
- package/dist/agent/classic-tools.mjs.map +1 -0
- package/dist/agent/converters/aisdk.cjs +16 -3
- package/dist/agent/converters/aisdk.cjs.map +1 -1
- package/dist/agent/converters/aisdk.d.cts.map +1 -1
- package/dist/agent/converters/aisdk.d.mts.map +1 -1
- package/dist/agent/converters/aisdk.mjs +18 -2
- package/dist/agent/converters/aisdk.mjs.map +1 -1
- package/dist/agent/converters/tanstack.cjs +201 -29
- package/dist/agent/converters/tanstack.cjs.map +1 -1
- package/dist/agent/converters/tanstack.d.cts +90 -6
- package/dist/agent/converters/tanstack.d.cts.map +1 -1
- package/dist/agent/converters/tanstack.d.mts +90 -6
- package/dist/agent/converters/tanstack.d.mts.map +1 -1
- package/dist/agent/converters/tanstack.mjs +201 -28
- package/dist/agent/converters/tanstack.mjs.map +1 -1
- package/dist/agent/learned-skills.cjs +15 -17
- package/dist/agent/learned-skills.cjs.map +1 -1
- package/dist/agent/learned-skills.d.cts +9 -3
- package/dist/agent/learned-skills.d.cts.map +1 -1
- package/dist/agent/learned-skills.d.mts +9 -3
- package/dist/agent/learned-skills.d.mts.map +1 -1
- package/dist/agent/learned-skills.mjs +15 -16
- package/dist/agent/learned-skills.mjs.map +1 -1
- package/dist/agent/model.cjs +42 -0
- package/dist/agent/model.cjs.map +1 -0
- package/dist/agent/model.d.cts +19 -0
- package/dist/agent/model.d.cts.map +1 -0
- package/dist/agent/model.d.mts +19 -0
- package/dist/agent/model.d.mts.map +1 -0
- package/dist/agent/model.mjs +41 -0
- package/dist/agent/model.mjs.map +1 -0
- package/dist/agent/state-delta.cjs +0 -1
- package/dist/agent/state-delta.cjs.map +1 -1
- package/dist/agent.cjs +558 -0
- package/dist/agent.cjs.map +1 -0
- package/dist/agent.d.cts +455 -0
- package/dist/agent.d.cts.map +1 -0
- package/dist/agent.d.mts +455 -0
- package/dist/agent.d.mts.map +1 -0
- package/dist/agent.mjs +551 -0
- package/dist/agent.mjs.map +1 -0
- package/dist/index.cjs +21 -27
- package/dist/index.d.cts +10 -11
- package/dist/index.d.mts +10 -11
- package/dist/index.mjs +5 -6
- package/dist/internal/learned-skills.d.cts +1 -1
- package/dist/internal/learned-skills.d.mts +1 -1
- package/dist/node.cjs +1 -2
- package/dist/node.d.cts +2 -2
- package/dist/node.d.mts +2 -2
- package/dist/node.mjs +2 -2
- package/dist/runtime/core/channel-manager.cjs +10 -2
- package/dist/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/runtime/core/channel-manager.d.cts +1 -1
- package/dist/runtime/core/channel-manager.d.mts +1 -1
- package/dist/runtime/core/channel-manager.mjs +10 -1
- package/dist/runtime/core/channel-manager.mjs.map +1 -1
- package/dist/runtime/core/debug-event-bus.cjs +4 -3
- package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
- package/dist/runtime/core/debug-event-bus.d.cts +5 -1
- package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
- package/dist/runtime/core/debug-event-bus.d.mts +4 -0
- package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
- package/dist/runtime/core/debug-event-bus.mjs +5 -3
- package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
- package/dist/runtime/core/fetch-handler.cjs +15 -12
- package/dist/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/runtime/core/fetch-handler.d.cts +8 -0
- package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/runtime/core/fetch-handler.d.mts +8 -0
- package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/runtime/core/fetch-handler.mjs +7 -3
- package/dist/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/runtime/core/learning.d.cts +1 -1
- package/dist/runtime/core/logger.cjs +105 -14
- package/dist/runtime/core/logger.cjs.map +1 -1
- package/dist/runtime/core/logger.d.cts +25 -8
- package/dist/runtime/core/logger.d.cts.map +1 -1
- package/dist/runtime/core/logger.d.mts +25 -8
- package/dist/runtime/core/logger.d.mts.map +1 -1
- package/dist/runtime/core/logger.mjs +105 -12
- package/dist/runtime/core/logger.mjs.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.cjs +3 -4
- package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
- package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
- package/dist/runtime/core/middleware.cjs +5 -5
- package/dist/runtime/core/middleware.cjs.map +1 -1
- package/dist/runtime/core/middleware.mjs +4 -3
- package/dist/runtime/core/middleware.mjs.map +1 -1
- package/dist/runtime/core/package-info.cjs +1 -1
- package/dist/runtime/core/package-info.mjs +1 -1
- package/dist/runtime/core/runtime.cjs +11 -10
- package/dist/runtime/core/runtime.cjs.map +1 -1
- package/dist/runtime/core/runtime.d.cts +22 -4
- package/dist/runtime/core/runtime.d.cts.map +1 -1
- package/dist/runtime/core/runtime.d.mts +22 -4
- package/dist/runtime/core/runtime.d.mts.map +1 -1
- package/dist/runtime/core/runtime.mjs +11 -9
- package/dist/runtime/core/runtime.mjs.map +1 -1
- package/dist/runtime/endpoints/auto-start-channels.cjs +3 -4
- package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
- package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
- package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.cjs +3 -7
- package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.cts +3 -4
- package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.mts +3 -4
- package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.mjs +3 -5
- package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
- package/dist/runtime/endpoints/node.cjs +4 -2
- package/dist/runtime/endpoints/node.cjs.map +1 -1
- package/dist/runtime/endpoints/node.d.cts.map +1 -1
- package/dist/runtime/endpoints/node.d.mts.map +1 -1
- package/dist/runtime/endpoints/node.mjs +4 -2
- package/dist/runtime/endpoints/node.mjs.map +1 -1
- package/dist/runtime/event-transforms/index.d.cts +4 -0
- package/dist/runtime/event-transforms/index.d.mts +4 -0
- package/dist/runtime/event-transforms/index.mjs +5 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
- package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.cjs +58 -0
- package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.d.cts +23 -0
- package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.d.mts +23 -0
- package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
- package/dist/runtime/event-transforms/recorded-events.mjs +58 -0
- package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
- package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
- package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
- package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
- package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
- package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
- package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
- package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.cjs +5 -1
- package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.mjs +5 -1
- package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/runtime/handlers/handle-connect.cjs +3 -8
- package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
- package/dist/runtime/handlers/handle-connect.mjs +3 -8
- package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
- package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
- package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
- package/dist/runtime/handlers/handle-run.cjs +11 -14
- package/dist/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/runtime/handlers/handle-run.mjs +8 -10
- package/dist/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/runtime/handlers/handle-stop.cjs +5 -5
- package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
- package/dist/runtime/handlers/handle-stop.mjs +2 -1
- package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
- package/dist/runtime/handlers/handle-suggest.cjs +6 -3
- package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
- package/dist/runtime/handlers/handle-suggest.mjs +6 -2
- package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
- package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
- package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/annotate.cjs +8 -8
- package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/annotate.mjs +4 -3
- package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
- package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
- package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/memories.cjs +27 -22
- package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/memories.mjs +11 -5
- package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/run.cjs +38 -30
- package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/run.mjs +37 -28
- package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -5
- package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
- package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.cjs +36 -27
- package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.mjs +13 -3
- package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.cjs +35 -34
- package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.mjs +29 -27
- package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
- package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +4 -3
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +4 -3
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
- package/dist/runtime/handlers/shared/sse-response.cjs +77 -78
- package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/runtime/handlers/shared/sse-response.mjs +77 -77
- package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.cjs +3 -2
- package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.mjs +3 -2
- package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
- package/dist/runtime/handlers/sse/connect.cjs +2 -0
- package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
- package/dist/runtime/handlers/sse/connect.mjs +2 -0
- package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
- package/dist/runtime/handlers/sse/run.cjs +5 -2
- package/dist/runtime/handlers/sse/run.cjs.map +1 -1
- package/dist/runtime/handlers/sse/run.mjs +5 -2
- package/dist/runtime/handlers/sse/run.mjs.map +1 -1
- package/dist/runtime/index.d.cts +9 -15
- package/dist/runtime/index.d.mts +9 -15
- package/dist/runtime/intelligence-platform/analytics-context.cjs +84 -0
- package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/analytics-context.mjs +83 -0
- package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/client.cjs +27 -1
- package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.cts +24 -1
- package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.mts +24 -1
- package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/client.mjs +27 -0
- package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
- package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
- package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
- package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
- package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
- package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
- package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +22 -19
- package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
- package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +22 -19
- package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/stop-run.cjs +50 -0
- package/dist/runtime/intelligence-platform/stop-run.cjs.map +1 -0
- package/dist/runtime/intelligence-platform/stop-run.mjs +50 -0
- package/dist/runtime/intelligence-platform/stop-run.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -3
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
- package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
- package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
- package/dist/runtime/node.d.cts +1 -1
- package/dist/runtime/node.d.mts +1 -1
- package/dist/runtime/runner/agent-runner.cjs +0 -1
- package/dist/runtime/runner/agent-runner.cjs.map +1 -1
- package/dist/runtime/runner/agent-runner.d.cts +9 -0
- package/dist/runtime/runner/agent-runner.d.cts.map +1 -1
- package/dist/runtime/runner/agent-runner.d.mts +9 -0
- package/dist/runtime/runner/agent-runner.d.mts.map +1 -1
- package/dist/runtime/runner/agent-runner.mjs.map +1 -1
- package/dist/runtime/runner/in-memory.cjs +0 -1
- package/dist/runtime/runner/in-memory.cjs.map +1 -1
- package/dist/runtime/runner/index.d.cts +1 -1
- package/dist/runtime/runner/index.d.mts +1 -1
- package/dist/runtime/runner/index.mjs +1 -1
- package/dist/runtime/runner/intelligence.cjs +55 -9
- package/dist/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/runtime/runner/intelligence.d.cts +12 -1
- package/dist/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/runtime/runner/intelligence.d.mts +12 -1
- package/dist/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/runtime/runner/intelligence.mjs +56 -10
- package/dist/runtime/runner/intelligence.mjs.map +1 -1
- package/dist/runtime/telemetry/disclosure.cjs +2 -3
- package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
- package/dist/runtime/telemetry/disclosure.mjs +3 -3
- package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
- package/dist/runtime/telemetry/events.d.cts +1 -1
- package/dist/runtime/telemetry/events.d.mts +1 -1
- package/dist/runtime/telemetry/instance-created.cjs +33 -12
- package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
- package/dist/runtime/telemetry/instance-created.mjs +33 -12
- package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-client.cjs +0 -5
- package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-client.mjs +0 -4
- package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
- package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
- package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
- package/package.json +55 -30
- package/dist/_virtual/_rolldown/runtime.cjs +0 -29
- package/dist/agent/converters/index.d.mts +0 -2
- package/dist/agent/index.cjs +0 -1328
- package/dist/agent/index.cjs.map +0 -1
- package/dist/agent/index.d.cts +0 -467
- package/dist/agent/index.d.cts.map +0 -1
- package/dist/agent/index.d.mts +0 -468
- package/dist/agent/index.d.mts.map +0 -1
- package/dist/agent/index.mjs +0 -1318
- package/dist/agent/index.mjs.map +0 -1
- package/dist/agent/mcp-tool-names.cjs +0 -82
- package/dist/agent/mcp-tool-names.cjs.map +0 -1
- package/dist/agent/mcp-tool-names.mjs +0 -80
- package/dist/agent/mcp-tool-names.mjs.map +0 -1
- package/dist/agent/url-download.cjs.map +0 -1
- package/dist/agent/url-download.d.cts.map +0 -1
- package/dist/agent/url-download.d.mts.map +0 -1
- package/dist/agent/url-download.mjs.map +0 -1
- package/dist/runtime/index.d.cts.map +0 -1
- package/dist/runtime/index.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-runner.d.mts","names":[],"sources":["../../../src/runtime/runner/agent-runner.ts"],"mappings":";;;;;;AAeA;;;;cAAa,yBAAA,SAAkC,KAAA;EAAA,SACpC,IAAA;;;;cASE,+BAAA;;;;;AAcb;;;;;;;;cAAa,uBAAA,SAAgC,KAAA;EAAA,SAClC,IAAA;;;;iBASK,yBAAA,CAA0B,KAAA;AAkB1C;;;;;AAGA;;;;;AAIA;AAPA,cAAa,oBAAA;;iBAGG,mBAAA,CAAoB,OAAA;AAAA,UAInB,qBAAA;EACf,QAAA;
|
|
1
|
+
{"version":3,"file":"agent-runner.d.mts","names":[],"sources":["../../../src/runtime/runner/agent-runner.ts"],"mappings":";;;;;;AAeA;;;;cAAa,yBAAA,SAAkC,KAAA;EAAA,SACpC,IAAA;;;;cASE,+BAAA;;;;;AAcb;;;;;;;;cAAa,uBAAA,SAAgC,KAAA;EAAA,SAClC,IAAA;;;;iBASK,yBAAA,CAA0B,KAAA;AAkB1C;;;;;AA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,wBAAA,aACI,OAAA;AAAA;;;;;;iBAQC,uBAAA,CACd,MAAA,EAAQ,WAAA,GACP,MAAA,IAAU,qBAAA;AAAA,uBAIS,WAAA;EAAA,SACX,6BAAA;EA1CP;EA6CF,kBAAA,CAAA,CACE,QAAA,UACA,KAAA,EAAO,wBAAA,aACI,OAAA;EAAA,SAEJ,GAAA,CAAI,OAAA,EAAS,qBAAA,GAAwB,UAAA,CAAW,SAAA;EAAA,SAChD,OAAA,CAAQ,OAAA,EAAS,yBAAA,GAA4B,UAAA,CAAW,SAAA;EAAA,SACxD,SAAA,CAAU,OAAA,EAAS,2BAAA,GAA8B,OAAA;EAAA,SACjD,IAAA,CAAK,OAAA,EAAS,sBAAA,GAAyB,OAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-runner.mjs","names":[],"sources":["../../../src/runtime/runner/agent-runner.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\n\n/**\n * Thrown by a runner when the thread already has a run in flight. The SSE\n * handler sends it to the client as a `RUN_ERROR` with\n * {@link THREAD_ALREADY_RUNNING_ERROR_CODE}, matched on `code` so a copy of\n * this class from another package version still counts.\n */\nexport class ThreadAlreadyRunningError extends Error {\n readonly code = THREAD_ALREADY_RUNNING_ERROR_CODE;\n\n constructor() {\n super(\"Thread already running\");\n this.name = \"ThreadAlreadyRunningError\";\n }\n}\n\n/** `code` of {@link ThreadAccessDeniedError}, also sent on the SSE `RUN_ERROR`. */\nexport const THREAD_ACCESS_DENIED_ERROR_CODE = \"THREAD_ACCESS_DENIED\";\n\n/**\n * Thrown by a runner when a run targets a Thread that another identity owns.\n *\n * Defense in depth: the run handler checks `isThreadAccessible` first and\n * refuses with an HTTP error, so the runner throws this only when another\n * identity claims the Thread between that check and the run, or for direct\n * runner callers. A synchronous throw from `run()` is still mapped to the\n * HTTP error; a later one reaches the client as a `RUN_ERROR` with\n * {@link THREAD_ACCESS_DENIED_ERROR_CODE}. Neither is reported as an agent\n * failure. Matched on `code`, so a copy of this class from another package\n * version still counts.\n */\nexport class ThreadAccessDeniedError extends Error {\n readonly code = THREAD_ACCESS_DENIED_ERROR_CODE;\n\n constructor() {\n super(\"Thread access denied\");\n this.name = \"ThreadAccessDeniedError\";\n }\n}\n\n/** True for a {@link ThreadAccessDeniedError}, from any package version. */\nexport function isThreadAccessDeniedError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error as { code?: unknown }).code === THREAD_ACCESS_DENIED_ERROR_CODE\n );\n}\n\n/**\n * Owner of a Thread created, or reached, by a runner call that names no owner:\n * a run, connect, stop or isRunning without `ownerId`, or a Thread endpoint call\n * without a scope. Such calls come only from trusted server-side code (for\n * example a Channel listener), and they act as this one server identity.\n *\n * No HTTP caller can act as it: request identities are `\"\"` (anonymous) or an\n * id that `identifyUser` returned, and a valid id cannot hold a NUL character.\n * So an omitted owner never means \"every Thread\", and a Thread created\n * server-side is never reachable by an anonymous caller.\n */\nexport const ɵSERVER_THREAD_OWNER = \"\\u0000server\";\n\n/** The owner a runner call acts as: `ownerId`, or the server owner when omitted. */\nexport function ɵresolveThreadOwner(ownerId: string | undefined): string {\n return ownerId ?? ɵSERVER_THREAD_OWNER;\n}\n\nexport interface AgentRunnerRunRequest {\n threadId: string;\n /** Backend execution ID supplied by Intelligence for imported non-UUID sessions. */\n backendThreadId?: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n persistedInputMessages?: Message[];\n /** Short-lived token scoped to this runner invocation. */\n authToken?: string;\n /**\n * Identity the run acts as. A runner that tracks owners records it on the\n * Thread's first run and refuses a run from any other identity. `\"\"` is the\n * anonymous owner. When omitted, the run acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerConnectRequest {\n threadId: string;\n agentId?: string;\n headers?: Record<string, string>;\n joinCode?: string;\n /**\n * Caller identity. A Thread owned by another identity is treated as unknown.\n * When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerIsRunningRequest {\n threadId: string;\n /**\n * Caller identity. A Thread owned by another identity reports \"not running\".\n * When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerStopRequest {\n threadId: string;\n /** When present, stop only this exact run and never a newer run on the Thread. */\n runId?: string;\n /**\n * Caller identity. A run on a Thread owned by another identity is not\n * stopped. When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface LocalThreadEndpointRecord {\n id: string;\n name: string | null;\n agentId: string;\n organizationId: string;\n createdById: string;\n archived: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Limits a local Thread endpoint call to the Threads of one owner. `\"\"` is the\n * anonymous owner. A call without a scope acts as\n * {@link ɵSERVER_THREAD_OWNER}: it sees only Threads created server-side, never\n * every Thread.\n */\nexport interface LocalThreadEndpointScope {\n ownerId: string;\n}\n\nexport interface LocalThreadEndpointRunner extends AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints: true;\n listThreads(scope?: LocalThreadEndpointScope): LocalThreadEndpointRecord[];\n getThreadMessages(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Message[];\n getThreadEvents(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): BaseEvent[];\n getThreadState(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Record<string, unknown> | null;\n clearThreads(scope?: LocalThreadEndpointScope): void;\n /** See {@link ThreadOwnershipRunner.isThreadAccessible}. */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean;\n}\n\nexport function supportsLocalThreadEndpoints(\n runner: AgentRunner,\n): runner is LocalThreadEndpointRunner {\n return runner.ɵsupportsLocalThreadEndpoints === true;\n}\n\n/**\n * A runner that records each Thread's owner and enforces it. Implementing\n * `isThreadAccessible` is the promise that `run`, `connect`, `stop` and\n * `isRunning` honor `ownerId` the same way: a call never reaches a Thread that\n * another owner holds.\n */\nexport interface ThreadOwnershipRunner extends AgentRunner {\n /** False when the Thread id is held by an owner other than `scope`'s. */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean | Promise<boolean>;\n}\n\n/**\n * True when `runner` enforces Thread owners. Checks the method itself, so a\n * runner built against an older interface (one that sets the endpoint flag\n * but has no `isThreadAccessible`) is not taken to enforce them.\n */\nexport function enforcesThreadOwnership(\n runner: AgentRunner,\n): runner is ThreadOwnershipRunner {\n return typeof runner.isThreadAccessible === \"function\";\n}\n\nexport abstract class AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints?: boolean;\n\n /** See {@link ThreadOwnershipRunner}. Optional: not every runner tracks owners. */\n isThreadAccessible?(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean | Promise<boolean>;\n\n abstract run(request: AgentRunnerRunRequest): Observable<BaseEvent>;\n abstract connect(request: AgentRunnerConnectRequest): Observable<BaseEvent>;\n abstract isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean>;\n abstract stop(request: AgentRunnerStopRequest): Promise<boolean | undefined>;\n}\n"],"mappings":";;;;;;;;;AAeA,IAAa,4BAAb,cAA+C,MAAM;CAGnD,cAAc;AACZ,QAAM,yBAAyB;cAHjB;AAId,OAAK,OAAO;;;;AAKhB,MAAa,kCAAkC;;;;;;;;;;;;;AAc/C,IAAa,0BAAb,cAA6C,MAAM;CAGjD,cAAc;AACZ,QAAM,uBAAuB;cAHf;AAId,OAAK,OAAO;;;;AAKhB,SAAgB,0BAA0B,OAAyB;AACjE,QACE,iBAAiB,SAChB,MAA6B,SAAS;;;;;;;;;;;;;AAe3C,MAAa,uBAAuB;;AAGpC,SAAgB,oBAAoB,SAAqC;AACvE,QAAO,WAAW;;
|
|
1
|
+
{"version":3,"file":"agent-runner.mjs","names":[],"sources":["../../../src/runtime/runner/agent-runner.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\n\n/**\n * Thrown by a runner when the thread already has a run in flight. The SSE\n * handler sends it to the client as a `RUN_ERROR` with\n * {@link THREAD_ALREADY_RUNNING_ERROR_CODE}, matched on `code` so a copy of\n * this class from another package version still counts.\n */\nexport class ThreadAlreadyRunningError extends Error {\n readonly code = THREAD_ALREADY_RUNNING_ERROR_CODE;\n\n constructor() {\n super(\"Thread already running\");\n this.name = \"ThreadAlreadyRunningError\";\n }\n}\n\n/** `code` of {@link ThreadAccessDeniedError}, also sent on the SSE `RUN_ERROR`. */\nexport const THREAD_ACCESS_DENIED_ERROR_CODE = \"THREAD_ACCESS_DENIED\";\n\n/**\n * Thrown by a runner when a run targets a Thread that another identity owns.\n *\n * Defense in depth: the run handler checks `isThreadAccessible` first and\n * refuses with an HTTP error, so the runner throws this only when another\n * identity claims the Thread between that check and the run, or for direct\n * runner callers. A synchronous throw from `run()` is still mapped to the\n * HTTP error; a later one reaches the client as a `RUN_ERROR` with\n * {@link THREAD_ACCESS_DENIED_ERROR_CODE}. Neither is reported as an agent\n * failure. Matched on `code`, so a copy of this class from another package\n * version still counts.\n */\nexport class ThreadAccessDeniedError extends Error {\n readonly code = THREAD_ACCESS_DENIED_ERROR_CODE;\n\n constructor() {\n super(\"Thread access denied\");\n this.name = \"ThreadAccessDeniedError\";\n }\n}\n\n/** True for a {@link ThreadAccessDeniedError}, from any package version. */\nexport function isThreadAccessDeniedError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error as { code?: unknown }).code === THREAD_ACCESS_DENIED_ERROR_CODE\n );\n}\n\n/**\n * Owner of a Thread created, or reached, by a runner call that names no owner:\n * a run, connect, stop or isRunning without `ownerId`, or a Thread endpoint call\n * without a scope. Such calls come only from trusted server-side code (for\n * example a Channel listener), and they act as this one server identity.\n *\n * No HTTP caller can act as it: request identities are `\"\"` (anonymous) or an\n * id that `identifyUser` returned, and a valid id cannot hold a NUL character.\n * So an omitted owner never means \"every Thread\", and a Thread created\n * server-side is never reachable by an anonymous caller.\n */\nexport const ɵSERVER_THREAD_OWNER = \"\\u0000server\";\n\n/** The owner a runner call acts as: `ownerId`, or the server owner when omitted. */\nexport function ɵresolveThreadOwner(ownerId: string | undefined): string {\n return ownerId ?? ɵSERVER_THREAD_OWNER;\n}\n\nexport interface AgentRunnerRunRequest {\n threadId: string;\n /** Backend execution ID supplied by Intelligence for imported non-UUID sessions. */\n backendThreadId?: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n persistedInputMessages?: Message[];\n /** Short-lived token scoped to this runner invocation. */\n authToken?: string;\n /**\n * Identity the run acts as. A runner that tracks owners records it on the\n * Thread's first run and refuses a run from any other identity. `\"\"` is the\n * anonymous owner. When omitted, the run acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n /**\n * Records a stop of this run with Intelligence. An Intelligence runner calls\n * it when the runtime stops the run itself (not when Intelligence relayed\n * the stop), and sends the run's terminal event only once it settles or a\n * short deadline passes, so Intelligence counts the run as cancelled. The\n * signal aborts when that deadline passes. A failure never stops the run\n * from stopping. Runners that do not deliver to Intelligence ignore it.\n */\n recordStop?: (signal: AbortSignal) => Promise<void>;\n}\n\nexport interface AgentRunnerConnectRequest {\n threadId: string;\n agentId?: string;\n headers?: Record<string, string>;\n joinCode?: string;\n /**\n * Caller identity. A Thread owned by another identity is treated as unknown.\n * When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerIsRunningRequest {\n threadId: string;\n /**\n * Caller identity. A Thread owned by another identity reports \"not running\".\n * When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerStopRequest {\n threadId: string;\n /** When present, stop only this exact run and never a newer run on the Thread. */\n runId?: string;\n /**\n * Caller identity. A run on a Thread owned by another identity is not\n * stopped. When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface LocalThreadEndpointRecord {\n id: string;\n name: string | null;\n agentId: string;\n organizationId: string;\n createdById: string;\n archived: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Limits a local Thread endpoint call to the Threads of one owner. `\"\"` is the\n * anonymous owner. A call without a scope acts as\n * {@link ɵSERVER_THREAD_OWNER}: it sees only Threads created server-side, never\n * every Thread.\n */\nexport interface LocalThreadEndpointScope {\n ownerId: string;\n}\n\nexport interface LocalThreadEndpointRunner extends AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints: true;\n listThreads(scope?: LocalThreadEndpointScope): LocalThreadEndpointRecord[];\n getThreadMessages(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Message[];\n getThreadEvents(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): BaseEvent[];\n getThreadState(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Record<string, unknown> | null;\n clearThreads(scope?: LocalThreadEndpointScope): void;\n /** See {@link ThreadOwnershipRunner.isThreadAccessible}. */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean;\n}\n\nexport function supportsLocalThreadEndpoints(\n runner: AgentRunner,\n): runner is LocalThreadEndpointRunner {\n return runner.ɵsupportsLocalThreadEndpoints === true;\n}\n\n/**\n * A runner that records each Thread's owner and enforces it. Implementing\n * `isThreadAccessible` is the promise that `run`, `connect`, `stop` and\n * `isRunning` honor `ownerId` the same way: a call never reaches a Thread that\n * another owner holds.\n */\nexport interface ThreadOwnershipRunner extends AgentRunner {\n /** False when the Thread id is held by an owner other than `scope`'s. */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean | Promise<boolean>;\n}\n\n/**\n * True when `runner` enforces Thread owners. Checks the method itself, so a\n * runner built against an older interface (one that sets the endpoint flag\n * but has no `isThreadAccessible`) is not taken to enforce them.\n */\nexport function enforcesThreadOwnership(\n runner: AgentRunner,\n): runner is ThreadOwnershipRunner {\n return typeof runner.isThreadAccessible === \"function\";\n}\n\nexport abstract class AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints?: boolean;\n\n /** See {@link ThreadOwnershipRunner}. Optional: not every runner tracks owners. */\n isThreadAccessible?(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean | Promise<boolean>;\n\n abstract run(request: AgentRunnerRunRequest): Observable<BaseEvent>;\n abstract connect(request: AgentRunnerConnectRequest): Observable<BaseEvent>;\n abstract isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean>;\n abstract stop(request: AgentRunnerStopRequest): Promise<boolean | undefined>;\n}\n"],"mappings":";;;;;;;;;AAeA,IAAa,4BAAb,cAA+C,MAAM;CAGnD,cAAc;AACZ,QAAM,yBAAyB;cAHjB;AAId,OAAK,OAAO;;;;AAKhB,MAAa,kCAAkC;;;;;;;;;;;;;AAc/C,IAAa,0BAAb,cAA6C,MAAM;CAGjD,cAAc;AACZ,QAAM,uBAAuB;cAHf;AAId,OAAK,OAAO;;;;AAKhB,SAAgB,0BAA0B,OAAyB;AACjE,QACE,iBAAiB,SAChB,MAA6B,SAAS;;;;;;;;;;;;;AAe3C,MAAa,uBAAuB;;AAGpC,SAAgB,oBAAoB,SAAqC;AACvE,QAAO,WAAW;;AAyGpB,SAAgB,6BACd,QACqC;AACrC,QAAO,OAAO,kCAAkC;;;;;;;AAsBlD,SAAgB,wBACd,QACiC;AACjC,QAAO,OAAO,OAAO,uBAAuB;;AAG9C,IAAsB,cAAtB,MAAkC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"in-memory.cjs","names":["ɵresolveThreadOwner","ɵSERVER_THREAD_OWNER","AgentRunner","ThreadAccessDeniedError","ThreadAlreadyRunningError","EventType","ReplaySubject"],"sources":["../../../src/runtime/runner/in-memory.ts"],"sourcesContent":["import type {\n AgentRunnerConnectRequest,\n AgentRunnerIsRunningRequest,\n AgentRunnerRunRequest,\n LocalThreadEndpointScope,\n} from \"./agent-runner\";\nimport {\n AgentRunner,\n ThreadAccessDeniedError,\n ThreadAlreadyRunningError,\n ɵSERVER_THREAD_OWNER,\n ɵresolveThreadOwner,\n} from \"./agent-runner\";\nimport type { AgentRunnerStopRequest } from \"./agent-runner\";\nimport type { Observable } from \"rxjs\";\nimport { ReplaySubject } from \"rxjs\";\nimport type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunStartedEvent,\n StateSnapshotEvent,\n} from \"@ag-ui/client\";\nimport { EventType, compactEvents } from \"@ag-ui/client\";\nimport { finalizeRunEvents } from \"@copilotkit/shared\";\n\nexport interface InMemoryLimits {\n /** LRU cap on distinct threads. */\n maxThreads?: number;\n /** FIFO cap on runs kept per thread. `Infinity` or `0` disables the cap. */\n maxRunsPerThread?: number;\n /**\n * Approximate byte ceiling on RETAINED thread/run history. Enforced at run\n * completion (in `appendRun`), where LRU non-running threads are evicted to\n * keep the total under this limit.\n *\n * Limitation: this bounds only history that has already been committed. A\n * single in-flight run's buffered events (`currentRunEvents` and the two\n * `ReplaySubject<BaseEvent>(Infinity)` buffers in `run()`) are NOT counted\n * until that run completes, so `maxBytes` does not bound a single runaway\n * run mid-stream.\n *\n * Limitation: byte eviction drops only other LRU non-running threads and\n * never self-evicts the active/just-appended thread, so a single dominant\n * thread's own retained history is not byte-trimmed (bounded only by\n * `maxRunsPerThread`). `maxBytes` is thus a cross-thread ceiling enforced by\n * evicting OTHER threads, not a per-thread cap.\n */\n maxBytes?: number;\n}\n\n/**\n * Constructor options for {@link InMemoryAgentRunner}.\n *\n * Extends {@link InMemoryLimits} so bounds can be passed inline alongside the\n * per-runner behavior flags. Be aware of the scope difference: the limits\n * reconfigure the process-global store shared by every runner, whereas\n * `onConcurrentRun` applies only to the runner instance it is passed to.\n */\nexport interface InMemoryAgentRunnerOptions extends InMemoryLimits {\n /**\n * How to handle a `run()` for a thread that already has an in-flight run.\n * `\"throw\"` (default) rejects with \"Thread already running\". `\"supersede\"`\n * aborts the prior run and starts the new one.\n */\n onConcurrentRun?: \"throw\" | \"supersede\";\n}\n\nexport const ɵINMEMORY_DEFAULTS: Required<InMemoryLimits> = {\n maxThreads: 1000,\n maxRunsPerThread: 100,\n maxBytes: 512 * 1024 ** 2,\n};\n\n/**\n * A limit value is well-formed iff it is a non-negative integer OR `+Infinity`.\n * `+Infinity` is the documented \"disabled/unbounded\" sentinel and `0` is the\n * documented run-cap disable sentinel; both are non-negative and pass. Every\n * enforcement site (`evictThreadsIfNeeded`, `enforceRunCap`,\n * `evictByBytesIfNeeded`) compares its counter against the limit with `>` in a\n * `while`/`if` guard, so only these shapes keep those loops finite and correct.\n * Rejected: negatives (drive `count > -1` true on an empty collection, so\n * `enforceRunCap` `shift()!`s `undefined` and throws), `-Infinity` (loops never\n * terminate their intent — always \"over\"), `NaN` (every `>` is false, silently\n * disabling the bound), and non-integer finites (fractional caps are nonsense).\n */\nfunction ɵisValidLimit(value: number): boolean {\n return value === Infinity || (Number.isInteger(value) && value >= 0);\n}\n\n/**\n * Normalize a fully-resolved limits bag so every field is well-formed before it\n * can reach an enforcement loop. Each field is validated independently against\n * {@link ɵisValidLimit}; an invalid value is CLAMPED to its\n * {@link ɵINMEMORY_DEFAULTS} floor and a single `console.warn` naming the field\n * and the received value is emitted.\n *\n * Clamp-and-warn (rather than throw) is deliberate and matches this file's\n * established posture toward bad input: `ɵestimateBytes` swallows serialization\n * failures and returns 0, the limits-clobber path warns rather than throwing,\n * and both the eviction and clobber logs are wrapped so \"logging must never\n * break construction/a run\". Constructing a bounded in-memory runner is a\n * best-effort, non-durable convenience; a typo'd bound must degrade to a safe\n * default, never abort construction or (worse) surface later as an unhandled\n * rejection from the fire-and-forget finalize path.\n */\nexport function ɵnormalizeLimits(\n limits: Required<InMemoryLimits>,\n): Required<InMemoryLimits> {\n const normalized = { ...limits };\n for (const field of Object.keys(\n ɵINMEMORY_DEFAULTS,\n ) as (keyof InMemoryLimits)[]) {\n const value = limits[field];\n if (!ɵisValidLimit(value)) {\n const fallback = ɵINMEMORY_DEFAULTS[field];\n normalized[field] = fallback;\n try {\n console.warn(\n `[CopilotKit] InMemoryAgentRunner: invalid ${field} value ` +\n `${String(value)} (expected a non-negative integer or Infinity); ` +\n `falling back to ${String(fallback)}.`,\n );\n } catch {\n // best-effort: logging must never break construction\n }\n }\n }\n return normalized;\n}\n\nconst EVICTION_GUIDANCE =\n \"[CopilotKit] InMemoryAgentRunner evicted in-memory thread history to stay \" +\n \"under memory limits. This runner is bounded and non-durable by design. For \" +\n \"durable or production threads, configure an Intelligence backend.\";\n\nconst LIMITS_CLOBBER_GUIDANCE =\n \"[CopilotKit] InMemoryAgentRunner was constructed with in-memory limits that \" +\n \"differ from the already-configured process-global store; the last-constructed \" +\n \"runner's limits apply to ALL in-memory threads (the store is shared per-process). \" +\n \"Configure a single consistent set of limits, or use an Intelligence backend for \" +\n \"isolated bounds.\";\n\n/**\n * Best-effort approximate byte size of a value, via serialized length.\n * Never throws — returns 0 when the value cannot be serialized. This is an\n * approximation (UTF-16 length, not exact heap bytes), used only for relative\n * accounting against `maxBytes`.\n */\nexport function ɵestimateBytes(value: unknown): number {\n try {\n return JSON.stringify(value)?.length ?? 0;\n } catch {\n return 0;\n }\n}\n\n/**\n * Per-run finalize intent, captured once when a run starts and mutated (only)\n * by whoever aborts THAT run — `stop()` or a superseding `run()`. The run's own\n * teardown reads this captured holder instead of the shared, mutable\n * `store.stopRequested`, so a later run that resets store state can never cause\n * an intentionally-stopped run to be finalized as an error (or vice versa).\n */\ninterface RunFinalizeControl {\n /** True once THIS run has been asked to stop (clean stop, not an error). */\n stopRequested: boolean;\n}\n\ninterface HistoricRun {\n threadId: string;\n runId: string;\n /** ID of the agent that executed this run. */\n agentId: string;\n parentRunId: string | null;\n events: BaseEvent[];\n /**\n * Snapshot of all messages (input + generated) at the end of this run, as\n * passed in by the caller. NOTE: `BoundedThreadStore.appendRun` moves this\n * snapshot to the THREAD level (`InMemoryEventStore.messagesSnapshot`) and\n * clears this field to `[]`, so a stored HistoricRun never carries messages.\n * The thread-messages fallback reads the thread-level snapshot, not this.\n */\n messages: Message[];\n createdAt: number;\n /** Approximate retained byte size of `events`; set by BoundedThreadStore at append. */\n approxEventBytes?: number;\n /**\n * Legacy field retained for shape compatibility. `appendRun` always zeroes it\n * because message bytes are accounted at the thread level, not per run.\n */\n approxMessageBytes?: number;\n}\n\n/**\n * Lightweight thread summary returned by {@link InMemoryAgentRunner.listThreads}.\n * Shape matches CopilotKit Intelligence's ThreadRecord so the same HTTP\n * response envelope can be used for both backends.\n */\nexport interface InMemoryThread {\n id: string;\n name: string | null;\n agentId: string;\n organizationId: \"\"; // always empty in in-memory mode\n /** Identity that owns the thread; `\"\"` for a thread created without identity. */\n createdById: string;\n archived: false; // always false in in-memory mode\n createdAt: string;\n updatedAt: string;\n}\n\nclass InMemoryEventStore {\n /**\n * @param ownerId Identity that owns this thread, recorded when the thread is\n * created by its first run. `\"\"` is the anonymous owner;\n * {@link ɵSERVER_THREAD_OWNER} is the owner of a thread created server-side.\n */\n constructor(\n public threadId: string,\n public readonly ownerId: string,\n ) {}\n\n /** The subject that current consumers subscribe to. */\n subject: ReplaySubject<BaseEvent> | null = null;\n\n /** True while a run is actively producing events. */\n isRunning = false;\n\n /** Current run ID */\n currentRunId: string | null = null;\n\n /** Historic completed runs */\n historicRuns: HistoricRun[] = [];\n\n /** Currently running agent instance (if any). */\n agent: AbstractAgent | null = null;\n\n /** Subject returned from run() while the run is active. */\n runSubject: ReplaySubject<BaseEvent> | null = null;\n\n /**\n * Thread-level lifecycle flag: true once a stop/supersede has been requested\n * for the currently-owning run but that run has not yet finalized. Drives\n * eviction protection, the connect() bridge, and stop() de-dup. This is NOT\n * the finalize intent read by a run's teardown — that lives per-run on\n * {@link activeFinalize}, so a superseding run resetting this field cannot\n * mislabel the run it replaced. A new run resets this to false when it takes\n * ownership.\n */\n stopRequested = false;\n\n /**\n * Finalize control of the currently-owning run. `stop()` and a superseding\n * `run()` flip the owning run's flag through this reference; each run also\n * captures the SAME object in its closure, so its teardown finalizes against\n * its own intent regardless of what a later run does to the store.\n */\n activeFinalize: RunFinalizeControl | null = null;\n\n /** Reference to the events emitted in the current run. */\n currentEvents: BaseEvent[] | null = null;\n\n /**\n * The thread's single latest NON-EMPTY message snapshot, held at the THREAD\n * level (independent of `historicRuns` lifecycle). Decoupling the snapshot\n * from per-run storage means run-cap FIFO eviction and interleaved\n * empty-snapshot runs can never drop or pin the thread's message history.\n */\n messagesSnapshot: Message[] = [];\n\n /** Approximate retained byte size of `messagesSnapshot`. */\n approxMessagesSnapshotBytes = 0;\n\n /**\n * The thread's true creation timestamp (epoch ms), captured from the FIRST\n * run ever appended and held at the THREAD level (independent of\n * `historicRuns` lifecycle). Decoupling it from per-run storage means run-cap\n * FIFO eviction — which shifts the oldest entries off `historicRuns` — can\n * never move the reported creation time forward. `null` until the first run\n * lands. Mirrors the `messagesSnapshot` thread-level decoupling.\n */\n createdAt: number | null = null;\n}\n\n/**\n * True when a caller acting as `owner` may reach `store`: only the thread's\n * own owner may. Resolve an optional owner or scope with\n * {@link ɵresolveThreadOwner} first; an omitted one is the server owner, never\n * \"every thread\".\n */\nfunction isVisibleTo(store: InMemoryEventStore, owner: string): boolean {\n return store.ownerId === owner;\n}\n\n/** The owner a Thread endpoint call acts as. */\nfunction scopeOwner(scope: LocalThreadEndpointScope | undefined): string {\n return ɵresolveThreadOwner(scope?.ownerId);\n}\n\n/**\n * How long, and how many, owner records the store keeps for threads that left\n * it through LRU eviction or a scoped clear. See\n * {@link ɵBoundedThreadStore.ownerOf}.\n *\n * When a record is added over a limit, expired records go first; then, when\n * the record's owner holds more than `maxEntriesPerOwner`, that owner's\n * oldest record; then, over `maxEntries`, the oldest record of any owner. So\n * one identity that churns threads (anonymous callers share one identity)\n * only displaces its own records. Residual risk: many distinct identities\n * together can still exceed `maxEntries` and push out another identity's\n * live record. That frees the id for a new owner but leaks nothing, since\n * the removed thread's history is already gone, and it needs the victim's\n * thread id.\n */\nexport interface ɵOwnerRetention {\n /** Milliseconds an owner record is kept after its thread was removed. */\n ttlMs: number;\n /** Most owner records kept in all. */\n maxEntries: number;\n /** Most owner records kept for one owner. */\n maxEntriesPerOwner: number;\n /** Clock, replaceable in tests. */\n now: () => number;\n}\n\nexport const ɵOWNER_RETENTION_DEFAULTS: ɵOwnerRetention = {\n ttlMs: 24 * 60 * 60 * 1000,\n maxEntries: 100_000,\n maxEntriesPerOwner: 10_000,\n now: () => Date.now(),\n};\n\nexport class ɵBoundedThreadStore {\n private readonly map = new Map<string, InMemoryEventStore>();\n /**\n * Owners of threads that were removed from `map`, oldest first. A removed\n * thread's history is gone, but its id stays reserved for its owner until\n * the record expires, so another identity cannot claim the id and receive\n * the owner's next runs or later replays.\n */\n private readonly removedOwners = new Map<\n string,\n { ownerId: string; removedAt: number }\n >();\n /** The ids in `removedOwners`, per owner, oldest first. */\n private readonly removedOwnersByOwner = new Map<string, Set<string>>();\n private ownerRetention: ɵOwnerRetention = ɵOWNER_RETENTION_DEFAULTS;\n private totalBytes = 0;\n private warned = false;\n /** True once limits have been EXPLICITLY set (via setLimits), not just the constructor default. */\n private limitsExplicitlySet = false;\n /** Warn-once latch for the clobber warning, kept distinct from the eviction `warned` latch. */\n private clobberWarned = false;\n\n private limits: Required<InMemoryLimits>;\n\n constructor(limits: Required<InMemoryLimits>) {\n // Normalize once at construction so `this.limits` is ALWAYS well-formed,\n // regardless of entry point (direct construction or a later `setLimits`).\n this.limits = ɵnormalizeLimits(limits);\n }\n\n get byteTotal(): number {\n return this.totalBytes;\n }\n\n /**\n * The store's CURRENT effective bounds. Exposed (with the `ɵ` internal-API\n * prefix) so a partial `setLimits` can coalesce unspecified fields against the\n * live config rather than the hardcoded {@link ɵINMEMORY_DEFAULTS} — a partial\n * update must be a partial update, never a silent reset of the fields the\n * caller did not mention. Returns a copy so callers cannot mutate the store's\n * bounds through it.\n */\n get ɵlimits(): Required<InMemoryLimits> {\n return { ...this.limits };\n }\n\n /**\n * Reconfigure the process-global store's bounds. Called by the\n * {@link InMemoryAgentRunner} constructor when limits are passed. Because the\n * store is a per-process singleton, this replaces the bounds for ALL in-memory\n * threads. Emits {@link LIMITS_CLOBBER_GUIDANCE} at most ONCE per store when a\n * SECOND (or later) explicit set arrives whose resolved values differ from the\n * prior explicit set — i.e. a genuine clobber of an already-customized config.\n * The first explicit customization (defaults → custom) is the intended\n * override and never warns; identical re-sets never warn.\n */\n setLimits(limits: Required<InMemoryLimits>): void {\n // Normalize FIRST so invalid fields can never reach an enforcement loop and\n // so the clobber comparison below is against the EFFECTIVE (clamped) values,\n // not the raw ones — a typo'd bound that clamps to the current default is not\n // a genuine clobber and must not warn.\n const normalized = ɵnormalizeLimits(limits);\n if (\n this.limitsExplicitlySet &&\n !this.clobberWarned &&\n (normalized.maxThreads !== this.limits.maxThreads ||\n normalized.maxRunsPerThread !== this.limits.maxRunsPerThread ||\n normalized.maxBytes !== this.limits.maxBytes)\n ) {\n this.clobberWarned = true;\n try {\n console.warn(LIMITS_CLOBBER_GUIDANCE);\n } catch {\n // best-effort: logging must never break construction\n }\n }\n this.limitsExplicitlySet = true;\n this.limits = normalized;\n }\n\n get size(): number {\n return this.map.size;\n }\n\n /** Re-insert at the tail so Map iteration order stays LRU-first. */\n private touchOrder(threadId: string, store: InMemoryEventStore): void {\n this.map.delete(threadId);\n this.map.set(threadId, store);\n }\n\n /**\n * The thread's store, created and owned by `ownerId` when it does not exist\n * yet. An existing store keeps its owner; callers check access first.\n */\n getOrCreate(\n threadId: string,\n ownerId: string = ɵSERVER_THREAD_OWNER,\n ): InMemoryEventStore {\n const existing = this.map.get(threadId);\n if (existing) {\n this.touchOrder(threadId, existing);\n return existing;\n }\n const store = new InMemoryEventStore(threadId, ownerId);\n // The live store now records the owner.\n this.forgetOwner(threadId);\n this.map.set(threadId, store);\n this.evictThreadsIfNeeded(threadId);\n return store;\n }\n\n get(\n threadId: string,\n opts: { touch: boolean },\n ): InMemoryEventStore | undefined {\n const store = this.map.get(threadId);\n if (store && opts.touch) this.touchOrder(threadId, store);\n return store;\n }\n\n peek(threadId: string): InMemoryEventStore | undefined {\n return this.map.get(threadId);\n }\n\n /**\n * Evict the least-recently-used thread that is neither running NOR\n * mid-finalization. Returns false if none evictable. The `protect` thread\n * (typically the one just created) is never evicted, so a fresh thread is not\n * immediately dropped when it is the only non-running candidate.\n *\n * A thread is skipped while `isRunning` OR `stopRequested` is set.\n * `stop()` flips `isRunning` to false the moment it aborts the agent, but the\n * run keeps finalizing asynchronously (the abort trips the `catch` in\n * `runAgent`, which later calls `appendRun`). During that window\n * `stopRequested` stays true; evicting the thread then would make the pending\n * `appendRun` hit `if (!store) return` and silently drop the aborted run's\n * history. Guarding on `stopRequested` keeps the thread alive until\n * finalization completes.\n */\n private evictOneLru(protect?: string): boolean {\n for (const [threadId, store] of this.map) {\n if (threadId === protect) continue; // never evict the just-created thread\n // never evict a running or still-finalizing (stop-requested) thread\n if (store.isRunning || store.stopRequested) continue;\n this.removeThread(threadId, store);\n this.noteEviction();\n return true;\n }\n return false;\n }\n\n /**\n * Append a finished run to `writer`, the store its run started on. Nothing is\n * written when `writer` is no longer the live store for `threadId` (the thread\n * was removed, or removed and claimed again): a run must never write into a\n * thread it did not start on, which may now belong to another owner.\n */\n appendRun(\n threadId: string,\n writer: InMemoryEventStore | undefined,\n run: HistoricRun,\n ): void {\n const store = this.map.get(threadId);\n if (!store || store !== writer) return;\n\n // Thread-level creation timestamp: capture the FIRST run's createdAt once\n // and never overwrite it. Held on the store (not derived from\n // `historicRuns[0]`) so run-cap FIFO eviction of the oldest runs cannot\n // drift the thread's reported creation time forward. Mirrors the\n // thread-level `messagesSnapshot` decoupling below.\n if (store.createdAt === null) {\n store.createdAt = run.createdAt;\n }\n\n // Thread-level message snapshot: keep the single latest NON-EMPTY snapshot\n // on the store, decoupled from `historicRuns`. When the incoming run\n // carries a non-empty snapshot, replace the thread's snapshot (adjusting\n // byte accounting). When it's empty (non-array `agent.messages` or an\n // error-path run), leave the existing thread snapshot untouched so history\n // is never lost. The snapshot never lives on a HistoricRun, so run-cap FIFO\n // eviction can never drop it and an interleaved empty run can never pin it.\n if (run.messages.length > 0) {\n this.totalBytes -= store.approxMessagesSnapshotBytes;\n // Store the incoming array directly (SHALLOW, array-level copy). `run.messages`\n // is already a fresh `[...agent.messages]` array created in run(), so we own the\n // array and it is decoupled from `agent.messages` at the array level (push/splice\n // on the agent's array cannot mutate our snapshot). We deliberately do NOT deep-copy\n // here: `structuredClone` throws DataCloneError on a non-cloneable message field,\n // which would wedge the thread and hang SSE — inconsistent with `ɵestimateBytes`,\n // which tolerates the same bad-payload class. The tradeoff is that the inner\n // `Message` objects remain shared by reference with `agent.messages`, so an agent\n // that mutates its own message objects IN PLACE after the run can still be observed\n // through this snapshot. That inner-object isolation is a known limitation tracked as\n // follow-up; callers must treat returned messages as read-only. Estimate bytes on the\n // same value so accounting matches exactly what is retained.\n store.messagesSnapshot = run.messages;\n store.approxMessagesSnapshotBytes = ɵestimateBytes(run.messages);\n this.totalBytes += store.approxMessagesSnapshotBytes;\n }\n\n // Do not carry message bytes on the HistoricRun: the snapshot is now tracked\n // at the thread level, so historicRuns must never account message bytes.\n run.messages = [];\n run.approxMessageBytes = 0;\n\n // Compute this run's approximate event size once, at append time.\n run.approxEventBytes = ɵestimateBytes(run.events);\n store.historicRuns.push(run);\n this.totalBytes += run.approxEventBytes;\n this.touchOrder(threadId, store);\n\n this.enforceRunCap(store);\n this.evictByBytesIfNeeded(threadId);\n }\n\n private enforceRunCap(store: InMemoryEventStore): void {\n const cap = this.limits.maxRunsPerThread;\n if (!cap || cap === Infinity) return; // 0 or Infinity → disabled\n while (store.historicRuns.length > cap) {\n const dropped = store.historicRuns.shift()!;\n // Only event bytes live on a HistoricRun; the message snapshot is tracked\n // at the thread level and survives run-cap eviction.\n this.totalBytes -= dropped.approxEventBytes ?? 0;\n // Per-thread run-cap trimming is also eviction — history is being dropped.\n // Route it through the SAME warn-once latch as whole-thread LRU eviction so\n // this shows up in logs rather than as silent data loss. `noteEviction` is\n // latched (one warning per store, reset by `clear()`), so a hot thread that\n // trims on every subsequent append warns once, never per dropped run. The\n // loop only runs when a run is ACTUALLY over the cap, so a disabled or\n // under-cap `enforceRunCap` stays silent (it returned / never entered here).\n this.noteEviction();\n }\n }\n\n /**\n * Trim the store back under the byte ceiling by evicting LRU non-running\n * threads. `protect` (the just-appended thread) is never self-evicted, so a\n * fresh run pushes OTHER threads out rather than dropping itself.\n */\n private evictByBytesIfNeeded(protect?: string): void {\n while (this.totalBytes > this.limits.maxBytes) {\n if (!this.evictOneLru(protect)) break; // only protected/running threads left → accept overage\n }\n }\n\n private removeThread(threadId: string, store: InMemoryEventStore): void {\n for (const run of store.historicRuns) {\n this.totalBytes -= run.approxEventBytes ?? 0;\n }\n // The thread's message snapshot is tracked at the store level, so it must\n // be reclaimed here in addition to the per-run event bytes.\n this.totalBytes -= store.approxMessagesSnapshotBytes;\n this.map.delete(threadId);\n this.rememberOwner(threadId, store.ownerId);\n }\n\n /**\n * Keep the owner of a removed thread, within the retention bounds. See\n * {@link ɵOwnerRetention} for which records go first over a limit.\n */\n private rememberOwner(threadId: string, ownerId: string): void {\n const { maxEntries, maxEntriesPerOwner, now } = this.ownerRetention;\n this.forgetOwner(threadId); // re-insert at the tail (newest)\n this.removedOwners.set(threadId, { ownerId, removedAt: now() });\n let owned = this.removedOwnersByOwner.get(ownerId);\n if (!owned) {\n owned = new Set();\n this.removedOwnersByOwner.set(ownerId, owned);\n }\n owned.add(threadId);\n this.pruneRemovedOwners();\n while (owned.size > maxEntriesPerOwner) {\n const oldest = owned.values().next().value;\n if (oldest === undefined) break;\n this.forgetOwner(oldest);\n }\n while (this.removedOwners.size > maxEntries) {\n const oldest = this.removedOwners.keys().next().value;\n if (oldest === undefined) break;\n this.forgetOwner(oldest);\n }\n }\n\n /** Remove the owner record of `threadId`, if any. */\n private forgetOwner(threadId: string): void {\n const record = this.removedOwners.get(threadId);\n if (!record) return;\n this.removedOwners.delete(threadId);\n const owned = this.removedOwnersByOwner.get(record.ownerId);\n owned?.delete(threadId);\n if (owned?.size === 0) this.removedOwnersByOwner.delete(record.ownerId);\n }\n\n /** Drop expired owner records. They are oldest first, so stop at the first live one. */\n private pruneRemovedOwners(): void {\n const { ttlMs, now } = this.ownerRetention;\n const cutoff = now() - ttlMs;\n for (const [threadId, record] of this.removedOwners) {\n if (record.removedAt >= cutoff) break;\n this.forgetOwner(threadId);\n }\n }\n\n /**\n * Owner of `threadId`: the live thread's owner, or the retained owner of a\n * thread that was evicted or cleared. `undefined` when nobody owns the id, so\n * the next run may claim it.\n */\n ownerOf(threadId: string): string | undefined {\n const store = this.map.get(threadId);\n if (store) return store.ownerId;\n this.pruneRemovedOwners();\n const record = this.removedOwners.get(threadId);\n if (!record) return undefined;\n const { ttlMs, now } = this.ownerRetention;\n if (record.removedAt < now() - ttlMs) {\n this.forgetOwner(threadId);\n return undefined;\n }\n return record.ownerId;\n }\n\n /** True when a caller acting as `owner` may run on, or claim, `threadId`. */\n canClaim(threadId: string, owner: string): boolean {\n const current = this.ownerOf(threadId);\n return current === undefined || current === owner;\n }\n\n /**\n * Replace the owner-record retention. Omitted fields fall back to\n * {@link ɵOWNER_RETENTION_DEFAULTS}. Internal: for tests.\n */\n ɵsetOwnerRetention(retention: Partial<ɵOwnerRetention>): void {\n this.ownerRetention = { ...ɵOWNER_RETENTION_DEFAULTS, ...retention };\n }\n\n private evictThreadsIfNeeded(protect?: string): void {\n while (this.map.size > this.limits.maxThreads) {\n if (!this.evictOneLru(protect)) break; // everything evictable is running → accept overage\n }\n }\n\n private noteEviction(): void {\n if (this.warned) return;\n this.warned = true;\n try {\n console.warn(EVICTION_GUIDANCE);\n } catch {\n // best-effort: logging must never break a run\n }\n }\n\n listThreads(scope?: LocalThreadEndpointScope): InMemoryThread[] {\n const threads: InMemoryThread[] = [];\n for (const [threadId, store] of this.map) {\n if (store.historicRuns.length === 0) continue;\n if (!isVisibleTo(store, scopeOwner(scope))) continue;\n const lastRun = store.historicRuns[store.historicRuns.length - 1]!;\n // Creation time comes from the thread-level `store.createdAt` (the first\n // run ever appended), NOT `historicRuns[0]` (the oldest RETAINED run):\n // run-cap FIFO eviction drops the oldest retained runs, so deriving it\n // from `historicRuns[0]` would silently drift the timestamp forward over\n // a thread's lifetime. `updatedAt` stays on `lastRun` because FIFO\n // eviction removes from the FRONT, so the newest run is never evicted.\n // The `?? lastRun.createdAt` fallback is defensive only: any thread with\n // runs has had `store.createdAt` set by `appendRun`.\n threads.push({\n id: threadId,\n name: null,\n agentId: lastRun.agentId,\n organizationId: \"\",\n createdById: store.ownerId,\n archived: false,\n createdAt: new Date(store.createdAt ?? lastRun.createdAt).toISOString(),\n updatedAt: new Date(lastRun.createdAt).toISOString(),\n });\n }\n return threads.sort(\n (a, b) =>\n new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),\n );\n }\n\n /**\n * Removes every thread visible to `scope`, except threads that are running\n * or still finalizing: removing one would drop its owner record while its\n * run still writes, so another identity could claim the id. Those threads\n * stay, as in `evictOneLru`. A scoped clear leaves other owners' threads\n * untouched.\n *\n * Without a scope the whole store is reset, running threads included. That\n * is an internal reset for tests; `appendRun` keeps an orphaned run from\n * writing into a thread created after the reset.\n */\n clear(scope?: LocalThreadEndpointScope): void {\n if (scope !== undefined) {\n // Deleting the current entry while iterating a Map is safe.\n for (const [threadId, store] of this.map) {\n if (store.isRunning || store.stopRequested) continue;\n if (isVisibleTo(store, scopeOwner(scope)))\n this.removeThread(threadId, store);\n }\n return;\n }\n this.map.clear();\n this.removedOwners.clear();\n this.removedOwnersByOwner.clear();\n this.totalBytes = 0;\n this.warned = false;\n }\n}\n\n/**\n * Process-wide singleton backing every {@link InMemoryAgentRunner}. Exported\n * (with the `ɵ` internal-API prefix) so tests can inspect the exact store the\n * runner writes to; not part of the public API.\n */\nexport const ɵGLOBAL_STORE = new ɵBoundedThreadStore(ɵINMEMORY_DEFAULTS);\nconst sharedStore = ɵGLOBAL_STORE;\n\nexport class InMemoryAgentRunner extends AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints = true;\n\n /**\n * How to handle a `run()` for a thread that already has an in-flight run.\n * `\"throw\"` (default) preserves the historic behavior. `\"supersede\"` aborts\n * the prior run (mirroring `stop()`) and starts the new one — opted into by\n * the hosted-bot listener so a fast follow-up turn on the same thread cleanly\n * replaces a still-running (or wedged) prior turn instead of erroring with\n * \"Thread already running\".\n */\n private readonly onConcurrentRun: \"throw\" | \"supersede\";\n\n /**\n * @param options Per-runner behavior (`onConcurrentRun`) plus optional bounds\n * for the in-memory store ({@link InMemoryLimits}).\n *\n * Note the differing scopes: `onConcurrentRun` is per-runner instance, while\n * the limits reconfigure the PROCESS-GLOBAL store shared by every\n * `InMemoryAgentRunner`. Omit the limits for safe defaults\n * ({@link ɵINMEMORY_DEFAULTS}); passing none leaves the store untouched. When\n * multiple runners are constructed with differing limits, the last-constructed\n * wins — in practice the OSS/SSE default construction passes nothing. If a\n * second (or later) runner is constructed with limits that DIFFER from an\n * already-customized store, a one-time `console.warn` is emitted to signal that\n * the shared store's bounds are being clobbered for ALL in-memory threads.\n */\n constructor(options?: InMemoryAgentRunnerOptions) {\n super();\n const { onConcurrentRun, ...limits } = options ?? {};\n this.onConcurrentRun = onConcurrentRun ?? \"throw\";\n\n // Only reconfigure the shared store when a bound was actually supplied.\n // `new InMemoryAgentRunner({ onConcurrentRun: \"supersede\" })` must stay\n // inert with respect to limits.\n if (\n limits.maxThreads !== undefined ||\n limits.maxRunsPerThread !== undefined ||\n limits.maxBytes !== undefined\n ) {\n // Coalesce each unspecified field against the store's CURRENT effective\n // limits, NOT ɵINMEMORY_DEFAULTS. The store is process-global, so tuning\n // one bound must leave every previously-customized sibling bound intact —\n // a partial update stays a partial update instead of silently resetting the\n // fields the caller never mentioned. Passing all three (e.g.\n // ɵINMEMORY_DEFAULTS) still fully replaces the config, so the defaults-\n // restore path is unaffected.\n const current = sharedStore.ɵlimits;\n sharedStore.setLimits({\n maxThreads: limits.maxThreads ?? current.maxThreads,\n maxRunsPerThread: limits.maxRunsPerThread ?? current.maxRunsPerThread,\n maxBytes: limits.maxBytes ?? current.maxBytes,\n });\n }\n }\n\n run(request: AgentRunnerRunRequest): Observable<BaseEvent> {\n // A thread belongs to the identity of its first run. Check before\n // `getOrCreate` so a refused run does not touch the thread's LRU position.\n const owner = ɵresolveThreadOwner(request.ownerId);\n if (!sharedStore.canClaim(request.threadId, owner)) {\n throw new ThreadAccessDeniedError();\n }\n const store = sharedStore.getOrCreate(request.threadId, owner);\n\n // Enter the concurrency branch whenever a prior run still owns the thread —\n // either actively running OR still finalizing after a stop()/supersede.\n // `stop()` flips `isRunning` to false the instant it aborts the agent, but\n // the run keeps finalizing asynchronously (`stopRequested` stays true).\n // Gating on `isRunning` alone let a `run()` slip through that window\n // unhandled: no supersede/throw, no per-run intent capture, and a leaked\n // bridge from the dying run's subject.\n if (store.isRunning || store.stopRequested) {\n if (this.onConcurrentRun !== \"supersede\") {\n throw new ThreadAlreadyRunningError();\n }\n // Supersede: abort the prior (possibly wedged) run so this one can start.\n // Mirrors stop(). Record the prior run's OWN finalize intent on its\n // captured control BEFORE resetting the shared store flags for the new\n // run: a supersede is a clean stop of the prior run, so its async teardown\n // must finalize as RUN_FINISHED, never a synthetic RUN_ERROR. The prior\n // run's async finalization is prevented from clobbering this run's state\n // by the run-id guard below.\n const priorAgent = store.agent;\n const priorFinalize = store.activeFinalize;\n if (priorFinalize) {\n priorFinalize.stopRequested = true;\n }\n store.isRunning = false;\n if (priorAgent) {\n try {\n priorAgent.abortRun();\n } catch (error) {\n console.error(\"Failed to abort superseded run\", error);\n }\n }\n }\n store.isRunning = true;\n store.currentRunId = request.input.runId;\n store.agent = request.agent;\n store.stopRequested = false;\n\n // Per-run finalize control. This run's teardown reads THIS captured holder\n // (never the shared `store.stopRequested`, which a later run resets), so an\n // aborted run is always finalized against its own stop-intent.\n const finalizeControl: RunFinalizeControl = { stopRequested: false };\n store.activeFinalize = finalizeControl;\n\n // Track seen message IDs and current run events for this run\n const seenMessageIds = new Set<string>();\n const currentRunEvents: BaseEvent[] = [];\n store.currentEvents = currentRunEvents;\n\n // Get all previously seen message IDs from historic runs\n const historicMessageIds = new Set<string>();\n for (const run of store.historicRuns) {\n for (const event of run.events) {\n if (\"messageId\" in event && typeof event.messageId === \"string\") {\n historicMessageIds.add(event.messageId);\n }\n if (event.type === EventType.RUN_STARTED) {\n const runStarted = event as RunStartedEvent;\n const messages = runStarted.input?.messages ?? [];\n for (const message of messages) {\n historicMessageIds.add(message.id);\n }\n }\n }\n }\n\n const nextSubject = new ReplaySubject<BaseEvent>(Infinity);\n\n // Update the store's subject immediately. We intentionally do NOT capture\n // and bridge the previous subject: see the note before `runAgent()` below.\n store.subject = nextSubject;\n\n // Create a subject for run() return value\n const runSubject = new ReplaySubject<BaseEvent>(Infinity);\n store.runSubject = runSubject;\n\n // Helper function to run the agent and handle errors\n const runAgent = async () => {\n // Get parent run ID for chaining\n const lastRun = store.historicRuns[store.historicRuns.length - 1];\n const parentRunId = lastRun?.runId ?? null;\n\n // Shared teardown for both the success and error paths. Keeping this one\n // helper means the two paths cannot drift apart (they were near-identical\n // and must stay symmetric). `interruptionMessage` is set only on the error\n // path; its presence is what distinguishes the two.\n const finalizeRun = (opts: { interruptionMessage?: string }) => {\n const isError = opts.interruptionMessage !== undefined;\n\n // Capture the count of REAL (agent-emitted) events BEFORE finalizing.\n // `finalizeRunEvents` mutates `currentRunEvents` IN PLACE — it always\n // pushes a synthetic terminal (and any closers) when the stream ended\n // without one — so after the call `currentRunEvents.length` is never 0.\n // The persistence guard below must gate on this pre-finalize count, or\n // the \"skip an immediate throw that emitted nothing\" check is dead.\n const preFinalizeEventCount = currentRunEvents.length;\n\n // Stop can arrive before the agent sends its first event.\n if (\n finalizeControl.stopRequested &&\n !currentRunEvents.some(\n (event) => event.type === EventType.RUN_STARTED,\n )\n ) {\n const started: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: request.threadId,\n runId: request.input.runId,\n input: {\n ...request.input,\n messages: request.input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n ),\n },\n };\n currentRunEvents.unshift(started);\n runSubject.next(started);\n nextSubject.next(started);\n }\n\n // Finalize against THIS run's own captured stop-intent — never the\n // shared `store.stopRequested`, which a superseding run resets. An\n // aborted run is thus finalized as a clean RUN_FINISHED, not a synthetic\n // RUN_ERROR.\n const appendedEvents = finalizeRunEvents(currentRunEvents, {\n stopRequested: finalizeControl.stopRequested,\n protocolVersion: request.input.protocolVersion,\n ...(isError ? { interruptionMessage: opts.interruptionMessage } : {}),\n });\n for (const event of appendedEvents) {\n runSubject.next(event);\n nextSubject.next(event);\n }\n\n // Does this run still own the thread? A superseding run has changed\n // `currentRunId`, so the run it replaced no longer owns the store.\n const ownsThread = store.currentRunId === request.input.runId;\n\n // Store this run's events. Guard on the per-run id (not the shared\n // `store.currentRunId`): a superseded run no longer owns the store, so\n // it must not push history under a newer run's id.\n // Keep explicit stops even when abort rejects before the first event.\n // Other immediate errors with no real events must not create history.\n if (\n ownsThread &&\n (!isError ||\n preFinalizeEventCount > 0 ||\n finalizeControl.stopRequested)\n ) {\n // Compact the events before storing (like SQLite does)\n const compactedEvents = compactEvents(currentRunEvents);\n sharedStore.appendRun(request.threadId, store, {\n threadId: request.threadId,\n runId: request.input.runId,\n agentId: request.agent.agentId ?? \"default\",\n parentRunId,\n events: compactedEvents,\n // Snapshot all messages (input + generated) for the thread-messages endpoint\n messages: Array.isArray(request.agent.messages)\n ? [...request.agent.messages]\n : [],\n createdAt: Date.now(),\n });\n }\n\n // Complete the run. Guard the shared-store reset: if a newer run has\n // superseded this one (`currentRunId` changed), that run now owns the\n // store — don't clobber its state. Always complete THIS run's subjects.\n if (ownsThread) {\n store.currentEvents = null;\n store.currentRunId = null;\n store.agent = null;\n store.runSubject = null;\n store.stopRequested = false;\n store.isRunning = false;\n store.activeFinalize = null;\n }\n runSubject.complete();\n nextSubject.complete();\n // Time-scoped release: this run's events are now in historicRuns, so its\n // infinite ReplaySubject buffer is pure duplication — drop the store's\n // reference so it becomes collectable. The identity guard is what makes\n // this correct, and it does so differently on each path:\n //\n // - Owning path: no newer run superseded this one, so store.subject is\n // still nextSubject and the guard passes. The `if (ownsThread)` block\n // above just cleared isRunning and stopRequested, so connect() — which\n // bridges store.subject only while isRunning || stopRequested — will\n // not re-subscribe; it rebuilds this run's events from historicRuns\n // instead. Nulling the reference is therefore safe.\n //\n // - Superseded path (`onConcurrentRun: \"supersede\"`): a newer run has\n // already installed ITS subject and run id on the store, so the guard\n // fails and we leave store.subject untouched. Here isRunning/\n // stopRequested describe that live run (isRunning is typically true),\n // so it is precisely the identity guard — not those flags — that\n // prevents us from nulling the live run's subject and cutting\n // connect() off from the in-flight stream. This run's own buffer is no\n // longer referenced by the store and becomes collectable regardless.\n if (store.subject === nextSubject) {\n store.subject = null;\n }\n };\n\n try {\n await request.agent.runAgent(request.input, {\n onEvent: ({ event }) => {\n let processedEvent: BaseEvent = event;\n if (event.type === EventType.RUN_STARTED) {\n const runStartedEvent = event as RunStartedEvent;\n if (!runStartedEvent.input) {\n const sanitizedMessages = request.input.messages\n ? request.input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n )\n : undefined;\n const updatedInput = {\n ...request.input,\n ...(sanitizedMessages !== undefined\n ? { messages: sanitizedMessages }\n : {}),\n };\n runStartedEvent.input = updatedInput;\n processedEvent = runStartedEvent;\n }\n }\n\n runSubject.next(processedEvent); // For run() return - only agent events\n nextSubject.next(processedEvent); // For connect() / store - all events\n currentRunEvents.push(processedEvent); // Accumulate for storage\n },\n onNewMessage: ({ message }) => {\n // Called for each new message\n if (!seenMessageIds.has(message.id)) {\n seenMessageIds.add(message.id);\n }\n },\n onRunStartedEvent: () => {\n // Mark any messages from the input as seen so they aren't emitted twice\n if (request.input.messages) {\n for (const message of request.input.messages) {\n if (!seenMessageIds.has(message.id)) {\n seenMessageIds.add(message.id);\n }\n }\n }\n },\n });\n\n finalizeRun({});\n } catch (error) {\n const interruptionMessage =\n error instanceof Error ? error.message : String(error);\n finalizeRun({ interruptionMessage });\n }\n };\n\n // NOTE: we deliberately do NOT bridge the previous store subject into\n // `nextSubject`. `store.subject` is nulled the moment a run fully tears down\n // (identity guard in `finalizeRun`), so the previous subject is non-null\n // ONLY when this run is superseding a prior run that is still in flight or\n // finalizing. Forwarding that dying run's subject would replay its buffered\n // RUN_STARTED and push its terminal event (RUN_FINISHED/RUN_ERROR) into THIS\n // live run's stream — an invalid AG-UI sequence on a healthy run. A\n // superseded run's stream must stay isolated: it reaches only its own\n // connect() subscribers via its own (now-detached) subject, never the\n // superseding run's.\n\n // Start the agent execution immediately (not lazily). When finishing the\n // run throws on both paths, release the thread anyway: otherwise it stays\n // \"running\", refuses every later run and is never evicted.\n runAgent().catch((error) => {\n console.error(\n \"Failed to finish agent run\",\n { threadId: request.threadId, runId: request.input.runId },\n error,\n );\n if (store.currentRunId === request.input.runId) {\n store.currentEvents = null;\n store.currentRunId = null;\n store.agent = null;\n store.runSubject = null;\n store.stopRequested = false;\n store.isRunning = false;\n store.activeFinalize = null;\n }\n runSubject.complete();\n nextSubject.complete();\n if (store.subject === nextSubject) {\n store.subject = null;\n }\n });\n\n // Return the run subject (only agent events, no injected messages)\n return runSubject.asObservable();\n }\n\n connect(request: AgentRunnerConnectRequest): Observable<BaseEvent> {\n const found = sharedStore.peek(request.threadId);\n // A thread owned by another identity is indistinguishable from an\n // unknown one: no replay, no live bridge.\n const store =\n found && isVisibleTo(found, ɵresolveThreadOwner(request.ownerId))\n ? sharedStore.get(request.threadId, { touch: true })\n : undefined;\n const connectionSubject = new ReplaySubject<BaseEvent>(Infinity);\n\n if (!store) {\n // No store means no events\n connectionSubject.complete();\n return connectionSubject.asObservable();\n }\n\n // Collect all historic events from memory\n const allHistoricEvents: BaseEvent[] = [];\n for (const run of store.historicRuns) {\n allHistoricEvents.push(...run.events);\n }\n\n // Apply compaction to all historic events together (like SQLite)\n const compactedEvents = compactEvents(allHistoricEvents);\n\n // Emit compacted events and track message IDs\n const emittedMessageIds = new Set<string>();\n for (const event of compactedEvents) {\n connectionSubject.next(event);\n if (\"messageId\" in event && typeof event.messageId === \"string\") {\n emittedMessageIds.add(event.messageId);\n }\n }\n\n // Bridge active run to connection if exists\n if (store.subject && (store.isRunning || store.stopRequested)) {\n store.subject.subscribe({\n next: (event) => {\n // Skip message events that we've already emitted from historic\n if (\n \"messageId\" in event &&\n typeof event.messageId === \"string\" &&\n emittedMessageIds.has(event.messageId)\n ) {\n return;\n }\n connectionSubject.next(event);\n },\n complete: () => connectionSubject.complete(),\n error: (err) => connectionSubject.error(err),\n });\n } else {\n // No active run, complete after historic events\n connectionSubject.complete();\n }\n\n return connectionSubject.asObservable();\n }\n\n isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean> {\n const store = sharedStore.peek(request.threadId);\n // Another identity's thread reports \"not running\".\n if (!store || !isVisibleTo(store, ɵresolveThreadOwner(request.ownerId))) {\n return Promise.resolve(false);\n }\n return Promise.resolve(store.isRunning);\n }\n\n stop(request: AgentRunnerStopRequest): Promise<boolean | undefined> {\n const store = sharedStore.peek(request.threadId);\n if (!store || !store.isRunning) {\n return Promise.resolve(false);\n }\n // Another identity's run reports the same as \"no active run\".\n if (!isVisibleTo(store, ɵresolveThreadOwner(request.ownerId))) {\n return Promise.resolve(false);\n }\n if (request.runId !== undefined && store.currentRunId !== request.runId) {\n return Promise.resolve(false);\n }\n if (store.stopRequested) {\n return Promise.resolve(false);\n }\n\n store.stopRequested = true;\n store.isRunning = false;\n // Record the stop on the running run's OWN finalize control so its async\n // teardown finalizes as a clean RUN_FINISHED. This is the same object that\n // run's closure reads, so a later run cannot mislabel this stop.\n const finalizeControl = store.activeFinalize;\n if (finalizeControl) {\n finalizeControl.stopRequested = true;\n }\n\n const agent = store.agent;\n if (!agent) {\n store.stopRequested = false;\n store.isRunning = false;\n if (finalizeControl) {\n finalizeControl.stopRequested = false;\n }\n return Promise.resolve(false);\n }\n\n try {\n agent.abortRun();\n return Promise.resolve(true);\n } catch (error) {\n console.error(\"Failed to abort agent run\", error);\n store.stopRequested = false;\n store.isRunning = true;\n if (finalizeControl) {\n finalizeControl.stopRequested = false;\n }\n return Promise.resolve(false);\n }\n }\n\n /**\n * Returns a summary of every thread that `scope`'s owner holds in the\n * process-wide store, which every InMemoryAgentRunner shares. Without a\n * scope, the server owner's threads ({@link ɵSERVER_THREAD_OWNER}).\n *\n * This powers the local-dev fallback for `GET /threads` when the Intelligence\n * platform is not configured. Each entry mirrors the shape of a platform\n * `ThreadRecord` so the HTTP handler can use the same response envelope.\n */\n listThreads(scope?: LocalThreadEndpointScope): InMemoryThread[] {\n return sharedStore.listThreads(scope);\n }\n\n /**\n * Returns all messages for a thread, using the snapshot captured at the end\n * of the most recent run.\n *\n * This powers the local-dev fallback for `GET /threads/:threadId/messages`\n * when CopilotKit Intelligence is not configured. The returned `Message[]`\n * objects come directly from the ag-ui agent, so their shape is compatible\n * with CopilotKit Intelligence's `ThreadMessage` type.\n */\n getThreadMessages(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Message[] {\n const store = this.peekVisible(threadId, scope);\n if (!store) return [];\n // The thread's latest non-empty snapshot is held at the store level,\n // independent of `historicRuns` lifecycle, so run-cap eviction and\n // interleaved empty-snapshot runs can never lose it. Return a SHALLOW\n // (array-level) copy: a fresh array so a caller mutating array STRUCTURE\n // (push/splice/reassign elements) cannot affect the stored snapshot. We\n // deliberately do NOT deep-copy: `structuredClone` throws DataCloneError on a\n // non-cloneable message field, which would wedge the thread and hang SSE —\n // inconsistent with `ɵestimateBytes`, which tolerates the same bad-payload class.\n // The tradeoff is that the inner `Message` objects remain shared by reference with\n // the stored snapshot, so mutating a returned message's FIELD\n // (e.g. `getThreadMessages(t)[0].content = \"x\"`) is NOT isolated and would corrupt\n // the stored snapshot. That inner-object isolation is a known limitation tracked as\n // follow-up; callers must treat returned messages as read-only.\n return [...store.messagesSnapshot];\n }\n\n /**\n * Returns all AG-UI events for a thread, compacted across historic runs.\n *\n * Powers the local-dev fallback for `GET /threads/:threadId/events` when the\n * CopilotKit Intelligence is not configured. The compaction logic matches\n * the connection-replay path in {@link connect}, so the stream a\n * late-joining inspector sees matches what this method returns.\n */\n getThreadEvents(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): BaseEvent[] {\n const store = this.peekVisible(threadId, scope);\n if (!store || store.historicRuns.length === 0) return [];\n const all: BaseEvent[] = [];\n for (const run of store.historicRuns) all.push(...run.events);\n return compactEvents(all);\n }\n\n /**\n * Returns the agent state snapshot for a thread.\n *\n * Derived from the last `STATE_SNAPSHOT` in the compacted event stream. The\n * AG-UI `compactEvents` helper consolidates STATE_DELTA events and produces\n * a single trailing STATE_SNAPSHOT when state changes exist, so this is a\n * faithful view of state at the end of the most recent run.\n *\n * Returns `null` when the thread has never emitted a STATE_SNAPSHOT.\n */\n getThreadState(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Record<string, unknown> | null {\n const events = this.getThreadEvents(threadId, scope);\n // Walk backwards — the last snapshot wins.\n for (let i = events.length - 1; i >= 0; i--) {\n const event = events[i]!;\n if (event.type === EventType.STATE_SNAPSHOT) {\n const snapshot = (event as StateSnapshotEvent).snapshot;\n // Only plain objects satisfy the Record<string, unknown> contract.\n // `typeof [] === \"object\"` is true, so arrays must be rejected\n // explicitly to avoid returning an array typed as a Record.\n if (\n snapshot &&\n typeof snapshot === \"object\" &&\n !Array.isArray(snapshot)\n ) {\n // Return a defensive shallow copy so callers can't mutate the\n // snapshot object held inside the stored event (matches the\n // getThreadMessages defensive-copy approach).\n return { ...(snapshot as Record<string, unknown>) };\n }\n return null;\n }\n }\n return null;\n }\n\n /**\n * Clears the in-memory history of `scope`'s threads (without a scope, the\n * server owner's). A thread with a run still active or finalizing is kept;\n * see {@link ɵBoundedThreadStore.clear}.\n *\n * Powers the local-dev fallback for `POST /threads/clear`, letting consumers\n * (e.g. the demo's Clear button) reset to an empty thread list without\n * restarting the runtime. Intentionally not exposed on the Intelligence\n * platform path: there, thread history lives in a real database and must\n * not be wiped this way.\n */\n clearThreads(scope?: LocalThreadEndpointScope): void {\n sharedStore.clear({ ownerId: scopeOwner(scope) });\n }\n\n /**\n * False when the thread id is held by an owner other than `scope`'s: a\n * live thread, or the retained owner of an evicted or cleared one.\n */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean {\n return sharedStore.canClaim(threadId, scopeOwner(scope));\n }\n\n /** The thread's store, or `undefined` when unknown or not visible to `scope`. */\n private peekVisible(\n threadId: string,\n scope: LocalThreadEndpointScope | undefined,\n ): InMemoryEventStore | undefined {\n const store = sharedStore.peek(threadId);\n return store && isVisibleTo(store, scopeOwner(scope)) ? store : undefined;\n }\n}\n"],"mappings":";;;;;;;AAoEA,MAAa,qBAA+C;CAC1D,YAAY;CACZ,kBAAkB;CAClB,UAAU,MAAM,QAAQ;CACzB;;;;;;;;;;;;;AAcD,SAAS,cAAc,OAAwB;AAC7C,QAAO,UAAU,YAAa,OAAO,UAAU,MAAM,IAAI,SAAS;;;;;;;;;;;;;;;;;;AAmBpE,SAAgB,iBACd,QAC0B;CAC1B,MAAM,aAAa,EAAE,GAAG,QAAQ;AAChC,MAAK,MAAM,SAAS,OAAO,KACzB,mBACD,EAA8B;EAC7B,MAAM,QAAQ,OAAO;AACrB,MAAI,CAAC,cAAc,MAAM,EAAE;GACzB,MAAM,WAAW,mBAAmB;AACpC,cAAW,SAAS;AACpB,OAAI;AACF,YAAQ,KACN,6CAA6C,MAAM,SAC9C,OAAO,MAAM,CAAC,kEACE,OAAO,SAAS,CAAC,GACvC;WACK;;;AAKZ,QAAO;;AAGT,MAAM,oBACJ;AAIF,MAAM,0BACJ;;;;;;;AAYF,SAAgB,eAAe,OAAwB;AACrD,KAAI;AACF,SAAO,KAAK,UAAU,MAAM,EAAE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gBACE,UACA,OACa;EACb,MAAM,QAAQ,KAAK,YAAY,UAAU,MAAM;AAC/C,MAAI,CAAC,SAAS,MAAM,aAAa,WAAW,EAAG,QAAO,EAAE;EACxD,MAAM,MAAmB,EAAE;AAC3B,OAAK,MAAM,OAAO,MAAM,aAAc,KAAI,KAAK,GAAG,IAAI,OAAO;AAC7D,0CAAqB,IAAI;;;;;;;;;;;;CAa3B,eACE,UACA,OACgC;EAChC,MAAM,SAAS,KAAK,gBAAgB,UAAU,MAAM;AAEpD,OAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK;GAC3C,MAAM,QAAQ,OAAO;AACrB,OAAI,MAAM,SAASK,wBAAU,gBAAgB;IAC3C,MAAM,WAAY,MAA6B;AAI/C,QACE,YACA,OAAO,aAAa,YACpB,CAAC,MAAM,QAAQ,SAAS,CAKxB,QAAO,EAAE,GAAI,UAAsC;AAErD,WAAO;;;AAGX,SAAO;;;;;;;;;;;;;CAcT,aAAa,OAAwC;AACnD,cAAY,MAAM,EAAE,SAAS,WAAW,MAAM,EAAE,CAAC;;;;;;CAOnD,mBACE,UACA,OACS;AACT,SAAO,YAAY,SAAS,UAAU,WAAW,MAAM,CAAC;;;CAI1D,AAAQ,YACN,UACA,OACgC;EAChC,MAAM,QAAQ,YAAY,KAAK,SAAS;AACxC,SAAO,SAAS,YAAY,OAAO,WAAW,MAAM,CAAC,GAAG,QAAQ"}
|
|
1
|
+
{"version":3,"file":"in-memory.cjs","names":["ɵresolveThreadOwner","ɵSERVER_THREAD_OWNER","AgentRunner","ThreadAccessDeniedError","ThreadAlreadyRunningError","EventType","ReplaySubject"],"sources":["../../../src/runtime/runner/in-memory.ts"],"sourcesContent":["import type {\n AgentRunnerConnectRequest,\n AgentRunnerIsRunningRequest,\n AgentRunnerRunRequest,\n LocalThreadEndpointScope,\n} from \"./agent-runner\";\nimport {\n AgentRunner,\n ThreadAccessDeniedError,\n ThreadAlreadyRunningError,\n ɵSERVER_THREAD_OWNER,\n ɵresolveThreadOwner,\n} from \"./agent-runner\";\nimport type { AgentRunnerStopRequest } from \"./agent-runner\";\nimport type { Observable } from \"rxjs\";\nimport { ReplaySubject } from \"rxjs\";\nimport type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunStartedEvent,\n StateSnapshotEvent,\n} from \"@ag-ui/client\";\nimport { EventType, compactEvents } from \"@ag-ui/client\";\nimport { finalizeRunEvents } from \"@copilotkit/shared\";\n\nexport interface InMemoryLimits {\n /** LRU cap on distinct threads. */\n maxThreads?: number;\n /** FIFO cap on runs kept per thread. `Infinity` or `0` disables the cap. */\n maxRunsPerThread?: number;\n /**\n * Approximate byte ceiling on RETAINED thread/run history. Enforced at run\n * completion (in `appendRun`), where LRU non-running threads are evicted to\n * keep the total under this limit.\n *\n * Limitation: this bounds only history that has already been committed. A\n * single in-flight run's buffered events (`currentRunEvents` and the two\n * `ReplaySubject<BaseEvent>(Infinity)` buffers in `run()`) are NOT counted\n * until that run completes, so `maxBytes` does not bound a single runaway\n * run mid-stream.\n *\n * Limitation: byte eviction drops only other LRU non-running threads and\n * never self-evicts the active/just-appended thread, so a single dominant\n * thread's own retained history is not byte-trimmed (bounded only by\n * `maxRunsPerThread`). `maxBytes` is thus a cross-thread ceiling enforced by\n * evicting OTHER threads, not a per-thread cap.\n */\n maxBytes?: number;\n}\n\n/**\n * Constructor options for {@link InMemoryAgentRunner}.\n *\n * Extends {@link InMemoryLimits} so bounds can be passed inline alongside the\n * per-runner behavior flags. Be aware of the scope difference: the limits\n * reconfigure the process-global store shared by every runner, whereas\n * `onConcurrentRun` applies only to the runner instance it is passed to.\n */\nexport interface InMemoryAgentRunnerOptions extends InMemoryLimits {\n /**\n * How to handle a `run()` for a thread that already has an in-flight run.\n * `\"throw\"` (default) rejects with \"Thread already running\". `\"supersede\"`\n * aborts the prior run and starts the new one.\n */\n onConcurrentRun?: \"throw\" | \"supersede\";\n}\n\nexport const ɵINMEMORY_DEFAULTS: Required<InMemoryLimits> = {\n maxThreads: 1000,\n maxRunsPerThread: 100,\n maxBytes: 512 * 1024 ** 2,\n};\n\n/**\n * A limit value is well-formed iff it is a non-negative integer OR `+Infinity`.\n * `+Infinity` is the documented \"disabled/unbounded\" sentinel and `0` is the\n * documented run-cap disable sentinel; both are non-negative and pass. Every\n * enforcement site (`evictThreadsIfNeeded`, `enforceRunCap`,\n * `evictByBytesIfNeeded`) compares its counter against the limit with `>` in a\n * `while`/`if` guard, so only these shapes keep those loops finite and correct.\n * Rejected: negatives (drive `count > -1` true on an empty collection, so\n * `enforceRunCap` `shift()!`s `undefined` and throws), `-Infinity` (loops never\n * terminate their intent — always \"over\"), `NaN` (every `>` is false, silently\n * disabling the bound), and non-integer finites (fractional caps are nonsense).\n */\nfunction ɵisValidLimit(value: number): boolean {\n return value === Infinity || (Number.isInteger(value) && value >= 0);\n}\n\n/**\n * Normalize a fully-resolved limits bag so every field is well-formed before it\n * can reach an enforcement loop. Each field is validated independently against\n * {@link ɵisValidLimit}; an invalid value is CLAMPED to its\n * {@link ɵINMEMORY_DEFAULTS} floor and a single `console.warn` naming the field\n * and the received value is emitted.\n *\n * Clamp-and-warn (rather than throw) is deliberate and matches this file's\n * established posture toward bad input: `ɵestimateBytes` swallows serialization\n * failures and returns 0, the limits-clobber path warns rather than throwing,\n * and both the eviction and clobber logs are wrapped so \"logging must never\n * break construction/a run\". Constructing a bounded in-memory runner is a\n * best-effort, non-durable convenience; a typo'd bound must degrade to a safe\n * default, never abort construction or (worse) surface later as an unhandled\n * rejection from the fire-and-forget finalize path.\n */\nexport function ɵnormalizeLimits(\n limits: Required<InMemoryLimits>,\n): Required<InMemoryLimits> {\n const normalized = { ...limits };\n for (const field of Object.keys(\n ɵINMEMORY_DEFAULTS,\n ) as (keyof InMemoryLimits)[]) {\n const value = limits[field];\n if (!ɵisValidLimit(value)) {\n const fallback = ɵINMEMORY_DEFAULTS[field];\n normalized[field] = fallback;\n try {\n console.warn(\n `[CopilotKit] InMemoryAgentRunner: invalid ${field} value ` +\n `${String(value)} (expected a non-negative integer or Infinity); ` +\n `falling back to ${String(fallback)}.`,\n );\n } catch {\n // best-effort: logging must never break construction\n }\n }\n }\n return normalized;\n}\n\nconst EVICTION_GUIDANCE =\n \"[CopilotKit] InMemoryAgentRunner evicted in-memory thread history to stay \" +\n \"under memory limits. This runner is bounded and non-durable by design. For \" +\n \"durable or production threads, configure an Intelligence backend.\";\n\nconst LIMITS_CLOBBER_GUIDANCE =\n \"[CopilotKit] InMemoryAgentRunner was constructed with in-memory limits that \" +\n \"differ from the already-configured process-global store; the last-constructed \" +\n \"runner's limits apply to ALL in-memory threads (the store is shared per-process). \" +\n \"Configure a single consistent set of limits, or use an Intelligence backend for \" +\n \"isolated bounds.\";\n\n/**\n * Best-effort approximate byte size of a value, via serialized length.\n * Never throws — returns 0 when the value cannot be serialized. This is an\n * approximation (UTF-16 length, not exact heap bytes), used only for relative\n * accounting against `maxBytes`.\n */\nexport function ɵestimateBytes(value: unknown): number {\n try {\n return JSON.stringify(value)?.length ?? 0;\n } catch {\n return 0;\n }\n}\n\n/**\n * Per-run finalize intent, captured once when a run starts and mutated (only)\n * by whoever aborts THAT run — `stop()` or a superseding `run()`. The run's own\n * teardown reads this captured holder instead of the shared, mutable\n * `store.stopRequested`, so a later run that resets store state can never cause\n * an intentionally-stopped run to be finalized as an error (or vice versa).\n */\ninterface RunFinalizeControl {\n /** True once THIS run has been asked to stop (clean stop, not an error). */\n stopRequested: boolean;\n}\n\ninterface HistoricRun {\n threadId: string;\n runId: string;\n /** ID of the agent that executed this run. */\n agentId: string;\n parentRunId: string | null;\n events: BaseEvent[];\n /**\n * Snapshot of all messages (input + generated) at the end of this run, as\n * passed in by the caller. NOTE: `BoundedThreadStore.appendRun` moves this\n * snapshot to the THREAD level (`InMemoryEventStore.messagesSnapshot`) and\n * clears this field to `[]`, so a stored HistoricRun never carries messages.\n * The thread-messages fallback reads the thread-level snapshot, not this.\n */\n messages: Message[];\n createdAt: number;\n /** Approximate retained byte size of `events`; set by BoundedThreadStore at append. */\n approxEventBytes?: number;\n /**\n * Legacy field retained for shape compatibility. `appendRun` always zeroes it\n * because message bytes are accounted at the thread level, not per run.\n */\n approxMessageBytes?: number;\n}\n\n/**\n * Lightweight thread summary returned by {@link InMemoryAgentRunner.listThreads}.\n * Shape matches CopilotKit Intelligence's ThreadRecord so the same HTTP\n * response envelope can be used for both backends.\n */\nexport interface InMemoryThread {\n id: string;\n name: string | null;\n agentId: string;\n organizationId: \"\"; // always empty in in-memory mode\n /** Identity that owns the thread; `\"\"` for a thread created without identity. */\n createdById: string;\n archived: false; // always false in in-memory mode\n createdAt: string;\n updatedAt: string;\n}\n\nclass InMemoryEventStore {\n /**\n * @param ownerId Identity that owns this thread, recorded when the thread is\n * created by its first run. `\"\"` is the anonymous owner;\n * {@link ɵSERVER_THREAD_OWNER} is the owner of a thread created server-side.\n */\n constructor(\n public threadId: string,\n public readonly ownerId: string,\n ) {}\n\n /** The subject that current consumers subscribe to. */\n subject: ReplaySubject<BaseEvent> | null = null;\n\n /** True while a run is actively producing events. */\n isRunning = false;\n\n /** Current run ID */\n currentRunId: string | null = null;\n\n /** Historic completed runs */\n historicRuns: HistoricRun[] = [];\n\n /** Currently running agent instance (if any). */\n agent: AbstractAgent | null = null;\n\n /** Subject returned from run() while the run is active. */\n runSubject: ReplaySubject<BaseEvent> | null = null;\n\n /**\n * Thread-level lifecycle flag: true once a stop/supersede has been requested\n * for the currently-owning run but that run has not yet finalized. Drives\n * eviction protection, the connect() bridge, and stop() de-dup. This is NOT\n * the finalize intent read by a run's teardown — that lives per-run on\n * {@link activeFinalize}, so a superseding run resetting this field cannot\n * mislabel the run it replaced. A new run resets this to false when it takes\n * ownership.\n */\n stopRequested = false;\n\n /**\n * Finalize control of the currently-owning run. `stop()` and a superseding\n * `run()` flip the owning run's flag through this reference; each run also\n * captures the SAME object in its closure, so its teardown finalizes against\n * its own intent regardless of what a later run does to the store.\n */\n activeFinalize: RunFinalizeControl | null = null;\n\n /** Reference to the events emitted in the current run. */\n currentEvents: BaseEvent[] | null = null;\n\n /**\n * The thread's single latest NON-EMPTY message snapshot, held at the THREAD\n * level (independent of `historicRuns` lifecycle). Decoupling the snapshot\n * from per-run storage means run-cap FIFO eviction and interleaved\n * empty-snapshot runs can never drop or pin the thread's message history.\n */\n messagesSnapshot: Message[] = [];\n\n /** Approximate retained byte size of `messagesSnapshot`. */\n approxMessagesSnapshotBytes = 0;\n\n /**\n * The thread's true creation timestamp (epoch ms), captured from the FIRST\n * run ever appended and held at the THREAD level (independent of\n * `historicRuns` lifecycle). Decoupling it from per-run storage means run-cap\n * FIFO eviction — which shifts the oldest entries off `historicRuns` — can\n * never move the reported creation time forward. `null` until the first run\n * lands. Mirrors the `messagesSnapshot` thread-level decoupling.\n */\n createdAt: number | null = null;\n}\n\n/**\n * True when a caller acting as `owner` may reach `store`: only the thread's\n * own owner may. Resolve an optional owner or scope with\n * {@link ɵresolveThreadOwner} first; an omitted one is the server owner, never\n * \"every thread\".\n */\nfunction isVisibleTo(store: InMemoryEventStore, owner: string): boolean {\n return store.ownerId === owner;\n}\n\n/** The owner a Thread endpoint call acts as. */\nfunction scopeOwner(scope: LocalThreadEndpointScope | undefined): string {\n return ɵresolveThreadOwner(scope?.ownerId);\n}\n\n/**\n * How long, and how many, owner records the store keeps for threads that left\n * it through LRU eviction or a scoped clear. See\n * {@link ɵBoundedThreadStore.ownerOf}.\n *\n * When a record is added over a limit, expired records go first; then, when\n * the record's owner holds more than `maxEntriesPerOwner`, that owner's\n * oldest record; then, over `maxEntries`, the oldest record of any owner. So\n * one identity that churns threads (anonymous callers share one identity)\n * only displaces its own records. Residual risk: many distinct identities\n * together can still exceed `maxEntries` and push out another identity's\n * live record. That frees the id for a new owner but leaks nothing, since\n * the removed thread's history is already gone, and it needs the victim's\n * thread id.\n */\nexport interface ɵOwnerRetention {\n /** Milliseconds an owner record is kept after its thread was removed. */\n ttlMs: number;\n /** Most owner records kept in all. */\n maxEntries: number;\n /** Most owner records kept for one owner. */\n maxEntriesPerOwner: number;\n /** Clock, replaceable in tests. */\n now: () => number;\n}\n\nexport const ɵOWNER_RETENTION_DEFAULTS: ɵOwnerRetention = {\n ttlMs: 24 * 60 * 60 * 1000,\n maxEntries: 100_000,\n maxEntriesPerOwner: 10_000,\n now: () => Date.now(),\n};\n\nexport class ɵBoundedThreadStore {\n private readonly map = new Map<string, InMemoryEventStore>();\n /**\n * Owners of threads that were removed from `map`, oldest first. A removed\n * thread's history is gone, but its id stays reserved for its owner until\n * the record expires, so another identity cannot claim the id and receive\n * the owner's next runs or later replays.\n */\n private readonly removedOwners = new Map<\n string,\n { ownerId: string; removedAt: number }\n >();\n /** The ids in `removedOwners`, per owner, oldest first. */\n private readonly removedOwnersByOwner = new Map<string, Set<string>>();\n private ownerRetention: ɵOwnerRetention = ɵOWNER_RETENTION_DEFAULTS;\n private totalBytes = 0;\n private warned = false;\n /** True once limits have been EXPLICITLY set (via setLimits), not just the constructor default. */\n private limitsExplicitlySet = false;\n /** Warn-once latch for the clobber warning, kept distinct from the eviction `warned` latch. */\n private clobberWarned = false;\n\n private limits: Required<InMemoryLimits>;\n\n constructor(limits: Required<InMemoryLimits>) {\n // Normalize once at construction so `this.limits` is ALWAYS well-formed,\n // regardless of entry point (direct construction or a later `setLimits`).\n this.limits = ɵnormalizeLimits(limits);\n }\n\n get byteTotal(): number {\n return this.totalBytes;\n }\n\n /**\n * The store's CURRENT effective bounds. Exposed (with the `ɵ` internal-API\n * prefix) so a partial `setLimits` can coalesce unspecified fields against the\n * live config rather than the hardcoded {@link ɵINMEMORY_DEFAULTS} — a partial\n * update must be a partial update, never a silent reset of the fields the\n * caller did not mention. Returns a copy so callers cannot mutate the store's\n * bounds through it.\n */\n get ɵlimits(): Required<InMemoryLimits> {\n return { ...this.limits };\n }\n\n /**\n * Reconfigure the process-global store's bounds. Called by the\n * {@link InMemoryAgentRunner} constructor when limits are passed. Because the\n * store is a per-process singleton, this replaces the bounds for ALL in-memory\n * threads. Emits {@link LIMITS_CLOBBER_GUIDANCE} at most ONCE per store when a\n * SECOND (or later) explicit set arrives whose resolved values differ from the\n * prior explicit set — i.e. a genuine clobber of an already-customized config.\n * The first explicit customization (defaults → custom) is the intended\n * override and never warns; identical re-sets never warn.\n */\n setLimits(limits: Required<InMemoryLimits>): void {\n // Normalize FIRST so invalid fields can never reach an enforcement loop and\n // so the clobber comparison below is against the EFFECTIVE (clamped) values,\n // not the raw ones — a typo'd bound that clamps to the current default is not\n // a genuine clobber and must not warn.\n const normalized = ɵnormalizeLimits(limits);\n if (\n this.limitsExplicitlySet &&\n !this.clobberWarned &&\n (normalized.maxThreads !== this.limits.maxThreads ||\n normalized.maxRunsPerThread !== this.limits.maxRunsPerThread ||\n normalized.maxBytes !== this.limits.maxBytes)\n ) {\n this.clobberWarned = true;\n try {\n console.warn(LIMITS_CLOBBER_GUIDANCE);\n } catch {\n // best-effort: logging must never break construction\n }\n }\n this.limitsExplicitlySet = true;\n this.limits = normalized;\n }\n\n get size(): number {\n return this.map.size;\n }\n\n /** Re-insert at the tail so Map iteration order stays LRU-first. */\n private touchOrder(threadId: string, store: InMemoryEventStore): void {\n this.map.delete(threadId);\n this.map.set(threadId, store);\n }\n\n /**\n * The thread's store, created and owned by `ownerId` when it does not exist\n * yet. An existing store keeps its owner; callers check access first.\n */\n getOrCreate(\n threadId: string,\n ownerId: string = ɵSERVER_THREAD_OWNER,\n ): InMemoryEventStore {\n const existing = this.map.get(threadId);\n if (existing) {\n this.touchOrder(threadId, existing);\n return existing;\n }\n const store = new InMemoryEventStore(threadId, ownerId);\n // The live store now records the owner.\n this.forgetOwner(threadId);\n this.map.set(threadId, store);\n this.evictThreadsIfNeeded(threadId);\n return store;\n }\n\n get(\n threadId: string,\n opts: { touch: boolean },\n ): InMemoryEventStore | undefined {\n const store = this.map.get(threadId);\n if (store && opts.touch) this.touchOrder(threadId, store);\n return store;\n }\n\n peek(threadId: string): InMemoryEventStore | undefined {\n return this.map.get(threadId);\n }\n\n /**\n * Evict the least-recently-used thread that is neither running NOR\n * mid-finalization. Returns false if none evictable. The `protect` thread\n * (typically the one just created) is never evicted, so a fresh thread is not\n * immediately dropped when it is the only non-running candidate.\n *\n * A thread is skipped while `isRunning` OR `stopRequested` is set.\n * `stop()` flips `isRunning` to false the moment it aborts the agent, but the\n * run keeps finalizing asynchronously (the abort trips the `catch` in\n * `runAgent`, which later calls `appendRun`). During that window\n * `stopRequested` stays true; evicting the thread then would make the pending\n * `appendRun` hit `if (!store) return` and silently drop the aborted run's\n * history. Guarding on `stopRequested` keeps the thread alive until\n * finalization completes.\n */\n private evictOneLru(protect?: string): boolean {\n for (const [threadId, store] of this.map) {\n if (threadId === protect) continue; // never evict the just-created thread\n // never evict a running or still-finalizing (stop-requested) thread\n if (store.isRunning || store.stopRequested) continue;\n this.removeThread(threadId, store);\n this.noteEviction();\n return true;\n }\n return false;\n }\n\n /**\n * Append a finished run to `writer`, the store its run started on. Nothing is\n * written when `writer` is no longer the live store for `threadId` (the thread\n * was removed, or removed and claimed again): a run must never write into a\n * thread it did not start on, which may now belong to another owner.\n */\n appendRun(\n threadId: string,\n writer: InMemoryEventStore | undefined,\n run: HistoricRun,\n ): void {\n const store = this.map.get(threadId);\n if (!store || store !== writer) return;\n\n // Thread-level creation timestamp: capture the FIRST run's createdAt once\n // and never overwrite it. Held on the store (not derived from\n // `historicRuns[0]`) so run-cap FIFO eviction of the oldest runs cannot\n // drift the thread's reported creation time forward. Mirrors the\n // thread-level `messagesSnapshot` decoupling below.\n if (store.createdAt === null) {\n store.createdAt = run.createdAt;\n }\n\n // Thread-level message snapshot: keep the single latest NON-EMPTY snapshot\n // on the store, decoupled from `historicRuns`. When the incoming run\n // carries a non-empty snapshot, replace the thread's snapshot (adjusting\n // byte accounting). When it's empty (non-array `agent.messages` or an\n // error-path run), leave the existing thread snapshot untouched so history\n // is never lost. The snapshot never lives on a HistoricRun, so run-cap FIFO\n // eviction can never drop it and an interleaved empty run can never pin it.\n if (run.messages.length > 0) {\n this.totalBytes -= store.approxMessagesSnapshotBytes;\n // Store the incoming array directly (SHALLOW, array-level copy). `run.messages`\n // is already a fresh `[...agent.messages]` array created in run(), so we own the\n // array and it is decoupled from `agent.messages` at the array level (push/splice\n // on the agent's array cannot mutate our snapshot). We deliberately do NOT deep-copy\n // here: `structuredClone` throws DataCloneError on a non-cloneable message field,\n // which would wedge the thread and hang SSE — inconsistent with `ɵestimateBytes`,\n // which tolerates the same bad-payload class. The tradeoff is that the inner\n // `Message` objects remain shared by reference with `agent.messages`, so an agent\n // that mutates its own message objects IN PLACE after the run can still be observed\n // through this snapshot. That inner-object isolation is a known limitation tracked as\n // follow-up; callers must treat returned messages as read-only. Estimate bytes on the\n // same value so accounting matches exactly what is retained.\n store.messagesSnapshot = run.messages;\n store.approxMessagesSnapshotBytes = ɵestimateBytes(run.messages);\n this.totalBytes += store.approxMessagesSnapshotBytes;\n }\n\n // Do not carry message bytes on the HistoricRun: the snapshot is now tracked\n // at the thread level, so historicRuns must never account message bytes.\n run.messages = [];\n run.approxMessageBytes = 0;\n\n // Compute this run's approximate event size once, at append time.\n run.approxEventBytes = ɵestimateBytes(run.events);\n store.historicRuns.push(run);\n this.totalBytes += run.approxEventBytes;\n this.touchOrder(threadId, store);\n\n this.enforceRunCap(store);\n this.evictByBytesIfNeeded(threadId);\n }\n\n private enforceRunCap(store: InMemoryEventStore): void {\n const cap = this.limits.maxRunsPerThread;\n if (!cap || cap === Infinity) return; // 0 or Infinity → disabled\n while (store.historicRuns.length > cap) {\n const dropped = store.historicRuns.shift()!;\n // Only event bytes live on a HistoricRun; the message snapshot is tracked\n // at the thread level and survives run-cap eviction.\n this.totalBytes -= dropped.approxEventBytes ?? 0;\n // Per-thread run-cap trimming is also eviction — history is being dropped.\n // Route it through the SAME warn-once latch as whole-thread LRU eviction so\n // this shows up in logs rather than as silent data loss. `noteEviction` is\n // latched (one warning per store, reset by `clear()`), so a hot thread that\n // trims on every subsequent append warns once, never per dropped run. The\n // loop only runs when a run is ACTUALLY over the cap, so a disabled or\n // under-cap `enforceRunCap` stays silent (it returned / never entered here).\n this.noteEviction();\n }\n }\n\n /**\n * Trim the store back under the byte ceiling by evicting LRU non-running\n * threads. `protect` (the just-appended thread) is never self-evicted, so a\n * fresh run pushes OTHER threads out rather than dropping itself.\n */\n private evictByBytesIfNeeded(protect?: string): void {\n while (this.totalBytes > this.limits.maxBytes) {\n if (!this.evictOneLru(protect)) break; // only protected/running threads left → accept overage\n }\n }\n\n private removeThread(threadId: string, store: InMemoryEventStore): void {\n for (const run of store.historicRuns) {\n this.totalBytes -= run.approxEventBytes ?? 0;\n }\n // The thread's message snapshot is tracked at the store level, so it must\n // be reclaimed here in addition to the per-run event bytes.\n this.totalBytes -= store.approxMessagesSnapshotBytes;\n this.map.delete(threadId);\n this.rememberOwner(threadId, store.ownerId);\n }\n\n /**\n * Keep the owner of a removed thread, within the retention bounds. See\n * {@link ɵOwnerRetention} for which records go first over a limit.\n */\n private rememberOwner(threadId: string, ownerId: string): void {\n const { maxEntries, maxEntriesPerOwner, now } = this.ownerRetention;\n this.forgetOwner(threadId); // re-insert at the tail (newest)\n this.removedOwners.set(threadId, { ownerId, removedAt: now() });\n let owned = this.removedOwnersByOwner.get(ownerId);\n if (!owned) {\n owned = new Set();\n this.removedOwnersByOwner.set(ownerId, owned);\n }\n owned.add(threadId);\n this.pruneRemovedOwners();\n while (owned.size > maxEntriesPerOwner) {\n const oldest = owned.values().next().value;\n if (oldest === undefined) break;\n this.forgetOwner(oldest);\n }\n while (this.removedOwners.size > maxEntries) {\n const oldest = this.removedOwners.keys().next().value;\n if (oldest === undefined) break;\n this.forgetOwner(oldest);\n }\n }\n\n /** Remove the owner record of `threadId`, if any. */\n private forgetOwner(threadId: string): void {\n const record = this.removedOwners.get(threadId);\n if (!record) return;\n this.removedOwners.delete(threadId);\n const owned = this.removedOwnersByOwner.get(record.ownerId);\n owned?.delete(threadId);\n if (owned?.size === 0) this.removedOwnersByOwner.delete(record.ownerId);\n }\n\n /** Drop expired owner records. They are oldest first, so stop at the first live one. */\n private pruneRemovedOwners(): void {\n const { ttlMs, now } = this.ownerRetention;\n const cutoff = now() - ttlMs;\n for (const [threadId, record] of this.removedOwners) {\n if (record.removedAt >= cutoff) break;\n this.forgetOwner(threadId);\n }\n }\n\n /**\n * Owner of `threadId`: the live thread's owner, or the retained owner of a\n * thread that was evicted or cleared. `undefined` when nobody owns the id, so\n * the next run may claim it.\n */\n ownerOf(threadId: string): string | undefined {\n const store = this.map.get(threadId);\n if (store) return store.ownerId;\n this.pruneRemovedOwners();\n const record = this.removedOwners.get(threadId);\n if (!record) return undefined;\n const { ttlMs, now } = this.ownerRetention;\n if (record.removedAt < now() - ttlMs) {\n this.forgetOwner(threadId);\n return undefined;\n }\n return record.ownerId;\n }\n\n /** True when a caller acting as `owner` may run on, or claim, `threadId`. */\n canClaim(threadId: string, owner: string): boolean {\n const current = this.ownerOf(threadId);\n return current === undefined || current === owner;\n }\n\n /**\n * Replace the owner-record retention. Omitted fields fall back to\n * {@link ɵOWNER_RETENTION_DEFAULTS}. Internal: for tests.\n */\n ɵsetOwnerRetention(retention: Partial<ɵOwnerRetention>): void {\n this.ownerRetention = { ...ɵOWNER_RETENTION_DEFAULTS, ...retention };\n }\n\n private evictThreadsIfNeeded(protect?: string): void {\n while (this.map.size > this.limits.maxThreads) {\n if (!this.evictOneLru(protect)) break; // everything evictable is running → accept overage\n }\n }\n\n private noteEviction(): void {\n if (this.warned) return;\n this.warned = true;\n try {\n console.warn(EVICTION_GUIDANCE);\n } catch {\n // best-effort: logging must never break a run\n }\n }\n\n listThreads(scope?: LocalThreadEndpointScope): InMemoryThread[] {\n const threads: InMemoryThread[] = [];\n for (const [threadId, store] of this.map) {\n if (store.historicRuns.length === 0) continue;\n if (!isVisibleTo(store, scopeOwner(scope))) continue;\n const lastRun = store.historicRuns[store.historicRuns.length - 1]!;\n // Creation time comes from the thread-level `store.createdAt` (the first\n // run ever appended), NOT `historicRuns[0]` (the oldest RETAINED run):\n // run-cap FIFO eviction drops the oldest retained runs, so deriving it\n // from `historicRuns[0]` would silently drift the timestamp forward over\n // a thread's lifetime. `updatedAt` stays on `lastRun` because FIFO\n // eviction removes from the FRONT, so the newest run is never evicted.\n // The `?? lastRun.createdAt` fallback is defensive only: any thread with\n // runs has had `store.createdAt` set by `appendRun`.\n threads.push({\n id: threadId,\n name: null,\n agentId: lastRun.agentId,\n organizationId: \"\",\n createdById: store.ownerId,\n archived: false,\n createdAt: new Date(store.createdAt ?? lastRun.createdAt).toISOString(),\n updatedAt: new Date(lastRun.createdAt).toISOString(),\n });\n }\n return threads.sort(\n (a, b) =>\n new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),\n );\n }\n\n /**\n * Removes every thread visible to `scope`, except threads that are running\n * or still finalizing: removing one would drop its owner record while its\n * run still writes, so another identity could claim the id. Those threads\n * stay, as in `evictOneLru`. A scoped clear leaves other owners' threads\n * untouched.\n *\n * Without a scope the whole store is reset, running threads included. That\n * is an internal reset for tests; `appendRun` keeps an orphaned run from\n * writing into a thread created after the reset.\n */\n clear(scope?: LocalThreadEndpointScope): void {\n if (scope !== undefined) {\n // Deleting the current entry while iterating a Map is safe.\n for (const [threadId, store] of this.map) {\n if (store.isRunning || store.stopRequested) continue;\n if (isVisibleTo(store, scopeOwner(scope)))\n this.removeThread(threadId, store);\n }\n return;\n }\n this.map.clear();\n this.removedOwners.clear();\n this.removedOwnersByOwner.clear();\n this.totalBytes = 0;\n this.warned = false;\n }\n}\n\n/**\n * Process-wide singleton backing every {@link InMemoryAgentRunner}. Exported\n * (with the `ɵ` internal-API prefix) so tests can inspect the exact store the\n * runner writes to; not part of the public API.\n */\nexport const ɵGLOBAL_STORE = new ɵBoundedThreadStore(ɵINMEMORY_DEFAULTS);\nconst sharedStore = ɵGLOBAL_STORE;\n\nexport class InMemoryAgentRunner extends AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints = true;\n\n /**\n * How to handle a `run()` for a thread that already has an in-flight run.\n * `\"throw\"` (default) preserves the historic behavior. `\"supersede\"` aborts\n * the prior run (mirroring `stop()`) and starts the new one — opted into by\n * the hosted-bot listener so a fast follow-up turn on the same thread cleanly\n * replaces a still-running (or wedged) prior turn instead of erroring with\n * \"Thread already running\".\n */\n private readonly onConcurrentRun: \"throw\" | \"supersede\";\n\n /**\n * @param options Per-runner behavior (`onConcurrentRun`) plus optional bounds\n * for the in-memory store ({@link InMemoryLimits}).\n *\n * Note the differing scopes: `onConcurrentRun` is per-runner instance, while\n * the limits reconfigure the PROCESS-GLOBAL store shared by every\n * `InMemoryAgentRunner`. Omit the limits for safe defaults\n * ({@link ɵINMEMORY_DEFAULTS}); passing none leaves the store untouched. When\n * multiple runners are constructed with differing limits, the last-constructed\n * wins — in practice the OSS/SSE default construction passes nothing. If a\n * second (or later) runner is constructed with limits that DIFFER from an\n * already-customized store, a one-time `console.warn` is emitted to signal that\n * the shared store's bounds are being clobbered for ALL in-memory threads.\n */\n constructor(options?: InMemoryAgentRunnerOptions) {\n super();\n const { onConcurrentRun, ...limits } = options ?? {};\n this.onConcurrentRun = onConcurrentRun ?? \"throw\";\n\n // Only reconfigure the shared store when a bound was actually supplied.\n // `new InMemoryAgentRunner({ onConcurrentRun: \"supersede\" })` must stay\n // inert with respect to limits.\n if (\n limits.maxThreads !== undefined ||\n limits.maxRunsPerThread !== undefined ||\n limits.maxBytes !== undefined\n ) {\n // Coalesce each unspecified field against the store's CURRENT effective\n // limits, NOT ɵINMEMORY_DEFAULTS. The store is process-global, so tuning\n // one bound must leave every previously-customized sibling bound intact —\n // a partial update stays a partial update instead of silently resetting the\n // fields the caller never mentioned. Passing all three (e.g.\n // ɵINMEMORY_DEFAULTS) still fully replaces the config, so the defaults-\n // restore path is unaffected.\n const current = sharedStore.ɵlimits;\n sharedStore.setLimits({\n maxThreads: limits.maxThreads ?? current.maxThreads,\n maxRunsPerThread: limits.maxRunsPerThread ?? current.maxRunsPerThread,\n maxBytes: limits.maxBytes ?? current.maxBytes,\n });\n }\n }\n\n run(request: AgentRunnerRunRequest): Observable<BaseEvent> {\n // A thread belongs to the identity of its first run. Check before\n // `getOrCreate` so a refused run does not touch the thread's LRU position.\n const owner = ɵresolveThreadOwner(request.ownerId);\n if (!sharedStore.canClaim(request.threadId, owner)) {\n throw new ThreadAccessDeniedError();\n }\n const store = sharedStore.getOrCreate(request.threadId, owner);\n\n // Enter the concurrency branch whenever a prior run still owns the thread —\n // either actively running OR still finalizing after a stop()/supersede.\n // `stop()` flips `isRunning` to false the instant it aborts the agent, but\n // the run keeps finalizing asynchronously (`stopRequested` stays true).\n // Gating on `isRunning` alone let a `run()` slip through that window\n // unhandled: no supersede/throw, no per-run intent capture, and a leaked\n // bridge from the dying run's subject.\n if (store.isRunning || store.stopRequested) {\n if (this.onConcurrentRun !== \"supersede\") {\n throw new ThreadAlreadyRunningError();\n }\n // Supersede: abort the prior (possibly wedged) run so this one can start.\n // Mirrors stop(). Record the prior run's OWN finalize intent on its\n // captured control BEFORE resetting the shared store flags for the new\n // run: a supersede is a clean stop of the prior run, so its async teardown\n // must finalize as RUN_FINISHED, never a synthetic RUN_ERROR. The prior\n // run's async finalization is prevented from clobbering this run's state\n // by the run-id guard below.\n const priorAgent = store.agent;\n const priorFinalize = store.activeFinalize;\n if (priorFinalize) {\n priorFinalize.stopRequested = true;\n }\n store.isRunning = false;\n if (priorAgent) {\n try {\n priorAgent.abortRun();\n } catch (error) {\n console.error(\"Failed to abort superseded run\", error);\n }\n }\n }\n store.isRunning = true;\n store.currentRunId = request.input.runId;\n store.agent = request.agent;\n store.stopRequested = false;\n\n // Per-run finalize control. This run's teardown reads THIS captured holder\n // (never the shared `store.stopRequested`, which a later run resets), so an\n // aborted run is always finalized against its own stop-intent.\n const finalizeControl: RunFinalizeControl = { stopRequested: false };\n store.activeFinalize = finalizeControl;\n\n // Track seen message IDs and current run events for this run\n const seenMessageIds = new Set<string>();\n const currentRunEvents: BaseEvent[] = [];\n store.currentEvents = currentRunEvents;\n\n // Get all previously seen message IDs from historic runs\n const historicMessageIds = new Set<string>();\n for (const run of store.historicRuns) {\n for (const event of run.events) {\n if (\"messageId\" in event && typeof event.messageId === \"string\") {\n historicMessageIds.add(event.messageId);\n }\n if (event.type === EventType.RUN_STARTED) {\n const runStarted = event as RunStartedEvent;\n const messages = runStarted.input?.messages ?? [];\n for (const message of messages) {\n historicMessageIds.add(message.id);\n }\n }\n }\n }\n\n const nextSubject = new ReplaySubject<BaseEvent>(Infinity);\n\n // Update the store's subject immediately. We intentionally do NOT capture\n // and bridge the previous subject: see the note before `runAgent()` below.\n store.subject = nextSubject;\n\n // Create a subject for run() return value\n const runSubject = new ReplaySubject<BaseEvent>(Infinity);\n store.runSubject = runSubject;\n\n // Helper function to run the agent and handle errors\n const runAgent = async () => {\n // Get parent run ID for chaining\n const lastRun = store.historicRuns[store.historicRuns.length - 1];\n const parentRunId = lastRun?.runId ?? null;\n\n // Shared teardown for both the success and error paths. Keeping this one\n // helper means the two paths cannot drift apart (they were near-identical\n // and must stay symmetric). `interruptionMessage` is set only on the error\n // path; its presence is what distinguishes the two.\n const finalizeRun = (opts: { interruptionMessage?: string }) => {\n const isError = opts.interruptionMessage !== undefined;\n\n // Capture the count of REAL (agent-emitted) events BEFORE finalizing.\n // `finalizeRunEvents` mutates `currentRunEvents` IN PLACE — it always\n // pushes a synthetic terminal (and any closers) when the stream ended\n // without one — so after the call `currentRunEvents.length` is never 0.\n // The persistence guard below must gate on this pre-finalize count, or\n // the \"skip an immediate throw that emitted nothing\" check is dead.\n const preFinalizeEventCount = currentRunEvents.length;\n\n // Stop can arrive before the agent sends its first event.\n if (\n finalizeControl.stopRequested &&\n !currentRunEvents.some(\n (event) => event.type === EventType.RUN_STARTED,\n )\n ) {\n const started: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: request.threadId,\n runId: request.input.runId,\n input: {\n ...request.input,\n messages: request.input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n ),\n },\n };\n currentRunEvents.unshift(started);\n runSubject.next(started);\n nextSubject.next(started);\n }\n\n // Finalize against THIS run's own captured stop-intent — never the\n // shared `store.stopRequested`, which a superseding run resets. An\n // aborted run is thus finalized as a clean RUN_FINISHED, not a synthetic\n // RUN_ERROR.\n const appendedEvents = finalizeRunEvents(currentRunEvents, {\n stopRequested: finalizeControl.stopRequested,\n protocolVersion: request.input.protocolVersion,\n ...(isError ? { interruptionMessage: opts.interruptionMessage } : {}),\n });\n for (const event of appendedEvents) {\n runSubject.next(event);\n nextSubject.next(event);\n }\n\n // Does this run still own the thread? A superseding run has changed\n // `currentRunId`, so the run it replaced no longer owns the store.\n const ownsThread = store.currentRunId === request.input.runId;\n\n // Store this run's events. Guard on the per-run id (not the shared\n // `store.currentRunId`): a superseded run no longer owns the store, so\n // it must not push history under a newer run's id.\n // Keep explicit stops even when abort rejects before the first event.\n // Other immediate errors with no real events must not create history.\n if (\n ownsThread &&\n (!isError ||\n preFinalizeEventCount > 0 ||\n finalizeControl.stopRequested)\n ) {\n // Compact the events before storing (like SQLite does)\n const compactedEvents = compactEvents(currentRunEvents);\n sharedStore.appendRun(request.threadId, store, {\n threadId: request.threadId,\n runId: request.input.runId,\n agentId: request.agent.agentId ?? \"default\",\n parentRunId,\n events: compactedEvents,\n // Snapshot all messages (input + generated) for the thread-messages endpoint\n messages: Array.isArray(request.agent.messages)\n ? [...request.agent.messages]\n : [],\n createdAt: Date.now(),\n });\n }\n\n // Complete the run. Guard the shared-store reset: if a newer run has\n // superseded this one (`currentRunId` changed), that run now owns the\n // store — don't clobber its state. Always complete THIS run's subjects.\n if (ownsThread) {\n store.currentEvents = null;\n store.currentRunId = null;\n store.agent = null;\n store.runSubject = null;\n store.stopRequested = false;\n store.isRunning = false;\n store.activeFinalize = null;\n }\n runSubject.complete();\n nextSubject.complete();\n // Time-scoped release: this run's events are now in historicRuns, so its\n // infinite ReplaySubject buffer is pure duplication — drop the store's\n // reference so it becomes collectable. The identity guard is what makes\n // this correct, and it does so differently on each path:\n //\n // - Owning path: no newer run superseded this one, so store.subject is\n // still nextSubject and the guard passes. The `if (ownsThread)` block\n // above just cleared isRunning and stopRequested, so connect() — which\n // bridges store.subject only while isRunning || stopRequested — will\n // not re-subscribe; it rebuilds this run's events from historicRuns\n // instead. Nulling the reference is therefore safe.\n //\n // - Superseded path (`onConcurrentRun: \"supersede\"`): a newer run has\n // already installed ITS subject and run id on the store, so the guard\n // fails and we leave store.subject untouched. Here isRunning/\n // stopRequested describe that live run (isRunning is typically true),\n // so it is precisely the identity guard — not those flags — that\n // prevents us from nulling the live run's subject and cutting\n // connect() off from the in-flight stream. This run's own buffer is no\n // longer referenced by the store and becomes collectable regardless.\n if (store.subject === nextSubject) {\n store.subject = null;\n }\n };\n\n try {\n await request.agent.runAgent(request.input, {\n onEvent: ({ event }) => {\n let processedEvent: BaseEvent = event;\n if (event.type === EventType.RUN_STARTED) {\n const runStartedEvent = event as RunStartedEvent;\n if (!runStartedEvent.input) {\n const sanitizedMessages = request.input.messages\n ? request.input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n )\n : undefined;\n const updatedInput = {\n ...request.input,\n ...(sanitizedMessages !== undefined\n ? { messages: sanitizedMessages }\n : {}),\n };\n runStartedEvent.input = updatedInput;\n processedEvent = runStartedEvent;\n }\n }\n\n runSubject.next(processedEvent); // For run() return - only agent events\n nextSubject.next(processedEvent); // For connect() / store - all events\n currentRunEvents.push(processedEvent); // Accumulate for storage\n },\n onNewMessage: ({ message }) => {\n // Called for each new message\n if (!seenMessageIds.has(message.id)) {\n seenMessageIds.add(message.id);\n }\n },\n onRunStartedEvent: () => {\n // Mark any messages from the input as seen so they aren't emitted twice\n if (request.input.messages) {\n for (const message of request.input.messages) {\n if (!seenMessageIds.has(message.id)) {\n seenMessageIds.add(message.id);\n }\n }\n }\n },\n });\n\n finalizeRun({});\n } catch (error) {\n const interruptionMessage =\n error instanceof Error ? error.message : String(error);\n finalizeRun({ interruptionMessage });\n }\n };\n\n // NOTE: we deliberately do NOT bridge the previous store subject into\n // `nextSubject`. `store.subject` is nulled the moment a run fully tears down\n // (identity guard in `finalizeRun`), so the previous subject is non-null\n // ONLY when this run is superseding a prior run that is still in flight or\n // finalizing. Forwarding that dying run's subject would replay its buffered\n // RUN_STARTED and push its terminal event (RUN_FINISHED/RUN_ERROR) into THIS\n // live run's stream — an invalid AG-UI sequence on a healthy run. A\n // superseded run's stream must stay isolated: it reaches only its own\n // connect() subscribers via its own (now-detached) subject, never the\n // superseding run's.\n\n // Start the agent execution immediately (not lazily). When finishing the\n // run throws on both paths, release the thread anyway: otherwise it stays\n // \"running\", refuses every later run and is never evicted.\n runAgent().catch((error) => {\n console.error(\n \"Failed to finish agent run\",\n { threadId: request.threadId, runId: request.input.runId },\n error,\n );\n if (store.currentRunId === request.input.runId) {\n store.currentEvents = null;\n store.currentRunId = null;\n store.agent = null;\n store.runSubject = null;\n store.stopRequested = false;\n store.isRunning = false;\n store.activeFinalize = null;\n }\n runSubject.complete();\n nextSubject.complete();\n if (store.subject === nextSubject) {\n store.subject = null;\n }\n });\n\n // Return the run subject (only agent events, no injected messages)\n return runSubject.asObservable();\n }\n\n connect(request: AgentRunnerConnectRequest): Observable<BaseEvent> {\n const found = sharedStore.peek(request.threadId);\n // A thread owned by another identity is indistinguishable from an\n // unknown one: no replay, no live bridge.\n const store =\n found && isVisibleTo(found, ɵresolveThreadOwner(request.ownerId))\n ? sharedStore.get(request.threadId, { touch: true })\n : undefined;\n const connectionSubject = new ReplaySubject<BaseEvent>(Infinity);\n\n if (!store) {\n // No store means no events\n connectionSubject.complete();\n return connectionSubject.asObservable();\n }\n\n // Collect all historic events from memory\n const allHistoricEvents: BaseEvent[] = [];\n for (const run of store.historicRuns) {\n allHistoricEvents.push(...run.events);\n }\n\n // Apply compaction to all historic events together (like SQLite)\n const compactedEvents = compactEvents(allHistoricEvents);\n\n // Emit compacted events and track message IDs\n const emittedMessageIds = new Set<string>();\n for (const event of compactedEvents) {\n connectionSubject.next(event);\n if (\"messageId\" in event && typeof event.messageId === \"string\") {\n emittedMessageIds.add(event.messageId);\n }\n }\n\n // Bridge active run to connection if exists\n if (store.subject && (store.isRunning || store.stopRequested)) {\n store.subject.subscribe({\n next: (event) => {\n // Skip message events that we've already emitted from historic\n if (\n \"messageId\" in event &&\n typeof event.messageId === \"string\" &&\n emittedMessageIds.has(event.messageId)\n ) {\n return;\n }\n connectionSubject.next(event);\n },\n complete: () => connectionSubject.complete(),\n error: (err) => connectionSubject.error(err),\n });\n } else {\n // No active run, complete after historic events\n connectionSubject.complete();\n }\n\n return connectionSubject.asObservable();\n }\n\n isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean> {\n const store = sharedStore.peek(request.threadId);\n // Another identity's thread reports \"not running\".\n if (!store || !isVisibleTo(store, ɵresolveThreadOwner(request.ownerId))) {\n return Promise.resolve(false);\n }\n return Promise.resolve(store.isRunning);\n }\n\n stop(request: AgentRunnerStopRequest): Promise<boolean | undefined> {\n const store = sharedStore.peek(request.threadId);\n if (!store || !store.isRunning) {\n return Promise.resolve(false);\n }\n // Another identity's run reports the same as \"no active run\".\n if (!isVisibleTo(store, ɵresolveThreadOwner(request.ownerId))) {\n return Promise.resolve(false);\n }\n if (request.runId !== undefined && store.currentRunId !== request.runId) {\n return Promise.resolve(false);\n }\n if (store.stopRequested) {\n return Promise.resolve(false);\n }\n\n store.stopRequested = true;\n store.isRunning = false;\n // Record the stop on the running run's OWN finalize control so its async\n // teardown finalizes as a clean RUN_FINISHED. This is the same object that\n // run's closure reads, so a later run cannot mislabel this stop.\n const finalizeControl = store.activeFinalize;\n if (finalizeControl) {\n finalizeControl.stopRequested = true;\n }\n\n const agent = store.agent;\n if (!agent) {\n store.stopRequested = false;\n store.isRunning = false;\n if (finalizeControl) {\n finalizeControl.stopRequested = false;\n }\n return Promise.resolve(false);\n }\n\n try {\n agent.abortRun();\n return Promise.resolve(true);\n } catch (error) {\n console.error(\"Failed to abort agent run\", error);\n store.stopRequested = false;\n store.isRunning = true;\n if (finalizeControl) {\n finalizeControl.stopRequested = false;\n }\n return Promise.resolve(false);\n }\n }\n\n /**\n * Returns a summary of every thread that `scope`'s owner holds in the\n * process-wide store, which every InMemoryAgentRunner shares. Without a\n * scope, the server owner's threads ({@link ɵSERVER_THREAD_OWNER}).\n *\n * This powers the local-dev fallback for `GET /threads` when the Intelligence\n * platform is not configured. Each entry mirrors the shape of a platform\n * `ThreadRecord` so the HTTP handler can use the same response envelope.\n */\n listThreads(scope?: LocalThreadEndpointScope): InMemoryThread[] {\n return sharedStore.listThreads(scope);\n }\n\n /**\n * Returns all messages for a thread, using the snapshot captured at the end\n * of the most recent run.\n *\n * This powers the local-dev fallback for `GET /threads/:threadId/messages`\n * when CopilotKit Intelligence is not configured. The returned `Message[]`\n * objects come directly from the ag-ui agent, so their shape is compatible\n * with CopilotKit Intelligence's `ThreadMessage` type.\n */\n getThreadMessages(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Message[] {\n const store = this.peekVisible(threadId, scope);\n if (!store) return [];\n // The thread's latest non-empty snapshot is held at the store level,\n // independent of `historicRuns` lifecycle, so run-cap eviction and\n // interleaved empty-snapshot runs can never lose it. Return a SHALLOW\n // (array-level) copy: a fresh array so a caller mutating array STRUCTURE\n // (push/splice/reassign elements) cannot affect the stored snapshot. We\n // deliberately do NOT deep-copy: `structuredClone` throws DataCloneError on a\n // non-cloneable message field, which would wedge the thread and hang SSE —\n // inconsistent with `ɵestimateBytes`, which tolerates the same bad-payload class.\n // The tradeoff is that the inner `Message` objects remain shared by reference with\n // the stored snapshot, so mutating a returned message's FIELD\n // (e.g. `getThreadMessages(t)[0].content = \"x\"`) is NOT isolated and would corrupt\n // the stored snapshot. That inner-object isolation is a known limitation tracked as\n // follow-up; callers must treat returned messages as read-only.\n return [...store.messagesSnapshot];\n }\n\n /**\n * Returns all AG-UI events for a thread, compacted across historic runs.\n *\n * Powers the local-dev fallback for `GET /threads/:threadId/events` when the\n * CopilotKit Intelligence is not configured. The compaction logic matches\n * the connection-replay path in {@link connect}, so the stream a\n * late-joining inspector sees matches what this method returns.\n */\n getThreadEvents(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): BaseEvent[] {\n const store = this.peekVisible(threadId, scope);\n if (!store || store.historicRuns.length === 0) return [];\n const all: BaseEvent[] = [];\n for (const run of store.historicRuns) all.push(...run.events);\n return compactEvents(all);\n }\n\n /**\n * Returns the agent state snapshot for a thread.\n *\n * Derived from the last `STATE_SNAPSHOT` in the compacted event stream. The\n * AG-UI `compactEvents` helper consolidates STATE_DELTA events and produces\n * a single trailing STATE_SNAPSHOT when state changes exist, so this is a\n * faithful view of state at the end of the most recent run.\n *\n * Returns `null` when the thread has never emitted a STATE_SNAPSHOT.\n */\n getThreadState(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Record<string, unknown> | null {\n const events = this.getThreadEvents(threadId, scope);\n // Walk backwards — the last snapshot wins.\n for (let i = events.length - 1; i >= 0; i--) {\n const event = events[i]!;\n if (event.type === EventType.STATE_SNAPSHOT) {\n const snapshot = (event as StateSnapshotEvent).snapshot;\n // Only plain objects satisfy the Record<string, unknown> contract.\n // `typeof [] === \"object\"` is true, so arrays must be rejected\n // explicitly to avoid returning an array typed as a Record.\n if (\n snapshot &&\n typeof snapshot === \"object\" &&\n !Array.isArray(snapshot)\n ) {\n // Return a defensive shallow copy so callers can't mutate the\n // snapshot object held inside the stored event (matches the\n // getThreadMessages defensive-copy approach).\n return { ...(snapshot as Record<string, unknown>) };\n }\n return null;\n }\n }\n return null;\n }\n\n /**\n * Clears the in-memory history of `scope`'s threads (without a scope, the\n * server owner's). A thread with a run still active or finalizing is kept;\n * see {@link ɵBoundedThreadStore.clear}.\n *\n * Powers the local-dev fallback for `POST /threads/clear`, letting consumers\n * (e.g. the demo's Clear button) reset to an empty thread list without\n * restarting the runtime. Intentionally not exposed on the Intelligence\n * platform path: there, thread history lives in a real database and must\n * not be wiped this way.\n */\n clearThreads(scope?: LocalThreadEndpointScope): void {\n sharedStore.clear({ ownerId: scopeOwner(scope) });\n }\n\n /**\n * False when the thread id is held by an owner other than `scope`'s: a\n * live thread, or the retained owner of an evicted or cleared one.\n */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean {\n return sharedStore.canClaim(threadId, scopeOwner(scope));\n }\n\n /** The thread's store, or `undefined` when unknown or not visible to `scope`. */\n private peekVisible(\n threadId: string,\n scope: LocalThreadEndpointScope | undefined,\n ): InMemoryEventStore | undefined {\n const store = sharedStore.peek(threadId);\n return store && isVisibleTo(store, scopeOwner(scope)) ? store : undefined;\n }\n}\n"],"mappings":";;;;;;AAoEA,MAAa,qBAA+C;CAC1D,YAAY;CACZ,kBAAkB;CAClB,UAAU,MAAM,QAAQ;CACzB;;;;;;;;;;;;;AAcD,SAAS,cAAc,OAAwB;AAC7C,QAAO,UAAU,YAAa,OAAO,UAAU,MAAM,IAAI,SAAS;;;;;;;;;;;;;;;;;;AAmBpE,SAAgB,iBACd,QAC0B;CAC1B,MAAM,aAAa,EAAE,GAAG,QAAQ;AAChC,MAAK,MAAM,SAAS,OAAO,KACzB,mBACD,EAA8B;EAC7B,MAAM,QAAQ,OAAO;AACrB,MAAI,CAAC,cAAc,MAAM,EAAE;GACzB,MAAM,WAAW,mBAAmB;AACpC,cAAW,SAAS;AACpB,OAAI;AACF,YAAQ,KACN,6CAA6C,MAAM,SAC9C,OAAO,MAAM,CAAC,kEACE,OAAO,SAAS,CAAC,GACvC;WACK;;;AAKZ,QAAO;;AAGT,MAAM,oBACJ;AAIF,MAAM,0BACJ;;;;;;;AAYF,SAAgB,eAAe,OAAwB;AACrD,KAAI;AACF,SAAO,KAAK,UAAU,MAAM,EAAE,UAAU;SAClC;AACN,SAAO;;;AA0DX,IAAM,qBAAN,MAAyB;;;;;;CAMvB,YACE,AAAO,UACP,AAAgB,SAChB;EAFO;EACS;iBAIyB;mBAG/B;sBAGkB;sBAGA,EAAE;eAGF;oBAGgB;uBAW9B;wBAQ4B;uBAGR;0BAQN,EAAE;qCAGF;mB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AO;AAC7D,0CAAqB,IAAI;;;;;;;;;;;;CAa3B,eACE,UACA,OACgC;EAChC,MAAM,SAAS,KAAK,gBAAgB,UAAU,MAAM;AAEpD,OAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK;GAC3C,MAAM,QAAQ,OAAO;AACrB,OAAI,MAAM,SAASK,wBAAU,gBAAgB;IAC3C,MAAM,WAAY,MAA6B;AAI/C,QACE,YACA,OAAO,aAAa,YACpB,CAAC,MAAM,QAAQ,SAAS,CAKxB,QAAO,EAAE,GAAI,UAAsC;AAErD,WAAO;;;AAGX,SAAO;;;;;;;;;;;;;CAcT,aAAa,OAAwC;AACnD,cAAY,MAAM,EAAE,SAAS,WAAW,MAAM,EAAE,CAAC;;;;;;CAOnD,mBACE,UACA,OACS;AACT,SAAO,YAAY,SAAS,UAAU,WAAW,MAAM,CAAC;;;CAI1D,AAAQ,YACN,UACA,OACgC;EAChC,MAAM,QAAQ,YAAY,KAAK,SAAS;AACxC,SAAO,SAAS,YAAY,OAAO,WAAW,MAAM,CAAC,GAAG,QAAQ"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, LocalThreadEndpointScope, THREAD_ACCESS_DENIED_ERROR_CODE, ThreadAccessDeniedError, ThreadAlreadyRunningError, ThreadOwnershipRunner, enforcesThreadOwnership, isThreadAccessDeniedError, supportsLocalThreadEndpoints, ɵSERVER_THREAD_OWNER, ɵresolveThreadOwner } from "./agent-runner.cjs";
|
|
2
2
|
import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵOwnerRetention, ɵestimateBytes, ɵnormalizeLimits } from "./in-memory.cjs";
|
|
3
|
-
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./intelligence.cjs";
|
|
3
|
+
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary, STOP_RECORD_DEADLINE_MS } from "./intelligence.cjs";
|
|
4
4
|
import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "@copilotkit/shared";
|
|
5
5
|
export { type FinalizeRunOptions, type RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, LocalThreadEndpointScope, THREAD_ACCESS_DENIED_ERROR_CODE, ThreadAccessDeniedError, ThreadAlreadyRunningError, ThreadOwnershipRunner, enforcesThreadOwnership, isThreadAccessDeniedError, supportsLocalThreadEndpoints, ɵSERVER_THREAD_OWNER, ɵresolveThreadOwner } from "./agent-runner.mjs";
|
|
2
2
|
import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵOwnerRetention, ɵestimateBytes, ɵnormalizeLimits } from "./in-memory.mjs";
|
|
3
|
-
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./intelligence.mjs";
|
|
3
|
+
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary, STOP_RECORD_DEADLINE_MS } from "./intelligence.mjs";
|
|
4
4
|
import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer as createRunEventFinalizer$1, finalizeRunEvents as finalizeRunEvents$1 } from "@copilotkit/shared";
|
|
5
5
|
export { type FinalizeRunOptions, type RunEventFinalizer, createRunEventFinalizer$1 as createRunEventFinalizer, finalizeRunEvents$1 as finalizeRunEvents };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AgentRunner, THREAD_ACCESS_DENIED_ERROR_CODE, ThreadAccessDeniedError, ThreadAlreadyRunningError, enforcesThreadOwnership, isThreadAccessDeniedError, supportsLocalThreadEndpoints, ɵSERVER_THREAD_OWNER, ɵresolveThreadOwner } from "./agent-runner.mjs";
|
|
2
2
|
import { InMemoryAgentRunner, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./in-memory.mjs";
|
|
3
|
-
import { IntelligenceAgentRunner } from "./intelligence.mjs";
|
|
3
|
+
import { IntelligenceAgentRunner, STOP_RECORD_DEADLINE_MS } from "./intelligence.mjs";
|
|
4
4
|
import { createRunEventFinalizer as createRunEventFinalizer$1, finalizeRunEvents as finalizeRunEvents$1 } from "@copilotkit/shared";
|
|
5
5
|
|
|
6
6
|
export { createRunEventFinalizer$1 as createRunEventFinalizer, finalizeRunEvents$1 as finalizeRunEvents };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_logger = require('../core/logger.cjs');
|
|
2
2
|
const require_agent_runner = require('./agent-runner.cjs');
|
|
3
3
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
|
+
let phoenix = require("phoenix");
|
|
4
5
|
let rxjs = require("rxjs");
|
|
5
6
|
let _ag_ui_client = require("@ag-ui/client");
|
|
6
|
-
let phoenix = require("phoenix");
|
|
7
7
|
|
|
8
8
|
//#region src/runtime/runner/intelligence.ts
|
|
9
9
|
const MAX_CONSECUTIVE_SOCKET_ERRORS = 5;
|
|
@@ -13,11 +13,18 @@ const RUNNER_EVENT_BATCH_CAPABILITY = "runner_event_batch_v1";
|
|
|
13
13
|
const MAX_RUNNER_EVENT_BATCH_SIZE = 32;
|
|
14
14
|
const RUNNER_EVENT_BATCH_FLUSH_MS = 5;
|
|
15
15
|
const EVENT_DURABILITY_DEADLINE_MS = 6e4;
|
|
16
|
+
/**
|
|
17
|
+
* How long a runtime-side stop waits for Intelligence to record it before the
|
|
18
|
+
* terminal event is sent anyway. The agent is aborted at once; only the
|
|
19
|
+
* terminal event waits, so a slow or failing record never keeps a run going.
|
|
20
|
+
*/
|
|
21
|
+
const STOP_RECORD_DEADLINE_MS = 2e3;
|
|
16
22
|
var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
17
23
|
constructor(options) {
|
|
18
24
|
super();
|
|
19
25
|
this.threads = /* @__PURE__ */ new Map();
|
|
20
26
|
this.options = options;
|
|
27
|
+
this.logger = require_logger.getRuntimeLogger(options);
|
|
21
28
|
}
|
|
22
29
|
/**
|
|
23
30
|
* Create a new Phoenix socket with explicit exponential backoff.
|
|
@@ -157,6 +164,8 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
|
157
164
|
completion,
|
|
158
165
|
resolveCompletion,
|
|
159
166
|
stopTimer: null,
|
|
167
|
+
...request.recordStop ? { recordStop: request.recordStop } : {},
|
|
168
|
+
stopRecorded: null,
|
|
160
169
|
pendingEvents: /* @__PURE__ */ new Map(),
|
|
161
170
|
activeEventBatch: null,
|
|
162
171
|
nextEventPushAttempt: 0,
|
|
@@ -201,11 +210,11 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
|
201
210
|
if (consecutiveSocketErrors >= MAX_CONSECUTIVE_SOCKET_ERRORS) state.agent?.abortRun();
|
|
202
211
|
});
|
|
203
212
|
channel.on(_copilotkit_shared.AG_UI_CHANNEL_EVENT, (payload) => {
|
|
204
|
-
if (this.isCurrentThreadState(threadId, state) && payload.type === _ag_ui_client.EventType.CUSTOM && payload.name === "stop") this.
|
|
213
|
+
if (this.isCurrentThreadState(threadId, state) && payload.type === _ag_ui_client.EventType.CUSTOM && payload.name === "stop") this.stopRun({
|
|
205
214
|
threadId,
|
|
206
215
|
runId: state.runId
|
|
207
|
-
}).catch((error) => {
|
|
208
|
-
|
|
216
|
+
}, { recordWithIntelligence: false }).catch((error) => {
|
|
217
|
+
this.logger.error({
|
|
209
218
|
err: error,
|
|
210
219
|
threadId,
|
|
211
220
|
runId: state.runId
|
|
@@ -302,10 +311,14 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
|
302
311
|
}
|
|
303
312
|
/** Stops this run and waits until its terminal events have been acknowledged. */
|
|
304
313
|
stop(request) {
|
|
314
|
+
return this.stopRun(request, { recordWithIntelligence: true });
|
|
315
|
+
}
|
|
316
|
+
stopRun(request, options) {
|
|
305
317
|
const state = this.threads.get(request.threadId);
|
|
306
318
|
if (!state || !state.isRunning || state.stopRequested) return Promise.resolve(false);
|
|
307
319
|
if (request.runId !== void 0 && state.runId !== request.runId) return Promise.resolve(false);
|
|
308
320
|
state.stopRequested = true;
|
|
321
|
+
if (options.recordWithIntelligence && state.recordStop) state.stopRecorded = recordStopWithin(state, STOP_RECORD_DEADLINE_MS, this.logger);
|
|
309
322
|
state.cancelRun();
|
|
310
323
|
state.stopTimer = setTimeout(() => {
|
|
311
324
|
this.failThread(state.threadId, state, /* @__PURE__ */ new Error("Timed out stopping Intelligence run"));
|
|
@@ -316,14 +329,14 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
|
316
329
|
} catch {}
|
|
317
330
|
if (typeof state.agent.detachActiveRun === "function") try {
|
|
318
331
|
Promise.resolve(state.agent.detachActiveRun()).catch((error) => {
|
|
319
|
-
|
|
332
|
+
this.logger.warn({
|
|
320
333
|
err: error,
|
|
321
334
|
threadId: state.threadId,
|
|
322
335
|
runId: state.runId
|
|
323
336
|
}, "Failed to detach stopped agent");
|
|
324
337
|
});
|
|
325
338
|
} catch (error) {
|
|
326
|
-
|
|
339
|
+
this.logger.warn({
|
|
327
340
|
err: error,
|
|
328
341
|
threadId: state.threadId,
|
|
329
342
|
runId: state.runId
|
|
@@ -335,7 +348,7 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
|
335
348
|
return true;
|
|
336
349
|
});
|
|
337
350
|
}
|
|
338
|
-
async executeAgentRun(request, state, threadId,
|
|
351
|
+
async executeAgentRun(request, state, threadId, notifyHandler) {
|
|
339
352
|
const { currentEvents } = state;
|
|
340
353
|
const pushCanonicalEvent = (event) => {
|
|
341
354
|
if (!this.isCurrentThreadState(threadId, state)) return;
|
|
@@ -343,7 +356,7 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
|
343
356
|
currentEvents.push(canonicalEvent);
|
|
344
357
|
if (canonicalEvent.type === _ag_ui_client.EventType.RUN_STARTED) state.hasRunStarted = true;
|
|
345
358
|
this.queueRunnerEvent(this.createRunnerEventPayload(canonicalEvent, request, state), state);
|
|
346
|
-
if (canonicalEvent.type === _ag_ui_client.EventType.RUN_ERROR)
|
|
359
|
+
if (canonicalEvent.type === _ag_ui_client.EventType.RUN_STARTED || canonicalEvent.type === _ag_ui_client.EventType.RUN_ERROR) notifyHandler(canonicalEvent);
|
|
347
360
|
};
|
|
348
361
|
const getPersistedInputMessages = () => request.persistedInputMessages ?? request.input.messages;
|
|
349
362
|
const buildRunStartedEvent = (source) => {
|
|
@@ -391,6 +404,7 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
|
391
404
|
message: error instanceof Error ? error.message : String(error)
|
|
392
405
|
});
|
|
393
406
|
} finally {
|
|
407
|
+
if (state.stopRecorded) await state.stopRecorded;
|
|
394
408
|
if (!this.isCurrentThreadState(threadId, state)) return;
|
|
395
409
|
ensureRunStarted();
|
|
396
410
|
const appended = (0, _copilotkit_shared.finalizeRunEvents)(currentEvents, {
|
|
@@ -610,7 +624,39 @@ var IntelligenceAgentRunner = class extends require_agent_runner.AgentRunner {
|
|
|
610
624
|
} catch {}
|
|
611
625
|
}
|
|
612
626
|
};
|
|
627
|
+
/**
|
|
628
|
+
* Runs a thread's stop record, bounded by a deadline. Never rejects: a stop
|
|
629
|
+
* that Intelligence could not record still stops the run.
|
|
630
|
+
*/
|
|
631
|
+
function recordStopWithin(state, deadlineMs, logger) {
|
|
632
|
+
const record = state.recordStop;
|
|
633
|
+
if (!record) return Promise.resolve();
|
|
634
|
+
const scope = {
|
|
635
|
+
threadId: state.threadId,
|
|
636
|
+
runId: state.runId
|
|
637
|
+
};
|
|
638
|
+
return new Promise((resolve) => {
|
|
639
|
+
const controller = new AbortController();
|
|
640
|
+
const deadline = setTimeout(() => {
|
|
641
|
+
controller.abort();
|
|
642
|
+
logger.warn(scope, "Timed out recording the run's stop with Intelligence");
|
|
643
|
+
resolve();
|
|
644
|
+
}, deadlineMs);
|
|
645
|
+
Promise.resolve().then(() => record(controller.signal)).then(() => {
|
|
646
|
+
clearTimeout(deadline);
|
|
647
|
+
resolve();
|
|
648
|
+
}, (error) => {
|
|
649
|
+
clearTimeout(deadline);
|
|
650
|
+
logger.warn({
|
|
651
|
+
...scope,
|
|
652
|
+
err: error
|
|
653
|
+
}, "Failed to record the run's stop with Intelligence");
|
|
654
|
+
resolve();
|
|
655
|
+
});
|
|
656
|
+
});
|
|
657
|
+
}
|
|
613
658
|
|
|
614
659
|
//#endregion
|
|
615
660
|
exports.IntelligenceAgentRunner = IntelligenceAgentRunner;
|
|
661
|
+
exports.STOP_RECORD_DEADLINE_MS = STOP_RECORD_DEADLINE_MS;
|
|
616
662
|
//# sourceMappingURL=intelligence.cjs.map
|