@copilotkit/runtime 2.0.0-rc.40 → 2.0.0-rc.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +2 -2
  2. package/dist/agent.cjs.map +1 -1
  3. package/dist/agent.d.cts +2 -2
  4. package/dist/agent.d.mts +2 -2
  5. package/dist/agent.mjs.map +1 -1
  6. package/dist/index.d.cts +2 -1
  7. package/dist/index.d.mts +2 -1
  8. package/dist/runtime/core/debug-event-bus.cjs +4 -2
  9. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  10. package/dist/runtime/core/debug-event-bus.d.cts +4 -0
  11. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  12. package/dist/runtime/core/debug-event-bus.d.mts +4 -0
  13. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  14. package/dist/runtime/core/debug-event-bus.mjs +5 -3
  15. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  16. package/dist/runtime/core/fetch-handler.cjs +8 -7
  17. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  18. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  19. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  20. package/dist/runtime/core/fetch-handler.mjs +3 -2
  21. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  22. package/dist/runtime/core/logger.cjs +20 -1
  23. package/dist/runtime/core/logger.cjs.map +1 -1
  24. package/dist/runtime/core/logger.d.cts +9 -5
  25. package/dist/runtime/core/logger.d.cts.map +1 -1
  26. package/dist/runtime/core/logger.d.mts +9 -5
  27. package/dist/runtime/core/logger.d.mts.map +1 -1
  28. package/dist/runtime/core/logger.mjs +20 -2
  29. package/dist/runtime/core/logger.mjs.map +1 -1
  30. package/dist/runtime/core/middleware-sse-parser.cjs +3 -3
  31. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  32. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
  33. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
  34. package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
  35. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  36. package/dist/runtime/core/middleware.cjs +5 -4
  37. package/dist/runtime/core/middleware.cjs.map +1 -1
  38. package/dist/runtime/core/middleware.mjs +4 -3
  39. package/dist/runtime/core/middleware.mjs.map +1 -1
  40. package/dist/runtime/core/package-info.cjs +1 -1
  41. package/dist/runtime/core/package-info.mjs +1 -1
  42. package/dist/runtime/core/runtime.cjs +11 -9
  43. package/dist/runtime/core/runtime.cjs.map +1 -1
  44. package/dist/runtime/core/runtime.d.cts +19 -1
  45. package/dist/runtime/core/runtime.d.cts.map +1 -1
  46. package/dist/runtime/core/runtime.d.mts +19 -1
  47. package/dist/runtime/core/runtime.d.mts.map +1 -1
  48. package/dist/runtime/core/runtime.mjs +11 -9
  49. package/dist/runtime/core/runtime.mjs.map +1 -1
  50. package/dist/runtime/endpoints/auto-start-channels.cjs +3 -3
  51. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  52. package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
  53. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  54. package/dist/runtime/endpoints/node-fetch-handler.cjs +3 -3
  55. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  56. package/dist/runtime/endpoints/node-fetch-handler.d.cts +2 -1
  57. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  58. package/dist/runtime/endpoints/node-fetch-handler.d.mts +2 -1
  59. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  60. package/dist/runtime/endpoints/node-fetch-handler.mjs +2 -2
  61. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  62. package/dist/runtime/endpoints/node.cjs +4 -2
  63. package/dist/runtime/endpoints/node.cjs.map +1 -1
  64. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  65. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  66. package/dist/runtime/endpoints/node.mjs +4 -2
  67. package/dist/runtime/endpoints/node.mjs.map +1 -1
  68. package/dist/runtime/handlers/get-runtime-info.cjs +5 -1
  69. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  70. package/dist/runtime/handlers/get-runtime-info.mjs +5 -1
  71. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  72. package/dist/runtime/handlers/handle-connect.cjs +3 -8
  73. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  74. package/dist/runtime/handlers/handle-connect.mjs +3 -8
  75. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  76. package/dist/runtime/handlers/handle-run.cjs +4 -9
  77. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  78. package/dist/runtime/handlers/handle-run.mjs +4 -9
  79. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  80. package/dist/runtime/handlers/handle-stop.cjs +2 -1
  81. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  82. package/dist/runtime/handlers/handle-stop.mjs +2 -1
  83. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  84. package/dist/runtime/handlers/handle-suggest.cjs +3 -1
  85. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  86. package/dist/runtime/handlers/handle-suggest.mjs +3 -1
  87. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  88. package/dist/runtime/handlers/intelligence/annotate.cjs +6 -5
  89. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  90. package/dist/runtime/handlers/intelligence/annotate.mjs +4 -3
  91. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  92. package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
  93. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  94. package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
  95. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  96. package/dist/runtime/handlers/intelligence/memories.cjs +20 -14
  97. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  98. package/dist/runtime/handlers/intelligence/memories.mjs +11 -5
  99. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  100. package/dist/runtime/handlers/intelligence/run.cjs +15 -13
  101. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  102. package/dist/runtime/handlers/intelligence/run.mjs +14 -12
  103. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  104. package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -4
  105. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  106. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
  107. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  108. package/dist/runtime/handlers/intelligence/threads.cjs +30 -20
  109. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  110. package/dist/runtime/handlers/intelligence/threads.mjs +13 -3
  111. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  112. package/dist/runtime/handlers/shared/agent-utils.cjs +26 -25
  113. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  114. package/dist/runtime/handlers/shared/agent-utils.mjs +27 -26
  115. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  116. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +3 -2
  117. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  118. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +3 -2
  119. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  120. package/dist/runtime/handlers/shared/sse-response.cjs +5 -14
  121. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  122. package/dist/runtime/handlers/shared/sse-response.mjs +5 -14
  123. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  124. package/dist/runtime/handlers/shared/thread-access.cjs +3 -2
  125. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  126. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
  127. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
  128. package/dist/runtime/handlers/shared/thread-access.mjs +3 -2
  129. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  130. package/dist/runtime/handlers/sse/connect.cjs +2 -0
  131. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  132. package/dist/runtime/handlers/sse/connect.mjs +2 -0
  133. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  134. package/dist/runtime/handlers/sse/run.cjs +5 -2
  135. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  136. package/dist/runtime/handlers/sse/run.mjs +5 -2
  137. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  138. package/dist/runtime/index.d.cts +1 -0
  139. package/dist/runtime/index.d.mts +1 -0
  140. package/dist/runtime/intelligence-platform/analytics-context.cjs +3 -3
  141. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -1
  142. package/dist/runtime/intelligence-platform/analytics-context.mjs +2 -2
  143. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -1
  144. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -2
  145. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  146. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
  147. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  148. package/dist/runtime/runner/intelligence.cjs +9 -7
  149. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  150. package/dist/runtime/runner/intelligence.d.cts +4 -0
  151. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  152. package/dist/runtime/runner/intelligence.d.mts +4 -0
  153. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  154. package/dist/runtime/runner/intelligence.mjs +8 -6
  155. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  156. package/dist/runtime/telemetry/disclosure.cjs +2 -2
  157. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  158. package/dist/runtime/telemetry/disclosure.mjs +3 -3
  159. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  160. package/package.json +7 -11
