@copilotkit/runtime 1.55.2 → 1.55.3-canary.1776243725

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 (103) hide show
  1. package/dist/agent/converters/tanstack.cjs.map +1 -1
  2. package/dist/agent/converters/tanstack.d.cts +6 -19
  3. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  4. package/dist/agent/converters/tanstack.d.mts +6 -19
  5. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  6. package/dist/agent/converters/tanstack.mjs.map +1 -1
  7. package/dist/agent/index.cjs +14 -0
  8. package/dist/agent/index.cjs.map +1 -1
  9. package/dist/agent/index.d.cts +12 -1
  10. package/dist/agent/index.d.cts.map +1 -1
  11. package/dist/agent/index.d.mts +12 -1
  12. package/dist/agent/index.d.mts.map +1 -1
  13. package/dist/agent/index.mjs +14 -0
  14. package/dist/agent/index.mjs.map +1 -1
  15. package/dist/index.d.cts +2 -1
  16. package/dist/index.d.mts +2 -1
  17. package/dist/lib/index.d.cts +1 -0
  18. package/dist/lib/index.d.cts.map +1 -1
  19. package/dist/lib/index.d.mts +1 -0
  20. package/dist/lib/index.d.mts.map +1 -1
  21. package/dist/lib/runtime/copilot-runtime.cjs +13 -4
  22. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  23. package/dist/lib/runtime/copilot-runtime.d.cts +3 -3
  24. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  25. package/dist/lib/runtime/copilot-runtime.d.mts +3 -3
  26. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  27. package/dist/lib/runtime/copilot-runtime.mjs +13 -4
  28. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  29. package/dist/package.cjs +4 -3
  30. package/dist/package.mjs +4 -3
  31. package/dist/service-adapters/openai/openai-adapter.cjs +1 -1
  32. package/dist/service-adapters/openai/openai-adapter.cjs.map +1 -1
  33. package/dist/service-adapters/openai/openai-adapter.d.cts.map +1 -1
  34. package/dist/service-adapters/openai/openai-adapter.d.mts.map +1 -1
  35. package/dist/service-adapters/openai/openai-adapter.mjs +2 -2
  36. package/dist/service-adapters/openai/openai-adapter.mjs.map +1 -1
  37. package/dist/service-adapters/openai/openai-assistant-adapter.cjs +8 -9
  38. package/dist/service-adapters/openai/openai-assistant-adapter.cjs.map +1 -1
  39. package/dist/service-adapters/openai/openai-assistant-adapter.d.cts.map +1 -1
  40. package/dist/service-adapters/openai/openai-assistant-adapter.d.mts.map +1 -1
  41. package/dist/service-adapters/openai/openai-assistant-adapter.mjs +9 -10
  42. package/dist/service-adapters/openai/openai-assistant-adapter.mjs.map +1 -1
  43. package/dist/service-adapters/openai/utils.cjs +53 -0
  44. package/dist/service-adapters/openai/utils.cjs.map +1 -1
  45. package/dist/service-adapters/openai/utils.mjs +51 -1
  46. package/dist/service-adapters/openai/utils.mjs.map +1 -1
  47. package/dist/v2/index.cjs +1 -0
  48. package/dist/v2/index.d.cts +3 -3
  49. package/dist/v2/index.d.mts +3 -3
  50. package/dist/v2/index.mjs +2 -2
  51. package/dist/v2/runtime/core/runtime.cjs +13 -0
  52. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  53. package/dist/v2/runtime/core/runtime.d.cts +43 -3
  54. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  55. package/dist/v2/runtime/core/runtime.d.mts +43 -3
  56. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  57. package/dist/v2/runtime/core/runtime.mjs +13 -1
  58. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  59. package/dist/v2/runtime/handlers/get-runtime-info.cjs +18 -10
  60. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  61. package/dist/v2/runtime/handlers/get-runtime-info.mjs +19 -11
  62. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  63. package/dist/v2/runtime/handlers/handle-connect.cjs +1 -1
  64. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  65. package/dist/v2/runtime/handlers/handle-connect.mjs +1 -1
  66. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  67. package/dist/v2/runtime/handlers/handle-run.cjs +1 -1
  68. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  69. package/dist/v2/runtime/handlers/handle-run.mjs +1 -1
  70. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  71. package/dist/v2/runtime/handlers/handle-stop.cjs +2 -1
  72. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  73. package/dist/v2/runtime/handlers/handle-stop.mjs +2 -1
  74. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  75. package/dist/v2/runtime/handlers/intelligence/thread-names.cjs +1 -1
  76. package/dist/v2/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  77. package/dist/v2/runtime/handlers/intelligence/thread-names.mjs +1 -1
  78. package/dist/v2/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  79. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -2
  80. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  81. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +3 -2
  82. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  83. package/dist/v2/runtime/index.d.cts +1 -1
  84. package/dist/v2/runtime/index.d.mts +1 -1
  85. package/package.json +5 -4
  86. package/src/agent/__tests__/capabilities.test.ts +81 -0
  87. package/src/agent/converters/tanstack.ts +15 -7
  88. package/src/agent/index.ts +33 -0
  89. package/src/lib/runtime/__tests__/v1-agent-factory.test.ts +109 -0
  90. package/src/lib/runtime/copilot-runtime.ts +23 -2
  91. package/src/service-adapters/openai/__tests__/openai-v5-compat.test.ts +177 -0
  92. package/src/service-adapters/openai/openai-adapter.ts +3 -1
  93. package/src/service-adapters/openai/openai-assistant-adapter.ts +7 -9
  94. package/src/service-adapters/openai/utils.ts +100 -0
  95. package/src/v2/runtime/__tests__/agents-factory.test.ts +136 -0
  96. package/src/v2/runtime/__tests__/get-runtime-info.test.ts +134 -1
  97. package/src/v2/runtime/core/runtime.ts +63 -2
  98. package/src/v2/runtime/handlers/get-runtime-info.ts +33 -8
  99. package/src/v2/runtime/handlers/handle-connect.ts +1 -1
  100. package/src/v2/runtime/handlers/handle-run.ts +1 -1
  101. package/src/v2/runtime/handlers/handle-stop.ts +2 -1
  102. package/src/v2/runtime/handlers/intelligence/thread-names.ts +1 -1
  103. package/src/v2/runtime/handlers/shared/agent-utils.ts +3 -2
