@copilotkit/runtime 1.82.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 (144) hide show
  1. package/dist/agent/index.cjs +8 -3
  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 +8 -3
  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 +3 -0
  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 +3 -0
  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 +1 -1
  40. package/dist/v2/runtime/core/channel-manager.mjs +1 -1
  41. package/dist/v2/runtime/core/fetch-handler.cjs +2 -2
  42. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  43. package/dist/v2/runtime/core/fetch-handler.mjs +2 -2
  44. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  45. package/dist/v2/runtime/core/package-info.cjs +1 -1
  46. package/dist/v2/runtime/core/package-info.mjs +1 -1
  47. package/dist/v2/runtime/core/runtime.cjs +12 -2
  48. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  49. package/dist/v2/runtime/core/runtime.d.cts +40 -1
  50. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  51. package/dist/v2/runtime/core/runtime.d.mts +40 -1
  52. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  53. package/dist/v2/runtime/core/runtime.mjs +12 -2
  54. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  55. package/dist/v2/runtime/handlers/get-runtime-info.cjs +6 -6
  56. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  57. package/dist/v2/runtime/handlers/get-runtime-info.mjs +6 -6
  58. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  59. package/dist/v2/runtime/handlers/handle-connect.cjs +9 -1
  60. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  61. package/dist/v2/runtime/handlers/handle-connect.mjs +9 -1
  62. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  63. package/dist/v2/runtime/handlers/handle-inspector-learning.cjs +1 -1
  64. package/dist/v2/runtime/handlers/handle-inspector-learning.mjs +1 -1
  65. package/dist/v2/runtime/handlers/handle-run.cjs +16 -2
  66. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  67. package/dist/v2/runtime/handlers/handle-run.mjs +16 -2
  68. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  69. package/dist/v2/runtime/handlers/handle-stop.cjs +14 -3
  70. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  71. package/dist/v2/runtime/handlers/handle-stop.mjs +14 -3
  72. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  73. package/dist/v2/runtime/handlers/handle-trajectory-connect.cjs +1 -1
  74. package/dist/v2/runtime/handlers/handle-trajectory-connect.mjs +1 -1
  75. package/dist/v2/runtime/handlers/intelligence/annotate.cjs +2 -2
  76. package/dist/v2/runtime/handlers/intelligence/annotate.mjs +2 -2
  77. package/dist/v2/runtime/handlers/intelligence/memories.cjs +1 -1
  78. package/dist/v2/runtime/handlers/intelligence/memories.mjs +1 -1
  79. package/dist/v2/runtime/handlers/intelligence/run.cjs +4 -4
  80. package/dist/v2/runtime/handlers/intelligence/run.mjs +4 -4
  81. package/dist/v2/runtime/handlers/intelligence/threads.cjs +137 -31
  82. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
  83. package/dist/v2/runtime/handlers/intelligence/threads.mjs +138 -32
  84. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
  85. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -3
  86. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +3 -3
  87. package/dist/v2/runtime/handlers/shared/platform-error.cjs +1 -1
  88. package/dist/v2/runtime/handlers/shared/platform-error.mjs +1 -1
  89. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +22 -3
  90. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  91. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +22 -4
  92. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  93. package/dist/v2/runtime/handlers/shared/sse-response.cjs +19 -2
  94. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  95. package/dist/v2/runtime/handlers/shared/sse-response.mjs +19 -2
  96. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  97. package/dist/v2/runtime/handlers/shared/thread-access.cjs +138 -0
  98. package/dist/v2/runtime/handlers/shared/thread-access.cjs.map +1 -0
  99. package/dist/v2/runtime/handlers/shared/thread-access.d.cts +29 -0
  100. package/dist/v2/runtime/handlers/shared/thread-access.d.cts.map +1 -0
  101. package/dist/v2/runtime/handlers/shared/thread-access.d.mts +29 -0
  102. package/dist/v2/runtime/handlers/shared/thread-access.d.mts.map +1 -0
  103. package/dist/v2/runtime/handlers/shared/thread-access.mjs +133 -0
  104. package/dist/v2/runtime/handlers/shared/thread-access.mjs.map +1 -0
  105. package/dist/v2/runtime/handlers/sse/connect.cjs +2 -1
  106. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  107. package/dist/v2/runtime/handlers/sse/connect.mjs +2 -1
  108. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  109. package/dist/v2/runtime/handlers/sse/run.cjs +23 -6
  110. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  111. package/dist/v2/runtime/handlers/sse/run.mjs +23 -6
  112. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  113. package/dist/v2/runtime/index.d.cts +3 -2
  114. package/dist/v2/runtime/index.d.cts.map +1 -1
  115. package/dist/v2/runtime/index.d.mts +3 -2
  116. package/dist/v2/runtime/index.d.mts.map +1 -1
  117. package/dist/v2/runtime/intelligence-platform/client.cjs +16 -4
  118. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  119. package/dist/v2/runtime/intelligence-platform/client.d.cts +4 -37
  120. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  121. package/dist/v2/runtime/intelligence-platform/client.d.mts +4 -37
  122. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  123. package/dist/v2/runtime/intelligence-platform/client.mjs +16 -4
  124. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  125. package/dist/v2/runtime/runner/agent-runner.cjs +55 -0
  126. package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
  127. package/dist/v2/runtime/runner/agent-runner.d.cts +90 -6
  128. package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
  129. package/dist/v2/runtime/runner/agent-runner.d.mts +90 -6
  130. package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
  131. package/dist/v2/runtime/runner/agent-runner.mjs +50 -1
  132. package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
  133. package/dist/v2/runtime/runner/in-memory.cjs +205 -25
  134. package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
  135. package/dist/v2/runtime/runner/in-memory.d.cts +112 -15
  136. package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
  137. package/dist/v2/runtime/runner/in-memory.d.mts +112 -15
  138. package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
  139. package/dist/v2/runtime/runner/in-memory.mjs +206 -27
  140. package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
  141. package/dist/v2/runtime/runner/index.d.cts +2 -2
  142. package/dist/v2/runtime/runner/index.d.mts +2 -2
  143. package/dist/v2/runtime/runner/index.mjs +2 -2
  144. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"handle-run.cjs","names":["telemetry","readGuardrailsEnabled","cloneAgentForRequest","parseRunRequest","attachIntelligenceEnterpriseLearning","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n },\n );\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n // transport of this run.\n const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n input.forwardedProps,\n )?.metadata.extensions.copilotkit_transport;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n providerGenerativeUITransport,\n isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n input.forwardedProps ?? {},\n \"__proxiedMCPRequest\",\n ),\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n startTime,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\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":";;;;;;;;;;;;AAeA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,eAAe,QAAQ,QAAQ,IAAI,gCAAgC;AACzE,EAAC,QAAQ,aAAaA,kCAAW,QAC/B,uCACA;EACE,4BAA4B,MAAMC,8CAAsB,QAAQ;EAChE,aAAa;EACb,0BAA0B,CAAC,CAAC;EAC5B,GAAI,eAAe,EAAE,wBAAwB,cAAc,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,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,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":"handle-run.cjs","names":["telemetry","readGuardrailsEnabled","cloneAgentForRequest","parseRunRequest","isIntelligenceRuntime","resolveLocalThreadOwner","enforcesThreadOwnership","threadAccessDeniedResponse","attachIntelligenceEnterpriseLearning","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\nimport { enforcesThreadOwnership } from \"../runner/agent-runner\";\nimport {\n resolveLocalThreadOwner,\n threadAccessDeniedResponse,\n} from \"./shared/thread-access\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n },\n );\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: middleware configuration\n // needs the A2UI catalog signal the React provider forwards (see\n // `a2uiCatalogAvailable` below). Middleware is applied to the agent here;\n // the run itself is kicked off later, so this is safe. The body is read\n // from a clone, so `identifyUser` can still read the original request.\n const input = await parseRunRequest(request.clone());\n if (input instanceof Response) {\n return input;\n }\n\n // A thread belongs to the identity of its first run. Running needs no\n // configured identity (anonymous runs keep working), but nobody may add to\n // a thread that another identity owns.\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"run\",\n });\n if (owner instanceof Response) return owner;\n if (\n enforcesThreadOwnership(runtime.runner) &&\n !(await runtime.runner.isThreadAccessible(input.threadId, {\n ownerId: owner,\n }))\n ) {\n return threadAccessDeniedResponse();\n }\n ownerId = owner;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n // transport of this run.\n const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n input.forwardedProps,\n )?.metadata.extensions.copilotkit_transport;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n providerGenerativeUITransport,\n isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n input.forwardedProps ?? {},\n \"__proxiedMCPRequest\",\n ),\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n startTime,\n ownerId,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\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":";;;;;;;;;;;;;;AAoBA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,eAAe,QAAQ,QAAQ,IAAI,gCAAgC;AACzE,EAAC,QAAQ,aAAaA,kCAAW,QAC/B,uCACA;EACE,4BAA4B,MAAMC,8CAAsB,QAAQ;EAChE,aAAa;EACb,0BAA0B,CAAC,CAAC;EAC5B,GAAI,eAAe,EAAE,wBAAwB,cAAc,GAAG,EAAE;EACjE,CACF;AAED,KAAI;EACF,MAAM,QAAQ,MAAMC,yCAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;EAOhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ,OAAO,CAAC;AACpD,MAAI,iBAAiB,SACnB,QAAO;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M,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,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,4 +1,6 @@
1
1
  import "reflect-metadata";
2
+ import { enforcesThreadOwnership } from "../runner/agent-runner.mjs";
3
+ import { resolveLocalThreadOwner, threadAccessDeniedResponse } from "./shared/thread-access.mjs";
2
4
  import telemetry from "../telemetry/telemetry-client.mjs";
3
5
  import { getRuntimeErrorReporter } from "../core/runtime-error-reporter.mjs";
4
6
  import { isIntelligenceRuntime } from "../core/runtime.mjs";
@@ -22,8 +24,19 @@ async function handleRunAgent({ runtime, request, agentId }) {
22
24
  const agent = await cloneAgentForRequest(runtime, agentId, request);
23
25
  if (agent instanceof Response) return agent;
24
26
  agent.agentId = agentId;
25
- const input = await parseRunRequest(request);
27
+ const input = await parseRunRequest(request.clone());
26
28
  if (input instanceof Response) return input;
29
+ let ownerId;
30
+ if (!isIntelligenceRuntime(runtime)) {
31
+ const owner = await resolveLocalThreadOwner({
32
+ runtime,
33
+ request,
34
+ operation: "run"
35
+ });
36
+ if (owner instanceof Response) return owner;
37
+ if (enforcesThreadOwnership(runtime.runner) && !await runtime.runner.isThreadAccessible(input.threadId, { ownerId: owner })) return threadAccessDeniedResponse();
38
+ ownerId = owner;
39
+ }
27
40
  const providerA2UIHasCatalog = input.forwardedProps?.a2uiCatalogAvailable === true;
28
41
  const providerGenerativeUITransport = readCopilotKitUIEnvelope(input.forwardedProps)?.metadata.extensions.copilotkit_transport;
29
42
  configureAgentForRequest({
@@ -64,7 +77,8 @@ async function handleRunAgent({ runtime, request, agentId }) {
64
77
  agentId,
65
78
  debug: runtime.debug,
66
79
  logger: runtime.debugLogger,
67
- startTime
80
+ startTime,
81
+ ownerId
68
82
  });
69
83
  } catch (error) {
70
84
  getRuntimeErrorReporter(runtime)?.report({
@@ -1 +1 @@
1
- {"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n },\n );\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: the request is single-read,\n // and middleware configuration needs the A2UI catalog signal the React\n // provider forwards (see `a2uiCatalogAvailable` below). Middleware is applied\n // to the agent here; the run itself is kicked off later, so this is safe.\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n // transport of this run.\n const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n input.forwardedProps,\n )?.metadata.extensions.copilotkit_transport;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n providerGenerativeUITransport,\n isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n input.forwardedProps ?? {},\n \"__proxiedMCPRequest\",\n ),\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n startTime,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application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AC;UACK,OAAO;AACd,0BAAwB,QAAQ,EAAE,OAAO;GACvC;GACA;GACA,WAAW;GACX;GACA,OAAO;GACP;GACD,CAAC;AACF,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,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":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { readCopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport { readGuardrailsEnabled } from \"./shared/cloud-telemetry\";\nimport type { RunAgentParameters } from \"./shared/agent-utils\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\nimport { getRuntimeErrorReporter } from \"../core/runtime-error-reporter\";\nimport { enforcesThreadOwnership } from \"../runner/agent-runner\";\nimport {\n resolveLocalThreadOwner,\n threadAccessDeniedResponse,\n} from \"./shared/thread-access\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n const startTime = Date.now();\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n (runtime.telemetry ?? telemetry).capture(\n \"oss.runtime.copilot_request_created\",\n {\n \"cloud.guardrails.enabled\": await readGuardrailsEnabled(request),\n requestType: \"run\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n },\n );\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n // Parse the body before configuring middleware: middleware configuration\n // needs the A2UI catalog signal the React provider forwards (see\n // `a2uiCatalogAvailable` below). Middleware is applied to the agent here;\n // the run itself is kicked off later, so this is safe. The body is read\n // from a clone, so `identifyUser` can still read the original request.\n const input = await parseRunRequest(request.clone());\n if (input instanceof Response) {\n return input;\n }\n\n // A thread belongs to the identity of its first run. Running needs no\n // configured identity (anonymous runs keep working), but nobody may add to\n // a thread that another identity owns.\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"run\",\n });\n if (owner instanceof Response) return owner;\n if (\n enforcesThreadOwnership(runtime.runner) &&\n !(await runtime.runner.isThreadAccessible(input.threadId, {\n ownerId: owner,\n }))\n ) {\n return threadAccessDeniedResponse();\n }\n ownerId = owner;\n }\n\n // `<CopilotKit a2ui={{ catalog }}>` forwards this flag on every run. Its\n // presence alone is enough to turn A2UI on end-to-end — no runtime-side\n // `a2ui` config required.\n const providerA2UIHasCatalog =\n (input.forwardedProps as Record<string, unknown> | undefined)\n ?.a2uiCatalogAvailable === true;\n // The generative UI envelope (`forwardedProps.copilotkit.ui`) picks the\n // transport of this run.\n const providerGenerativeUITransport = readCopilotKitUIEnvelope(\n input.forwardedProps,\n )?.metadata.extensions.copilotkit_transport;\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n providerA2UIHasCatalog,\n providerGenerativeUITransport,\n isMcpProxyRequest: Object.prototype.hasOwnProperty.call(\n input.forwardedProps ?? {},\n \"__proxiedMCPRequest\",\n ),\n });\n const memoryResponse = await attachIntelligenceEnterpriseLearning({\n runtime,\n request,\n agent,\n });\n if (memoryResponse instanceof Response) return memoryResponse;\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n startTime,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n startTime,\n ownerId,\n });\n } catch (error) {\n getRuntimeErrorReporter(runtime)?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n phase: \"common\",\n startTime,\n });\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\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":";;;;;;;;;;;;;AAoBA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;CACrB,MAAM,YAAY,KAAK,KAAK;CAC5B,MAAM,eAAe,QAAQ,QAAQ,IAAI,gCAAgC;AACzE,EAAC,QAAQ,aAAa,WAAW,QAC/B,uCACA;EACE,4BAA4B,MAAM,sBAAsB,QAAQ;EAChE,aAAa;EACb,0BAA0B,CAAC,CAAC;EAC5B,GAAI,eAAe,EAAE,wBAAwB,cAAc,GAAG,EAAE;EACjE,CACF;AAED,KAAI;EACF,MAAM,QAAQ,MAAM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;GACX;GACA,OAAO;GACP;GACD,CAAC;AACF,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,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,9 +1,10 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
3
- const require_runtime$1 = require('../core/runtime.cjs');
4
3
  const require_json_response = require('./shared/json-response.cjs');
5
4
  const require_intelligence_utils = require('./shared/intelligence-utils.cjs');
6
5
  const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
6
+ const require_thread_access = require('./shared/thread-access.cjs');
7
+ const require_runtime$1 = require('../core/runtime.cjs');
7
8
  let _ag_ui_client = require("@ag-ui/client");
8
9
 
9
10
  //#region src/v2/runtime/handlers/handle-stop.ts
@@ -28,7 +29,16 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
28
29
  if (require_json_response.isHandlerResponse(scope)) return scope;
29
30
  const { runId } = scope;
30
31
  let stopThreadId = threadId;
31
- if (require_runtime$1.isIntelligenceRuntime(runtime)) {
32
+ let ownerId;
33
+ if (!require_runtime$1.isIntelligenceRuntime(runtime)) {
34
+ const owner = await require_thread_access.resolveLocalThreadOwner({
35
+ runtime,
36
+ request,
37
+ operation: "stop"
38
+ });
39
+ if (require_json_response.isHandlerResponse(owner)) return owner;
40
+ ownerId = owner;
41
+ } else {
32
42
  const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
33
43
  runtime,
34
44
  request
@@ -56,7 +66,8 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
56
66
  });
57
67
  if (!await runtime.runner.stop({
58
68
  threadId: stopThreadId,
59
- ...runId === void 0 ? {} : { runId }
69
+ ...runId === void 0 ? {} : { runId },
70
+ ...ownerId === void 0 ? {} : { ownerId }
60
71
  })) return new Response(JSON.stringify({
61
72
  stopped: false,
62
73
  message: runId === void 0 ? `No active run for thread '${threadId}'.` : `Run '${runId}' is not the active run for thread '${threadId}'.`
@@ -1 +1 @@
1
- {"version":3,"file":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n if (isIntelligenceRuntime(runtime)) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\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":";;;;;;;;;;AAeA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,OAAO;SACtB;AACN,SAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;AAK5E,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;EAIF,MAAM,QAAQ,MAAM,eAAe,QAAQ,OAAO,CAAC;AACnD,MAAIA,wCAAkB,MAAM,CAAE,QAAO;EACrC,MAAM,EAAE,UAAU;EAClB,IAAI,eAAe;AACnB,MAAIC,wCAAsB,QAAQ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MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,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":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveLocalThreadOwner","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\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":";;;;;;;;;;;AAgBA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,OAAO;SACtB;AACN,SAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;AAK5E,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;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,OAAO;GACxC,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SACE,UAAU,SACN,6BAA6B,SAAS,MACtC,QAAQ,MAAM,sCAAsC,SAAS;GACpE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAMC,wBAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,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,8 +1,9 @@
1
1
  import "reflect-metadata";
2
- import { isIntelligenceRuntime, resolveAgents } from "../core/runtime.mjs";
3
2
  import { isHandlerResponse } from "./shared/json-response.mjs";
4
3
  import { getPlatformErrorStatus } from "./shared/intelligence-utils.mjs";
5
4
  import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs";
5
+ import { resolveLocalThreadOwner } from "./shared/thread-access.mjs";
6
+ import { isIntelligenceRuntime, resolveAgents } from "../core/runtime.mjs";
6
7
  import { EventType } from "@ag-ui/client";
7
8
 
8
9
  //#region src/v2/runtime/handlers/handle-stop.ts
@@ -27,7 +28,16 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
27
28
  if (isHandlerResponse(scope)) return scope;
28
29
  const { runId } = scope;
29
30
  let stopThreadId = threadId;
30
- if (isIntelligenceRuntime(runtime)) {
31
+ let ownerId;
32
+ if (!isIntelligenceRuntime(runtime)) {
33
+ const owner = await resolveLocalThreadOwner({
34
+ runtime,
35
+ request,
36
+ operation: "stop"
37
+ });
38
+ if (isHandlerResponse(owner)) return owner;
39
+ ownerId = owner;
40
+ } else {
31
41
  const user = await resolveIntelligenceUser({
32
42
  runtime,
33
43
  request
@@ -55,7 +65,8 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
55
65
  });
56
66
  if (!await runtime.runner.stop({
57
67
  threadId: stopThreadId,
58
- ...runId === void 0 ? {} : { runId }
68
+ ...runId === void 0 ? {} : { runId },
69
+ ...ownerId === void 0 ? {} : { ownerId }
59
70
  })) return new Response(JSON.stringify({
60
71
  stopped: false,
61
72
  message: runId === void 0 ? `No active run for thread '${threadId}'.` : `Run '${runId}' is not the active run for thread '${threadId}'.`
@@ -1 +1 @@
1
- {"version":3,"file":"handle-stop.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n if (isIntelligenceRuntime(runtime)) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\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":";;;;;;;;;AAeA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,OAAO;SACtB;AACN,SAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;AAK5E,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;EAIF,MAAM,QAAQ,MAAM,eAAe,QAAQ,OAAO,CAAC;AACnD,MAAI,kBAAkB,MAAM,CAAE,QAAO;EACrC,MAAM,EAAE,UAAU;EACl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ACT,MAAM,UAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,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":"handle-stop.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\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":";;;;;;;;;;AAgBA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,OAAO;SACtB;AACN,SAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;AAK5E,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;EAIF,MAAM,QAAQ,MAAM,eAAe,QAAQ,OAAO,CAAC;A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C,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SACE,UAAU,SACN,6BAA6B,SAAS,MACtC,QAAQ,MAAM,sCAAsC,SAAS;GACpE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAM,UAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,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,7 +1,7 @@
1
1
  require("reflect-metadata");
2
- const require_runtime = require('../core/runtime.cjs');
3
2
  const require_trajectories = require('../intelligence-platform/trajectories.cjs');
4
3
  const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
4
+ const require_runtime = require('../core/runtime.cjs');
5
5
 
6
6
  //#region src/v2/runtime/handlers/handle-trajectory-connect.ts
7
7
  function trajectoryErrorResponse(code, message, status) {
@@ -1,7 +1,7 @@
1
1
  import "reflect-metadata";
2
- import { isIntelligenceRuntime } from "../core/runtime.mjs";
3
2
  import { TrajectoryConnectionError, isValidTrajectoryId } from "../intelligence-platform/trajectories.mjs";
4
3
  import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs";
4
+ import { isIntelligenceRuntime } from "../core/runtime.mjs";
5
5
 
6
6
  //#region src/v2/runtime/handlers/handle-trajectory-connect.ts
7
7
  function trajectoryErrorResponse(code, message, status) {
@@ -1,9 +1,9 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
- const require_runtime$1 = require('../../core/runtime.cjs');
4
- const require_client = require('../../intelligence-platform/client.cjs');
5
3
  const require_json_response = require('../shared/json-response.cjs');
4
+ const require_client = require('../../intelligence-platform/client.cjs');
6
5
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
6
+ const require_runtime$1 = require('../../core/runtime.cjs');
7
7
  let _copilotkit_shared = require("@copilotkit/shared");
8
8
 
9
9
  //#region src/v2/runtime/handlers/intelligence/annotate.ts
@@ -1,8 +1,8 @@
1
1
  import "reflect-metadata";
2
- import { isIntelligenceRuntime } from "../../core/runtime.mjs";
3
- import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
4
2
  import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
3
+ import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
5
4
  import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
5
+ import { isIntelligenceRuntime } from "../../core/runtime.mjs";
6
6
  import { logger } from "@copilotkit/shared";
7
7
 
8
8
  //#region src/v2/runtime/handlers/intelligence/annotate.ts
@@ -1,8 +1,8 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
- const require_runtime$1 = require('../../core/runtime.cjs');
4
3
  const require_json_response = require('../shared/json-response.cjs');
5
4
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
5
+ const require_runtime$1 = require('../../core/runtime.cjs');
6
6
  const require_memory_policy = require('../shared/memory-policy.cjs');
7
7
  const require_platform_error = require('../shared/platform-error.cjs');
8
8
  let _copilotkit_shared = require("@copilotkit/shared");
@@ -1,7 +1,7 @@
1
1
  import "reflect-metadata";
2
- import { isIntelligenceRuntime } from "../../core/runtime.mjs";
3
2
  import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
4
3
  import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
4
+ import { isIntelligenceRuntime } from "../../core/runtime.mjs";
5
5
  import { grantAllowsMemory, resolveWebMemory } from "../shared/memory-policy.mjs";
6
6
  import { platformErrorResponse } from "../shared/platform-error.mjs";
7
7
  import { logger } from "@copilotkit/shared";
@@ -1,12 +1,12 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
- const require_telemetry_client = require('../../telemetry/telemetry-client.cjs');
4
- const require_runtime_error_reporter = require('../../core/runtime-error-reporter.cjs');
5
- const require_learning = require('../../core/learning.cjs');
6
- const require_thread_lock_heartbeat = require('../../intelligence-platform/thread-lock-heartbeat.cjs');
7
3
  const require_json_response = require('../shared/json-response.cjs');
4
+ const require_learning = require('../../core/learning.cjs');
8
5
  const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
9
6
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
7
+ const require_telemetry_client = require('../../telemetry/telemetry-client.cjs');
8
+ const require_runtime_error_reporter = require('../../core/runtime-error-reporter.cjs');
9
+ const require_thread_lock_heartbeat = require('../../intelligence-platform/thread-lock-heartbeat.cjs');
10
10
  const require_thread_names = require('./thread-names.cjs');
11
11
  let _copilotkit_shared = require("@copilotkit/shared");
12
12
  let _ag_ui_client = require("@ag-ui/client");
@@ -1,11 +1,11 @@
1
1
  import "reflect-metadata";
2
- import telemetry from "../../telemetry/telemetry-client.mjs";
3
- import { getRuntimeErrorReporter } from "../../core/runtime-error-reporter.mjs";
4
- import { resolveLearningContainerId, resolveLearningContainerSelector } from "../../core/learning.mjs";
5
- import { startThreadLockHeartbeat } from "../../intelligence-platform/thread-lock-heartbeat.mjs";
6
2
  import { isHandlerResponse } from "../shared/json-response.mjs";
3
+ import { resolveLearningContainerId, resolveLearningContainerSelector } from "../../core/learning.mjs";
7
4
  import { getPlatformErrorStatus } from "../shared/intelligence-utils.mjs";
8
5
  import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
6
+ import telemetry from "../../telemetry/telemetry-client.mjs";
7
+ import { getRuntimeErrorReporter } from "../../core/runtime-error-reporter.mjs";
8
+ import { startThreadLockHeartbeat } from "../../intelligence-platform/thread-lock-heartbeat.mjs";
9
9
  import { generateThreadNameForNewThread } from "./thread-names.mjs";
10
10
  import { logger } from "@copilotkit/shared";
11
11
  import { EventType } from "@ag-ui/client";
@@ -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
  }