@@ -1 +1 @@
1
- {"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","takeAnalyticsContext","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\nimport { takeAnalyticsContext } from \"../intelligence-platform/analytics-context\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const parsed = await parseRunRequest(request);\n if (parsed instanceof Response) {\n return parsed;\n }\n // Suggestions are not Intelligence runs, so an app's analytics context goes\n // nowhere from here; it is only kept away from the agent.\n const { input } = takeAnalyticsContext(parsed);\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,SAAS,MAAMC,oCAAgB,QAAQ;AAC7C,KAAI,kBAAkB,SACpB,QAAO;CAIT,MAAM,EAAE,UAAUC,+CAAqB,OAAO;CAc9C,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAIC,iBAAuB,eAAe;GAMxC,MAAM,6DAAqC;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
1
+ {"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","getRuntimeLogger","takeAnalyticsContext","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { getRuntimeLogger } from \"../core/logger\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\nimport { takeAnalyticsContext } from \"../intelligence-platform/analytics-context\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const parsed = await parseRunRequest(request, getRuntimeLogger(runtime));\n if (parsed instanceof Response) {\n return parsed;\n }\n // Suggestions are not Intelligence runs, so an app's analytics context goes\n // nowhere from here; it is only kept away from the agent.\n const { input } = takeAnalyticsContext(parsed);\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n logger: getRuntimeLogger(runtime),\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,SAAS,MAAMC,oCAAgB,SAASC,gCAAiB,QAAQ,CAAC;AACxE,KAAI,kBAAkB,SACpB,QAAO;CAIT,MAAM,EAAE,UAAUC,+CAAqB,OAAO;CAc9C,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,QAAQJ,gCAAiB,QAAQ;EACjC,0BAA0B,QAAQ;EAClC,yBACE,IAAIK,iBAAuB,eAAe;GAMxC,MAAM,6DAAqC;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { mergeForwardableHeaders, resolveForwardHeadersPolicy } from "./header-utils.mjs";
2
+ import { getRuntimeLogger } from "../core/logger.mjs";
2
3
  import { takeAnalyticsContext } from "../intelligence-platform/analytics-context.mjs";
3
4
  import { cloneAgentForRequest, parseRunRequest } from "./shared/agent-utils.mjs";
4
5
  import { createSseEventResponse } from "./shared/sse-response.mjs";
@@ -43,7 +44,7 @@ async function handleSuggestAgent({ runtime, request, agentId }) {
43
44
  const agent = await cloneAgentForRequest(runtime, agentId, request);
44
45
  if (agent instanceof Response) return agent;
45
46
  agent.agentId = agentId;
46
- const parsed = await parseRunRequest(request);
47
+ const parsed = await parseRunRequest(request, getRuntimeLogger(runtime));
47
48
  if (parsed instanceof Response) return parsed;
48
49
  const { input } = takeAnalyticsContext(parsed);
49
50
  const headerCarryingAgent = agent;
@@ -55,6 +56,7 @@ async function handleSuggestAgent({ runtime, request, agentId }) {
55
56
  request,
56
57
  agentId,
57
58
  captureTelemetry: false,
59
+ logger: getRuntimeLogger(runtime),
58
60
  keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
59
61
  observableFactory: () => new Observable((subscriber) => {
60
62
  const finalizer = createRunEventFinalizer();
@@ -1 +1 @@
1
- {"version":3,"file":"handle-suggest.mjs","names":[],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\nimport { takeAnalyticsContext } from \"../intelligence-platform/analytics-context\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const parsed = await parseRunRequest(request);\n if (parsed instanceof Response) {\n return parsed;\n }\n // Suggestions are not Intelligence runs, so an app's analytics context goes\n // nowhere from here; it is only kept away from the agent.\n const { input } = takeAnalyticsContext(parsed);\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,SAAS,MAAM,gBAAgB,QAAQ;AAC7C,KAAI,kBAAkB,SACpB,QAAO;CAIT,MAAM,EAAE,UAAU,qBAAqB,OAAO;CAc9C,MAAM,sBAAsB;AAG5B,qBAAoB,UAAU,wBAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwB,4BAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAO,uBAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAI,YAAuB,eAAe;GAMxC,MAAM,YAAY,yBAAyB;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
1
+ {"version":3,"file":"handle-suggest.mjs","names":[],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { getRuntimeLogger } from \"../core/logger\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\nimport { takeAnalyticsContext } from \"../intelligence-platform/analytics-context\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const parsed = await parseRunRequest(request, getRuntimeLogger(runtime));\n if (parsed instanceof Response) {\n return parsed;\n }\n // Suggestions are not Intelligence runs, so an app's analytics context goes\n // nowhere from here; it is only kept away from the agent.\n const { input } = takeAnalyticsContext(parsed);\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n logger: getRuntimeLogger(runtime),\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,SAAS,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,CAAC;AACxE,KAAI,kBAAkB,SACpB,QAAO;CAIT,MAAM,EAAE,UAAU,qBAAqB,OAAO;CAc9C,MAAM,sBAAsB;AAG5B,qBAAoB,UAAU,wBAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwB,4BAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAO,uBAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,QAAQ,iBAAiB,QAAQ;EACjC,0BAA0B,QAAQ;EAClC,yBACE,IAAI,YAAuB,eAAe;GAMxC,MAAM,YAAY,yBAAyB;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
@@ -1,15 +1,15 @@
1
+ const require_logger = require('../../core/logger.cjs');
1
2
  const require_json_response = require('../shared/json-response.cjs');
2
3
  const require_client = require('../../intelligence-platform/client.cjs');
3
4
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
4
5
  const require_runtime = require('../../core/runtime.cjs');
5
- let _copilotkit_shared = require("@copilotkit/shared");
6
6
 
7
7
  //#region src/runtime/handlers/intelligence/annotate.ts
8
- async function parseJsonBody(request) {
8
+ async function parseJsonBody(request, logger) {
9
9
  try {
10
10
  return await request.json();
11
11
  } catch (error) {
12
- _copilotkit_shared.logger.error({ err: error }, "Malformed JSON in annotate body");
12
+ logger.error({ err: error }, "Malformed JSON in annotate body");
13
13
  return require_json_response.errorResponse("Invalid request body", 400);
14
14
  }
15
15
  }
@@ -35,9 +35,10 @@ function isNonEmptyString(value) {
35
35
  * original row).
36
36
  */
37
37
  async function handleAnnotate({ runtime, request }) {
38
+ const logger = require_logger.getRuntimeLogger(runtime);
38
39
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
39
40
  if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
40
- const body = await parseJsonBody(request);
41
+ const body = await parseJsonBody(request, logger);
41
42
  if (require_json_response.isHandlerResponse(body)) return body;
42
43
  const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
43
44
  runtime: intelligenceRuntime,
@@ -60,7 +61,7 @@ async function handleAnnotate({ runtime, request }) {
60
61
  headers: { "Content-Type": "application/json" }
61
62
  });
62
63
  } catch (err) {
63
- _copilotkit_shared.logger.error({ err }, "annotate: platform call failed");
64
+ logger.error({ err }, "annotate: platform call failed");
64
65
  if (err instanceof require_client.PlatformRequestError && err.status >= 400 && err.status < 500) return require_json_response.errorResponse(err.message, err.status);
65
66
  return require_json_response.errorResponse("Failed to annotate", 502);
66
67
  }
@@ -1 +1 @@
1
- {"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../src/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\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 annotate 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. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAOD,oCACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD,eAAsB,eAAe,EACnC,SACA,WAC2C;CAC3C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CAAE,QAAO;CAEnD,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIA,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EACzC,SAAS;EACT;EACD,CAAC;AACF,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,SAAS,kBAAkB,KAAK;AACtC,KAAIA,wCAAkB,OAAO,CAAE,QAAO;AAEtC,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;GAC7D,QAAQ,KAAK;GACb,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,eAAe,OAAO;GACtB,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;GAC1C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,KAAK;AACZ,4BAAO,MAAM,EAAE,KAAK,EAAE,iCAAiC;AAKvD,MACE,eAAeE,uCACf,IAAI,UAAU,OACd,IAAI,SAAS,IAEb,QAAOJ,oCAAc,IAAI,SAAS,IAAI,OAAO;AAE/C,SAAOA,oCAAc,sBAAsB,IAAI;;;AAInD,SAAS,kBACP,MACyB;AACzB,KAAI,CAAC,iBAAiB,KAAK,SAAS,CAClC,QAAOA,oCAAc,8BAA8B,IAAI;AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAOA,oCAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
1
+ {"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","getRuntimeLogger","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../src/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n logger: CopilotRuntimeLogger,\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 annotate 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. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request, logger);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;AA6BA,eAAe,cACb,SACA,QAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAOD,oCACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD,eAAsB,eAAe,EACnC,SACA,WAC2C;CAC3C,MAAM,SAASE,gCAAiB,QAAQ;CACxC,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIC,wCAAkB,oBAAoB,CAAE,QAAO;CAEnD,MAAM,OAAO,MAAM,cAAc,SAAS,OAAO;AACjD,KAAIA,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EACzC,SAAS;EACT;EACD,CAAC;AACF,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,SAAS,kBAAkB,KAAK;AACtC,KAAIA,wCAAkB,OAAO,CAAE,QAAO;AAEtC,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;GAC7D,QAAQ,KAAK;GACb,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,eAAe,OAAO;GACtB,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;GAC1C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,KAAK;AACZ,SAAO,MAAM,EAAE,KAAK,EAAE,iCAAiC;AAKvD,MACE,eAAeE,uCACf,IAAI,UAAU,OACd,IAAI,SAAS,IAEb,QAAOL,oCAAc,IAAI,SAAS,IAAI,OAAO;AAE/C,SAAOA,oCAAc,sBAAsB,IAAI;;;AAInD,SAAS,kBACP,MACyB;AACzB,KAAI,CAAC,iBAAiB,KAAK,SAAS,CAClC,QAAOA,oCAAc,8BAA8B,IAAI;AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAOA,oCAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
@@ -1,11 +1,11 @@
1
+ import { getRuntimeLogger } from "../../core/logger.mjs";
1
2
  import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
2
3
  import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
3
4
  import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
4
5
  import { isIntelligenceRuntime } from "../../core/runtime.mjs";
5
- import { logger } from "@copilotkit/shared";
6
6
 
7
7
  //#region src/runtime/handlers/intelligence/annotate.ts
8
- async function parseJsonBody(request) {
8
+ async function parseJsonBody(request, logger) {
9
9
  try {
10
10
  return await request.json();
11
11
  } catch (error) {
@@ -35,9 +35,10 @@ function isNonEmptyString(value) {
35
35
  * original row).
36
36
  */
37
37
  async function handleAnnotate({ runtime, request }) {
38
+ const logger = getRuntimeLogger(runtime);
38
39
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
39
40
  if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
40
- const body = await parseJsonBody(request);
41
+ const body = await parseJsonBody(request, logger);
41
42
  if (isHandlerResponse(body)) return body;
42
43
  const user = await resolveIntelligenceUser({
43
44
  runtime: intelligenceRuntime,
@@ -1 +1 @@
1
- {"version":3,"file":"annotate.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\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 annotate 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. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD,eAAsB,eAAe,EACnC,SACA,WAC2C;CAC3C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,kBAAkB,oBAAoB,CAAE,QAAO;CAEnD,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EACzC,SAAS;EACT;EACD,CAAC;AACF,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,SAAS,kBAAkB,KAAK;AACtC,KAAI,kBAAkB,OAAO,CAAE,QAAO;AAEtC,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;GAC7D,QAAQ,KAAK;GACb,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,eAAe,OAAO;GACtB,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;GAC1C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,KAAK;AACZ,SAAO,MAAM,EAAE,KAAK,EAAE,iCAAiC;AAKvD,MACE,eAAe,wBACf,IAAI,UAAU,OACd,IAAI,SAAS,IAEb,QAAO,cAAc,IAAI,SAAS,IAAI,OAAO;AAE/C,SAAO,cAAc,sBAAsB,IAAI;;;AAInD,SAAS,kBACP,MACyB;AACzB,KAAI,CAAC,iBAAiB,KAAK,SAAS,CAClC,QAAO,cAAc,8BAA8B,IAAI;AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAO,cAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
1
+ {"version":3,"file":"annotate.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n logger: CopilotRuntimeLogger,\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 annotate 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. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request, logger);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;AA6BA,eAAe,cACb,SACA,QAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD,eAAsB,eAAe,EACnC,SACA,WAC2C;CAC3C,MAAM,SAAS,iBAAiB,QAAQ;CACxC,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,kBAAkB,oBAAoB,CAAE,QAAO;CAEnD,MAAM,OAAO,MAAM,cAAc,SAAS,OAAO;AACjD,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EACzC,SAAS;EACT;EACD,CAAC;AACF,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,SAAS,kBAAkB,KAAK;AACtC,KAAI,kBAAkB,OAAO,CAAE,QAAO;AAEtC,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;GAC7D,QAAQ,KAAK;GACb,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,eAAe,OAAO;GACtB,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;GAC1C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,KAAK;AACZ,SAAO,MAAM,EAAE,KAAK,EAAE,iCAAiC;AAKvD,MACE,eAAe,wBACf,IAAI,UAAU,OACd,IAAI,SAAS,IAEb,QAAO,cAAc,IAAI,SAAS,IAAI,OAAO;AAE/C,SAAO,cAAc,sBAAsB,IAAI;;;AAInD,SAAS,kBACP,MACyB;AACzB,KAAI,CAAC,iBAAiB,KAAK,SAAS,CAClC,QAAO,cAAc,8BAA8B,IAAI;AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAO,cAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
@@ -1,3 +1,4 @@
1
+ const require_logger = require('../../core/logger.cjs');
1
2
  const require_json_response = require('../shared/json-response.cjs');
2
3
  const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
3
4
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
@@ -49,13 +50,16 @@ async function handleIntelligenceConnect({ runtime, request, agentId, threadId }
49
50
  message: error instanceof Error ? error.message : "Intelligence platform rejected the connect request"
50
51
  }, { status });
51
52
  if (typeof status === "number") {
52
- console.error(`Connect request failed with status ${status}:`, error);
53
+ require_logger.getRuntimeLogger(runtime).error({
54
+ err: error,
55
+ status
56
+ }, "Connect request failed");
53
57
  return Response.json({
54
58
  error: "Connect request failed",
55
59
  message
56
60
  }, { status });
57
61
  }
58
- console.error("Connect request could not reach Intelligence:", error);
62
+ require_logger.getRuntimeLogger(runtime).error({ err: error }, "Connect request could not reach Intelligence");
59
63
  return Response.json({
60
64
  error: "Connect request failed",
61
65
  message
@@ -1 +1 @@
1
- {"version":3,"file":"connect.cjs","names":["resolveIntelligenceUser","isHandlerResponse","getPlatformErrorStatus"],"sources":["../../../../src/runtime/handlers/intelligence/connect.ts"],"sourcesContent":["import type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\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 HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\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 try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n agentId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(\n {\n threadId: result.threadId,\n joinToken: result.joinToken,\n runId: result.runId,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: result.threadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n },\n );\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n const message =\n error instanceof Error ? error.message : \"Connect request failed\";\n\n if (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 409\n ) {\n return Response.json(\n {\n error: \"Connect request rejected\",\n message:\n error instanceof Error\n ? error.message\n : \"Intelligence platform rejected the connect request\",\n },\n { status },\n );\n }\n\n // The platform answered, but with a status we do not special-case above.\n // Pass it through rather than relabelling it: reporting a 503 as a 404 tells\n // the browser the thread does not exist, when the truth is that the platform\n // is temporarily unwell and the request is worth retrying.\n if (typeof status === \"number\") {\n console.error(`Connect request failed with status ${status}:`, error);\n return Response.json(\n { error: \"Connect request failed\", message },\n {\n status,\n },\n );\n }\n\n // No status at all, so this never reached the platform: a socket timeout, a\n // DNS failure, a connection reset, or a bug on our side. 502 says \"the thing\n // behind me is unreachable\", which is both true and actionable. It must not\n // be a 404, which asserts the thread does not exist and sends the caller off\n // to investigate the wrong thing entirely.\n console.error(\"Connect request could not reach Intelligence:\", error);\n return Response.json(\n {\n error: \"Connect request failed\",\n message,\n },\n { status: 502 },\n );\n }\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAUH,eAAsB,0BAA0B,EAC9C,SACA,SACA,SACA,YACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAMA,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAIC,wCAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KACd;GACE,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,OAAO,OAAO;GACd,UAAU,4BAA4B;IACpC,WAAW,QAAQ,aAAa,iBAAiB;IACjD,UAAU,OAAO;IAClB,CAAC;GACH,EACD,EACE,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CACF;UACM,OAAO;EACd,MAAM,SAASC,kDAAuB,MAAM;EAC5C,MAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,MACE,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,IAEX,QAAO,SAAS,KACd;GACE,OAAO;GACP,SACE,iBAAiB,QACb,MAAM,UACN;GACP,EACD,EAAE,QAAQ,CACX;AAOH,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAQ,MAAM,sCAAsC,OAAO,IAAI,MAAM;AACrE,UAAO,SAAS,KACd;IAAE,OAAO;IAA0B;IAAS,EAC5C,EACE,QACD,CACF;;AAQH,UAAQ,MAAM,iDAAiD,MAAM;AACrE,SAAO,SAAS,KACd;GACE,OAAO;GACP;GACD,EACD,EAAE,QAAQ,KAAK,CAChB"}
1
+ {"version":3,"file":"connect.cjs","names":["resolveIntelligenceUser","isHandlerResponse","getPlatformErrorStatus"],"sources":["../../../../src/runtime/handlers/intelligence/connect.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\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 HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\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 try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n agentId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(\n {\n threadId: result.threadId,\n joinToken: result.joinToken,\n runId: result.runId,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: result.threadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n },\n );\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n const message =\n error instanceof Error ? error.message : \"Connect request failed\";\n\n if (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 409\n ) {\n return Response.json(\n {\n error: \"Connect request rejected\",\n message:\n error instanceof Error\n ? error.message\n : \"Intelligence platform rejected the connect request\",\n },\n { status },\n );\n }\n\n // The platform answered, but with a status we do not special-case above.\n // Pass it through rather than relabelling it: reporting a 503 as a 404 tells\n // the browser the thread does not exist, when the truth is that the platform\n // is temporarily unwell and the request is worth retrying.\n if (typeof status === \"number\") {\n getRuntimeLogger(runtime).error(\n { err: error, status },\n \"Connect request failed\",\n );\n return Response.json(\n { error: \"Connect request failed\", message },\n {\n status,\n },\n );\n }\n\n // No status at all, so this never reached the platform: a socket timeout, a\n // DNS failure, a connection reset, or a bug on our side. 502 says \"the thing\n // behind me is unreachable\", which is both true and actionable. It must not\n // be a 404, which asserts the thread does not exist and sends the caller off\n // to investigate the wrong thing entirely.\n getRuntimeLogger(runtime).error(\n { err: error },\n \"Connect request could not reach Intelligence\",\n );\n return Response.json(\n {\n error: \"Connect request failed\",\n message,\n },\n { status: 502 },\n );\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAUH,eAAsB,0BAA0B,EAC9C,SACA,SACA,SACA,YACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAMA,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAIC,wCAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KACd;GACE,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,OAAO,OAAO;GACd,UAAU,4BAA4B;IACpC,WAAW,QAAQ,aAAa,iBAAiB;IACjD,UAAU,OAAO;IAClB,CAAC;GACH,EACD,EACE,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CACF;UACM,OAAO;EACd,MAAM,SAASC,kDAAuB,MAAM;EAC5C,MAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,MACE,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,IAEX,QAAO,SAAS,KACd;GACE,OAAO;GACP,SACE,iBAAiB,QACb,MAAM,UACN;GACP,EACD,EAAE,QAAQ,CACX;AAOH,MAAI,OAAO,WAAW,UAAU;AAC9B,mCAAiB,QAAQ,CAAC,MACxB;IAAE,KAAK;IAAO;IAAQ,EACtB,yBACD;AACD,UAAO,SAAS,KACd;IAAE,OAAO;IAA0B;IAAS,EAC5C,EACE,QACD,CACF;;AAQH,kCAAiB,QAAQ,CAAC,MACxB,EAAE,KAAK,OAAO,EACd,+CACD;AACD,SAAO,SAAS,KACd;GACE,OAAO;GACP;GACD,EACD,EAAE,QAAQ,KAAK,CAChB"}
@@ -1,3 +1,4 @@
1
+ import { getRuntimeLogger } from "../../core/logger.mjs";
1
2
  import { isHandlerResponse } from "../shared/json-response.mjs";
2
3
  import { getPlatformErrorStatus } from "../shared/intelligence-utils.mjs";
3
4
  import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
@@ -49,13 +50,16 @@ async function handleIntelligenceConnect({ runtime, request, agentId, threadId }
49
50
  message: error instanceof Error ? error.message : "Intelligence platform rejected the connect request"
50
51
  }, { status });
51
52
  if (typeof status === "number") {
52
- console.error(`Connect request failed with status ${status}:`, error);
53
+ getRuntimeLogger(runtime).error({
54
+ err: error,
55
+ status
56
+ }, "Connect request failed");
53
57
  return Response.json({
54
58
  error: "Connect request failed",
55
59
  message
56
60
  }, { status });
57
61
  }
58
- console.error("Connect request could not reach Intelligence:", error);
62
+ getRuntimeLogger(runtime).error({ err: error }, "Connect request could not reach Intelligence");
59
63
  return Response.json({
60
64
  error: "Connect request failed",
61
65
  message
@@ -1 +1 @@
1
- {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/connect.ts"],"sourcesContent":["import type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\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 HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\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 try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n agentId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(\n {\n threadId: result.threadId,\n joinToken: result.joinToken,\n runId: result.runId,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: result.threadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n },\n );\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n const message =\n error instanceof Error ? error.message : \"Connect request failed\";\n\n if (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 409\n ) {\n return Response.json(\n {\n error: \"Connect request rejected\",\n message:\n error instanceof Error\n ? error.message\n : \"Intelligence platform rejected the connect request\",\n },\n { status },\n );\n }\n\n // The platform answered, but with a status we do not special-case above.\n // Pass it through rather than relabelling it: reporting a 503 as a 404 tells\n // the browser the thread does not exist, when the truth is that the platform\n // is temporarily unwell and the request is worth retrying.\n if (typeof status === \"number\") {\n console.error(`Connect request failed with status ${status}:`, error);\n return Response.json(\n { error: \"Connect request failed\", message },\n {\n status,\n },\n );\n }\n\n // No status at all, so this never reached the platform: a socket timeout, a\n // DNS failure, a connection reset, or a bug on our side. 502 says \"the thing\n // behind me is unreachable\", which is both true and actionable. It must not\n // be a 404, which asserts the thread does not exist and sends the caller off\n // to investigate the wrong thing entirely.\n console.error(\"Connect request could not reach Intelligence:\", error);\n return Response.json(\n {\n error: \"Connect request failed\",\n message,\n },\n { status: 502 },\n );\n }\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAUH,eAAsB,0BAA0B,EAC9C,SACA,SACA,SACA,YACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KACd;GACE,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,OAAO,OAAO;GACd,UAAU,4BAA4B;IACpC,WAAW,QAAQ,aAAa,iBAAiB;IACjD,UAAU,OAAO;IAClB,CAAC;GACH,EACD,EACE,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CACF;UACM,OAAO;EACd,MAAM,SAAS,uBAAuB,MAAM;EAC5C,MAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,MACE,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,IAEX,QAAO,SAAS,KACd;GACE,OAAO;GACP,SACE,iBAAiB,QACb,MAAM,UACN;GACP,EACD,EAAE,QAAQ,CACX;AAOH,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAQ,MAAM,sCAAsC,OAAO,IAAI,MAAM;AACrE,UAAO,SAAS,KACd;IAAE,OAAO;IAA0B;IAAS,EAC5C,EACE,QACD,CACF;;AAQH,UAAQ,MAAM,iDAAiD,MAAM;AACrE,SAAO,SAAS,KACd;GACE,OAAO;GACP;GACD,EACD,EAAE,QAAQ,KAAK,CAChB"}
1
+ {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/connect.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { getPlatformErrorStatus } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\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 HandleIntelligenceConnectParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleIntelligenceConnect({\n runtime,\n request,\n agentId,\n threadId,\n}: HandleIntelligenceConnectParams): Promise<Response> {\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 try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n\n const result = await runtime.intelligence.ɵconnectThread({\n threadId,\n userId: user.id,\n agentId,\n });\n\n if (result === null) {\n return new Response(null, {\n status: 204,\n });\n }\n\n return Response.json(\n {\n threadId: result.threadId,\n joinToken: result.joinToken,\n runId: result.runId,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: result.threadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\", Connection: \"keep-alive\" },\n },\n );\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n const message =\n error instanceof Error ? error.message : \"Connect request failed\";\n\n if (\n status === 400 ||\n status === 401 ||\n status === 403 ||\n status === 404 ||\n status === 409\n ) {\n return Response.json(\n {\n error: \"Connect request rejected\",\n message:\n error instanceof Error\n ? error.message\n : \"Intelligence platform rejected the connect request\",\n },\n { status },\n );\n }\n\n // The platform answered, but with a status we do not special-case above.\n // Pass it through rather than relabelling it: reporting a 503 as a 404 tells\n // the browser the thread does not exist, when the truth is that the platform\n // is temporarily unwell and the request is worth retrying.\n if (typeof status === \"number\") {\n getRuntimeLogger(runtime).error(\n { err: error, status },\n \"Connect request failed\",\n );\n return Response.json(\n { error: \"Connect request failed\", message },\n {\n status,\n },\n );\n }\n\n // No status at all, so this never reached the platform: a socket timeout, a\n // DNS failure, a connection reset, or a bug on our side. 502 says \"the thing\n // behind me is unreachable\", which is both true and actionable. It must not\n // be a 404, which asserts the thread does not exist and sends the caller off\n // to investigate the wrong thing entirely.\n getRuntimeLogger(runtime).error(\n { err: error },\n \"Connect request could not reach Intelligence\",\n );\n return Response.json(\n {\n error: \"Connect request failed\",\n message,\n },\n { status: 502 },\n );\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB,OAAO,UAAU,OAAO;EACzB;;AAUH,eAAsB,0BAA0B,EAC9C,SACA,SACA,SACA,YACqD;AACrD,KAAI,CAAC,QAAQ,aACX,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAGH,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CACzB,QAAO;EAGT,MAAM,SAAS,MAAM,QAAQ,aAAa,eAAe;GACvD;GACA,QAAQ,KAAK;GACb;GACD,CAAC;AAEF,MAAI,WAAW,KACb,QAAO,IAAI,SAAS,MAAM,EACxB,QAAQ,KACT,CAAC;AAGJ,SAAO,SAAS,KACd;GACE,UAAU,OAAO;GACjB,WAAW,OAAO;GAClB,OAAO,OAAO;GACd,UAAU,4BAA4B;IACpC,WAAW,QAAQ,aAAa,iBAAiB;IACjD,UAAU,OAAO;IAClB,CAAC;GACH,EACD,EACE,SAAS;GAAE,iBAAiB;GAAY,YAAY;GAAc,EACnE,CACF;UACM,OAAO;EACd,MAAM,SAAS,uBAAuB,MAAM;EAC5C,MAAM,UACJ,iBAAiB,QAAQ,MAAM,UAAU;AAE3C,MACE,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,OACX,WAAW,IAEX,QAAO,SAAS,KACd;GACE,OAAO;GACP,SACE,iBAAiB,QACb,MAAM,UACN;GACP,EACD,EAAE,QAAQ,CACX;AAOH,MAAI,OAAO,WAAW,UAAU;AAC9B,oBAAiB,QAAQ,CAAC,MACxB;IAAE,KAAK;IAAO;IAAQ,EACtB,yBACD;AACD,UAAO,SAAS,KACd;IAAE,OAAO;IAA0B;IAAS,EAC5C,EACE,QACD,CACF;;AAQH,mBAAiB,QAAQ,CAAC,MACxB,EAAE,KAAK,OAAO,EACd,+CACD;AACD,SAAO,SAAS,KACd;GACE,OAAO;GACP;GACD,EACD,EAAE,QAAQ,KAAK,CAChB"}
@@ -1,9 +1,9 @@
1
+ const require_logger = require('../../core/logger.cjs');
1
2
  const require_json_response = require('../shared/json-response.cjs');
2
3
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
3
4
  const require_runtime = require('../../core/runtime.cjs');
4
5
  const require_memory_policy = require('../shared/memory-policy.cjs');
5
6
  const require_platform_error = require('../shared/platform-error.cjs');
6
- let _copilotkit_shared = require("@copilotkit/shared");
7
7
 
8
8
  //#region src/runtime/handlers/intelligence/memories.ts
9
9
  async function resolveClientMemory(runtime, request) {
@@ -34,11 +34,11 @@ const MEMORY_SCOPES = new Set(["user", "project"]);
34
34
  * kept so the many call sites below read the same as they always did.
35
35
  */
36
36
  const memoryErrorResponse = require_platform_error.platformErrorResponse;
37
- async function parseJsonBody(request) {
37
+ async function parseJsonBody(request, logger) {
38
38
  try {
39
39
  return await request.json();
40
40
  } catch (error) {
41
- _copilotkit_shared.logger.error({ err: error }, "Malformed JSON in memory request body");
41
+ logger.error({ err: error }, "Malformed JSON in memory request body");
42
42
  return require_json_response.errorResponse("Invalid request body", 400);
43
43
  }
44
44
  }
@@ -91,6 +91,7 @@ function parseRecallBody(body) {
91
91
  * consumes directly.
92
92
  */
93
93
  async function handleListMemories({ runtime, request }) {
94
+ const logger = require_logger.getRuntimeLogger(runtime);
94
95
  if (require_runtime.isIntelligenceRuntime(runtime)) try {
95
96
  const includeInvalidated = new URL(request.url).searchParams.get("includeInvalidated") === "true";
96
97
  const access = await resolveClientMemory(runtime, request);
@@ -101,12 +102,12 @@ async function handleListMemories({ runtime, request }) {
101
102
  ...includeInvalidated ? { includeInvalidated: true } : {}
102
103
  });
103
104
  if (data == null || typeof data !== "object" || !Array.isArray(data.memories)) {
104
- _copilotkit_shared.logger.error({ data }, "listMemories: platform returned a response without a `memories` array");
105
+ logger.error({ data }, "listMemories: platform returned a response without a `memories` array");
105
106
  return require_json_response.errorResponse("Memory platform returned an invalid list response", 502);
106
107
  }
107
108
  return Response.json(data);
108
109
  } catch (error) {
109
- _copilotkit_shared.logger.error({ err: error }, "Error listing memories");
110
+ logger.error({ err: error }, "Error listing memories");
110
111
  return memoryErrorResponse(error, "Failed to list memories");
111
112
  }
112
113
  return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
@@ -120,9 +121,10 @@ async function handleListMemories({ runtime, request }) {
120
121
  * each optionally carrying `score`.
121
122
  */
122
123
  async function handleRecallMemories({ runtime, request }) {
124
+ const logger = require_logger.getRuntimeLogger(runtime);
123
125
  if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
124
126
  try {
125
- const body = await parseJsonBody(request);
127
+ const body = await parseJsonBody(request, logger);
126
128
  if (require_json_response.isHandlerResponse(body)) return body;
127
129
  const fields = parseRecallBody(body);
128
130
  if (require_json_response.isHandlerResponse(fields)) return fields;
@@ -134,12 +136,12 @@ async function handleRecallMemories({ runtime, request }) {
134
136
  ...fields
135
137
  });
136
138
  if (data == null || typeof data !== "object" || !Array.isArray(data.memories)) {
137
- _copilotkit_shared.logger.error({ data }, "recallMemories: platform returned a response without a `memories` array");
139
+ logger.error({ data }, "recallMemories: platform returned a response without a `memories` array");
138
140
  return require_json_response.errorResponse("Memory platform returned an invalid recall response", 502);
139
141
  }
140
142
  return Response.json(data);
141
143
  } catch (error) {
142
- _copilotkit_shared.logger.error({ err: error }, "Error recalling memories");
144
+ logger.error({ err: error }, "Error recalling memories");
143
145
  return memoryErrorResponse(error, "Failed to recall memories");
144
146
  }
145
147
  }
@@ -159,6 +161,7 @@ async function handleRecallMemories({ runtime, request }) {
159
161
  * contract; the client opens only the user channel).
160
162
  */
161
163
  async function handleSubscribeToMemories({ runtime, request }) {
164
+ const logger = require_logger.getRuntimeLogger(runtime);
162
165
  if (require_runtime.isIntelligenceRuntime(runtime)) try {
163
166
  const access = await resolveClientMemory(runtime, request);
164
167
  if (require_json_response.isHandlerResponse(access)) return access;
@@ -173,7 +176,7 @@ async function handleSubscribeToMemories({ runtime, request }) {
173
176
  ...credentials.projectJoinCode !== void 0 ? { projectJoinCode: credentials.projectJoinCode } : {}
174
177
  });
175
178
  } catch (error) {
176
- _copilotkit_shared.logger.error({ err: error }, "Error subscribing to memories");
179
+ logger.error({ err: error }, "Error subscribing to memories");
177
180
  return memoryErrorResponse(error, "Failed to subscribe to memories");
178
181
  }
179
182
  return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
@@ -184,9 +187,10 @@ async function handleSubscribeToMemories({ runtime, request }) {
184
187
  * with the stored memory (the client store applies it server-authoritatively).
185
188
  */
186
189
  async function handleCreateMemory({ runtime, request }) {
190
+ const logger = require_logger.getRuntimeLogger(runtime);
187
191
  if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
188
192
  try {
189
- const body = await parseJsonBody(request);
193
+ const body = await parseJsonBody(request, logger);
190
194
  if (require_json_response.isHandlerResponse(body)) return body;
191
195
  const fields = parseMemoryBody(body);
192
196
  if (require_json_response.isHandlerResponse(fields)) return fields;
@@ -199,7 +203,7 @@ async function handleCreateMemory({ runtime, request }) {
199
203
  });
200
204
  return Response.json(data, { status: 201 });
201
205
  } catch (error) {
202
- _copilotkit_shared.logger.error({ err: error }, "Error creating memory");
206
+ logger.error({ err: error }, "Error creating memory");
203
207
  return memoryErrorResponse(error, "Failed to create memory");
204
208
  }
205
209
  }
@@ -208,9 +212,10 @@ async function handleCreateMemory({ runtime, request }) {
208
212
  * inserts the new content atomically; the response carries `retiredId`.
209
213
  */
210
214
  async function handleUpdateMemory({ runtime, request, memoryId }) {
215
+ const logger = require_logger.getRuntimeLogger(runtime);
211
216
  if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
212
217
  try {
213
- const body = await parseJsonBody(request);
218
+ const body = await parseJsonBody(request, logger);
214
219
  if (require_json_response.isHandlerResponse(body)) return body;
215
220
  const fields = parseMemoryBody(body);
216
221
  if (require_json_response.isHandlerResponse(fields)) return fields;
@@ -224,7 +229,7 @@ async function handleUpdateMemory({ runtime, request, memoryId }) {
224
229
  });
225
230
  return Response.json(data);
226
231
  } catch (error) {
227
- _copilotkit_shared.logger.error({ err: error }, "Error updating memory");
232
+ logger.error({ err: error }, "Error updating memory");
228
233
  return memoryErrorResponse(error, "Failed to update memory");
229
234
  }
230
235
  }
@@ -233,6 +238,7 @@ async function handleUpdateMemory({ runtime, request, memoryId }) {
233
238
  * on the platform side; returns 204.
234
239
  */
235
240
  async function handleRemoveMemory({ runtime, request, memoryId }) {
241
+ const logger = require_logger.getRuntimeLogger(runtime);
236
242
  if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
237
243
  try {
238
244
  const access = await resolveClientMemory(runtime, request);
@@ -244,7 +250,7 @@ async function handleRemoveMemory({ runtime, request, memoryId }) {
244
250
  });
245
251
  return new Response(null, { status: 204 });
246
252
  } catch (error) {
247
- _copilotkit_shared.logger.error({ err: error }, "Error removing memory");
253
+ logger.error({ err: error }, "Error removing memory");
248
254
  return memoryErrorResponse(error, "Failed to remove memory");
249
255
  }
250
256
  }