@copilotkit/runtime 1.61.0 → 1.61.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/agent/converters/tanstack.cjs +53 -10
  2. package/dist/agent/converters/tanstack.cjs.map +1 -1
  3. package/dist/agent/converters/tanstack.d.cts +24 -0
  4. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  5. package/dist/agent/converters/tanstack.d.mts +24 -0
  6. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  7. package/dist/agent/converters/tanstack.mjs +53 -10
  8. package/dist/agent/converters/tanstack.mjs.map +1 -1
  9. package/dist/package.cjs +3 -3
  10. package/dist/package.mjs +3 -3
  11. package/dist/v2/index.cjs +1 -0
  12. package/dist/v2/index.d.cts +2 -2
  13. package/dist/v2/index.d.mts +2 -2
  14. package/dist/v2/index.mjs +2 -2
  15. package/dist/v2/runtime/core/fetch-handler.cjs +5 -4
  16. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  17. package/dist/v2/runtime/core/fetch-handler.mjs +5 -4
  18. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  19. package/dist/v2/runtime/core/runtime.cjs +3 -3
  20. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  21. package/dist/v2/runtime/core/runtime.d.cts +7 -0
  22. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  23. package/dist/v2/runtime/core/runtime.d.mts +7 -0
  24. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  25. package/dist/v2/runtime/core/runtime.mjs +3 -3
  26. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  27. package/dist/v2/runtime/handlers/get-runtime-info.cjs +14 -1
  28. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  29. package/dist/v2/runtime/handlers/get-runtime-info.mjs +14 -1
  30. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  31. package/dist/v2/runtime/handlers/intelligence/threads.cjs +6 -6
  32. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
  33. package/dist/v2/runtime/handlers/intelligence/threads.mjs +6 -6
  34. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
  35. package/dist/v2/runtime/index.d.cts +1 -1
  36. package/dist/v2/runtime/index.d.mts +1 -1
  37. package/dist/v2/runtime/runner/agent-runner.cjs +4 -0
  38. package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
  39. package/dist/v2/runtime/runner/agent-runner.d.cts +21 -1
  40. package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
  41. package/dist/v2/runtime/runner/agent-runner.d.mts +21 -1
  42. package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
  43. package/dist/v2/runtime/runner/agent-runner.mjs +4 -1
  44. package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
  45. package/dist/v2/runtime/runner/in-memory.cjs +4 -0
  46. package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
  47. package/dist/v2/runtime/runner/in-memory.d.cts +1 -0
  48. package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
  49. package/dist/v2/runtime/runner/in-memory.d.mts +1 -0
  50. package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
  51. package/dist/v2/runtime/runner/in-memory.mjs +4 -0
  52. package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
  53. package/dist/v2/runtime/runner/index.d.cts +1 -1
  54. package/dist/v2/runtime/runner/index.d.mts +1 -1
  55. package/dist/v2/runtime/runner/index.mjs +1 -1
  56. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":["pkg"],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../lib/telemetry-disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\nimport telemetry from \"../telemetry/telemetry-client\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n name: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n}\n\nexport interface CopilotIntelligenceRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Resolves the authenticated user for intelligence requests. */\n identifyUser: IdentifyUserCallback;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n}\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n mode: RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.runner = runner;\n\n if (process.env.NODE_ENV !== \"production\") {\n this.debugEventBus = new DebugEventBus();\n }\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\n }\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n }),\n );\n this.intelligence = options.intelligence;\n this.identifyUser = options.identifyUser;\n this.generateThreadNames = options.generateThreadNames ?? true;\n // Match license-verifier's env fallback so telemetry attribution\n // resolves the same way as feature gating — otherwise customers who\n // set only COPILOTKIT_LICENSE_TOKEN would get a working license but\n // anonymous telemetry.\n const licenseToken =\n options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;\n this.licenseChecker = createLicenseChecker(licenseToken);\n if (licenseToken) {\n telemetry.setLicenseToken(licenseToken);\n }\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n */\nexport class CopilotRuntime implements CopilotRuntimeLike {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,MAAa,UAAUA,uBAAI;;;;;;AAyE3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAyGT,IAAe,qBAAf,MAAgE;CAiB9D,YAAY,SAAoC,QAAqB;AACnE,iCAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;AAEJ,OAAK,SAAS;AACd,OAAK,uBAAuB;AAC5B,OAAK,0BAA0B;AAC/B,OAAK,yBAAyB;AAC9B,OAAK,OAAO,QAAQ;AACpB,OAAK,UAAU;AACf,OAAK,mBAAmB;AACxB,OAAK,SAAS;AAEd,MAAI,QAAQ,IAAI,aAAa,aAC3B,MAAK,gBAAgB,IAAI,eAAe;AAE1C,OAAK,QAAQ,mBAAmB,QAAQ,MAAM;AAC9C,MAAI,KAAK,MAAM,QACb,MAAK,cAAc,aAAa;GAC9B,OAAO;GACP,WAAW;GACZ,CAAC;;;AAKR,IAAa,oBAAb,cACU,mBAEV;CAIE,YAAY,SAAmC;AAC7C,QAAM,SAAS,QAAQ,UAAU,IAAI,qBAAqB,CAAC;sBAJrC;cACR;;;AAOlB,IAAa,6BAAb,MAAa,mCACH,mBAEV;;8BAUyC;;;wCAEU;;CAEjD,YAAY,SAA4C;AACtD,QACE,SACA,IAAI,wBAAwB;GAC1B,KAAK,QAAQ,aAAa,iBAAiB;GAC3C,WAAW,QAAQ,aAAa,qBAAqB;GACrD,gBAAgB,QAAQ;GACxB,aAAa,QAAQ;GACtB,CAAC,CACH;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BAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,eACd;;CAGN,IAAI,iBAAqC;AACvC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,iBACd;;CAGN,IAAI,gBAAoC;AACtC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,gBACd;;CAGN,IAAI,+BAAmD;AACrD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,+BACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS"}
