@copilotkit/runtime 1.81.0 → 1.83.0

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 (156) hide show
  1. package/dist/agent/index.cjs +18 -10
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +41 -1
  4. package/dist/agent/index.d.cts.map +1 -1
  5. package/dist/agent/index.d.mts +42 -2
  6. package/dist/agent/index.d.mts.map +1 -1
  7. package/dist/agent/index.mjs +18 -10
  8. package/dist/agent/index.mjs.map +1 -1
  9. package/dist/agent/url-download.cjs +504 -0
  10. package/dist/agent/url-download.cjs.map +1 -0
  11. package/dist/agent/url-download.d.cts +80 -0
  12. package/dist/agent/url-download.d.cts.map +1 -0
  13. package/dist/agent/url-download.d.mts +80 -0
  14. package/dist/agent/url-download.d.mts.map +1 -0
  15. package/dist/agent/url-download.mjs +501 -0
  16. package/dist/agent/url-download.mjs.map +1 -0
  17. package/dist/lib/runtime/copilot-runtime.cjs +2 -1
  18. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  19. package/dist/lib/runtime/copilot-runtime.d.cts +5 -0
  20. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  21. package/dist/lib/runtime/copilot-runtime.d.mts +5 -0
  22. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  23. package/dist/lib/runtime/copilot-runtime.mjs +2 -1
  24. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  25. package/dist/lib/runtime/telemetry-agent-runner.cjs +4 -1
  26. package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
  27. package/dist/lib/runtime/telemetry-agent-runner.d.cts +7 -1
  28. package/dist/lib/runtime/telemetry-agent-runner.d.cts.map +1 -1
  29. package/dist/lib/runtime/telemetry-agent-runner.d.mts +7 -1
  30. package/dist/lib/runtime/telemetry-agent-runner.d.mts.map +1 -1
  31. package/dist/lib/runtime/telemetry-agent-runner.mjs +4 -1
  32. package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
  33. package/dist/package.cjs +1 -1
  34. package/dist/package.mjs +1 -1
  35. package/dist/v2/index.cjs +12 -3
  36. package/dist/v2/index.d.cts +5 -3
  37. package/dist/v2/index.d.mts +5 -3
  38. package/dist/v2/index.mjs +6 -5
  39. package/dist/v2/runtime/core/channel-manager.cjs +2 -1
  40. package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
  41. package/dist/v2/runtime/core/channel-manager.mjs +2 -1
  42. package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
  43. package/dist/v2/runtime/core/fetch-handler.cjs +3 -3
  44. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  45. package/dist/v2/runtime/core/fetch-handler.mjs +3 -3
  46. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  47. package/dist/v2/runtime/core/package-info.cjs +1 -1
  48. package/dist/v2/runtime/core/package-info.mjs +1 -1
  49. package/dist/v2/runtime/core/runtime.cjs +12 -2
  50. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  51. package/dist/v2/runtime/core/runtime.d.cts +40 -1
  52. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  53. package/dist/v2/runtime/core/runtime.d.mts +40 -1
  54. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  55. package/dist/v2/runtime/core/runtime.mjs +12 -2
  56. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  57. package/dist/v2/runtime/handlers/get-runtime-info.cjs +6 -6
  58. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  59. package/dist/v2/runtime/handlers/get-runtime-info.mjs +6 -6
  60. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  61. package/dist/v2/runtime/handlers/handle-connect.cjs +9 -1
  62. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  63. package/dist/v2/runtime/handlers/handle-connect.mjs +9 -1
  64. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  65. package/dist/v2/runtime/handlers/handle-inspector-learning.cjs +1 -1
  66. package/dist/v2/runtime/handlers/handle-inspector-learning.mjs +1 -1
  67. package/dist/v2/runtime/handlers/handle-run.cjs +16 -2
  68. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  69. package/dist/v2/runtime/handlers/handle-run.mjs +16 -2
  70. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  71. package/dist/v2/runtime/handlers/handle-stop.cjs +14 -3
  72. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  73. package/dist/v2/runtime/handlers/handle-stop.mjs +14 -3
  74. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  75. package/dist/v2/runtime/handlers/handle-trajectory-connect.cjs +1 -1
  76. package/dist/v2/runtime/handlers/handle-trajectory-connect.mjs +1 -1
  77. package/dist/v2/runtime/handlers/intelligence/annotate.cjs +2 -2
  78. package/dist/v2/runtime/handlers/intelligence/annotate.mjs +2 -2
  79. package/dist/v2/runtime/handlers/intelligence/memories.cjs +1 -1
  80. package/dist/v2/runtime/handlers/intelligence/memories.mjs +1 -1
  81. package/dist/v2/runtime/handlers/intelligence/run.cjs +7 -4
  82. package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
  83. package/dist/v2/runtime/handlers/intelligence/run.mjs +7 -4
  84. package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
  85. package/dist/v2/runtime/handlers/intelligence/threads.cjs +137 -31
  86. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
  87. package/dist/v2/runtime/handlers/intelligence/threads.mjs +138 -32
  88. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
  89. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -3
  90. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +3 -3
  91. package/dist/v2/runtime/handlers/shared/mcp-apps-servers.cjs +2 -1
  92. package/dist/v2/runtime/handlers/shared/mcp-apps-servers.cjs.map +1 -1
  93. package/dist/v2/runtime/handlers/shared/mcp-apps-servers.mjs +3 -1
  94. package/dist/v2/runtime/handlers/shared/mcp-apps-servers.mjs.map +1 -1
  95. package/dist/v2/runtime/handlers/shared/platform-error.cjs +1 -1
  96. package/dist/v2/runtime/handlers/shared/platform-error.mjs +1 -1
  97. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +22 -3
  98. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  99. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +22 -4
  100. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  101. package/dist/v2/runtime/handlers/shared/sse-response.cjs +20 -3
  102. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  103. package/dist/v2/runtime/handlers/shared/sse-response.mjs +20 -3
  104. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  105. package/dist/v2/runtime/handlers/shared/thread-access.cjs +138 -0
  106. package/dist/v2/runtime/handlers/shared/thread-access.cjs.map +1 -0
  107. package/dist/v2/runtime/handlers/shared/thread-access.d.cts +29 -0
  108. package/dist/v2/runtime/handlers/shared/thread-access.d.cts.map +1 -0
  109. package/dist/v2/runtime/handlers/shared/thread-access.d.mts +29 -0
  110. package/dist/v2/runtime/handlers/shared/thread-access.d.mts.map +1 -0
  111. package/dist/v2/runtime/handlers/shared/thread-access.mjs +133 -0
  112. package/dist/v2/runtime/handlers/shared/thread-access.mjs.map +1 -0
  113. package/dist/v2/runtime/handlers/sse/connect.cjs +2 -1
  114. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  115. package/dist/v2/runtime/handlers/sse/connect.mjs +2 -1
  116. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  117. package/dist/v2/runtime/handlers/sse/run.cjs +23 -6
  118. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  119. package/dist/v2/runtime/handlers/sse/run.mjs +23 -6
  120. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  121. package/dist/v2/runtime/index.d.cts +3 -2
  122. package/dist/v2/runtime/index.d.cts.map +1 -1
  123. package/dist/v2/runtime/index.d.mts +3 -2
  124. package/dist/v2/runtime/index.d.mts.map +1 -1
  125. package/dist/v2/runtime/intelligence-platform/client.cjs +17 -4
  126. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  127. package/dist/v2/runtime/intelligence-platform/client.d.cts +9 -37
  128. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  129. package/dist/v2/runtime/intelligence-platform/client.d.mts +9 -37
  130. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  131. package/dist/v2/runtime/intelligence-platform/client.mjs +17 -4
  132. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  133. package/dist/v2/runtime/runner/agent-runner.cjs +55 -0
  134. package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
  135. package/dist/v2/runtime/runner/agent-runner.d.cts +90 -6
  136. package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
  137. package/dist/v2/runtime/runner/agent-runner.d.mts +90 -6
  138. package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
  139. package/dist/v2/runtime/runner/agent-runner.mjs +50 -1
  140. package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
  141. package/dist/v2/runtime/runner/in-memory.cjs +205 -25
  142. package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
  143. package/dist/v2/runtime/runner/in-memory.d.cts +112 -15
  144. package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
  145. package/dist/v2/runtime/runner/in-memory.d.mts +112 -15
  146. package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
  147. package/dist/v2/runtime/runner/in-memory.mjs +206 -27
  148. package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
  149. package/dist/v2/runtime/runner/index.d.cts +2 -2
  150. package/dist/v2/runtime/runner/index.d.mts +2 -2
  151. package/dist/v2/runtime/runner/index.mjs +2 -2
  152. package/dist/v2/runtime/telemetry/telemetry-client.cjs +1 -1
  153. package/dist/v2/runtime/telemetry/telemetry-client.cjs.map +1 -1
  154. package/dist/v2/runtime/telemetry/telemetry-client.mjs +1 -1
  155. package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -1
  156. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/run.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkit/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\nimport type { AgentRunnerRunRequest } from \"../../runner/agent-runner\";\nimport type { Observable } from \"rxjs\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport type { RuntimeErrorPhase } from \"../../core/runtime-error-reporter\";\nimport {\n resolveLearningContainerId,\n resolveLearningContainerSelector,\n} from \"../../core/learning\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { startThreadLockHeartbeat } from \"../../intelligence-platform/thread-lock-heartbeat\";\nimport type { ThreadSummary } from \"../../intelligence-platform\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface RunnerStartupBoundary {\n events: Observable<BaseEvent>;\n startup: Promise<void>;\n}\n\ninterface RunnerWithStartupBoundary {\n runWithStartupBoundary(request: AgentRunnerRunRequest): RunnerStartupBoundary;\n}\n\nfunction hasRunnerStartupBoundary(\n runner: CopilotIntelligenceRuntimeLike[\"runner\"],\n): runner is CopilotIntelligenceRuntimeLike[\"runner\"] &\n RunnerWithStartupBoundary {\n const candidate = runner as { runWithStartupBoundary?: unknown };\n\n return (\n typeof candidate.runWithStartupBoundary === \"function\" &&\n (Object.prototype.hasOwnProperty.call(runner, \"runWithStartupBoundary\") ||\n Object.prototype.hasOwnProperty.call(runner, \"threads\"))\n );\n}\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n startTime?: number;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n}: HandleIntelligenceRunParams): Promise<Response> {\n const runtimeTelemetry = runtime.telemetry ?? telemetry;\n\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n const userId = user.id;\n\n const proxyRequest = (\n input.forwardedProps as Record<string, unknown> | undefined\n )?.__proxiedMCPRequest;\n const isDirectResourceRead =\n input.forwardedProps?.__copilotkitMcpResourceReadOnly === true &&\n proxyRequest &&\n typeof proxyRequest === \"object\" &&\n (proxyRequest as { method?: unknown }).method === \"resources/read\";\n\n let learningContainerId: string | undefined;\n try {\n const selector = runtime.intelligence.ɵgetLearningContainerId?.();\n learningContainerId = selector\n ? await resolveLearningContainerSelector(selector, {\n surface: \"web\",\n user,\n agentId,\n input,\n })\n : await resolveLearningContainerId(runtime.learning, {\n surface: \"web\",\n request,\n threadId: input.threadId,\n runId: input.runId,\n agentId,\n userId,\n });\n } catch (error) {\n logger.error(\"Failed to resolve Learning Container:\", error);\n return Response.json(\n { error: \"Failed to resolve Learning Container\" },\n { status: 500 },\n );\n }\n\n let thread: ThreadSummary;\n try {\n const initialized = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n ...(learningContainerId !== undefined ? { learningContainerId } : {}),\n });\n thread = initialized.thread;\n const { created } = initialized;\n\n if (created && runtime.generateThreadNames && !thread.name?.trim()) {\n void generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput: input,\n thread,\n userId,\n }).catch((nameError) => {\n logger.error(\"Failed to generate thread name:\", nameError);\n });\n }\n } catch (error) {\n logger.error(\"Failed to get or create thread:\", error);\n const platformStatus = getPlatformErrorStatus(error);\n return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n {\n status:\n platformStatus !== undefined &&\n platformStatus >= 400 &&\n platformStatus < 500\n ? platformStatus\n : 502,\n },\n );\n }\n\n // MCP App resources are presentation data. Initialize the thread through the\n // usual path, then fetch without claiming its mutation lock so an approval\n // can continue while the resource server is still answering.\n if (isDirectResourceRead) {\n try {\n if (thread.agentId && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread belongs to another agent\" },\n { status: 403 },\n );\n }\n agent.threadId = thread.id;\n const run = await agent.runAgent({\n runId: input.runId,\n tools: input.tools,\n context: input.context,\n forwardedProps: input.forwardedProps,\n });\n return Response.json({\n kind: \"mcp-resource-read\",\n threadId: thread.id,\n runId: input.runId,\n result: run.result ?? null,\n });\n } catch (error) {\n logger.error(\"MCP resource read failed:\", error);\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"MCP resource read failed\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n\n let canonicalThreadId = input.threadId;\n let canonicalRunId = input.runId;\n let joinToken: string | undefined;\n let backendThreadId: string | undefined;\n let lockTtlSeconds: number | undefined;\n let lockRequestedAt = 0;\n try {\n // The platform starts the lock's TTL when it handles the request, so time\n // the lifetime from the send rather than from the response.\n lockRequestedAt = Date.now();\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n supportsBackendThreadId: true,\n threadId: input.threadId,\n runId: input.runId,\n userId,\n agentId,\n ...(learningContainerId !== undefined ? { learningContainerId } : {}),\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n ttlSeconds: runtime.lockTtlSeconds,\n });\n canonicalThreadId = lockResult.threadId;\n canonicalRunId = lockResult.runId;\n joinToken = lockResult.joinToken;\n backendThreadId = lockResult.backendThreadId;\n lockTtlSeconds = lockResult.ttlSeconds;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n const platformStatus = getPlatformErrorStatus(error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n {\n status: platformStatus === 409 ? 409 : 502,\n },\n );\n }\n\n const cleanupLock = (reason: string): Promise<void> =>\n runtime.intelligence\n .ɵcleanupThreadLock({\n threadId: canonicalThreadId || input.threadId,\n runId: canonicalRunId || input.runId,\n })\n .catch((cleanupError) => {\n logger.error(\n { err: cleanupError, reason },\n \"Failed to cleanup thread lock\",\n );\n });\n\n if (!canonicalThreadId || !canonicalRunId || !joinToken) {\n await cleanupLock(\"malformed-lock-response\");\n return Response.json(\n {\n error: \"Run connection credentials not available\",\n message:\n \"Intelligence platform did not return canonical threadId, runId, and joinToken\",\n },\n { status: 502 },\n );\n }\n\n const canonicalInput: RunAgentInput = {\n ...input,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n };\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const historicMessageIds = new Set(\n await runtime.intelligence.ɵgetThreadMessageIds({\n threadId: canonicalThreadId,\n userId,\n }),\n );\n persistedInputMessages = input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n );\n } catch (error) {\n logger.error(\"Thread history lookup failed:\", error);\n await cleanupLock(\"thread-history-lookup-failed\");\n return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n runtimeTelemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n // Keep the thread lock alive while the run executes. Transient renewal\n // failures are retried within the lock's remaining TTL; only a lost lock\n // (or running out of time) aborts the run.\n const heartbeat = startThreadLockHeartbeat({\n renew: (signal) =>\n runtime.intelligence.ɵrenewThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n ttlSeconds: runtime.lockTtlSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n signal,\n }),\n intervalMs: runtime.lockHeartbeatIntervalSeconds * 1_000,\n fallbackTtlSeconds: runtime.lockTtlSeconds,\n // The acquire round trip and the history lookup above both run between\n // the lock request and now, so pass the lifetime the platform set minus\n // the time already spent.\n initialTtlSeconds:\n lockTtlSeconds === undefined\n ? undefined\n : lockTtlSeconds - (Date.now() - lockRequestedAt) / 1_000,\n onLost: (err) => {\n logger.error(\"Failed to renew thread lock:\", err);\n try {\n agent.abortRun();\n } catch (abortError) {\n logger.error(\n \"Failed to abort agent after lock renewal failure:\",\n abortError,\n );\n }\n },\n });\n\n const clearHeartbeat = () => {\n heartbeat.stop();\n };\n\n const runStarted = { current: false };\n let immediateStartupErrorMessage: string | undefined;\n let immediateStartupCleanup: Promise<void> | undefined;\n\n const runRequest: AgentRunnerRunRequest = {\n threadId: canonicalThreadId,\n ...(backendThreadId === undefined ? {} : { backendThreadId }),\n agent,\n input: canonicalInput,\n ...(persistedInputMessages !== undefined ? { persistedInputMessages } : {}),\n };\n\n const runtimeErrorReporter = getRuntimeErrorReporter(runtime);\n let agentErrorReported = false;\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n // Analytics describes the outcome; only the application-owned reporter\n // receives diagnostics that may contain customer or upstream content.\n runtimeTelemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: \"AGENT_EXECUTION_FAILED\",\n });\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n phase,\n startTime,\n });\n };\n\n try {\n const runStart = hasRunnerStartupBoundary(runtime.runner)\n ? runtime.runner.runWithStartupBoundary(runRequest)\n : {\n events: runtime.runner.run(runRequest),\n startup: Promise.resolve(),\n };\n\n runStart.events.subscribe({\n next: (event: BaseEvent) => {\n if (event.type === EventType.RUN_STARTED) {\n runStarted.current = true;\n }\n if (event.type === EventType.RUN_ERROR) {\n const message =\n \"message\" in event && typeof event.message === \"string\"\n ? event.message\n : \"Runner failed before the run started\";\n reportAgentError(\n new Error(message),\n runStarted.current\n ? \"intelligence.subscription\"\n : \"intelligence.startup\",\n );\n if (!runStarted.current) {\n clearHeartbeat();\n immediateStartupErrorMessage = message;\n immediateStartupCleanup = cleanupLock(\"runner-start-failed\");\n }\n }\n },\n error: (error) => {\n reportAgentError(\n error,\n runStarted.current\n ? \"intelligence.subscription\"\n : \"intelligence.startup\",\n );\n clearHeartbeat();\n if (!runStarted.current) {\n immediateStartupErrorMessage =\n error instanceof Error ? error.message : String(error);\n immediateStartupCleanup = cleanupLock(\"runner-start-error\");\n } else {\n cleanupLock(\"runner-error\");\n }\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n clearHeartbeat();\n // Preserve the existing completion count even when the stream contains\n // RUN_ERROR. Failure reporting is separate and carries only a safe code.\n runtimeTelemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n {},\n );\n },\n });\n\n await runStart.startup;\n } catch (error) {\n reportAgentError(error, \"intelligence.startup\");\n clearHeartbeat();\n await (immediateStartupCleanup ?? cleanupLock(\"runner-start-threw\"));\n logger.error(\"Error starting agent runner:\", error);\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n\n if (immediateStartupErrorMessage) {\n await immediateStartupCleanup;\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: immediateStartupErrorMessage,\n },\n { status: 502 },\n );\n }\n\n // IntelligenceAgentRunner resolves this boundary after Phoenix channel join.\n // Other runner implementations fall back to construction/subscription errors.\n return Response.json(\n {\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: canonicalThreadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAYH,SAAS,yBACP,QAE0B;AAG1B,QACE,OAHgB,OAGC,2BAA2B,eAC3C,OAAO,UAAU,eAAe,KAAK,QAAQ,yBAAyB,IACrE,OAAO,UAAU,eAAe,KAAK,QAAQ,UAAU;;AAa7D,eAAsB,sBAAsB,EAC1C,SACA,SACA,SACA,OACA,OACA,aACiD;CACjD,MAAM,mBAAmB,QAAQ,aAAa;AAE9C,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CAGH,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CACzB,QAAO;CAET,MAAM,SAAS,KAAK;CAEpB,MAAM,eACJ,MAAM,gBACL;CACH,MAAM,uBACJ,MAAM,gBAAgB,oCAAoC,QAC1D,gBACA,OAAO,iBAAiB,YACvB,aAAsC,WAAW;CAEpD,IAAI;AACJ,KAAI;EACF,MAAM,WAAW,QAAQ,aAAa,2BAA2B;AACjE,wBAAsB,WAClB,MAAM,iCAAiC,UAAU;GAC/C,SAAS;GACT;GACA;GACA;GACD,CAAC,GACF,MAAM,2BAA2B,QAAQ,UAAU;GACjD,SAAS;GACT;GACA,UAAU,MAAM;GAChB,OAAO,MAAM;GACb;GACA;GACD,CAAC;UACC,OAAO;AACd,SAAO,MAAM,yCAAyC,MAAM;AAC5D,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;EACE,UAAU;EACV,OAAO;EACP;EACA,UAAU,4BAA4B;GACpC,WAAW,QAAQ,aAAa,iBAAiB;GACjD,UAAU;GACX,CAAC;EACH,EACD,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
1
+ {"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/run.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkit/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\nimport type { AgentRunnerRunRequest } from \"../../runner/agent-runner\";\nimport type { Observable } from \"rxjs\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport type { RuntimeErrorPhase } from \"../../core/runtime-error-reporter\";\nimport {\n resolveLearningContainerId,\n resolveLearningContainerSelector,\n} from \"../../core/learning\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { startThreadLockHeartbeat } from \"../../intelligence-platform/thread-lock-heartbeat\";\nimport type { ThreadSummary } from \"../../intelligence-platform\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface RunnerStartupBoundary {\n events: Observable<BaseEvent>;\n startup: Promise<void>;\n}\n\ninterface RunnerWithStartupBoundary {\n runWithStartupBoundary(request: AgentRunnerRunRequest): RunnerStartupBoundary;\n}\n\nfunction hasRunnerStartupBoundary(\n runner: CopilotIntelligenceRuntimeLike[\"runner\"],\n): runner is CopilotIntelligenceRuntimeLike[\"runner\"] &\n RunnerWithStartupBoundary {\n const candidate = runner as { runWithStartupBoundary?: unknown };\n\n return (\n typeof candidate.runWithStartupBoundary === \"function\" &&\n (Object.prototype.hasOwnProperty.call(runner, \"runWithStartupBoundary\") ||\n Object.prototype.hasOwnProperty.call(runner, \"threads\"))\n );\n}\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n startTime?: number;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n}: HandleIntelligenceRunParams): Promise<Response> {\n const runtimeTelemetry = runtime.telemetry ?? telemetry;\n\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n const userId = user.id;\n\n const proxyRequest = (\n input.forwardedProps as Record<string, unknown> | undefined\n )?.__proxiedMCPRequest;\n const isDirectResourceRead =\n input.forwardedProps?.__copilotkitMcpResourceReadOnly === true &&\n proxyRequest &&\n typeof proxyRequest === \"object\" &&\n (proxyRequest as { method?: unknown }).method === \"resources/read\";\n\n // CopilotKit core sends one request ID across a request's follow-up runs\n // and resumes. Older clients send none, and the platform then uses the run ID.\n const forwardedRequestId = input.forwardedProps?.__copilotkitRequestId;\n const requestId =\n typeof forwardedRequestId === \"string\" && forwardedRequestId.length > 0\n ? forwardedRequestId\n : undefined;\n\n let learningContainerId: string | undefined;\n try {\n const selector = runtime.intelligence.ɵgetLearningContainerId?.();\n learningContainerId = selector\n ? await resolveLearningContainerSelector(selector, {\n surface: \"web\",\n user,\n agentId,\n input,\n })\n : await resolveLearningContainerId(runtime.learning, {\n surface: \"web\",\n request,\n threadId: input.threadId,\n runId: input.runId,\n agentId,\n userId,\n });\n } catch (error) {\n logger.error(\"Failed to resolve Learning Container:\", error);\n return Response.json(\n { error: \"Failed to resolve Learning Container\" },\n { status: 500 },\n );\n }\n\n let thread: ThreadSummary;\n try {\n const initialized = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n ...(learningContainerId !== undefined ? { learningContainerId } : {}),\n });\n thread = initialized.thread;\n const { created } = initialized;\n\n if (created && runtime.generateThreadNames && !thread.name?.trim()) {\n void generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput: input,\n thread,\n userId,\n }).catch((nameError) => {\n logger.error(\"Failed to generate thread name:\", nameError);\n });\n }\n } catch (error) {\n logger.error(\"Failed to get or create thread:\", error);\n const platformStatus = getPlatformErrorStatus(error);\n return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n {\n status:\n platformStatus !== undefined &&\n platformStatus >= 400 &&\n platformStatus < 500\n ? platformStatus\n : 502,\n },\n );\n }\n\n // MCP App resources are presentation data. Initialize the thread through the\n // usual path, then fetch without claiming its mutation lock so an approval\n // can continue while the resource server is still answering.\n if (isDirectResourceRead) {\n try {\n if (thread.agentId && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread belongs to another agent\" },\n { status: 403 },\n );\n }\n agent.threadId = thread.id;\n const run = await agent.runAgent({\n runId: input.runId,\n tools: input.tools,\n context: input.context,\n forwardedProps: input.forwardedProps,\n });\n return Response.json({\n kind: \"mcp-resource-read\",\n threadId: thread.id,\n runId: input.runId,\n result: run.result ?? null,\n });\n } catch (error) {\n logger.error(\"MCP resource read failed:\", error);\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"MCP resource read failed\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n\n let canonicalThreadId = input.threadId;\n let canonicalRunId = input.runId;\n let joinToken: string | undefined;\n let backendThreadId: string | undefined;\n let lockTtlSeconds: number | undefined;\n let lockRequestedAt = 0;\n try {\n // The platform starts the lock's TTL when it handles the request, so time\n // the lifetime from the send rather than from the response.\n lockRequestedAt = Date.now();\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n supportsBackendThreadId: true,\n threadId: input.threadId,\n runId: input.runId,\n userId,\n agentId,\n ...(learningContainerId !== undefined ? { learningContainerId } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n ttlSeconds: runtime.lockTtlSeconds,\n });\n canonicalThreadId = lockResult.threadId;\n canonicalRunId = lockResult.runId;\n joinToken = lockResult.joinToken;\n backendThreadId = lockResult.backendThreadId;\n lockTtlSeconds = lockResult.ttlSeconds;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n const platformStatus = getPlatformErrorStatus(error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n {\n status: platformStatus === 409 ? 409 : 502,\n },\n );\n }\n\n const cleanupLock = (reason: string): Promise<void> =>\n runtime.intelligence\n .ɵcleanupThreadLock({\n threadId: canonicalThreadId || input.threadId,\n runId: canonicalRunId || input.runId,\n })\n .catch((cleanupError) => {\n logger.error(\n { err: cleanupError, reason },\n \"Failed to cleanup thread lock\",\n );\n });\n\n if (!canonicalThreadId || !canonicalRunId || !joinToken) {\n await cleanupLock(\"malformed-lock-response\");\n return Response.json(\n {\n error: \"Run connection credentials not available\",\n message:\n \"Intelligence platform did not return canonical threadId, runId, and joinToken\",\n },\n { status: 502 },\n );\n }\n\n const canonicalInput: RunAgentInput = {\n ...input,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n };\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const historicMessageIds = new Set(\n await runtime.intelligence.ɵgetThreadMessageIds({\n threadId: canonicalThreadId,\n userId,\n }),\n );\n persistedInputMessages = input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n );\n } catch (error) {\n logger.error(\"Thread history lookup failed:\", error);\n await cleanupLock(\"thread-history-lookup-failed\");\n return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n runtimeTelemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n // Keep the thread lock alive while the run executes. Transient renewal\n // failures are retried within the lock's remaining TTL; only a lost lock\n // (or running out of time) aborts the run.\n const heartbeat = startThreadLockHeartbeat({\n renew: (signal) =>\n runtime.intelligence.ɵrenewThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n ttlSeconds: runtime.lockTtlSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n signal,\n }),\n intervalMs: runtime.lockHeartbeatIntervalSeconds * 1_000,\n fallbackTtlSeconds: runtime.lockTtlSeconds,\n // The acquire round trip and the history lookup above both run between\n // the lock request and now, so pass the lifetime the platform set minus\n // the time already spent.\n initialTtlSeconds:\n lockTtlSeconds === undefined\n ? undefined\n : lockTtlSeconds - (Date.now() - lockRequestedAt) / 1_000,\n onLost: (err) => {\n logger.error(\"Failed to renew thread lock:\", err);\n try {\n agent.abortRun();\n } catch (abortError) {\n logger.error(\n \"Failed to abort agent after lock renewal failure:\",\n abortError,\n );\n }\n },\n });\n\n const clearHeartbeat = () => {\n heartbeat.stop();\n };\n\n const runStarted = { current: false };\n let immediateStartupErrorMessage: string | undefined;\n let immediateStartupCleanup: Promise<void> | undefined;\n\n const runRequest: AgentRunnerRunRequest = {\n threadId: canonicalThreadId,\n ...(backendThreadId === undefined ? {} : { backendThreadId }),\n agent,\n input: canonicalInput,\n ...(persistedInputMessages !== undefined ? { persistedInputMessages } : {}),\n };\n\n const runtimeErrorReporter = getRuntimeErrorReporter(runtime);\n let agentErrorReported = false;\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n // Analytics describes the outcome; only the application-owned reporter\n // receives diagnostics that may contain customer or upstream content.\n runtimeTelemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: \"AGENT_EXECUTION_FAILED\",\n });\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n phase,\n startTime,\n });\n };\n\n try {\n const runStart = hasRunnerStartupBoundary(runtime.runner)\n ? runtime.runner.runWithStartupBoundary(runRequest)\n : {\n events: runtime.runner.run(runRequest),\n startup: Promise.resolve(),\n };\n\n runStart.events.subscribe({\n next: (event: BaseEvent) => {\n if (event.type === EventType.RUN_STARTED) {\n runStarted.current = true;\n }\n if (event.type === EventType.RUN_ERROR) {\n const message =\n \"message\" in event && typeof event.message === \"string\"\n ? event.message\n : \"Runner failed before the run started\";\n reportAgentError(\n new Error(message),\n runStarted.current\n ? \"intelligence.subscription\"\n : \"intelligence.startup\",\n );\n if (!runStarted.current) {\n clearHeartbeat();\n immediateStartupErrorMessage = message;\n immediateStartupCleanup = cleanupLock(\"runner-start-failed\");\n }\n }\n },\n error: (error) => {\n reportAgentError(\n error,\n runStarted.current\n ? \"intelligence.subscription\"\n : \"intelligence.startup\",\n );\n clearHeartbeat();\n if (!runStarted.current) {\n immediateStartupErrorMessage =\n error instanceof Error ? error.message : String(error);\n immediateStartupCleanup = cleanupLock(\"runner-start-error\");\n } else {\n cleanupLock(\"runner-error\");\n }\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n clearHeartbeat();\n // Preserve the existing completion count even when the stream contains\n // RUN_ERROR. Failure reporting is separate and carries only a safe code.\n runtimeTelemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n {},\n );\n },\n });\n\n await runStart.startup;\n } catch (error) {\n reportAgentError(error, \"intelligence.startup\");\n clearHeartbeat();\n await (immediateStartupCleanup ?? cleanupLock(\"runner-start-threw\"));\n logger.error(\"Error starting agent runner:\", error);\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n\n if (immediateStartupErrorMessage) {\n await immediateStartupCleanup;\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: immediateStartupErrorMessage,\n },\n { status: 502 },\n );\n }\n\n // IntelligenceAgentRunner resolves this boundary after Phoenix channel join.\n // Other runner implementations fall back to construction/subscription errors.\n return Response.json(\n {\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: canonicalThreadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAYH,SAAS,yBACP,QAE0B;AAG1B,QACE,OAHgB,OAGC,2BAA2B,eAC3C,OAAO,UAAU,eAAe,KAAK,QAAQ,yBAAyB,IACrE,OAAO,UAAU,eAAe,KAAK,QAAQ,UAAU;;AAa7D,eAAsB,sBAAsB,EAC1C,SACA,SACA,SACA,OACA,OACA,aACiD;CACjD,MAAM,mBAAmB,QAAQ,aAAa;AAE9C,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;CAGH,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CACzB,QAAO;CAET,MAAM,SAAS,KAAK;CAEpB,MAAM,eACJ,MAAM,gBACL;CACH,MAAM,uBACJ,MAAM,gBAAgB,oCAAoC,QAC1D,gBACA,OAAO,iBAAiB,YACvB,aAAsC,WAAW;CAIpD,MAAM,qBAAqB,MAAM,gBAAgB;CACjD,MAAM,YACJ,OAAO,uBAAuB,YAAY,mBAAmB,SAAS,IAClE,qBACA;CAEN,IAAI;AACJ,KAAI;EACF,MAAM,WAAW,QAAQ,aAAa,2BAA2B;AACjE,wBAAsB,WAClB,MAAM,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AACnD,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,EACD,EAAE,QAAQ,KAAK,CAChB;;AAGH,KAAI,8BAA8B;AAChC,QAAM;AACN,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS;GACV,EACD,EAAE,QAAQ,KAAK,CAChB;;AAKH,QAAO,SAAS,KACd;EACE,UAAU;EACV,OAAO;EACP;EACA,UAAU,4BAA4B;GACpC,WAAW,QAAQ,aAAa,iBAAiB;GACjD,UAAU;GACX,CAAC;EACH,EACD,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
@@ -1,10 +1,11 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
3
  const require_agent_runner = require('../../runner/agent-runner.cjs');
4
- const require_runtime$1 = require('../../core/runtime.cjs');
5
4
  const require_json_response = require('../shared/json-response.cjs');
6
5
  const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
7
6
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
7
+ const require_thread_access = require('../shared/thread-access.cjs');
8
+ const require_runtime$1 = require('../../core/runtime.cjs');
8
9
  const require_platform_error = require('../shared/platform-error.cjs');
9
10
  let _copilotkit_shared = require("@copilotkit/shared");
10
11
 
@@ -37,6 +38,42 @@ async function resolveThreadMutationContext(runtime, request) {
37
38
  agentId
38
39
  };
39
40
  }
41
+ /**
42
+ * The platform's `_inspect` events and state endpoints are scoped by the
43
+ * project key only. Before calling them, confirm the thread is visible to the
44
+ * resolved user through the user-scoped thread lookup, and return its
45
+ * canonical id for the read, so the check and the read name the same thread.
46
+ *
47
+ * Returns the error Response instead when the lookup refuses: the platform's
48
+ * 4xx for a thread the user cannot see (an expected denial, logged as a
49
+ * warning), 502 for a malformed lookup result, and the mapped platform error
50
+ * for anything else (logged as an error).
51
+ */
52
+ async function requireUserThread(runtime, threadId, userId, failure) {
53
+ let thread;
54
+ try {
55
+ thread = await runtime.intelligence.getThread({
56
+ threadId,
57
+ userId
58
+ });
59
+ } catch (error) {
60
+ const status = require_intelligence_utils.getPlatformErrorStatus(error);
61
+ if (status !== void 0 && status >= 400 && status < 500 && status !== 401) _copilotkit_shared.logger.warn({
62
+ threadId,
63
+ status
64
+ }, "Thread not visible to the user");
65
+ else _copilotkit_shared.logger.error({
66
+ err: error,
67
+ threadId
68
+ }, "Error resolving thread");
69
+ return require_platform_error.platformErrorResponse(error, failure);
70
+ }
71
+ if (!thread || typeof thread.id !== "string" || !thread.id.trim()) {
72
+ _copilotkit_shared.logger.error({ threadId }, "Invalid thread response from getThread");
73
+ return require_json_response.errorResponse("Invalid thread response", 502);
74
+ }
75
+ return { threadId: thread.id };
76
+ }
40
77
  async function handleListThreads({ runtime, request }) {
41
78
  if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
42
79
  const url = new URL(request.url);
@@ -63,27 +100,54 @@ async function handleListThreads({ runtime, request }) {
63
100
  return require_json_response.errorResponse("Failed to list threads", 500);
64
101
  }
65
102
  if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
66
- const agentId = new URL(request.url).searchParams.get("agentId");
67
- let threads = runtime.runner.listThreads();
68
- if (agentId) threads = threads.filter((t) => t.agentId === agentId);
69
- return Response.json({
70
- threads,
71
- nextCursor: null
103
+ const ownerId = await require_thread_access.resolveLocalThreadOwner({
104
+ runtime,
105
+ request,
106
+ operation: "list"
72
107
  });
108
+ if (require_json_response.isHandlerResponse(ownerId)) return ownerId;
109
+ try {
110
+ const agentId = new URL(request.url).searchParams.get("agentId");
111
+ let threads = runtime.runner.listThreads({ ownerId });
112
+ if (agentId) threads = threads.filter((t) => t.agentId === agentId);
113
+ return Response.json({
114
+ threads,
115
+ nextCursor: null
116
+ });
117
+ } catch (error) {
118
+ _copilotkit_shared.logger.error({ err: error }, "Error listing threads");
119
+ return require_json_response.errorResponse("Failed to list threads", 500);
120
+ }
73
121
  }
74
122
  return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
75
123
  }
76
124
  /**
77
- * Clears all in-memory thread history for the local-dev InMemory fallback.
125
+ * Clears the caller's in-memory thread history for the local-dev fallback.
78
126
  *
79
127
  * The local-dev fallback exposes this so consumers (e.g. the demo's Clear
80
128
  * button) can wipe in-memory thread history without restarting the runtime.
129
+ * Only the caller's own threads are cleared, and a thread whose run is
130
+ * still active is kept. Without `identifyUser`, the access policy refuses it
131
+ * unless `threads: { access: "open" }` is set.
81
132
  * Intentionally a no-op when CopilotKit Intelligence is configured: real
82
133
  * thread history lives in the database and must not be wiped by a
83
134
  * client-side page load.
84
135
  */
85
- function handleClearThreads({ runtime }) {
86
- if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) runtime.runner.clearThreads();
136
+ async function handleClearThreads({ runtime, request }) {
137
+ if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
138
+ const ownerId = await require_thread_access.resolveLocalThreadOwner({
139
+ runtime,
140
+ request,
141
+ operation: "clear"
142
+ });
143
+ if (require_json_response.isHandlerResponse(ownerId)) return ownerId;
144
+ try {
145
+ runtime.runner.clearThreads({ ownerId });
146
+ } catch (error) {
147
+ _copilotkit_shared.logger.error({ err: error }, "Error clearing threads");
148
+ return require_json_response.errorResponse("Failed to clear threads", 500);
149
+ }
150
+ }
87
151
  return new Response(null, { status: 204 });
88
152
  }
89
153
  async function handleUpdateThread({ runtime, request, threadId }) {
@@ -191,7 +255,23 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
191
255
  return require_platform_error.platformErrorResponse(error, "Failed to fetch thread messages");
192
256
  }
193
257
  if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
194
- const mapped = runtime.runner.getThreadMessages(threadId).map((msg) => {
258
+ const ownerId = await require_thread_access.resolveLocalThreadOwner({
259
+ runtime,
260
+ request,
261
+ operation: "read"
262
+ });
263
+ if (require_json_response.isHandlerResponse(ownerId)) return ownerId;
264
+ let messages;
265
+ try {
266
+ messages = runtime.runner.getThreadMessages(threadId, { ownerId });
267
+ } catch (error) {
268
+ _copilotkit_shared.logger.error({
269
+ err: error,
270
+ threadId
271
+ }, "Error fetching thread messages");
272
+ return require_json_response.errorResponse("Failed to fetch thread messages", 500);
273
+ }
274
+ const mapped = messages.map((msg) => {
195
275
  switch (msg.role) {
196
276
  case "assistant": {
197
277
  const toolCalls = msg.toolCalls ?? [];
@@ -230,7 +310,12 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
230
310
  request
231
311
  });
232
312
  if (require_json_response.isHandlerResponse(user)) return user;
233
- const data = await runtime.intelligence.getThreadEvents({ threadId });
313
+ const thread = await requireUserThread(runtime, threadId, user.id, "Failed to fetch thread events");
314
+ if (require_json_response.isHandlerResponse(thread)) return thread;
315
+ const data = await runtime.intelligence.getThreadEvents({
316
+ threadId: thread.threadId,
317
+ userId: user.id
318
+ });
234
319
  return Response.json({ events: data.events });
235
320
  } catch (error) {
236
321
  _copilotkit_shared.logger.error({
@@ -239,15 +324,23 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
239
324
  }, "Error fetching thread events");
240
325
  return require_platform_error.platformErrorResponse(error, "Failed to fetch thread events");
241
326
  }
242
- if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) try {
243
- const events = runtime.runner.getThreadEvents(threadId);
244
- return Response.json({ events });
245
- } catch (error) {
246
- _copilotkit_shared.logger.error({
247
- err: error,
248
- threadId
249
- }, "Error fetching thread events");
250
- return require_json_response.errorResponse("Failed to fetch thread events", 500);
327
+ if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
328
+ const ownerId = await require_thread_access.resolveLocalThreadOwner({
329
+ runtime,
330
+ request,
331
+ operation: "read"
332
+ });
333
+ if (require_json_response.isHandlerResponse(ownerId)) return ownerId;
334
+ try {
335
+ const events = runtime.runner.getThreadEvents(threadId, { ownerId });
336
+ return Response.json({ events });
337
+ } catch (error) {
338
+ _copilotkit_shared.logger.error({
339
+ err: error,
340
+ threadId
341
+ }, "Error fetching thread events");
342
+ return require_json_response.errorResponse("Failed to fetch thread events", 500);
343
+ }
251
344
  }
252
345
  return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
253
346
  }
@@ -258,7 +351,12 @@ async function handleGetThreadState({ runtime, request, threadId }) {
258
351
  request
259
352
  });
260
353
  if (require_json_response.isHandlerResponse(user)) return user;
261
- const data = await runtime.intelligence.getThreadState({ threadId });
354
+ const thread = await requireUserThread(runtime, threadId, user.id, "Failed to fetch thread state");
355
+ if (require_json_response.isHandlerResponse(thread)) return thread;
356
+ const data = await runtime.intelligence.getThreadState({
357
+ threadId: thread.threadId,
358
+ userId: user.id
359
+ });
262
360
  const state = data.kind === "snapshot" ? data.state : null;
263
361
  return Response.json({ state });
264
362
  } catch (error) {
@@ -268,15 +366,23 @@ async function handleGetThreadState({ runtime, request, threadId }) {
268
366
  }, "Error fetching thread state");
269
367
  return require_platform_error.platformErrorResponse(error, "Failed to fetch thread state");
270
368
  }