@@ -14,7 +14,7 @@ async function handleRunAgent({ runtime, request, agentId }) {
14
14
  ...request.headers.get("x-copilotcloud-public-api-key") ? { "cloud.public_api_key": request.headers.get("x-copilotcloud-public-api-key") } : {}
15
15
  });
16
16
  try {
17
- const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId);
17
+ const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId, request);
18
18
  if (agent instanceof Response) return agent;
19
19
  require_agent_utils.configureAgentForRequest({
20
20
  runtime,
@@ -1 +1 @@
1
- {"version":3,"file":"handle-run.cjs","names":["cloneAgentForRequest","parseRunRequest","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n RunAgentParameters,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId);\n if (agent instanceof Response) {\n return agent;\n }\n\n configureAgentForRequest({ runtime, request, agentId, agent });\n\n if (\n runtime.licenseChecker &&\n !runtime.licenseChecker.checkFeature(\"agents\")\n ) {\n console.warn(\n '[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({ runtime, request, agent, input });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AAWA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;AACrB,kCAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,QAAQ;AAC1D,MAAI,iBAAiB,SACnB,QAAO;AAGT,+CAAyB;GAAE;GAAS;GAAS;GAAS;GAAO,CAAC;AAE9D,MACE,QAAQ,kBACR,CAAC,QAAQ,eAAe,aAAa,SAAS,CAE9C,SAAQ,KACN,gGACD;EAGH,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,MAAI,iBAAiB,SACnB,QAAO;AAGT,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,SAAS,MAAM,MAAM;AAC3B,QAAM,WAAW,MAAM;AAEvB,MAAIC,sCAAsB,QAAQ,CAChC,QAAOC,kCAAsB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAOC,2BAAa;GAAE;GAAS;GAAS;GAAO;GAAO,CAAC;UAChD,OAAO;AACd,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"handle-run.cjs","names":["cloneAgentForRequest","parseRunRequest","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n RunAgentParameters,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n configureAgentForRequest({ runtime, request, agentId, agent });\n\n if (\n runtime.licenseChecker &&\n !runtime.licenseChecker.checkFeature(\"agents\")\n ) {\n console.warn(\n '[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({ runtime, request, agent, input });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AAWA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;AACrB,kCAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAGT,+CAAyB;GAAE;GAAS;GAAS;GAAS;GAAO,CAAC;AAE9D,MACE,QAAQ,kBACR,CAAC,QAAQ,eAAe,aAAa,SAAS,CAE9C,SAAQ,KACN,gGACD;EAGH,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,MAAI,iBAAiB,SACnB,QAAO;AAGT,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,SAAS,MAAM,MAAM;AAC3B,QAAM,WAAW,MAAM;AAEvB,MAAIC,sCAAsB,QAAQ,CAChC,QAAOC,kCAAsB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAOC,2BAAa;GAAE;GAAS;GAAS;GAAO;GAAO,CAAC;UAChD,OAAO;AACd,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -14,7 +14,7 @@ async function handleRunAgent({ runtime, request, agentId }) {
14
14
  ...request.headers.get("x-copilotcloud-public-api-key") ? { "cloud.public_api_key": request.headers.get("x-copilotcloud-public-api-key") } : {}
15
15
  });
16
16
  try {
17
- const agent = await cloneAgentForRequest(runtime, agentId);
17
+ const agent = await cloneAgentForRequest(runtime, agentId, request);
18
18
  if (agent instanceof Response) return agent;
19
19
  configureAgentForRequest({
20
20
  runtime,
@@ -1 +1 @@
1
- {"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n RunAgentParameters,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId);\n if (agent instanceof Response) {\n return agent;\n }\n\n configureAgentForRequest({ runtime, request, agentId, agent });\n\n if (\n runtime.licenseChecker &&\n !runtime.licenseChecker.checkFeature(\"agents\")\n ) {\n console.warn(\n '[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({ runtime, request, agent, input });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AAWA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;AACrB,WAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAM,qBAAqB,SAAS,QAAQ;AAC1D,MAAI,iBAAiB,SACnB,QAAO;AAGT,2BAAyB;GAAE;GAAS;GAAS;GAAS;GAAO,CAAC;AAE9D,MACE,QAAQ,kBACR,CAAC,QAAQ,eAAe,aAAa,SAAS,CAE9C,SAAQ,KACN,gGACD;EAGH,MAAM,QAAQ,MAAM,gBAAgB,QAAQ;AAC5C,MAAI,iBAAiB,SACnB,QAAO;AAGT,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,SAAS,MAAM,MAAM;AAC3B,QAAM,WAAW,MAAM;AAEvB,MAAI,sBAAsB,QAAQ,CAChC,QAAO,sBAAsB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAO,aAAa;GAAE;GAAS;GAAS;GAAO;GAAO,CAAC;UAChD,OAAO;AACd,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n RunAgentParameters,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n configureAgentForRequest({ runtime, request, agentId, agent });\n\n if (\n runtime.licenseChecker &&\n !runtime.licenseChecker.checkFeature(\"agents\")\n ) {\n console.warn(\n '[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({ runtime, request, agent, input });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AAWA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;AACrB,WAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAGT,2BAAyB;GAAE;GAAS;GAAS;GAAS;GAAO,CAAC;AAE9D,MACE,QAAQ,kBACR,CAAC,QAAQ,eAAe,aAAa,SAAS,CAE9C,SAAQ,KACN,gGACD;EAGH,MAAM,QAAQ,MAAM,gBAAgB,QAAQ;AAC5C,MAAI,iBAAiB,SACnB,QAAO;AAGT,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,SAAS,MAAM,MAAM;AAC3B,QAAM,WAAW,MAAM;AAEvB,MAAI,sBAAsB,QAAQ,CAChC,QAAO,sBAAsB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAO,aAAa;GAAE;GAAS;GAAS;GAAO;GAAO,CAAC;UAChD,OAAO;AACd,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -1,11 +1,12 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
3
+ const require_runtime$1 = require('../core/runtime.cjs');
3
4
  let _ag_ui_client = require("@ag-ui/client");
4
5
 
5
6
  //#region src/v2/runtime/handlers/handle-stop.ts
6
7
  async function handleStopAgent({ runtime, request, agentId, threadId }) {
7
8
  try {
8
- if (!(await runtime.agents)[agentId]) return new Response(JSON.stringify({
9
+ if (!(await require_runtime$1.resolveAgents(runtime.agents, request))[agentId]) return new Response(JSON.stringify({
9
10
  error: "Agent not found",
10
11
  message: `Agent '${agentId}' does not exist`
11
12
  }), {
@@ -1 +1 @@
1
- {"version":3,"file":"handle-stop.cjs","names":["EventType"],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters) {\n try {\n const agents = await runtime.agents;\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({ threadId });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message: `No active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;AAUA,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACsB;AACtB,KAAI;AAGF,MAAI,EAFW,MAAM,QAAQ,QAEjB,SACV,QAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,UAAU,QAAQ;GAC5B,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAKH,MAAI,CAFY,MAAM,QAAQ,OAAO,KAAK,EAAE,UAAU,CAAC,CAGrD,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SAAS,6BAA6B,SAAS;GAChD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAMA,wBAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"handle-stop.cjs","names":["resolveAgents","EventType"],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters) {\n try {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({ threadId });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message: `No active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;AAWA,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACsB;AACtB,KAAI;AAGF,MAAI,EAFW,MAAMA,gCAAc,QAAQ,QAAQ,QAAQ,EAE/C,SACV,QAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,UAAU,QAAQ;GAC5B,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAKH,MAAI,CAFY,MAAM,QAAQ,OAAO,KAAK,EAAE,UAAU,CAAC,CAGrD,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SAAS,6BAA6B,SAAS;GAChD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAMC,wBAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -1,10 +1,11 @@
1
1
  import "reflect-metadata";
2
+ import { resolveAgents } from "../core/runtime.mjs";
2
3
  import { EventType } from "@ag-ui/client";
3
4
 
4
5
  //#region src/v2/runtime/handlers/handle-stop.ts
5
6
  async function handleStopAgent({ runtime, request, agentId, threadId }) {
6
7
  try {
7
- if (!(await runtime.agents)[agentId]) return new Response(JSON.stringify({
8
+ if (!(await resolveAgents(runtime.agents, request))[agentId]) return new Response(JSON.stringify({
8
9
  error: "Agent not found",
9
10
  message: `Agent '${agentId}' does not exist`
10
11
  }), {
@@ -1 +1 @@
1
- {"version":3,"file":"handle-stop.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters) {\n try {\n const agents = await runtime.agents;\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({ threadId });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message: `No active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;AAUA,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACsB;AACtB,KAAI;AAGF,MAAI,EAFW,MAAM,QAAQ,QAEjB,SACV,QAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,UAAU,QAAQ;GAC5B,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAKH,MAAI,CAFY,MAAM,QAAQ,OAAO,KAAK,EAAE,UAAU,CAAC,CAGrD,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SAAS,6BAA6B,SAAS;GAChD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAM,UAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"handle-stop.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters) {\n try {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({ threadId });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message: `No active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;AAWA,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACsB;AACtB,KAAI;AAGF,MAAI,EAFW,MAAM,cAAc,QAAQ,QAAQ,QAAQ,EAE/C,SACV,QAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,UAAU,QAAQ;GAC5B,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAKH,MAAI,CAFY,MAAM,QAAQ,OAAO,KAAK,EAAE,UAAU,CAAC,CAGrD,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SAAS,6BAA6B,SAAS;GAChD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAM,UAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -60,7 +60,7 @@ async function generateThreadNameForNewThread({ runtime, request, agentId, sourc
60
60
  }
61
61
  async function runTitleGenerationAttempt(params) {
62
62
  const { runtime, request, agentId, threadId, prompt } = params;
63
- const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId);
63
+ const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId, request);
64
64
  if (require_json_response.isHandlerResponse(agent)) {
65
65
  _copilotkit_shared.logger.warn({
66
66
  agentId,
@@ -1 +1 @@
1
- {"version":3,"file":"thread-names.cjs","names":["cloneAgentForRequest","isHandlerResponse"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/thread-names.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"node:crypto\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: { name: generatedTitle ?? FALLBACK_THREAD_TITLE },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = randomUUID();\n const { newMessages } = await agent.runAgent({\n messages,\n state: {},\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n const lastMessage = newMessages.at(-1);\n const titleContent = lastMessage\n ? stringifyMessageContent(lastMessage.content)\n : \"\";\n\n return normalizeGeneratedTitle(titleContent);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Generate a short title for this conversation.\",\n \"Conversation:\",\n transcript.join(\"\\n\"),\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n }\n } catch {\n // Fall back to using the raw text.\n }\n\n candidate = candidate\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"mappings":";;;;;;;;AAWA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,M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AAC,MAAM;AAGzD,KAAI,UAAU,MAAM,MAAM,CAAC,SAAS,gBAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
1
+ {"version":3,"file":"thread-names.cjs","names":["cloneAgentForRequest","isHandlerResponse"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/thread-names.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"node:crypto\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: { name: generatedTitle ?? FALLBACK_THREAD_TITLE },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = randomUUID();\n const { newMessages } = await agent.runAgent({\n messages,\n state: {},\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n const lastMessage = newMessages.at(-1);\n const titleContent = lastMessage\n ? stringifyMessageContent(lastMessage.content)\n : \"\";\n\n return normalizeGeneratedTitle(titleContent);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Generate a short title for this conversation.\",\n \"Conversation:\",\n transcript.join(\"\\n\"),\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n }\n } catch {\n // Fall back to using the raw text.\n }\n\n candidate = candidate\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"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AC/B,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,eAAe,GAAG,CAC1B,QAAQ,QAAQ,IAAI,CACpB,MAAM;AAET,KAAI,CAAC,UACH,QAAO;AAGT,KAAI,UAAU,SAAS,iBACrB,aAAY,UAAU,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGzD,KAAI,UAAU,MAAM,MAAM,CAAC,SAAS,gBAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
@@ -59,7 +59,7 @@ async function generateThreadNameForNewThread({ runtime, request, agentId, sourc
59
59
  }
60
60
  async function runTitleGenerationAttempt(params) {
61
61
  const { runtime, request, agentId, threadId, prompt } = params;
62
- const agent = await cloneAgentForRequest(runtime, agentId);
62
+ const agent = await cloneAgentForRequest(runtime, agentId, request);
63
63
  if (isHandlerResponse(agent)) {
64
64
  logger.warn({
65
65
  agentId,
@@ -1 +1 @@
1
- {"version":3,"file":"thread-names.mjs","names":["randomUUID"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/thread-names.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"node:crypto\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: { name: generatedTitle ?? FALLBACK_THREAD_TITLE },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = randomUUID();\n const { newMessages } = await agent.runAgent({\n messages,\n state: {},\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n const lastMessage = newMessages.at(-1);\n const titleContent = lastMessage\n ? stringifyMessageContent(lastMessage.content)\n : \"\";\n\n return normalizeGeneratedTitle(titleContent);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Generate a short title for this conversation.\",\n \"Conversation:\",\n transcript.join(\"\\n\"),\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n }\n } catch {\n // Fall back to using the raw text.\n }\n\n candidate = candidate\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"mappings":";;;;;;;AAWA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;AAC1C,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3D,KAAI,CAAC,OACH;CAGF,IAAI,iBAAgC;AAEpC,MAAK,IAAI,UAAU,GAAG,WAAW,+BAA+B,UAC9D,KAAI;AACF,mBAAiB,MAAM,0BAA0B;GAC/C;GACA;GACA;GACA,UAAU,OAAO;GACjB;GACD,CAAC;AAEF,MAAI,eACF;AAGF,SAAO,KACL;GAAE;GAAS;GAAS,UAAU,OAAO;GAAI,EACzC,4DACD;UACM,OAAO;AACd,SAAO,KACL;GAAE,KAAK;GAAO;GAAS;GAAS,UAAU,OAAO;GAAI,EACrD,wCACD;;AAIL,OAAM,QAAQ,aAAa,aAAa;EACtC,UAAU,OAAO;EACjB;EACA;EACA,SAAS,EAAE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SACrB,QAAO,QAAQ,MAAM;AAGvB,KAAI,WAAW,KACb,QAAO;AAGT,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,CAAC,MAAM;SAC/B;AACN,SAAO;;;AAIX,SAAS,wBAAwB,UAAiC;CAChE,IAAI,YAAY,SAAS,MAAM;AAC/B,KAAI,CAAC,UACH,QAAO;AAGT,aAAY,UACT,QAAQ,qBAAqB,GAAG,CAChC,QAAQ,WAAW,GAAG,CACtB,MAAM;AAET,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,UAAU;AACpC,MAAI,OAAO,OAAO,UAAU,SAC1B,aAAY,OAAO;SAEf;AAIR,aAAY,UACT,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,eAAe,GAAG,CAC1B,QAAQ,QAAQ,IAAI,CACpB,MAAM;AAET,KAAI,CAAC,UACH,QAAO;AAGT,KAAI,UAAU,SAAS,iBACrB,aAAY,UAAU,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGzD,KAAI,UAAU,MAAM,MAAM,CAAC,SAAS,gBAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
1
+ {"version":3,"file":"thread-names.mjs","names":["randomUUID"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/thread-names.ts"],"sourcesContent":["import { AbstractAgent, Message, RunAgentInput } from \"@ag-ui/client\";\nimport { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"node:crypto\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n} from \"../shared/agent-utils\";\nimport { ThreadSummary } from \"../../intelligence-platform\";\nimport { isHandlerResponse } from \"../shared/json-response\";\n\nconst THREAD_NAME_SYSTEM_PROMPT = [\n \"You generate short, specific conversation titles.\",\n 'Return JSON only in this exact shape: {\"title\":\"...\"}',\n \"The title must be 2 to 5 words.\",\n \"Use sentence case.\",\n \"No quotes.\",\n \"No emoji.\",\n \"No markdown characters or formatting.\",\n \"Do not use *, _, #, `, [, ], (, ), !, ~, >, or |.\",\n \"No trailing punctuation.\",\n \"No explanations.\",\n \"Do not call tools.\",\n].join(\"\\n\");\n\nconst MAX_TITLE_LENGTH = 80;\nconst MAX_TITLE_WORDS = 8;\nconst MAX_TRANSCRIPT_MESSAGES = 8;\nconst MAX_TITLE_GENERATION_ATTEMPTS = 3;\nconst FALLBACK_THREAD_TITLE = \"Untitled\";\n\ninterface GenerateThreadNameParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n sourceInput: RunAgentInput;\n thread: ThreadSummary;\n userId: string;\n}\n\nexport async function generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput,\n thread,\n userId,\n}: GenerateThreadNameParams): Promise<void> {\n if (!runtime.generateThreadNames || hasThreadName(thread.name)) {\n return;\n }\n\n const prompt = buildThreadTitlePrompt(sourceInput.messages);\n if (!prompt) {\n return;\n }\n\n let generatedTitle: string | null = null;\n\n for (let attempt = 1; attempt <= MAX_TITLE_GENERATION_ATTEMPTS; attempt++) {\n try {\n generatedTitle = await runTitleGenerationAttempt({\n runtime,\n request,\n agentId,\n threadId: thread.id,\n prompt,\n });\n\n if (generatedTitle) {\n break;\n }\n\n logger.warn(\n { agentId, attempt, threadId: thread.id },\n \"Thread name generation returned an empty or invalid title\",\n );\n } catch (error) {\n logger.warn(\n { err: error, agentId, attempt, threadId: thread.id },\n \"Thread name generation attempt failed\",\n );\n }\n }\n\n await runtime.intelligence.updateThread({\n threadId: thread.id,\n userId,\n agentId,\n updates: { name: generatedTitle ?? FALLBACK_THREAD_TITLE },\n });\n}\n\nasync function runTitleGenerationAttempt(params: {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n prompt: string;\n}): Promise<string | null> {\n const { runtime, request, agentId, threadId, prompt } = params;\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (isHandlerResponse(agent)) {\n logger.warn(\n { agentId, threadId },\n \"Skipping thread naming because the agent could not be cloned\",\n );\n return null;\n }\n\n configureAgentForRequest({\n runtime,\n request,\n agentId,\n agent,\n });\n\n const messages: Message[] = [\n {\n id: randomUUID(),\n role: \"system\",\n content: THREAD_NAME_SYSTEM_PROMPT,\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: prompt,\n },\n ];\n\n agent.setMessages(messages);\n agent.setState({});\n agent.threadId = randomUUID();\n const { newMessages } = await agent.runAgent({\n messages,\n state: {},\n tools: [],\n context: [],\n forwardedProps: {},\n });\n\n const lastMessage = newMessages.at(-1);\n const titleContent = lastMessage\n ? stringifyMessageContent(lastMessage.content)\n : \"\";\n\n return normalizeGeneratedTitle(titleContent);\n}\n\nfunction buildThreadTitlePrompt(\n messages: Message[] | undefined,\n): string | null {\n const transcript = (messages ?? [])\n .filter((message) =>\n [\"user\", \"assistant\", \"system\", \"developer\"].includes(message.role),\n )\n .map((message) => {\n const content = stringifyMessageContent(message.content);\n if (!content) {\n return null;\n }\n\n return `${message.role}: ${content}`;\n })\n .filter((message): message is string => !!message)\n .slice(-MAX_TRANSCRIPT_MESSAGES);\n\n if (transcript.length === 0) {\n return null;\n }\n\n return [\n \"Generate a short title for this conversation.\",\n \"Conversation:\",\n transcript.join(\"\\n\"),\n ].join(\"\\n\\n\");\n}\n\nfunction stringifyMessageContent(content: Message[\"content\"]): string {\n if (typeof content === \"string\") {\n return content.trim();\n }\n\n if (content == null) {\n return \"\";\n }\n\n try {\n return JSON.stringify(content).trim();\n } catch {\n return \"\";\n }\n}\n\nfunction normalizeGeneratedTitle(rawTitle: string): string | null {\n let candidate = rawTitle.trim();\n if (!candidate) {\n return null;\n }\n\n candidate = candidate\n .replace(/^```(?:json)?\\s*/i, \"\")\n .replace(/\\s*```$/, \"\")\n .trim();\n\n try {\n const parsed = JSON.parse(candidate) as { title?: unknown };\n if (typeof parsed.title === \"string\") {\n candidate = parsed.title;\n }\n } catch {\n // Fall back to using the raw text.\n }\n\n candidate = candidate\n .replace(/^[\"'`]+|[\"'`]+$/g, \"\")\n .replace(/[*_#[\\]()!~>|]+/g, \"\")\n .replace(/[.!?,;:]+$/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n\n if (!candidate) {\n return null;\n }\n\n if (candidate.length > MAX_TITLE_LENGTH) {\n candidate = candidate.slice(0, MAX_TITLE_LENGTH).trim();\n }\n\n if (candidate.split(/\\s+/).length > MAX_TITLE_WORDS) {\n return null;\n }\n\n return candidate;\n}\n\nfunction hasThreadName(name: string | null | undefined): boolean {\n return typeof name === \"string\" && name.trim().length > 0;\n}\n\n/** @internal Exported for testing only. */\nexport const ɵnormalizeGeneratedTitle = normalizeGeneratedTitle;\n/** @internal Exported for testing only. */\nexport const ɵbuildThreadTitlePrompt = buildThreadTitlePrompt;\n/** @internal Exported for testing only. */\nexport const ɵhasThreadName = hasThreadName;\n"],"mappings":";;;;;;;AAWA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,KAAK,KAAK;AAEZ,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,0BAA0B;AAChC,MAAM,gCAAgC;AACtC,MAAM,wBAAwB;AAW9B,eAAsB,+BAA+B,EACnD,SACA,SACA,SACA,aACA,QACA,UAC0C;AAC1C,KAAI,CAAC,QAAQ,uBAAuB,cAAc,OAAO,KAAK,CAC5D;CAGF,MAAM,SAAS,uBAAuB,YAAY,SAAS;AAC3D,KAAI,CAAC,OACH;CAGF,IAAI,iBAAgC;AAEpC,MAAK,IAAI,UAAU,GAAG,WAAW,+BAA+B,UAC9D,KAAI;AACF,mBAAiB,MAAM,0BAA0B;GAC/C;GACA;GACA;GACA,UAAU,OAAO;GACjB;GACD,CAAC;AAEF,MAAI,eACF;AAGF,SAAO,KACL;GAAE;GAAS;GAAS,UAAU,OAAO;GAAI,EACz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AM,CAAC,wBAAwB;AAElC,KAAI,WAAW,WAAW,EACxB,QAAO;AAGT,QAAO;EACL;EACA;EACA,WAAW,KAAK,KAAK;EACtB,CAAC,KAAK,OAAO;;AAGhB,SAAS,wBAAwB,SAAqC;AACpE,KAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM;AAGvB,KAAI,WAAW,KACb,QAAO;AAGT,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,CAAC,MAAM;SAC/B;AACN,SAAO;;;AAIX,SAAS,wBAAwB,UAAiC;CAChE,IAAI,YAAY,SAAS,MAAM;AAC/B,KAAI,CAAC,UACH,QAAO;AAGT,aAAY,UACT,QAAQ,qBAAqB,GAAG,CAChC,QAAQ,WAAW,GAAG,CACtB,MAAM;AAET,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,UAAU;AACpC,MAAI,OAAO,OAAO,UAAU,SAC1B,aAAY,OAAO;SAEf;AAIR,aAAY,UACT,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,oBAAoB,GAAG,CAC/B,QAAQ,eAAe,GAAG,CAC1B,QAAQ,QAAQ,IAAI,CACpB,MAAM;AAET,KAAI,CAAC,UACH,QAAO;AAGT,KAAI,UAAU,SAAS,iBACrB,aAAY,UAAU,MAAM,GAAG,iBAAiB,CAAC,MAAM;AAGzD,KAAI,UAAU,MAAM,MAAM,CAAC,SAAS,gBAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,MAA0C;AAC/D,QAAO,OAAO,SAAS,YAAY,KAAK,MAAM,CAAC,SAAS"}
@@ -1,5 +1,6 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
+ const require_runtime$1 = require('../../core/runtime.cjs');
3
4
  const require_open_generative_ui_middleware = require('../../open-generative-ui-middleware.cjs');
4
5
  const require_header_utils = require('../header-utils.cjs');
5
6
  let _copilotkit_shared = require("@copilotkit/shared");
@@ -8,8 +9,8 @@ let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
8
9
  let _ag_ui_mcp_apps_middleware = require("@ag-ui/mcp-apps-middleware");
9
10
 
10
11
  //#region src/v2/runtime/handlers/shared/agent-utils.ts
11
- async function cloneAgentForRequest(runtime, agentId) {
12
- const agents = await runtime.agents;
12
+ async function cloneAgentForRequest(runtime, agentId, request) {
13
+ const agents = await require_runtime$1.resolveAgents(runtime.agents, request);
13
14
  if (!agents[agentId]) return new Response(JSON.stringify({
14
15
  error: "Agent not found",
15
16
  message: `Agent '${agentId}' does not exist`
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.cjs","names":["A2UIMiddleware","MCPAppsMiddleware","OpenGenerativeUIMiddleware","extractForwardableHeaders","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import {\n AbstractAgent,\n RunAgentInput,\n RunAgentInputSchema,\n} from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n): Promise<AbstractAgent | Response> {\n const agents = await runtime.agents;\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n}): void {\n const { runtime, request, agentId } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (runtime.a2ui) {\n const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new A2UIMiddleware(a2uiOptions));\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = runtime.mcpApps.servers\n .filter((server) => !server.agentId || server.agentId === agentId)\n .map((server) => {\n const mcpServer = { ...server };\n delete mcpServer.agentId;\n return mcpServer;\n });\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n if (agent.headers) {\n agent.headers = {\n ...agent.headers,\n ...extractForwardableHeaders(request),\n };\n }\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,eAAsB,qBACpB,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,QAAQ;AAE7B,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAKhC;CACP,MAAM,EAAE,SAAS,SAAS,YAAY;CACtC,MAAM,QAAQ,OAAO;AAErB,KAAI,QAAQ,MAAM;EAChB,MAAM,EAAE,QAAQ,cAAc,GAAG,gBAAgB,QAAQ;AAEzD,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IAAI,IAAIA,sCAAe,YAAY,CAAC;;AAI9C,KAAI,QAAQ,SAAS,SAAS,QAAQ;EACpC,MAAM,aAAa,QAAQ,QAAQ,QAChC,QAAQ,WAAW,CAAC,OAAO,WAAW,OAAO,YAAY,QAAQ,CACjE,KAAK,WAAW;GACf,MAAM,YAAY,EAAE,GAAG,QAAQ;AAC/B,UAAO,UAAU;AACjB,UAAO;IACP;AAEJ,MAAI,WAAW,SAAS,KAAK,OAAO,MAAM,QAAQ,WAChD,OAAM,IAAI,IAAIC,6CAAkB,EAAE,YAAY,CAAC,CAAC;;AAIpD,KAAI,QAAQ,kBAAkB;EAC5B,MAAM,SAAS,QAAQ;EACvB,MAAM,eAAe,OAAO,WAAW,WAAW,OAAO,SAAS;AAElE,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IAAI,IAAIC,kEAA4B,CAAC;;AAI/C,KAAI,MAAM,QACR,OAAM,UAAU;EACd,GAAG,MAAM;EACT,GAAGC,+CAA0B,QAAQ;EACtC;;AAIL,eAAsB,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAOC,kCAAoB,MAAM,YAAY;UACtC,OAAO;AACd,4BAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQA,kCAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"agent-utils.cjs","names":["resolveAgents","A2UIMiddleware","MCPAppsMiddleware","OpenGenerativeUIMiddleware","extractForwardableHeaders","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import {\n AbstractAgent,\n RunAgentInput,\n RunAgentInputSchema,\n} from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { CopilotRuntimeLike, resolveAgents } from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n}): void {\n const { runtime, request, agentId } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (runtime.a2ui) {\n const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new A2UIMiddleware(a2uiOptions));\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = runtime.mcpApps.servers\n .filter((server) => !server.agentId || server.agentId === agentId)\n .map((server) => {\n const mcpServer = { ...server };\n delete mcpServer.agentId;\n return mcpServer;\n });\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n if (agent.headers) {\n agent.headers = {\n ...agent.headers,\n ...extractForwardableHeaders(request),\n };\n }\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AA2BA,eAAsB,qBACpB,SAC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AAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAOC,kCAAoB,MAAM,YAAY;UACtC,OAAO;AACd,4BAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQA,kCAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -1,4 +1,5 @@
1
1
  import "reflect-metadata";
2
+ import { resolveAgents } from "../../core/runtime.mjs";
2
3
  import { OpenGenerativeUIMiddleware } from "../../open-generative-ui-middleware.mjs";
3
4
  import { extractForwardableHeaders } from "../header-utils.mjs";
4
5
  import { logger } from "@copilotkit/shared";
@@ -7,8 +8,8 @@ import { A2UIMiddleware } from "@ag-ui/a2ui-middleware";
7
8
  import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";
8
9
 
9
10
  //#region src/v2/runtime/handlers/shared/agent-utils.ts
10
- async function cloneAgentForRequest(runtime, agentId) {
11
- const agents = await runtime.agents;
11
+ async function cloneAgentForRequest(runtime, agentId, request) {
12
+ const agents = await resolveAgents(runtime.agents, request);
12
13
  if (!agents[agentId]) return new Response(JSON.stringify({
13
14
  error: "Agent not found",
14
15
  message: `Agent '${agentId}' does not exist`
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import {\n AbstractAgent,\n RunAgentInput,\n RunAgentInputSchema,\n} from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n): Promise<AbstractAgent | Response> {\n const agents = await runtime.agents;\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n}): void {\n const { runtime, request, agentId } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (runtime.a2ui) {\n const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new A2UIMiddleware(a2uiOptions));\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = runtime.mcpApps.servers\n .filter((server) => !server.agentId || server.agentId === agentId)\n .map((server) => {\n const mcpServer = { ...server };\n delete mcpServer.agentId;\n return mcpServer;\n });\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n if (agent.headers) {\n agent.headers = {\n ...agent.headers,\n ...extractForwardableHeaders(request),\n };\n }\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"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B,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAO,oBAAoB,MAAM,YAAY;UACtC,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,oBAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import {\n AbstractAgent,\n RunAgentInput,\n RunAgentInputSchema,\n} from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { CopilotRuntimeLike, resolveAgents } from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n}): void {\n const { runtime, request, agentId } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (runtime.a2ui) {\n const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new A2UIMiddleware(a2uiOptions));\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = runtime.mcpApps.servers\n .filter((server) => !server.agentId || server.agentId === agentId)\n .map((server) => {\n const mcpServer = { ...server };\n delete mcpServer.agentId;\n return mcpServer;\n });\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n if (agent.headers) {\n agent.headers = {\n ...agent.headers,\n ...extractForwardableHeaders(request),\n };\n }\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAKhC;CACP,MAAM,EAAE,SAAS,SAAS,YAAY;CACtC,MAAM,QAAQ,OAAO;AAErB,KAAI,QAAQ,MAAM;EAChB,MAAM,EAAE,QAAQ,cAAc,GAAG,gBAAgB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ACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -2,7 +2,7 @@
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.cjs";
3
3
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest } from "./runner/agent-runner.cjs";
4
4
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
5
- import { CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isIntelligenceRuntime } from "./core/runtime.cjs";
5
+ import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
6
6
  import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
7
7
  import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.cjs";
8
8
  import { CopilotEndpointCorsConfig, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.cjs";
@@ -3,7 +3,7 @@ import { TranscribeFileOptions, TranscriptionService } from "./transcription-ser
3
3
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest } from "./runner/agent-runner.mjs";
4
4
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
5
5
  import "./intelligence-platform/index.mjs";
6
- import { CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isIntelligenceRuntime } from "./core/runtime.mjs";
6
+ import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
7
7
  import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
8
8
  import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.mjs";
9
9
  import { CopilotEndpointCorsConfig, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkit/runtime",
3
- "version": "1.55.2",
3
+ "version": "1.55.3-canary.1776243725",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "ai",
@@ -104,7 +104,7 @@
104
104
  "graphql-scalars": "^1.23.0",
105
105
  "graphql-yoga": "^5.3.1",
106
106
  "hono": "^4.11.4",
107
- "openai": "^4.85.1",
107
+ "openai": "^4.85.1 || >=5.0.0",
108
108
  "partial-json": "^0.1.7",
109
109
  "phoenix": "^1.8.4",
110
110
  "pino": "^9.2.0",
@@ -115,7 +115,7 @@
115
115
  "uuid": "^10.0.0",
116
116
  "ws": "^8.18.0",
117
117
  "zod": "^3.23.3",
118
- "@copilotkit/shared": "1.55.2"
118
+ "@copilotkit/shared": "1.55.3-canary.1776243725"
119
119
  },
120
120
  "devDependencies": {
121
121
  "@copilotkit/aimock": "^1.10.0",
@@ -148,7 +148,8 @@
148
148
  "@langchain/langgraph-sdk": ">=0.1.2",
149
149
  "@langchain/openai": ">=0.4.2",
150
150
  "groq-sdk": ">=0.3.0 <1.0.0",
151
- "langchain": ">=0.3.3"
151
+ "langchain": ">=0.3.3",
152
+ "openai": "^4.85.1 || >=5.0.0"
152
153
  },
153
154
  "peerDependenciesMeta": {
154
155
  "@anthropic-ai/sdk": {
@@ -0,0 +1,81 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { BuiltInAgent } from "../index";
3
+
4
+ describe("BuiltInAgent.getCapabilities", () => {
5
+ it("should return default inferred capabilities", async () => {
6
+ const agent = new BuiltInAgent({
7
+ model: "openai/gpt-4o",
8
+ });
9
+
10
+ const capabilities = await agent.getCapabilities();
11
+
12
+ expect(capabilities).toEqual({
13
+ tools: {
14
+ supported: true,
15
+ clientProvided: true,
16
+ },
17
+ transport: {
18
+ streaming: true,
19
+ },
20
+ });
21
+ });
22
+
23
+ it("should merge explicit overrides with inferred defaults", async () => {
24
+ const agent = new BuiltInAgent({
25
+ model: "openai/gpt-4o",
26
+ capabilities: {
27
+ reasoning: {
28
+ supported: true,
29
+ streaming: true,
30
+ },
31
+ identity: {
32
+ name: "my-agent",
33
+ type: "custom",
34
+ },
35
+ },
36
+ });
37
+
38
+ const capabilities = await agent.getCapabilities();
39
+
40
+ expect(capabilities).toEqual({
41
+ tools: {
42
+ supported: true,
43
+ clientProvided: true,
44
+ },
45
+ transport: {
46
+ streaming: true,
47
+ },
48
+ reasoning: {
49
+ supported: true,
50
+ streaming: true,
51
+ },
52
+ identity: {
53
+ name: "my-agent",
54
+ type: "custom",
55
+ },
56
+ });
57
+ });
58
+
59
+ it("should allow overrides to replace entire categories", async () => {
60
+ const agent = new BuiltInAgent({
61
+ model: "openai/gpt-4o",
62
+ capabilities: {
63
+ tools: {
64
+ supported: true,
65
+ clientProvided: true,
66
+ parallelCalls: true,
67
+ },
68
+ },
69
+ });
70
+
71
+ const capabilities = await agent.getCapabilities();
72
+
73
+ expect(capabilities.tools).toEqual({
74
+ supported: true,
75
+ clientProvided: true,
76
+ parallelCalls: true,
77
+ });
78
+ // transport still inferred
79
+ expect(capabilities.transport).toEqual({ streaming: true });
80
+ });
81
+ });
@@ -11,24 +11,32 @@ import {
11
11
  } from "@ag-ui/client";
12
12
  import { randomUUID } from "@copilotkit/shared";
13
13
 
14
+ type ContentPartSource =
15
+ | { type: "data"; value: string; mimeType: string }
16
+ | { type: "url"; value: string; mimeType?: string };
17
+
14
18
  /**
15
19
  * A TanStack AI content part (text, image, audio, video, or document).
16
20
  */
17
21
  export type TanStackContentPart =
18
22
  | { type: "text"; content: string }
19
- | {
20
- type: "image" | "audio" | "video" | "document";
21
- source:
22
- | { type: "data"; value: string; mimeType: string }
23
- | { type: "url"; value: string; mimeType?: string };
24
- };
23
+ | { type: "image"; source: ContentPartSource }
24
+ | { type: "audio"; source: ContentPartSource }
25
+ | { type: "video"; source: ContentPartSource }
26
+ | { type: "document"; source: ContentPartSource };
25
27
 
26
28
  /**
27
29
  * Message format expected by TanStack AI's `chat()`.
30
+ *
31
+ * Content is typed as `any[]` for the multimodal case so messages are directly
32
+ * passable to any adapter without casts — different adapters constrain which
33
+ * modalities they accept (e.g. OpenAI only allows text + image).
34
+ * Use `TanStackContentPart` to inspect individual parts if needed.
28
35
  */
29
36
  export interface TanStackChatMessage {
30
37
  role: "user" | "assistant" | "tool";
31
- content: string | null | TanStackContentPart[];
38
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
+ content: string | null | any[];
32
40
  name?: string;
33
41
  toolCalls?: Array<{
34
42
  id: string;
@@ -20,6 +20,7 @@ import {
20
20
  StateSnapshotEvent,
21
21
  StateDeltaEvent,
22
22
  } from "@ag-ui/client";
23
+ import type { AgentCapabilities } from "@ag-ui/core";
23
24
  import {
24
25
  streamText,
25
26
  LanguageModel,
@@ -817,6 +818,15 @@ export interface BuiltInAgentClassicConfig {
817
818
  * Example: `{ openai: { reasoningEffort: "high" } }`
818
819
  */
819
820
  providerOptions?: Record<string, any>;
821
+ /**
822
+ * Explicit agent capabilities. **Shallow-merged** at the category level on
823
+ * top of auto-inferred defaults — providing a category (e.g. `tools`)
824
+ * replaces that entire category, not individual fields within it.
825
+ *
826
+ * For example, `{ tools: { supported: true } }` will drop the inferred
827
+ * `clientProvided` value. Include all fields for any category you override.
828
+ */
829
+ capabilities?: Partial<AgentCapabilities>;
820
830
  }
821
831
 
822
832
  /**
@@ -854,6 +864,29 @@ export class BuiltInAgent extends AbstractAgent {
854
864
  return this.config?.overridableProperties?.includes(property) ?? false;
855
865
  }
856
866
 
867
+ async getCapabilities(): Promise<AgentCapabilities> {
868
+ const inferred: AgentCapabilities = {
869
+ tools: {
870
+ supported: true,
871
+ clientProvided: true,
872
+ },
873
+ transport: {
874
+ streaming: true,
875
+ },
876
+ };
877
+
878
+ if (!this.config.capabilities) {
879
+ return inferred;
880
+ }
881
+
882
+ // Shallow merge at the category level — explicit overrides replace
883
+ // entire categories when provided, inferred defaults fill the rest.
884
+ return {
885
+ ...inferred,
886
+ ...this.config.capabilities,
887
+ };
888
+ }
889
+
857
890
  run(input: RunAgentInput): Observable<BaseEvent> {
858
891
  if (isFactoryConfig(this.config)) {
859
892
  return this.runFactory(input, this.config);