1
+ {"version":3,"file":"runtime.mjs","names":["pkg"],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../lib/telemetry-disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\nimport telemetry from \"../telemetry/telemetry-client\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n name: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n}\n\nexport interface CopilotIntelligenceRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Resolves the authenticated user for intelligence requests. */\n identifyUser: IdentifyUserCallback;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n}\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n mode: RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n\n /**\n * License token resolved once with the env fallback, so telemetry\n * attribution (below) and subclass feature gating\n * (CopilotIntelligenceRuntime's licenseChecker) read the exact same value\n * instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.\n */\n protected readonly resolvedLicenseToken?: string;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.runner = runner;\n\n // Resolve the license token once (matching the license-verifier's env\n // fallback) so telemetry attribution and subclass feature gating share\n // one value.\n this.resolvedLicenseToken =\n options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;\n\n // Attribute telemetry to the licensed customer for *every* runtime mode.\n // Done in the shared base (not the subclasses) so SSE and Intelligence\n // runtimes behave identically — previously only CopilotIntelligenceRuntime\n // set this, so self-hosted SSE users never got a telemetry_id on their\n // runtime events even with a license token configured.\n if (this.resolvedLicenseToken) {\n telemetry.setLicenseToken(this.resolvedLicenseToken);\n }\n\n if (process.env.NODE_ENV !== \"production\") {\n this.debugEventBus = new DebugEventBus();\n }\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\n }\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n }),\n );\n this.intelligence = options.intelligence;\n this.identifyUser = options.identifyUser;\n this.generateThreadNames = options.generateThreadNames ?? true;\n // Telemetry attribution is handled by the base constructor for all modes;\n // here we only need the token for feature gating. Reuse the base-resolved\n // value so gating and attribution can never disagree.\n this.licenseChecker = createLicenseChecker(this.resolvedLicenseToken);\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n */\nexport class CopilotRuntime implements CopilotRuntimeLike {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,MAAa,UAAUA,uBAAI;;;;;;AAyE3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAyGT,IAAe,qBAAf,MAAgE;CAyB9D,YAAY,SAAoC,QAAqB;AACnE,iCAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;AAEJ,OAAK,SAAS;AACd,OAAK,uBAAuB;AAC5B,OAAK,0BAA0B;AAC/B,OAAK,yBAAyB;AAC9B,OAAK,OAAO,QAAQ;AACpB,OAAK,UAAU;AACf,OAAK,mBAAmB;AACxB,OAAK,SAAS;AAKd,OAAK,uBACH,QAAQ,gBAAgB,QAAQ,IAAI;AAOtC,MAAI,KAAK,qBACP,WAAU,gBAAgB,KAAK,qBAAqB;AAGtD,MAAI,QAAQ,IAAI,aAAa,aAC3B,MAAK,gBAAgB,IAAI,eAAe;AAE1C,OAAK,QAAQ,mBAAmB,QAAQ,MAAM;AAC9C,MAAI,KAAK,MAAM,QACb,MAAK,cAAc,aAAa;GAC9B,OAAO;GACP,WAAW;GACZ,CAAC;;;AAKR,IAAa,oBAAb,cACU,mBAEV;CAIE,YAAY,SAAmC;AAC7C,QAAM,SAAS,QAAQ,UAAU,IAAI,qBAAqB,CAAC;sBAJrC;cACR;;;AAOlB,IAAa,6BAAb,MAAa,mCACH,mBAEV;;8BAUyC;;;wCAEU;;CAEjD,YAAY,SAA4C;AACtD,QACE,SACA,IAAI,wBAAwB;GAC1B,KAAK,QAAQ,aAAa,iBAAiB;GAC3C,WAAW,QAAQ,aAA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AAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,eACd;;CAGN,IAAI,iBAAqC;AACvC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,iBACd;;CAGN,IAAI,gBAAoC;AACtC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,gBACd;;CAGN,IAAI,+BAAmD;AACrD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,+BACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS"}
@@ -1,4 +1,5 @@
1
1
  require("reflect-metadata");
2
+ const require_agent_runner = require('../runner/agent-runner.cjs');
2
3
  const require_telemetry_client = require('../telemetry/telemetry-client.cjs');
3
4
  const require_runtime = require('../core/runtime.cjs');
4
5
 
@@ -13,7 +14,7 @@ function resolveLicenseStatus(runtime) {
13
14
  if (status.warningSeverity === "info") return "none";
14
15
  return "unknown";
15
16
  }