271
- if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) try {
272
- const state = runtime.runner.getThreadState(threadId);
273
- return Response.json({ state });
274
- } catch (error) {
275
- _copilotkit_shared.logger.error({
276
- err: error,
277
- threadId
278
- }, "Error fetching thread state");
279
- return require_json_response.errorResponse("Failed to fetch thread state", 500);
369
+ if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
370
+ const ownerId = await require_thread_access.resolveLocalThreadOwner({
371
+ runtime,
372
+ request,
373
+ operation: "read"
374
+ });
375
+ if (require_json_response.isHandlerResponse(ownerId)) return ownerId;
376
+ try {
377
+ const state = runtime.runner.getThreadState(threadId, { ownerId });
378
+ return Response.json({ state });
379
+ } catch (error) {
380
+ _copilotkit_shared.logger.error({
381
+ err: error,
382
+ threadId
383
+ }, "Error fetching thread state");
384
+ return require_json_response.errorResponse("Failed to fetch thread state", 500);
385
+ }
280
386
  }
281
387
  return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
282
388
  }
@@ -1 +1 @@
1
- {"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","supportsLocalThreadEndpoints","platformErrorResponse"],"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 { platformErrorResponse } from \"../shared/platform-error\";\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 // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const 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 CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport 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 // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; 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 platformErrorResponse(error, \"Failed to fetch thread events\");\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 // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\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 platformErrorResponse(error, \"Failed to fetch thread state\");\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":";;;;;;;;;;;AA2BA,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,oC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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","getPlatformErrorStatus","platformErrorResponse","supportsLocalThreadEndpoints","resolveLocalThreadOwner"],"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 {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QAAQ,CACjC,QAAOD,oCACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIE,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAACE,6CAAkB,QAAQ,CAC7B,QAAOJ,oCAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;;;;;;;;;;;;AAcH,eAAe,kBACb,SACA,UACA,QACA,SAC0C;CAC1C,IAAI;AACJ,KAAI;AACF,WAAS,MAAM,QAAQ,aAAa,UAAU;GAAE;GAAU;GAAQ,CAAC;UAC5D,OAAO;EACd,MAAM,SAASK,kDAAuB,MAAM;AAC5C,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