16
- async function handleGetRuntimeInfo({ runtime, request }) {
17
+ async function handleGetRuntimeInfo({ runtime, request, threadEndpointsEnabled = true }) {
17
18
  try {
18
19
  const agents = await require_runtime.resolveAgents(runtime.agents, request);
19
20
  const agentEntries = await Promise.all(Object.entries(agents).map(async ([name, agent]) => {
@@ -36,6 +37,7 @@ async function handleGetRuntimeInfo({ runtime, request }) {
36
37
  agents: Object.fromEntries(agentEntries),
37
38
  audioFileTranscriptionEnabled: !!runtime.transcriptionService,
38
39
  mode: runtime.mode,
40
+ threadEndpoints: resolveThreadEndpointInfo(runtime, threadEndpointsEnabled),
39
41
  ...require_runtime.isIntelligenceRuntime(runtime) ? { intelligence: { wsUrl: runtime.intelligence.ɵgetClientWsUrl() } } : {},
40
42
  a2uiEnabled: require_runtime.isA2UIEnabled(runtime.a2ui),
41
43
  ...require_runtime.isA2UIEnabled(runtime.a2ui) ? { a2ui: {
@@ -60,6 +62,17 @@ async function handleGetRuntimeInfo({ runtime, request }) {
60
62
  });
61
63
  }
62
64
  }
65
+ function resolveThreadEndpointInfo(runtime, threadEndpointsEnabled) {
66
+ const hasRestThreadBackend = require_runtime.isIntelligenceRuntime(runtime) || require_agent_runner.supportsLocalThreadEndpoints(runtime.runner);
67
+ const restEndpointsAvailable = threadEndpointsEnabled && hasRestThreadBackend;
68
+ const managedThreadMetadata = threadEndpointsEnabled && require_runtime.isIntelligenceRuntime(runtime);
69
+ return {
70
+ list: restEndpointsAvailable,
71
+ inspect: restEndpointsAvailable,
72
+ mutations: managedThreadMetadata,
73
+ realtimeMetadata: managedThreadMetadata
74
+ };
75
+ }
63
76
 
64
77
  //#endregion
65
78
  exports.handleGetRuntimeInfo = handleGetRuntimeInfo;
@@ -1 +1 @@
1
- {"version":3,"file":"get-runtime-info.cjs","names":["resolveAgents","VERSION","isIntelligenceRuntime","isA2UIEnabled","isTelemetryDisabled"],"sources":["../../../../src/v2/runtime/handlers/get-runtime-info.ts"],"sourcesContent":["import type { AgentCapabilities } from \"@ag-ui/core\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../core/runtime\";\nimport type { AgentDescription, RuntimeInfo } from \"@copilotkit/shared\";\nimport type { RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { VERSION } from \"../core/runtime\";\nimport { isTelemetryDisabled } from \"../telemetry/telemetry-client\";\n\nfunction resolveLicenseStatus(\n runtime: CopilotRuntimeLike,\n): RuntimeLicenseStatus {\n if (!runtime.licenseChecker) return \"none\";\n const status = runtime.licenseChecker.getStatus();\n if (status.warningSeverity === \"none\") return \"valid\";\n if (status.error === \"expired\") return \"expired\";\n if (status.warningSeverity === \"warning\") return \"expiring\";\n if (status.error) return \"invalid\";\n if (status.warningSeverity === \"info\") return \"none\";\n return \"unknown\";\n}\n\ninterface HandleGetRuntimeInfoParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\nexport async function handleGetRuntimeInfo({\n runtime,\n request,\n}: HandleGetRuntimeInfoParameters) {\n try {\n const agents = await resolveAgents(runtime.agents, request);\n\n const agentEntries = await Promise.all(\n Object.entries(agents).map(async ([name, agent]) => {\n let capabilities: AgentCapabilities | undefined;\n try {\n capabilities = agent.getCapabilities\n ? await agent.getCapabilities()\n : undefined;\n } catch (error) {\n // Per-agent isolation: a single agent failing to report capabilities\n // must not take down the entire /info endpoint.\n console.warn(\n `Failed to fetch capabilities for agent \"${name}\":`,\n error instanceof Error ? error.message : error,\n );\n capabilities = undefined;\n }\n\n const description: AgentDescription = {\n name,\n description: agent.description,\n className: agent.constructor.name,\n ...(capabilities ? { capabilities } : {}),\n };\n\n return [name, description] as const;\n }),\n );\n\n const agentsDict: Record<string, AgentDescription> =\n Object.fromEntries(agentEntries);\n\n const runtimeInfo: RuntimeInfo = {\n version: VERSION,\n agents: agentsDict,\n audioFileTranscriptionEnabled: !!runtime.transcriptionService,\n mode: runtime.mode,\n ...(isIntelligenceRuntime(runtime)\n ? {\n intelligence: {\n wsUrl: runtime.intelligence.ɵgetClientWsUrl(),\n },\n }\n : {}),\n // Legacy flat flag, kept for older clients. The `a2ui` object below is\n // the source of truth: it preserves the per-agent scoping that this\n // boolean discards (see CopilotKit/CopilotKit#5369). Both go through the\n // shared isA2UIEnabled() predicate so an explicit `enabled: false`\n // disables a2ui here exactly as it does on the run path.\n a2uiEnabled: isA2UIEnabled(runtime.a2ui),\n ...(isA2UIEnabled(runtime.a2ui)\n ? {\n a2ui: {\n enabled: true,\n ...(runtime.a2ui.agents ? { agents: runtime.a2ui.agents } : {}),\n },\n }\n : {}),\n openGenerativeUIEnabled: !!runtime.openGenerativeUI,\n ...(isIntelligenceRuntime(runtime)\n ? { licenseStatus: resolveLicenseStatus(runtime) }\n : {}),\n telemetryDisabled: isTelemetryDisabled(),\n };\n\n return new Response(JSON.stringify(runtimeInfo), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: \"Failed to retrieve runtime information\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;AAYA,SAAS,qBACP,SACsB;AACtB,KAAI,CAAC,QAAQ,eAAgB,QAAO;CACpC,MAAM,SAAS,QAAQ,eAAe,WAAW;AACjD,KAAI,OAAO,oBAAoB,OAAQ,QAAO;AAC9C,KAAI,OAAO,UAAU,UAAW,QAAO;AACvC,KAAI,OAAO,oBAAoB,UAAW,QAAO;AACjD,KAAI,OAAO,MAAO,QAAO;AACzB,KAAI,OAAO,oBAAoB,OAAQ,QAAO;AAC9C,QAAO;;AAQT,eAAsB,qBAAqB,EACzC,SACA,WACiC;AACjC,KAAI;EACF,MAAM,SAAS,MAAMA,8BAAc,QAAQ,QAAQ,QAAQ;EAE3D,MAAM,eAAe,MAAM,QAAQ,IACjC,OAAO,QAAQ,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,WAAW;GAClD,IAAI;AACJ,OAAI;AACF,mBAAe,MAAM,kBACjB,MAAM,MAAM,iBAAiB,GAC7B;YACG,OAAO;AAGd,YAAQ,KACN,2CAA2C,KAAK,KAChD,iBAAiB,QAAQ,MAAM,UAAU,MAC1C;AACD,mBAAe;;AAUjB,UAAO,CAAC,MAP8B;IACpC;IACA,aAAa,MAAM;IACnB,WAAW,MAAM,YAAY;IAC7B,GAAI,eAAe,EAAE,cAAc,GAAG,EAAE;IACzC,CAEyB;IAC1B,CACH;EAKD,MAAM,cAA2B;GAC/B,SAASC;GACT,QAJA,OAAO,YAAY,aAAa;GAKhC,+BAA+B,CAAC,CAAC,QAAQ;GACzC,MAAM,QAAQ;GACd,GAAIC,sCAAsB,QAAQ,GAC9B,EACE,cAAc,EACZ,OAAO,QAAQ,aAAa,iBAAiB,EAC9C,EACF,GACD,EAAE;GAMN,aAAaC,8BAAc,QAAQ,KAAK;GACxC,GAAIA,8BAAc,QAAQ,KAAK,GAC3B,EACE,MAAM;IACJ,SAAS;IACT,GAAI,QAAQ,KAAK,SAAS,EAAE,QAAQ,QAAQ,KAAK,QAAQ,GAAG,EAAE;IAC/D,EACF,GACD,EAAE;GACN,yBAAyB,CAAC,CAAC,QAAQ;GACnC,GAAID,sCAAsB,QAAQ,GAC9B,EAAE,eAAe,qBAAqB,QAAQ,EAAE,GAChD,EAAE;GACN,mBAAmBE,8CAAqB;GACzC;AAED,SAAO,IAAI,SAAS,KAAK,UAAU,YAAY,EAAE;GAC/C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,OAAO;AACd,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"get-runtime-info.cjs","names":["resolveAgents","VERSION","isIntelligenceRuntime","isA2UIEnabled","isTelemetryDisabled","supportsLocalThreadEndpoints"],"sources":["../../../../src/v2/runtime/handlers/get-runtime-info.ts"],"sourcesContent":["import type { AgentCapabilities } from \"@ag-ui/core\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../core/runtime\";\nimport type {\n AgentDescription,\n RuntimeInfo,\n ThreadEndpointRuntimeInfo,\n} from \"@copilotkit/shared\";\nimport type { RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { VERSION } from \"../core/runtime\";\nimport { isTelemetryDisabled } from \"../telemetry/telemetry-client\";\nimport { supportsLocalThreadEndpoints } from \"../runner/agent-runner\";\n\nfunction resolveLicenseStatus(\n runtime: CopilotRuntimeLike,\n): RuntimeLicenseStatus {\n if (!runtime.licenseChecker) return \"none\";\n const status = runtime.licenseChecker.getStatus();\n if (status.warningSeverity === \"none\") return \"valid\";\n if (status.error === \"expired\") return \"expired\";\n if (status.warningSeverity === \"warning\") return \"expiring\";\n if (status.error) return \"invalid\";\n if (status.warningSeverity === \"info\") return \"none\";\n return \"unknown\";\n}\n\ninterface HandleGetRuntimeInfoParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadEndpointsEnabled?: boolean;\n}\n\nexport async function handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled = true,\n}: HandleGetRuntimeInfoParameters) {\n try {\n const agents = await resolveAgents(runtime.agents, request);\n\n const agentEntries = await Promise.all(\n Object.entries(agents).map(async ([name, agent]) => {\n let capabilities: AgentCapabilities | undefined;\n try {\n capabilities = agent.getCapabilities\n ? await agent.getCapabilities()\n : undefined;\n } catch (error) {\n // Per-agent isolation: a single agent failing to report capabilities\n // must not take down the entire /info endpoint.\n console.warn(\n `Failed to fetch capabilities for agent \"${name}\":`,\n error instanceof Error ? error.message : error,\n );\n capabilities = undefined;\n }\n\n const description: AgentDescription = {\n name,\n description: agent.description,\n className: agent.constructor.name,\n ...(capabilities ? { capabilities } : {}),\n };\n\n return [name, description] as const;\n }),\n );\n\n const agentsDict: Record<string, AgentDescription> =\n Object.fromEntries(agentEntries);\n\n const runtimeInfo: RuntimeInfo = {\n version: VERSION,\n agents: agentsDict,\n audioFileTranscriptionEnabled: !!runtime.transcriptionService,\n mode: runtime.mode,\n threadEndpoints: resolveThreadEndpointInfo(\n runtime,\n threadEndpointsEnabled,\n ),\n ...(isIntelligenceRuntime(runtime)\n ? {\n intelligence: {\n wsUrl: runtime.intelligence.ɵgetClientWsUrl(),\n },\n }\n : {}),\n // Legacy flat flag, kept for older clients. The `a2ui` object below is\n // the source of truth: it preserves the per-agent scoping that this\n // boolean discards (see CopilotKit/CopilotKit#5369). Both go through the\n // shared isA2UIEnabled() predicate so an explicit `enabled: false`\n // disables a2ui here exactly as it does on the run path.\n a2uiEnabled: isA2UIEnabled(runtime.a2ui),\n ...(isA2UIEnabled(runtime.a2ui)\n ? {\n a2ui: {\n enabled: true,\n ...(runtime.a2ui.agents ? { agents: runtime.a2ui.agents } : {}),\n },\n }\n : {}),\n openGenerativeUIEnabled: !!runtime.openGenerativeUI,\n ...(isIntelligenceRuntime(runtime)\n ? { licenseStatus: resolveLicenseStatus(runtime) }\n : {}),\n telemetryDisabled: isTelemetryDisabled(),\n };\n\n return new Response(JSON.stringify(runtimeInfo), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: \"Failed to retrieve runtime information\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nfunction resolveThreadEndpointInfo(\n runtime: CopilotRuntimeLike,\n threadEndpointsEnabled: boolean,\n): ThreadEndpointRuntimeInfo {\n const hasRestThreadBackend =\n isIntelligenceRuntime(runtime) ||\n supportsLocalThreadEndpoints(runtime.runner);\n const restEndpointsAvailable = threadEndpointsEnabled && hasRestThreadBackend;\n const managedThreadMetadata =\n threadEndpointsEnabled && isIntelligenceRuntime(runtime);\n\n return {\n list: restEndpointsAvailable,\n inspect: restEndpointsAvailable,\n mutations: managedThreadMetadata,\n realtimeMetadata: managedThreadMetadata,\n };\n}\n"],"mappings":";;;;;;AAiBA,SAAS,qBACP,SACsB;AACtB,KAAI,CAAC,QAAQ,eAAgB,QAAO;CACpC,MAAM,SAAS,QAAQ,eAAe,WAAW;AACjD,KAAI,OAAO,oBAAoB,OAAQ,QAAO;AAC9C,KAAI,OAAO,UAAU,UAAW,QAAO;AACvC,KAAI,OAAO,oBAAoB,UAAW,QAAO;AACjD,KAAI,OAAO,MAAO,QAAO;AACzB,KAAI,OA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AAgB,oBAAoB;GAChD,CAAC;UACK,OAAO;AACd,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,SAAS,0BACP,SACA,wBAC2B;CAC3B,MAAM,uBACJF,sCAAsB,QAAQ,IAC9BG,kDAA6B,QAAQ,OAAO;CAC9C,MAAM,yBAAyB,0BAA0B;CACzD,MAAM,wBACJ,0BAA0BH,sCAAsB,QAAQ;AAE1D,QAAO;EACL,MAAM;EACN,SAAS;EACT,WAAW;EACX,kBAAkB;EACnB"}
@@ -1,4 +1,5 @@
1
1
  import "reflect-metadata";
2
+ import { supportsLocalThreadEndpoints } from "../runner/agent-runner.mjs";
2
3
  import { isTelemetryDisabled } from "../telemetry/telemetry-client.mjs";
3
4
  import { VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "../core/runtime.mjs";
4
5
 
@@ -13,7 +14,7 @@ function resolveLicenseStatus(runtime) {
13
14
  if (status.warningSeverity === "info") return "none";
14
15
  return "unknown";
15
16
  }
16
- async function handleGetRuntimeInfo({ runtime, request }) {
17
+ async function handleGetRuntimeInfo({ runtime, request, threadEndpointsEnabled = true }) {
17
18
  try {
18
19
  const agents = await resolveAgents(runtime.agents, request);
19
20
  const agentEntries = await Promise.all(Object.entries(agents).map(async ([name, agent]) => {
@@ -36,6 +37,7 @@ async function handleGetRuntimeInfo({ runtime, request }) {
36
37
  agents: Object.fromEntries(agentEntries),
37
38
  audioFileTranscriptionEnabled: !!runtime.transcriptionService,
38
39
  mode: runtime.mode,
40
+ threadEndpoints: resolveThreadEndpointInfo(runtime, threadEndpointsEnabled),
39
41
  ...isIntelligenceRuntime(runtime) ? { intelligence: { wsUrl: runtime.intelligence.ɵgetClientWsUrl() } } : {},
40
42
  a2uiEnabled: isA2UIEnabled(runtime.a2ui),
41
43
  ...isA2UIEnabled(runtime.a2ui) ? { a2ui: {
@@ -60,6 +62,17 @@ async function handleGetRuntimeInfo({ runtime, request }) {
60
62
  });
61
63
  }
62
64
  }
65
+ function resolveThreadEndpointInfo(runtime, threadEndpointsEnabled) {
66
+ const hasRestThreadBackend = isIntelligenceRuntime(runtime) || supportsLocalThreadEndpoints(runtime.runner);
67
+ const restEndpointsAvailable = threadEndpointsEnabled && hasRestThreadBackend;
68
+ const managedThreadMetadata = threadEndpointsEnabled && isIntelligenceRuntime(runtime);
69
+ return {
70
+ list: restEndpointsAvailable,
71
+ inspect: restEndpointsAvailable,
72
+ mutations: managedThreadMetadata,
73
+ realtimeMetadata: managedThreadMetadata
74
+ };
75
+ }
63
76
 
64
77
  //#endregion
65
78
  export { handleGetRuntimeInfo };
@@ -1 +1 @@
1
- {"version":3,"file":"get-runtime-info.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/get-runtime-info.ts"],"sourcesContent":["import type { AgentCapabilities } from \"@ag-ui/core\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../core/runtime\";\nimport type { AgentDescription, RuntimeInfo } from \"@copilotkit/shared\";\nimport type { RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { VERSION } from \"../core/runtime\";\nimport { isTelemetryDisabled } from \"../telemetry/telemetry-client\";\n\nfunction resolveLicenseStatus(\n runtime: CopilotRuntimeLike,\n): RuntimeLicenseStatus {\n if (!runtime.licenseChecker) return \"none\";\n const status = runtime.licenseChecker.getStatus();\n if (status.warningSeverity === \"none\") return \"valid\";\n if (status.error === \"expired\") return \"expired\";\n if (status.warningSeverity === \"warning\") return \"expiring\";\n if (status.error) return \"invalid\";\n if (status.warningSeverity === \"info\") return \"none\";\n return \"unknown\";\n}\n\ninterface HandleGetRuntimeInfoParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\nexport async function handleGetRuntimeInfo({\n runtime,\n request,\n}: HandleGetRuntimeInfoParameters) {\n try {\n const agents = await resolveAgents(runtime.agents, request);\n\n const agentEntries = await Promise.all(\n Object.entries(agents).map(async ([name, agent]) => {\n let capabilities: AgentCapabilities | undefined;\n try {\n capabilities = agent.getCapabilities\n ? await agent.getCapabilities()\n : undefined;\n } catch (error) {\n // Per-agent isolation: a single agent failing to report capabilities\n // must not take down the entire /info endpoint.\n console.warn(\n `Failed to fetch capabilities for agent \"${name}\":`,\n error instanceof Error ? error.message : error,\n );\n capabilities = undefined;\n }\n\n const description: AgentDescription = {\n name,\n description: agent.description,\n className: agent.constructor.name,\n ...(capabilities ? { capabilities } : {}),\n };\n\n return [name, description] as const;\n }),\n );\n\n const agentsDict: Record<string, AgentDescription> =\n Object.fromEntries(agentEntries);\n\n const runtimeInfo: RuntimeInfo = {\n version: VERSION,\n agents: agentsDict,\n audioFileTranscriptionEnabled: !!runtime.transcriptionService,\n mode: runtime.mode,\n ...(isIntelligenceRuntime(runtime)\n ? {\n intelligence: {\n wsUrl: runtime.intelligence.ɵgetClientWsUrl(),\n },\n }\n : {}),\n // Legacy flat flag, kept for older clients. The `a2ui` object below is\n // the source of truth: it preserves the per-agent scoping that this\n // boolean discards (see CopilotKit/CopilotKit#5369). Both go through the\n // shared isA2UIEnabled() predicate so an explicit `enabled: false`\n // disables a2ui here exactly as it does on the run path.\n a2uiEnabled: isA2UIEnabled(runtime.a2ui),\n ...(isA2UIEnabled(runtime.a2ui)\n ? {\n a2ui: {\n enabled: true,\n ...(runtime.a2ui.agents ? { agents: runtime.a2ui.agents } : {}),\n },\n }\n : {}),\n openGenerativeUIEnabled: !!runtime.openGenerativeUI,\n ...(isIntelligenceRuntime(runtime)\n ? { licenseStatus: resolveLicenseStatus(runtime) }\n : {}),\n telemetryDisabled: isTelemetryDisabled(),\n };\n\n return new Response(JSON.stringify(runtimeInfo), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: \"Failed to retrieve runtime information\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;AAYA,SAAS,qBACP,SACsB;AACtB,KAAI,CAAC,QAAQ,eAAgB,QAAO;CACpC,MAAM,SAAS,QAAQ,eAAe,WAAW;AACjD,KAAI,OAAO,oBAAoB,OAAQ,QAAO;AAC9C,KAAI,OAAO,UAAU,UAAW,QAAO;AACvC,KAAI,OAAO,oBAAoB,UAAW,QAAO;AACjD,KAAI,OAAO,MAAO,QAAO;AACzB,KAAI,OAAO,oBAAoB,OAAQ,QAAO;AAC9C,QAAO;;AAQT,eAAsB,qBAAqB,EACzC,SACA,WACiC;AACjC,KAAI;EACF,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QAAQ;EAE3D,MAAM,eAAe,MAAM,QAAQ,IACjC,OAAO,QAAQ,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,WAAW;GAClD,IAAI;AACJ,OAAI;AACF,mBAAe,MAAM,kBACjB,MAAM,MAAM,iBAAiB,GAC7B;YACG,OAAO;AAGd,YAAQ,KACN,2CAA2C,KAAK,KAChD,iBAAiB,QAAQ,MAAM,UAAU,MAC1C;AACD,mBAAe;;AAUjB,UAAO,CAAC,MAP8B;IACpC;IACA,aAAa,MAAM;IACnB,WAAW,MAAM,YAAY;IAC7B,GAAI,eAAe,EAAE,cAAc,GAAG,EAAE;IACzC,CAEyB;IAC1B,CACH;EAKD,MAAM,cAA2B;GAC/B,SAAS;GACT,QAJA,OAAO,YAAY,aAAa;GAKhC,+BAA+B,CAAC,CAAC,QAAQ;GACzC,MAAM,QAAQ;GACd,GAAI,sBAAsB,QAAQ,GAC9B,EACE,cAAc,EACZ,OAAO,QAAQ,aAAa,iBAAiB,EAC9C,EACF,GACD,EAAE;GAMN,aAAa,cAAc,QAAQ,KAAK;GACxC,GAAI,cAAc,QAAQ,KAAK,GAC3B,EACE,MAAM;IACJ,SAAS;IACT,GAAI,QAAQ,KAAK,SAAS,EAAE,QAAQ,QAAQ,KAAK,QAAQ,GAAG,EAAE;IAC/D,EACF,GACD,EAAE;GACN,yBAAyB,CAAC,CAAC,QAAQ;GACnC,GAAI,sBAAsB,QAAQ,GAC9B,EAAE,eAAe,qBAAqB,QAAQ,EAAE,GAChD,EAAE;GACN,mBAAmB,qBAAqB;GACzC;AAED,SAAO,IAAI,SAAS,KAAK,UAAU,YAAY,EAAE;GAC/C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,OAAO;AACd,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"get-runtime-info.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/get-runtime-info.ts"],"sourcesContent":["import type { AgentCapabilities } from \"@ag-ui/core\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../core/runtime\";\nimport type {\n AgentDescription,\n RuntimeInfo,\n ThreadEndpointRuntimeInfo,\n} from \"@copilotkit/shared\";\nimport type { RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { VERSION } from \"../core/runtime\";\nimport { isTelemetryDisabled } from \"../telemetry/telemetry-client\";\nimport { supportsLocalThreadEndpoints } from \"../runner/agent-runner\";\n\nfunction resolveLicenseStatus(\n runtime: CopilotRuntimeLike,\n): RuntimeLicenseStatus {\n if (!runtime.licenseChecker) return \"none\";\n const status = runtime.licenseChecker.getStatus();\n if (status.warningSeverity === \"none\") return \"valid\";\n if (status.error === \"expired\") return \"expired\";\n if (status.warningSeverity === \"warning\") return \"expiring\";\n if (status.error) return \"invalid\";\n if (status.warningSeverity === \"info\") return \"none\";\n return \"unknown\";\n}\n\ninterface HandleGetRuntimeInfoParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n threadEndpointsEnabled?: boolean;\n}\n\nexport async function handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled = true,\n}: HandleGetRuntimeInfoParameters) {\n try {\n const agents = await resolveAgents(runtime.agents, request);\n\n const agentEntries = await Promise.all(\n Object.entries(agents).map(async ([name, agent]) => {\n let capabilities: AgentCapabilities | undefined;\n try {\n capabilities = agent.getCapabilities\n ? await agent.getCapabilities()\n : undefined;\n } catch (error) {\n // Per-agent isolation: a single agent failing to report capabilities\n // must not take down the entire /info endpoint.\n console.warn(\n `Failed to fetch capabilities for agent \"${name}\":`,\n error instanceof Error ? error.message : error,\n );\n capabilities = undefined;\n }\n\n const description: AgentDescription = {\n name,\n description: agent.description,\n className: agent.constructor.name,\n ...(capabilities ? { capabilities } : {}),\n };\n\n return [name, description] as const;\n }),\n );\n\n const agentsDict: Record<string, AgentDescription> =\n Object.fromEntries(agentEntries);\n\n const runtimeInfo: RuntimeInfo = {\n version: VERSION,\n agents: agentsDict,\n audioFileTranscriptionEnabled: !!runtime.transcriptionService,\n mode: runtime.mode,\n threadEndpoints: resolveThreadEndpointInfo(\n runtime,\n threadEndpointsEnabled,\n ),\n ...(isIntelligenceRuntime(runtime)\n ? {\n intelligence: {\n wsUrl: runtime.intelligence.ɵgetClientWsUrl(),\n },\n }\n : {}),\n // Legacy flat flag, kept for older clients. The `a2ui` object below is\n // the source of truth: it preserves the per-agent scoping that this\n // boolean discards (see CopilotKit/CopilotKit#5369). Both go through the\n // shared isA2UIEnabled() predicate so an explicit `enabled: false`\n // disables a2ui here exactly as it does on the run path.\n a2uiEnabled: isA2UIEnabled(runtime.a2ui),\n ...(isA2UIEnabled(runtime.a2ui)\n ? {\n a2ui: {\n enabled: true,\n ...(runtime.a2ui.agents ? { agents: runtime.a2ui.agents } : {}),\n },\n }\n : {}),\n openGenerativeUIEnabled: !!runtime.openGenerativeUI,\n ...(isIntelligenceRuntime(runtime)\n ? { licenseStatus: resolveLicenseStatus(runtime) }\n : {}),\n telemetryDisabled: isTelemetryDisabled(),\n };\n\n return new Response(JSON.stringify(runtimeInfo), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: \"Failed to retrieve runtime information\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nfunction resolveThreadEndpointInfo(\n runtime: CopilotRuntimeLike,\n threadEndpointsEnabled: boolean,\n): ThreadEndpointRuntimeInfo {\n const hasRestThreadBackend =\n isIntelligenceRuntime(runtime) ||\n supportsLocalThreadEndpoints(runtime.runner);\n const restEndpointsAvailable = threadEndpointsEnabled && hasRestThreadBackend;\n const managedThreadMetadata =\n threadEndpointsEnabled && isIntelligenceRuntime(runtime);\n\n return {\n list: restEndpointsAvailable,\n inspect: restEndpointsAvailable,\n mutations: managedThreadMetadata,\n realtimeMetadata: managedThreadMetadata,\n };\n}\n"],"mappings":";;;;;;AAiBA,SAAS,qBACP,SACsB;AACtB,KAAI,CAAC,QAAQ,eAAgB,QAAO;CACpC,MAAM,SAAS,QAAQ,eAAe,WAAW;AACjD,KAAI,OAAO,oBAAoB,OAAQ,QAAO;AAC9C,KAAI,OAAO,UAAU,UAAW,QAAO;AACvC,KAAI,OAAO,oBAAoB,UAAW,QAAO;AACjD,KAAI,OAAO,MAAO,QAAO;AACzB,KAAI,OAAO,oBAAoB,OAAQ,QAAO;AAC9C,QAAO;;AAST,eAAsB,qBAAqB,EACzC,SACA,SACA,yBAAyB,QACQ;AACjC,KAAI;EACF,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QAAQ;EAE3D,MAAM,eAAe,MAAM,QAAQ,IACjC,OAAO,QAAQ,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,WAAW;GAClD,IAAI;AACJ,OAAI;AACF,mBAAe,MAAM,kBACjB,MAAM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yB,0BAA0B;CACzD,MAAM,wBACJ,0BAA0B,sBAAsB,QAAQ;AAE1D,QAAO;EACL,MAAM;EACN,SAAS;EACT,WAAW;EACX,kBAAkB;EACnB"}
@@ -1,6 +1,6 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
- const require_in_memory = require('../../runner/in-memory.cjs');
3
+ const require_agent_runner = require('../../runner/agent-runner.cjs');
4
4
  const require_runtime$1 = require('../../core/runtime.cjs');
5
5
  const require_json_response = require('../shared/json-response.cjs');
6
6
  const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
@@ -61,7 +61,7 @@ async function handleListThreads({ runtime, request }) {
61
61
  _copilotkit_shared.logger.error({ err: error }, "Error listing threads");
62
62
  return require_json_response.errorResponse("Failed to list threads", 500);
63
63
  }
64
- if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) {
64
+ if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
65
65
  const agentId = new URL(request.url).searchParams.get("agentId");
66
66
  let threads = runtime.runner.listThreads();
67
67
  if (agentId) threads = threads.filter((t) => t.agentId === agentId);
@@ -82,7 +82,7 @@ async function handleListThreads({ runtime, request }) {
82
82
  * client-side page load.
83
83
  */
84
84
  function handleClearThreads({ runtime }) {
85
- if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) runtime.runner.clearThreads();
85
+ if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) runtime.runner.clearThreads();
86
86
  return new Response(null, { status: 204 });
87
87
  }
88
88
  async function handleUpdateThread({ runtime, request, threadId }) {
@@ -190,7 +190,7 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
190
190
  }, "Error fetching thread messages");
191
191
  return require_json_response.errorResponse("Failed to fetch thread messages", 500);
192
192
  }
193
- if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) {
193
+ if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
194
194
  const mapped = runtime.runner.getThreadMessages(threadId).map((msg) => {
195
195
  switch (msg.role) {
196
196
  case "assistant": {
@@ -239,7 +239,7 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
239
239
  }, "Error fetching thread events");
240
240
  return require_json_response.errorResponse("Failed to fetch thread events", 500);
241
241
  }
242
- if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) try {
242
+ if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) try {
243
243
  const events = runtime.runner.getThreadEvents(threadId);
244
244
  return Response.json({ events });
245
245
  } catch (error) {
@@ -268,7 +268,7 @@ async function handleGetThreadState({ runtime, request, threadId }) {
268
268
  }, "Error fetching thread state");
269
269
  return require_json_response.errorResponse("Failed to fetch thread state", 500);
270
270
  }
271
- if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) try {
271
+ if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) try {
272
272
  const state = runtime.runner.getThreadState(threadId);
273
273
  return Response.json({ state });
274
274
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","InMemoryAgentRunner"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { InMemoryAgentRunner } from \"../../runner/in-memory\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (runtime.runner instanceof InMemoryAgentRunner) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when the Intelligence platform is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (runtime.runner instanceof InMemoryAgentRunner) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (runtime.runner instanceof InMemoryAgentRunner) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape the Intelligence platform\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (runtime.runner instanceof InMemoryAgentRunner) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (runtime.runner instanceof InMemoryAgentRunner) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n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CAAgC,IAAI;;AAI7D,KAAI,QAAQ,kBAAkBK,sCAC5B,KAAI;EACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOL,oCAAc,gCAAgC,IAAI;;AAI7D,QAAOA,oCACL,uJACA,IACD"}
1
+ {"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","supportsLocalThreadEndpoints"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when the Intelligence platform is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape the Intelligence platform\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QAAQ,CACjC,QAAOD,oCACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,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1
  import "reflect-metadata";
2
- import { InMemoryAgentRunner } from "../../runner/in-memory.mjs";
2
+ import { supportsLocalThreadEndpoints } from "../../runner/agent-runner.mjs";
3
3
  import { isIntelligenceRuntime } from "../../core/runtime.mjs";
4
4
  import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
5
5
  import { isValidIdentifier } from "../shared/intelligence-utils.mjs";
@@ -60,7 +60,7 @@ async function handleListThreads({ runtime, request }) {
60
60
  logger.error({ err: error }, "Error listing threads");
61
61
  return errorResponse("Failed to list threads", 500);
62
62
  }
63
- if (runtime.runner instanceof InMemoryAgentRunner) {
63
+ if (supportsLocalThreadEndpoints(runtime.runner)) {
64
64
  const agentId = new URL(request.url).searchParams.get("agentId");
65
65
  let threads = runtime.runner.listThreads();
66
66
  if (agentId) threads = threads.filter((t) => t.agentId === agentId);
@@ -81,7 +81,7 @@ async function handleListThreads({ runtime, request }) {
81
81
  * client-side page load.
82
82
  */
83
83
  function handleClearThreads({ runtime }) {
84
- if (runtime.runner instanceof InMemoryAgentRunner) runtime.runner.clearThreads();
84
+ if (supportsLocalThreadEndpoints(runtime.runner)) runtime.runner.clearThreads();
85
85
  return new Response(null, { status: 204 });
86
86
  }
87
87
  async function handleUpdateThread({ runtime, request, threadId }) {
@@ -189,7 +189,7 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
189
189
  }, "Error fetching thread messages");
190
190
  return errorResponse("Failed to fetch thread messages", 500);
191
191
  }
192
- if (runtime.runner instanceof InMemoryAgentRunner) {
192
+ if (supportsLocalThreadEndpoints(runtime.runner)) {
193
193
  const mapped = runtime.runner.getThreadMessages(threadId).map((msg) => {
194
194
  switch (msg.role) {
195
195
  case "assistant": {
@@ -238,7 +238,7 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
238
238
  }, "Error fetching thread events");
239
239
  return errorResponse("Failed to fetch thread events", 500);
240
240
  }
241
- if (runtime.runner instanceof InMemoryAgentRunner) try {
241
+ if (supportsLocalThreadEndpoints(runtime.runner)) try {
242
242
  const events = runtime.runner.getThreadEvents(threadId);
243
243
  return Response.json({ events });
244
244
  } catch (error) {
@@ -267,7 +267,7 @@ async function handleGetThreadState({ runtime, request, threadId }) {
267
267
  }, "Error fetching thread state");
268
268
  return errorResponse("Failed to fetch thread state", 500);
269
269
  }
270
- if (runtime.runner instanceof InMemoryAgentRunner) try {
270
+ if (supportsLocalThreadEndpoints(runtime.runner)) try {
271
271
  const state = runtime.runner.getThreadState(threadId);
272
272
  return Response.json({ state });
273
273
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"threads.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { InMemoryAgentRunner } from \"../../runner/in-memory\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (runtime.runner instanceof InMemoryAgentRunner) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when the Intelligence platform is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (runtime.runner instanceof InMemoryAgentRunner) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (runtime.runner instanceof InMemoryAgentRunner) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape the Intelligence platform\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (runtime.runner instanceof InMemoryAgentRunner) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (runtime.runner instanceof InMemoryAgentRunner) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QA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AQ,CAAC;UACtC,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,+BAA+B;AACtE,SAAO,cAAc,iCAAiC,IAAI;;AAK9D,KAAI,QAAQ,kBAAkB,oBAC5B,KAAI;EACF,MAAM,SAAS,QAAQ,OAAO,gBAAgB,SAAS;AACvD,SAAO,SAAS,KAAK,EAAE,QAAQ,CAAC;UACzB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,+BAA+B;AACtE,SAAO,cAAc,iCAAiC,IAAI;;AAI9D,QAAO,cACL,uJACA,IACD;;AAGH,eAAsB,qBAAqB,EACzC,SACA,SACA,YAC0C;AAI1C,KAAI,sBAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CAAE,QAAO;EAEpC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe,EAAE,UAAU,CAAC;EAMpE,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,KAAI,QAAQ,kBAAkB,oBAC5B,KAAI;EACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,QAAO,cACL,uJACA,IACD"}
1
+ {"version":3,"file":"threads.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when the Intelligence platform is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape the Intelligence platform\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,kBAAkB,QAAQ,CAC7B,QAAO,cAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;AAGH,eAAsB,kBAAkB,EACtC,SACA,WAC0C;AAE1C,KAAI,sBAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;EAChC,MAAM,UAAU,IAAI,aAAa,IAAI,UAAU;EAC/C,MAAM,kBACJ,IAAI,aAAa,IAAI,kB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M,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CAAE,QAAO;EAEpC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe,EAAE,UAAU,CAAC;EAMpE,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,KAAI,6BAA6B,QAAQ,OAAO,CAC9C,KAAI;EACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,QAAO,cACL,uJACA,IACD"}
@@ -1,6 +1,6 @@
1
1
 
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.cjs";
3
- import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest } from "./runner/agent-runner.cjs";
3
+ import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runner/agent-runner.cjs";
4
4
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
5
5
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
6
6
  import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
@@ -1,6 +1,6 @@
1
1
  import "reflect-metadata";
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.mjs";
3
- import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest } from "./runner/agent-runner.mjs";
3
+ import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runner/agent-runner.mjs";
4
4
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
5
5
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
6
6
  import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
@@ -1,8 +1,12 @@
1
1
  require("reflect-metadata");
2
2
 
3
3
  //#region src/v2/runtime/runner/agent-runner.ts
4
+ function supportsLocalThreadEndpoints(runner) {
5
+ return runner.ɵsupportsLocalThreadEndpoints === true;
6
+ }
4
7
  var AgentRunner = class {};
5
8
 
6
9
  //#endregion
7
10
  exports.AgentRunner = AgentRunner;
11
+ exports.supportsLocalThreadEndpoints = supportsLocalThreadEndpoints;
8
12
  //# sourceMappingURL=agent-runner.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-runner.cjs","names":[],"sources":["../../../../src/v2/runtime/runner/agent-runner.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\n\nexport interface AgentRunnerRunRequest {\n threadId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n persistedInputMessages?: Message[];\n}\n\nexport interface AgentRunnerConnectRequest {\n threadId: string;\n headers?: Record<string, string>;\n joinCode?: string;\n}\n\nexport interface AgentRunnerIsRunningRequest {\n threadId: string;\n}\n\nexport interface AgentRunnerStopRequest {\n threadId: string;\n}\n\nexport abstract class AgentRunner {\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":";;;AA6BA,IAAsB,cAAtB,MAAkC"}
1
+ {"version":3,"file":"agent-runner.cjs","names":[],"sources":["../../../../src/v2/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\";\n\nexport interface AgentRunnerRunRequest {\n threadId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n persistedInputMessages?: Message[];\n}\n\nexport interface AgentRunnerConnectRequest {\n threadId: string;\n headers?: Record<string, string>;\n joinCode?: string;\n}\n\nexport interface AgentRunnerIsRunningRequest {\n threadId: string;\n}\n\nexport interface AgentRunnerStopRequest {\n threadId: 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\nexport interface LocalThreadEndpointRunner extends AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints: true;\n listThreads(): LocalThreadEndpointRecord[];\n getThreadMessages(threadId: string): Message[];\n getThreadEvents(threadId: string): BaseEvent[];\n getThreadState(threadId: string): Record<string, unknown> | null;\n clearThreads(): void;\n}\n\nexport function supportsLocalThreadEndpoints(\n runner: AgentRunner,\n): runner is LocalThreadEndpointRunner {\n return runner.ɵsupportsLocalThreadEndpoints === true;\n}\n\nexport abstract class AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints?: 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":";;;AAiDA,SAAgB,6BACd,QACqC;AACrC,QAAO,OAAO,kCAAkC;;AAGlD,IAAsB,cAAtB,MAAkC"}