@copilotkit/runtime 1.55.2-next.1 → 1.55.3-canary.1776215089

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 (107) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/agent/converters/tanstack.cjs.map +1 -1
  3. package/dist/agent/converters/tanstack.d.cts +6 -19
  4. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  5. package/dist/agent/converters/tanstack.d.mts +6 -19
  6. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  7. package/dist/agent/converters/tanstack.mjs.map +1 -1
  8. package/dist/agent/index.cjs +14 -0
  9. package/dist/agent/index.cjs.map +1 -1
  10. package/dist/agent/index.d.cts +12 -1
  11. package/dist/agent/index.d.cts.map +1 -1
  12. package/dist/agent/index.d.mts +12 -1
  13. package/dist/agent/index.d.mts.map +1 -1
  14. package/dist/agent/index.mjs +14 -0
  15. package/dist/agent/index.mjs.map +1 -1
  16. package/dist/index.d.cts +2 -1
  17. package/dist/index.d.mts +2 -1
  18. package/dist/lib/index.d.cts +1 -0
  19. package/dist/lib/index.d.cts.map +1 -1
  20. package/dist/lib/index.d.mts +1 -0
  21. package/dist/lib/index.d.mts.map +1 -1
  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.map +1 -1
  28. package/dist/package.cjs +1 -1
  29. package/dist/package.mjs +1 -1
  30. package/dist/v2/index.cjs +1 -0
  31. package/dist/v2/index.d.cts +3 -3
  32. package/dist/v2/index.d.mts +3 -3
  33. package/dist/v2/index.mjs +2 -2
  34. package/dist/v2/runtime/core/fetch-handler.cjs +43 -3
  35. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  36. package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
  37. package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
  38. package/dist/v2/runtime/core/fetch-handler.mjs +43 -3
  39. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  40. package/dist/v2/runtime/core/fetch-router.cjs +26 -0
  41. package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
  42. package/dist/v2/runtime/core/fetch-router.mjs +26 -0
  43. package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
  44. package/dist/v2/runtime/core/hooks.cjs.map +1 -1
  45. package/dist/v2/runtime/core/hooks.d.cts +13 -0
  46. package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
  47. package/dist/v2/runtime/core/hooks.d.mts +13 -0
  48. package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
  49. package/dist/v2/runtime/core/hooks.mjs.map +1 -1
  50. package/dist/v2/runtime/core/runtime.cjs +13 -0
  51. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  52. package/dist/v2/runtime/core/runtime.d.cts +43 -3
  53. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  54. package/dist/v2/runtime/core/runtime.d.mts +43 -3
  55. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  56. package/dist/v2/runtime/core/runtime.mjs +13 -1
  57. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  58. package/dist/v2/runtime/handlers/get-runtime-info.cjs +18 -10
  59. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  60. package/dist/v2/runtime/handlers/get-runtime-info.mjs +19 -11
  61. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  62. package/dist/v2/runtime/handlers/handle-connect.cjs +1 -1
  63. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  64. package/dist/v2/runtime/handlers/handle-connect.mjs +1 -1
  65. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  66. package/dist/v2/runtime/handlers/handle-run.cjs +1 -1
  67. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  68. package/dist/v2/runtime/handlers/handle-run.mjs +1 -1
  69. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  70. package/dist/v2/runtime/handlers/handle-stop.cjs +2 -1
  71. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  72. package/dist/v2/runtime/handlers/handle-stop.mjs +2 -1
  73. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  74. package/dist/v2/runtime/handlers/intelligence/thread-names.cjs +1 -1
  75. package/dist/v2/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  76. package/dist/v2/runtime/handlers/intelligence/thread-names.mjs +1 -1
  77. package/dist/v2/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  78. package/dist/v2/runtime/handlers/intelligence/threads.cjs +179 -0
  79. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -0
  80. package/dist/v2/runtime/handlers/intelligence/threads.mjs +173 -0
  81. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -0
  82. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -2
  83. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  84. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +3 -2
  85. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  86. package/dist/v2/runtime/index.d.cts +1 -1
  87. package/dist/v2/runtime/index.d.mts +1 -1
  88. package/package.json +2 -2
  89. package/src/agent/__tests__/capabilities.test.ts +81 -0
  90. package/src/agent/converters/tanstack.ts +15 -7
  91. package/src/agent/index.ts +33 -0
  92. package/src/lib/runtime/copilot-runtime.ts +6 -1
  93. package/src/v2/runtime/__tests__/agents-factory.test.ts +136 -0
  94. package/src/v2/runtime/__tests__/fetch-router.test.ts +76 -0
  95. package/src/v2/runtime/__tests__/get-runtime-info.test.ts +134 -1
  96. package/src/v2/runtime/core/fetch-handler.ts +55 -4
  97. package/src/v2/runtime/core/fetch-router.ts +48 -0
  98. package/src/v2/runtime/core/hooks.ts +6 -1
  99. package/src/v2/runtime/core/runtime.ts +63 -2
  100. package/src/v2/runtime/handlers/get-runtime-info.ts +33 -8
  101. package/src/v2/runtime/handlers/handle-connect.ts +1 -1
  102. package/src/v2/runtime/handlers/handle-run.ts +1 -1
  103. package/src/v2/runtime/handlers/handle-stop.ts +2 -1
  104. package/src/v2/runtime/handlers/handle-threads.ts +1 -0
  105. package/src/v2/runtime/handlers/intelligence/thread-names.ts +1 -1
  106. package/src/v2/runtime/handlers/intelligence/threads.ts +28 -0
  107. package/src/v2/runtime/handlers/shared/agent-utils.ts +3 -2
@@ -5,12 +5,12 @@ import { CopilotServiceAdapter } from "../../service-adapters/service-adapter.cj
5
5
  import { RemoteChainParameters } from "../../service-adapters/langchain/langserve.cjs";
6
6
  import "../../service-adapters/index.cjs";
7
7
  import { AgentRunner } from "../../v2/runtime/runner/agent-runner.cjs";
8
- import { CopilotRuntime as CopilotRuntime$1, CopilotRuntimeOptions } from "../../v2/runtime/core/runtime.cjs";
8
+ import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotRuntime as CopilotRuntime$1, CopilotRuntimeOptions } from "../../v2/runtime/core/runtime.cjs";
9
9
  import "../../v2/runtime/index.cjs";
10
10
  import { CopilotKitEndpoint, EndpointDefinition, EndpointType, LangGraphPlatformEndpoint } from "./types.cjs";
11
11
  import { CopilotObservabilityConfig } from "../observability.cjs";
12
12
  import { MCPClient, MCPEndpointConfig } from "./mcp-tools-utils.cjs";
13
- import { Action, CopilotErrorHandler, MaybePromise, NonEmptyRecord, Parameter, PartialBy } from "@copilotkit/shared";
13
+ import { Action, CopilotErrorHandler, Parameter, PartialBy } from "@copilotkit/shared";
14
14
  import { AbstractAgent } from "@ag-ui/client";
15
15
 
16
16
  //#region src/lib/runtime/copilot-runtime.d.ts
@@ -184,7 +184,7 @@ interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> exten
184
184
  * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`
185
185
  * – the `Record<string, AbstractAgent>` constraint in `both
186
186
  */
187
- agents?: MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;
187
+ agents?: AgentsConfig;
188
188
  }
189
189
  /**
190
190
  * Central runtime object passed to all request handlers.
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.d.cts","names":[],"sources":["../../../src/lib/runtime/copilot-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;KAoEK,uBAAA,IACH,MAAA,EAAQ,iBAAA,KACL,OAAA,CAAQ,SAAA;AAAA,KAER,oBAAA,WAA+B,SAAA,gBAChC,MAAA,CAAO,CAAA,QACL,GAAA;EAAO,UAAA;EAAiB,GAAA;AAAA,MAAmB,MAAA,CAAO,CAAA;AAAA,UAE9C,sBAAA;EACR,QAAA;EACA,KAAA;EACA,aAAA,EAAe,SAAA;EACf,UAAA;EACA,GAAA;AAAA;AAAA,KAGG,sBAAA,IACH,OAAA,EAAS,sBAAA,YACC,OAAA;AAAA,UAEF,qBAAA;EACR,QAAA;EACA,KAAA;EACA,aAAA,EAAe,SAAA;EACf,cAAA,EAAgB,SAAA;EAChB,UAAA;EACA,GAAA;AAAA;AAAA,KAGG,qBAAA,IACH,OAAA,EAAS,qBAAA,YACC,OAAA;AAAA,UAEF,uBAAA;EACR,QAAA;EACA,KAAA;EACA,GAAA;EACA,SAAA;EACA,WAAA,EAAa,YAAA;AAAA;AAAA,KAEV,uBAAA,IACH,OAAA,EAAS,uBAAA,YACC,OAAA;AAAA,UAEF,UAAA;EAjCc;;;EAAtB;;;;EAyCA,eAAA,GAAkB,sBAAA;EAvCf;AAAA;;;;;;EAgDH,cAAA,GAAiB,qBAAA;AAAA;AAAA,UAGF,oCAAA,WACL,SAAA;EA7CF;;;;;;;;;;;;;;AAML;;;;;;;;EAKc;AAAA;;;EA8DjB,UAAA,GAAa,UAAA;EA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;EAcT,MAAA,GAAS,MAAA,SAAe,aAAA;EAQxB,uCAAA;EAlGiB;;;;;;AAAA;;;;;;;;;;AAsBnB;;;;;EAmGE,eAAA,GAAkB,0BAAA;EAjER;;;;;;EAyEV,UAAA,GAAa,iBAAA;EARK;;;;;;;;;;;;;;;;;;;;;;;;;EAmClB,eAAA,GAAkB,uBAAA;EAnClB;;;;;;;;;;;;AAgED;;;;;EAVC,OAAA,GAAU,mBAAA;EAEV,gBAAA,GAAmB,uBAAA;AAAA;AAAA,UAqBX,+BAAA,WAA0C,SAAA,sBAEhD,IAAA,CAAK,oCAAA,CAAqC,CAAA,cAC1C,IAAA,CAAK,qBAAA;EAAL;;;;;;;;EASF,MAAA,GAAS,YAAA;AAAA;;;;cAME,cAAA,iBAA+B,SAAA;EAC1C,MAAA,GAAS,+BAAA,CAAgC,CAAA;EAAA,QACjC,aAAA;EAAA,QAEA,aAAA;EAAA,QAEA,WAAA;EAAA,QACA,SAAA;cAGN,MAAA,GAAS,+BAAA,CAAgC,CAAA,IACvC,SAAA,CAAU,qBAAA;EAAA,IAwCV,QAAA,CAAA,GAAQ,gBAAA;EAAA,QAQJ,uBAAA;EAsBR,oBAAA,CAAqB,cAAA,EAAgB,qBAAA;EAAA,QA0C7B,mBAAA;EAAA,QAuBA,mBAAA;EAAA,QAoCA,4BAAA;EAAA,QAsEA,2BAAA;EA3KkD;;;EAAA,QAqM5C,6BAAA;EArRL;;;EAAA,QAkSD,4BAAA;EAAA,QAiDM,eAAA;AAAA;AAAA,iBAoGA,kBAAA,CACd,MAAA,EAAQ,IAAA,CAAK,kBAAA,YACZ,kBAAA;AAAA,iBAOa,yBAAA,CACd,MAAA,EAAQ,IAAA,CAAK,yBAAA,YACZ,yBAAA;AAAA,iBAOa,mBAAA,CAAoB,QAAA,EAAU,kBAAA,GAAkB,YAAA"}
@@ -5,12 +5,12 @@ import { CopilotServiceAdapter } from "../../service-adapters/service-adapter.mj
5
5
  import { RemoteChainParameters } from "../../service-adapters/langchain/langserve.mjs";
6
6
  import "../../service-adapters/index.mjs";
7
7
  import { AgentRunner } from "../../v2/runtime/runner/agent-runner.mjs";
8
- import { CopilotRuntime as CopilotRuntime$1, CopilotRuntimeOptions } from "../../v2/runtime/core/runtime.mjs";
8
+ import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotRuntime as CopilotRuntime$1, CopilotRuntimeOptions } from "../../v2/runtime/core/runtime.mjs";
9
9
  import "../../v2/runtime/index.mjs";
10
10
  import { CopilotKitEndpoint, EndpointDefinition, EndpointType, LangGraphPlatformEndpoint } from "./types.mjs";
11
11
  import { CopilotObservabilityConfig } from "../observability.mjs";
12
12
  import { MCPClient, MCPEndpointConfig } from "./mcp-tools-utils.mjs";
13
- import { Action, CopilotErrorHandler, MaybePromise, NonEmptyRecord, Parameter, PartialBy } from "@copilotkit/shared";
13
+ import { Action, CopilotErrorHandler, Parameter, PartialBy } from "@copilotkit/shared";
14
14
  import { AbstractAgent } from "@ag-ui/client";
15
15
 
16
16
  //#region src/lib/runtime/copilot-runtime.d.ts
@@ -184,7 +184,7 @@ interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> exten
184
184
  * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`
185
185
  * – the `Record<string, AbstractAgent>` constraint in `both
186
186
  */
187
- agents?: MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;
187
+ agents?: AgentsConfig;
188
188
  }
189
189
  /**
190
190
  * Central runtime object passed to all request handlers.
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.d.mts","names":[],"sources":["../../../src/lib/runtime/copilot-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;KAoEK,uBAAA,IACH,MAAA,EAAQ,iBAAA,KACL,OAAA,CAAQ,SAAA;AAAA,KAER,oBAAA,WAA+B,SAAA,gBAChC,MAAA,CAAO,CAAA,QACL,GAAA;EAAO,UAAA;EAAiB,GAAA;AAAA,MAAmB,MAAA,CAAO,CA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C,aAAA;EAAA,QAEA,aAAA;EAAA,QAEA,WAAA;EAAA,QACA,SAAA;cAGN,MAAA,GAAS,+BAAA,CAAgC,CAAA,IACvC,SAAA,CAAU,qBAAA;EAAA,IAwCV,QAAA,CAAA,GAAQ,gBAAA;EAAA,QAQJ,uBAAA;EAsBR,oBAAA,CAAqB,cAAA,EAAgB,qBAAA;EAAA,QA0C7B,mBAAA;EAAA,QAuBA,mBAAA;EAAA,QAoCA,4BAAA;EAAA,QAsEA,2BAAA;EA3KkD;;;EAAA,QAqM5C,6BAAA;EArRL;;;EAAA,QAkSD,4BAAA;EAAA,QAiDM,eAAA;AAAA;AAAA,iBAoGA,kBAAA,CACd,MAAA,EAAQ,IAAA,CAAK,kBAAA,YACZ,kBAAA;AAAA,iBAOa,yBAAA,CACd,MAAA,EAAQ,IAAA,CAAK,yBAAA,YACZ,yBAAA;AAAA,iBAOa,mBAAA,CAAoB,QAAA,EAAU,kBAAA,GAAkB,YAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"copilot-runtime.mjs","names":["CopilotRuntimeVNext"],"sources":["../../../src/lib/runtime/copilot-runtime.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/concepts/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n type Action,\n type CopilotErrorHandler,\n CopilotKitMisuseError,\n type MaybePromise,\n type NonEmptyRecord,\n type Parameter,\n readBody,\n getZodParameters,\n type PartialBy,\n isTelemetryDisabled,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport {\n CopilotRuntime as CopilotRuntimeVNext,\n type CopilotRuntimeOptions,\n type CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n type AgentRunner,\n InMemoryAgentRunner,\n} from \"../../v2/runtime\";\nimport { TelemetryAgentRunner } from \"./telemetry-agent-runner\";\nimport telemetry from \"../telemetry-client\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport {\n EndpointType,\n type EndpointDefinition,\n type CopilotKitEndpoint,\n type LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\n\n// +++ MCP Imports +++\nimport {\n type MCPClient,\n type MCPEndpointConfig,\n type MCPTool,\n extractParametersFromSchema,\n} from \"./mcp-tools-utils\";\nimport { BuiltInAgent, type BuiltInAgentClassicConfig } from \"../../agent\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n * Requires publicApiKey from CopilotKit component to be set:\n *\n * ```tsx\n * <CopilotKit publicApiKey=\"ck_pub_...\" />\n * ```\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * **Requires publicApiKey**: Error handling only works when requests include a valid publicApiKey.\n * This is a premium Copilot Cloud feature.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n}\n\n/**\n * Central runtime object passed to all request handlers.\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BuiltInAgentClassicConfig[\"tools\"]> =\n new Map();\n private runtimeArgs: CopilotRuntimeOptions;\n private _instance: CopilotRuntimeVNext;\n\n constructor(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Determine the base runner (user-provided or default)\n const baseRunner = params?.runner ?? new InMemoryAgentRunner();\n\n // Wrap with TelemetryAgentRunner unless telemetry is disabled\n // This ensures we always capture agent execution telemetry when enabled,\n // even if the user provides their own custom runner\n const runner = isTelemetryDisabled()\n ? baseRunner\n : new TelemetryAgentRunner({ runner: baseRunner });\n\n this.runtimeArgs = {\n agents: { ...endpointAgents, ...agents },\n runner,\n licenseToken: params?.licenseToken,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n };\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n this.runtimeArgs.agents = Promise.resolve(\n this.runtimeArgs.agents ?? {},\n ).then(async (agents) => {\n let agentsList = agents;\n const isAgentsListEmpty = !Object.keys(agents).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const model =\n serviceAdapter.getLanguageModel?.() ??\n `${serviceAdapter.provider}/${serviceAdapter.model}`;\n agentsList.default = new BuiltInAgent({ model });\n }\n\n const actions = this.params?.actions;\n if (actions) {\n const mcpTools = await this.getToolsFromMCP();\n agentsList = this.assignToolsToAgents(agents, [\n ...this.getToolsFromActions(actions),\n ...mcpTools,\n ]);\n }\n\n return agentsList;\n });\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: {}, url: undefined })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig = existingConfig as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...tools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // Capture telemetry for copilot request creation\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n const body = (await readBody(request)) as RunAgentInput;\n\n const forwardedProps = body?.forwardedProps as\n | {\n cloud?: { guardrails?: unknown };\n metadata?: { requestType?: string };\n }\n | undefined;\n\n // Get cloud base URL from environment or default\n const cloudBaseUrl =\n process.env.COPILOT_CLOUD_BASE_URL || \"https://api.cloud.copilotkit.ai\";\n\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\":\n forwardedProps?.cloud?.guardrails !== undefined,\n requestType: forwardedProps?.metadata?.requestType ?? \"unknown\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n \"cloud.base_url\": cloudBaseUrl,\n });\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n // TODO: provide old expected params here when available\n // @ts-expect-error -- missing arguments.\n params.middleware.onAfterRequest({});\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<BuiltInAgentClassicConfig[\"tools\"]> {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const allTools: BuiltInAgentClassicConfig[\"tools\"] = [];\n\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n // Return cached tool definitions when available\n const cached = this.mcpToolsCache.get(endpointUrl);\n if (cached) {\n allTools.push(...cached);\n continue;\n }\n\n try {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n\n // Cache per endpoint and add to aggregate\n this.mcpToolsCache.set(endpointUrl, toolDefs);\n allTools.push(...toolDefs);\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`,\n error,\n );\n // Cache empty to prevent repeated attempts within lifecycle\n this.mcpToolsCache.set(endpointUrl, []);\n }\n }\n\n // Dedupe tools by name while preserving last-in wins (request overrides)\n const dedupedByName = new Map<string, (typeof allTools)[number]>();\n for (const tool of allTools) {\n dedupedByName.set(tool.name, tool);\n }\n\n return Array.from(dedupedByName.values());\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsUA,IAAa,iBAAb,MAAmE;CASjE,YACE,QAEA;uCAPA,IAAI,KAAK;EAQT,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAGD,MAAM,aAAa,QAAQ,UAAU,IAAI,qBAAqB;EAK9D,MAAM,SAAS,qBAAqB,GAChC,aACA,IAAI,qBAAqB,EAAE,QAAQ,YAAY,CAAC;AAEpD,OAAK,cAAc;GACjB,QAAQ;IAAE,GAAG;IAAgB,GAAG;IAAQ;GACxC;GACA,cAAc,QAAQ;GAItB,yBACE,KAAK,6BAA6B,OAAO,CAAC,KAAK,KAAK;GACtD,GAAI,QAAQ,0BAA0B,QAAQ,YAAY,iBACtD,EACE,wBACE,KAAK,4BAA4B,OAAO,CAAC,KAAK,KAAK,EACtD,GACD,EAAE;GACN,MAAM,QAAQ;GACd,SAAS,QAAQ;GACjB,kBAAkB,QAAQ;GAC3B;AACD,OAAK,SAAS;AACd,OAAK,gBAAgB,QAAQ;;CAG/B,IAAI,WAAW;AACb,MAAI,CAAC,KAAK,UACR,MAAK,YAAY,IAAIA,iBAAoB,KAAK,YAAY;AAG5D,SAAO,KAAK;;CAGd,AAAQ,wBACN,WAC+B;EAC/B,IAAI,SAAwC,EAAE;AAE9C,MACE,UAAU,MACP,aACC,oBAAoB,SAAS,IAAI,aAAa,kBACjD,CAED,OAAM,IAAI,sBAAsB,EAC9B,SACE,mQAGH,CAAC;AAGJ,SAAO;;CAGT,qBAAqB,gBAAuC;AAC1D,OAAK,YAAY,SAAS,QAAQ,QAChC,KAAK,YAAY,UAAU,EAAE,CAC9B,CAAC,KAAK,OAAO,WAAW;GACvB,IAAI,aAAa;GACjB,MAAM,o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,EAAE;AAEvD,OAAK,MAAM,UAAU,oBAAoB;GACvC,MAAM,cAAc,OAAO;GAE3B,MAAM,SAAS,KAAK,cAAc,IAAI,YAAY;AAClD,OAAI,QAAQ;AACV,aAAS,KAAK,GAAG,OAAO;AACxB;;AAGF,OAAI;IAEF,MAAM,WAAW,OADF,MAAM,gBAAgB,OAAO,EACd,OAAO;IAErC,MAAM,WAA+C,OAAO,QAC1D,SACD,CAAC,KAAK,CAAC,UAAU,UAA6B;KAE7C,MAAM,YAAY,iBADU,4BAA4B,KAAK,CACnB;AAC1C,YAAO;MACL,MAAM;MACN,aACE,KAAK,eAAe,aAAa,SAAS,SAAS,YAAY;MACjE,YAAY;MACZ,eAAe,QAAQ,SAAS;MACjC;MACD;AAGF,SAAK,cAAc,IAAI,aAAa,SAAS;AAC7C,aAAS,KAAK,GAAG,SAAS;YACnB,OAAO;AACd,YAAQ,MACN,4CAA4C,YAAY,qBACxD,MACD;AAED,SAAK,cAAc,IAAI,aAAa,EAAE,CAAC;;;EAK3C,MAAM,gCAAgB,IAAI,KAAwC;AAClE,OAAK,MAAM,QAAQ,SACjB,eAAc,IAAI,KAAK,MAAM,KAAK;AAGpC,SAAO,MAAM,KAAK,cAAc,QAAQ,CAAC;;;AAK7C,SAAgB,mBACd,QACoB;AACpB,QAAO;EACL,GAAG;EACH,MAAM,aAAa;EACpB;;AAGH,SAAgB,0BACd,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAM,aAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAO,aAAa;KAEpB,QAAO,aAAa;AAIxB,QAAO,SAAS"}
1
+ {"version":3,"file":"copilot-runtime.mjs","names":["CopilotRuntimeVNext"],"sources":["../../../src/lib/runtime/copilot-runtime.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/concepts/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n type Action,\n type CopilotErrorHandler,\n CopilotKitMisuseError,\n type MaybePromise,\n type NonEmptyRecord,\n type Parameter,\n readBody,\n getZodParameters,\n type PartialBy,\n isTelemetryDisabled,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport {\n CopilotRuntime as CopilotRuntimeVNext,\n type CopilotRuntimeOptions,\n type CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n type AgentRunner,\n type AgentsConfig,\n type AgentsFactory,\n type AgentFactoryContext,\n InMemoryAgentRunner,\n} from \"../../v2/runtime\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport { TelemetryAgentRunner } from \"./telemetry-agent-runner\";\nimport telemetry from \"../telemetry-client\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport {\n EndpointType,\n type EndpointDefinition,\n type CopilotKitEndpoint,\n type LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\n\n// +++ MCP Imports +++\nimport {\n type MCPClient,\n type MCPEndpointConfig,\n type MCPTool,\n extractParametersFromSchema,\n} from \"./mcp-tools-utils\";\nimport { BuiltInAgent, type BuiltInAgentClassicConfig } from \"../../agent\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n * Requires publicApiKey from CopilotKit component to be set:\n *\n * ```tsx\n * <CopilotKit publicApiKey=\"ck_pub_...\" />\n * ```\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * **Requires publicApiKey**: Error handling only works when requests include a valid publicApiKey.\n * This is a premium Copilot Cloud feature.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n}\n\n/**\n * Central runtime object passed to all request handlers.\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BuiltInAgentClassicConfig[\"tools\"]> =\n new Map();\n private runtimeArgs: CopilotRuntimeOptions;\n private _instance: CopilotRuntimeVNext;\n\n constructor(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Determine the base runner (user-provided or default)\n const baseRunner = params?.runner ?? new InMemoryAgentRunner();\n\n // Wrap with TelemetryAgentRunner unless telemetry is disabled\n // This ensures we always capture agent execution telemetry when enabled,\n // even if the user provides their own custom runner\n const runner = isTelemetryDisabled()\n ? baseRunner\n : new TelemetryAgentRunner({ runner: baseRunner });\n\n this.runtimeArgs = {\n agents: { ...endpointAgents, ...agents },\n runner,\n licenseToken: params?.licenseToken,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n };\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n this.runtimeArgs.agents = Promise.resolve(\n this.runtimeArgs.agents ?? {},\n ).then(async (agents) => {\n let agentsList = agents;\n const isAgentsListEmpty = !Object.keys(agents).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const model =\n serviceAdapter.getLanguageModel?.() ??\n `${serviceAdapter.provider}/${serviceAdapter.model}`;\n agentsList.default = new BuiltInAgent({ model });\n }\n\n const actions = this.params?.actions;\n if (actions) {\n const mcpTools = await this.getToolsFromMCP();\n agentsList = this.assignToolsToAgents(agents, [\n ...this.getToolsFromActions(actions),\n ...mcpTools,\n ]);\n }\n\n return agentsList;\n });\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: {}, url: undefined })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig = existingConfig as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...tools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // Capture telemetry for copilot request creation\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n const body = (await readBody(request)) as RunAgentInput;\n\n const forwardedProps = body?.forwardedProps as\n | {\n cloud?: { guardrails?: unknown };\n metadata?: { requestType?: string };\n }\n | undefined;\n\n // Get cloud base URL from environment or default\n const cloudBaseUrl =\n process.env.COPILOT_CLOUD_BASE_URL || \"https://api.cloud.copilotkit.ai\";\n\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\":\n forwardedProps?.cloud?.guardrails !== undefined,\n requestType: forwardedProps?.metadata?.requestType ?? \"unknown\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n \"cloud.base_url\": cloudBaseUrl,\n });\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n // TODO: provide old expected params here when available\n // @ts-expect-error -- missing arguments.\n params.middleware.onAfterRequest({});\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<BuiltInAgentClassicConfig[\"tools\"]> {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const allTools: BuiltInAgentClassicConfig[\"tools\"] = [];\n\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n // Return cached tool definitions when available\n const cached = this.mcpToolsCache.get(endpointUrl);\n if (cached) {\n allTools.push(...cached);\n continue;\n }\n\n try {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n\n // Cache per endpoint and add to aggregate\n this.mcpToolsCache.set(endpointUrl, toolDefs);\n allTools.push(...toolDefs);\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`,\n error,\n );\n // Cache empty to prevent repeated attempts within lifecycle\n this.mcpToolsCache.set(endpointUrl, []);\n }\n }\n\n // Dedupe tools by name while preserving last-in wins (request overrides)\n const dedupedByName = new Map<string, (typeof allTools)[number]>();\n for (const tool of allTools) {\n dedupedByName.set(tool.name, tool);\n }\n\n return Array.from(dedupedByName.values());\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2UA,IAAa,iBAAb,MAAmE;CASjE,YACE,QAEA;uCAPA,IAAI,KAAK;EAQT,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAGD,MAAM,aAAa,QAAQ,UAAU,IAAI,qBAAqB;EAK9D,MAAM,SAAS,qBAAqB,GAChC,aACA,IAAI,qBAAqB,EAAE,QAAQ,YAAY,CAAC;AAEpD,OAAK,cAAc;GACjB,QAAQ;IAAE,GAAG;IAAgB,GAAG;IAAQ;GACxC;GACA,cAAc,QAAQ;GAItB,yBACE,KAAK,6BAA6B,OAAO,CAAC,KAAK,KAAK;GACtD,GAAI,QAAQ,0BAA0B,QAAQ,YAAY,iBACtD,EACE,wBACE,KAAK,4BAA4B,OAAO,CAAC,KAAK,KAAK,EACtD,GACD,EAAE;GACN,MAAM,QAAQ;GACd,SAAS,QAAQ;GACjB,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,SAAO,MAAM,KAAK,cAAc,QAAQ,CAAC;;;AAK7C,SAAgB,mBACd,QACoB;AACpB,QAAO;EACL,GAAG;EACH,MAAM,aAAa;EACpB;;AAGH,SAAgB,0BACd,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAM,aAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAO,aAAa;KAEpB,QAAO,aAAa;AAIxB,QAAO,SAAS"}
package/dist/package.cjs CHANGED
@@ -5,7 +5,7 @@ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
5
5
  var require_package = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, module) => {
6
6
  module.exports = {
7
7
  "name": "@copilotkit/runtime",
8
- "version": "1.55.2-next.1",
8
+ "version": "1.55.3-canary.1776215089",
9
9
  "private": false,
10
10
  "keywords": [
11
11
  "ai",
package/dist/package.mjs CHANGED
@@ -5,7 +5,7 @@ import { __commonJSMin } from "./_virtual/_rolldown/runtime.mjs";
5
5
  var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6
6
  module.exports = {
7
7
  "name": "@copilotkit/runtime",
8
- "version": "1.55.2-next.1",
8
+ "version": "1.55.3-canary.1776215089",
9
9
  "private": false,
10
10
  "keywords": [
11
11
  "ai",
package/dist/v2/index.cjs CHANGED
@@ -50,5 +50,6 @@ Object.defineProperty(exports, 'finalizeRunEvents', {
50
50
  }
51
51
  });
52
52
  exports.isIntelligenceRuntime = require_runtime$1.isIntelligenceRuntime;
53
+ exports.resolveAgents = require_runtime$1.resolveAgents;
53
54
  exports.resolveModel = require_index.resolveModel;
54
55
  exports.toFetchCorsConfig = require_hono.toFetchCorsConfig;
@@ -2,7 +2,7 @@
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./runtime/transcription-service/transcription-service.cjs";
3
3
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest } from "./runtime/runner/agent-runner.cjs";
4
4
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.cjs";
5
- import { CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isIntelligenceRuntime } from "./runtime/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 "./runtime/core/runtime.cjs";
6
6
  import { CopilotCorsConfig } from "./runtime/core/fetch-cors.cjs";
7
7
  import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./runtime/core/hooks.cjs";
8
8
  import { CopilotEndpointCorsConfig, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./runtime/endpoints/hono.cjs";
@@ -16,5 +16,5 @@ import { CopilotRuntimeFetchHandler, CopilotRuntimeHandlerOptions, createCopilot
16
16
  import { CopilotKitRequestHandler } from "./runtime/index.cjs";
17
17
  import { convertAISDKStream } from "../agent/converters/aisdk.cjs";
18
18
  import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.cjs";
19
- import { AgentFactoryContext, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.cjs";
20
- export { AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeFetchHandler, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, ListThreadsResponse, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, McpAppsConfig, McpAppsServerConfig, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isIntelligenceRuntime, resolveModel, toFetchCorsConfig };
19
+ import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.cjs";
20
+ export { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeFetchHandler, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, ListThreadsResponse, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, McpAppsConfig, McpAppsServerConfig, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isIntelligenceRuntime, resolveAgents, resolveModel, toFetchCorsConfig };
@@ -2,7 +2,7 @@ import "reflect-metadata";
2
2
  import { TranscribeFileOptions, TranscriptionService } from "./runtime/transcription-service/transcription-service.mjs";
3
3
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest } from "./runtime/runner/agent-runner.mjs";
4
4
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./runtime/intelligence-platform/client.mjs";
5
- import { CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isIntelligenceRuntime } from "./runtime/core/runtime.mjs";
5
+ import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, OpenGenerativeUIConfig, OpenGenerativeUIOptions, VERSION, isIntelligenceRuntime, resolveAgents } from "./runtime/core/runtime.mjs";
6
6
  import { CopilotCorsConfig } from "./runtime/core/fetch-cors.mjs";
7
7
  import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./runtime/core/hooks.mjs";
8
8
  import { CopilotEndpointCorsConfig, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./runtime/endpoints/hono.mjs";
@@ -16,5 +16,5 @@ import { CopilotRuntimeFetchHandler, CopilotRuntimeHandlerOptions, createCopilot
16
16
  import { CopilotKitRequestHandler } from "./runtime/index.mjs";
17
17
  import { convertAISDKStream } from "../agent/converters/aisdk.mjs";
18
18
  import { TanStackChatMessage, TanStackInputResult, convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.mjs";
19
- import { AgentFactoryContext, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
20
- export { AgentFactoryContext, AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeFetchHandler, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, ListThreadsResponse, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, McpAppsConfig, McpAppsServerConfig, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isIntelligenceRuntime, resolveModel, toFetchCorsConfig };
19
+ import { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
20
+ export { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, AgentsConfig, AgentsFactory, BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentAISDKFactoryConfig, BuiltInAgentClassicConfig, BuiltInAgentConfiguration, BuiltInAgentCustomFactoryConfig, BuiltInAgentFactoryConfig, BuiltInAgentModel, BuiltInAgentTanStackFactoryConfig, CopilotCorsConfig, CopilotEndpointCorsConfig, CopilotExpressEndpointParams, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotKitIntelligence, CopilotKitIntelligenceConfig, CopilotKitRequestHandler, CopilotRuntime, CopilotRuntimeFetchHandler, CopilotRuntimeHandlerOptions, CopilotRuntimeHooks, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, CreateThreadRequest, ErrorHookContext, HandlerHookContext, HookContext, IdentifyUserCallback, InMemoryAgentRunner, IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, ListThreadsResponse, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, McpAppsConfig, McpAppsServerConfig, MessageConversionOptions, ModelSpecifier, OpenGenerativeUIConfig, OpenGenerativeUIOptions, OverridableProperty, ResponseHookContext, RouteInfo, SubscribeToThreadsRequest, SubscribeToThreadsResponse, TanStackChatMessage, TanStackInputResult, ThreadSummary, ToolDefinition, TranscribeFileOptions, TranscriptionService, UpdateThreadRequest, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isIntelligenceRuntime, resolveAgents, resolveModel, toFetchCorsConfig };
package/dist/v2/index.mjs CHANGED
@@ -2,7 +2,7 @@ import "reflect-metadata";
2
2
  import { AgentRunner } from "./runtime/runner/agent-runner.mjs";
3
3
  import { InMemoryAgentRunner } from "./runtime/runner/in-memory.mjs";
4
4
  import { IntelligenceAgentRunner } from "./runtime/runner/intelligence.mjs";
5
- import { CopilotIntelligenceRuntime, CopilotRuntime, CopilotSseRuntime, VERSION, isIntelligenceRuntime } from "./runtime/core/runtime.mjs";
5
+ import { CopilotIntelligenceRuntime, CopilotRuntime, CopilotSseRuntime, VERSION, isIntelligenceRuntime, resolveAgents } from "./runtime/core/runtime.mjs";
6
6
  import { CopilotKitIntelligence } from "./runtime/intelligence-platform/client.mjs";
7
7
  import { createCopilotRuntimeHandler } from "./runtime/core/fetch-handler.mjs";
8
8
  import { createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./runtime/endpoints/hono.mjs";
@@ -15,4 +15,4 @@ import { convertAISDKStream } from "../agent/converters/aisdk.mjs";
15
15
  import { convertInputToTanStackAI, convertTanStackStream } from "../agent/converters/tanstack.mjs";
16
16
  import { BasicAgent, BuiltInAgent, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel } from "../agent/index.mjs";
17
17
 
18
- export { AgentRunner, BasicAgent, BuiltInAgent, CopilotIntelligenceRuntime, CopilotKitIntelligence, CopilotRuntime, CopilotSseRuntime, InMemoryAgentRunner, IntelligenceAgentRunner, TranscriptionService, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isIntelligenceRuntime, resolveModel, toFetchCorsConfig };
18
+ export { AgentRunner, BasicAgent, BuiltInAgent, CopilotIntelligenceRuntime, CopilotKitIntelligence, CopilotRuntime, CopilotSseRuntime, InMemoryAgentRunner, IntelligenceAgentRunner, TranscriptionService, VERSION, convertAISDKStream, convertInputToTanStackAI, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertTanStackStream, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, createCopilotEndpoint, createCopilotExpressHandler as createCopilotEndpointExpress, createCopilotExpressHandler, createCopilotEndpointSingleRoute, createCopilotEndpointSingleRouteExpress, createCopilotHonoHandler, createCopilotRuntimeHandler, defineTool, finalizeRunEvents, isIntelligenceRuntime, resolveAgents, resolveModel, toFetchCorsConfig };
@@ -9,6 +9,7 @@ const require_handle_connect = require('../handlers/handle-connect.cjs');
9
9
  const require_handle_stop = require('../handlers/handle-stop.cjs');
10
10
  const require_get_runtime_info = require('../handlers/get-runtime-info.cjs');
11
11
  const require_handle_transcribe = require('../handlers/handle-transcribe.cjs');
12
+ const require_threads = require('../handlers/intelligence/threads.cjs');
12
13
  const require_single_route_helpers = require('../endpoints/single-route-helpers.cjs');
13
14
  let _copilotkit_shared = require("@copilotkit/shared");
14
15
 
@@ -160,6 +161,35 @@ function dispatchRoute(runtime, request, route) {
160
161
  runtime,
161
162
  request
162
163
  });
164
+ case "threads/list": return require_threads.handleListThreads({
165
+ runtime,
166
+ request
167
+ });
168
+ case "threads/subscribe": return require_threads.handleSubscribeToThreads({
169
+ runtime,
170
+ request
171
+ });
172
+ case "threads/update":
173
+ if (request.method.toUpperCase() === "DELETE") return require_threads.handleDeleteThread({
174
+ runtime,
175
+ request,
176
+ threadId: route.threadId
177
+ });
178
+ return require_threads.handleUpdateThread({
179
+ runtime,
180
+ request,
181
+ threadId: route.threadId
182
+ });
183
+ case "threads/archive": return require_threads.handleArchiveThread({
184
+ runtime,
185
+ request,
186
+ threadId: route.threadId
187
+ });
188
+ case "threads/messages": return require_threads.handleGetThreadMessages({
189
+ runtime,
190
+ request,
191
+ threadId: route.threadId
192
+ });
163
193
  }
164
194
  }
165
195
  async function resolveSingleRoute(request, basePath, pathname) {
@@ -204,9 +234,19 @@ async function resolveSingleRoute(request, basePath, pathname) {
204
234
  }
205
235
  function validateHttpMethod(httpMethod, route) {
206
236
  const method = httpMethod.toUpperCase();
207
- if (route.method === "info" && method === "GET") return null;
208
- if (route.method !== "info" && method === "POST") return null;
209
- return jsonResponse({ error: "Method not allowed" }, 405, { Allow: route.method === "info" ? "GET" : "POST" });
237
+ switch (route.method) {
238
+ case "info":
239
+ case "threads/list":
240
+ case "threads/messages":
241
+ if (method === "GET") return null;
242
+ return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "GET" });
243
+ case "threads/update":
244
+ if (method === "PATCH" || method === "DELETE") return null;
245
+ return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
246
+ default:
247
+ if (method === "POST") return null;
248
+ return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "POST" });
249
+ }
210
250
  }
211
251
  function resolveCorsConfig(cors) {
212
252
  if (!cors) return null;
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.cjs","names":["handleCors","runOnRequest","callBeforeRequestMiddleware","runOnBeforeHandler","createJsonRequest","matchRoute","runOnResponse","runOnError","handleRunAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe","parseMethodCall","expectString","addCorsHeaders"],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n */\n\nimport type { CopilotRuntimeLike } from \"./runtime\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n type MethodCall,\n} from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n}\n\nexport type CopilotRuntimeFetchHandler = (\n request: Request,\n) => Promise<Response>;\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n const corsConfig = resolveCorsConfig(cors);\n\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route);\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route);\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n): Promise<Response> {\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({ runtime, request });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n if (route.method === \"info\" && method === \"GET\") return null;\n if (route.method !== \"info\" && method === \"POST\") return null;\n const allowed = route.method === \"info\" ? \"GET\" : \"POST\";\n return jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: allowed });\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n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AE,OAD5C,MAAM,WAAW,SAAS,QAAQ,QAC0B,CAAC;;AAO/E,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAOC,kCAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
1
+ {"version":3,"file":"fetch-handler.cjs","names":["handleCors","runOnRequest","callBeforeRequestMiddleware","runOnBeforeHandler","createJsonRequest","matchRoute","runOnResponse","runOnError","handleRunAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe","handleListThreads","handleSubscribeToThreads","handleDeleteThread","handleUpdateThread","handleArchiveThread","handleGetThreadMessages","parseMethodCall","expectString","addCorsHeaders"],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n */\n\nimport type { CopilotRuntimeLike } from \"./runtime\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport {\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n} from \"../handlers/handle-threads\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n type MethodCall,\n} from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n}\n\nexport type CopilotRuntimeFetchHandler = (\n request: Request,\n) => Promise<Response>;\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n const corsConfig = resolveCorsConfig(cors);\n\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route);\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route);\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n): Promise<Response> {\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({ runtime, request });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8GA,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAAe,MAAM,UAAU;CAEjE,MAAM,aAAa,kBAAkB,KAAK;AAE1C,QAAO,OAAO,YAAwC;EAEpD,MAAM,OADM,IAAI,IAAI,QAAQ,KAAK,mBAAmB,CACnC;EACjB,MAAM,gBAAgB,QAAQ,QAAQ,IAAI,SAAS;EAGnD,MAAM,UAAuB;GAAE;GAAS;GAAM;GAAS;EAEvD,IAAI;AAEJ,MAAI;AAEF,OAAI,YAAY;IACd,MAAM,YAAYA,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O,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,OACR,CAAC;EAEJ,KAAK;AACH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ;AACE,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;;;AAQR,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAOC,kCAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;UA4DiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EAkCT;;;;;AAOF;;;;EA9BE,QAAA;EA+BA;;;;;EAxBA,IAAA;;;;;;EAOA,IAAA,aAAiB,iBAAA;;;;EAKjB,KAAA,GAAQ,mBAAA;AAAA;AAAA,KAGE,0BAAA,IACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;AAAA,iBAMG,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
1
+ {"version":3,"file":"fetch-handler.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;UAoEiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EAkCT;;;;;AAOF;;;;EA9BE,QAAA;EA+BA;;;;;EAxBA,IAAA;;;;;;EAOA,IAAA,aAAiB,iBAAA;;;;EAKjB,KAAA,GAAQ,mBAAA;AAAA;AAAA,KAGE,0BAAA,IACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;AAAA,iBAMG,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;UA4DiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EAkCT;;;;;AAOF;;;;EA9BE,QAAA;EA+BA;;;;;EAxBA,IAAA;;;;;;EAOA,IAAA,aAAiB,iBAAA;;;;EAKjB,KAAA,GAAQ,mBAAA;AAAA;AAAA,KAGE,0BAAA,IACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;AAAA,iBAMG,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
1
+ {"version":3,"file":"fetch-handler.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;UAoEiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EAkCT;;;;;AAOF;;;;EA9BE,QAAA;EA+BA;;;;;EAxBA,IAAA;;;;;;EAOA,IAAA,aAAiB,iBAAA;;;;EAKjB,KAAA,GAAQ,mBAAA;AAAA;AAAA,KAGE,0BAAA,IACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;AAAA,iBAMG,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
@@ -8,6 +8,7 @@ import { handleConnectAgent } from "../handlers/handle-connect.mjs";
8
8
  import { handleStopAgent } from "../handlers/handle-stop.mjs";
9
9
  import { handleGetRuntimeInfo } from "../handlers/get-runtime-info.mjs";
10
10
  import { handleTranscribe } from "../handlers/handle-transcribe.mjs";
11
+ import { handleArchiveThread, handleDeleteThread, handleGetThreadMessages, handleListThreads, handleSubscribeToThreads, handleUpdateThread } from "../handlers/intelligence/threads.mjs";
11
12
  import { createJsonRequest, expectString, parseMethodCall } from "../endpoints/single-route-helpers.mjs";
12
13
  import { logger } from "@copilotkit/shared";
13
14
 
@@ -159,6 +160,35 @@ function dispatchRoute(runtime, request, route) {
159
160
  runtime,
160
161
  request
161
162
  });
163
+ case "threads/list": return handleListThreads({
164
+ runtime,
165
+ request
166
+ });
167
+ case "threads/subscribe": return handleSubscribeToThreads({
168
+ runtime,
169
+ request
170
+ });
171
+ case "threads/update":
172
+ if (request.method.toUpperCase() === "DELETE") return handleDeleteThread({
173
+ runtime,
174
+ request,
175
+ threadId: route.threadId
176
+ });
177
+ return handleUpdateThread({
178
+ runtime,
179
+ request,
180
+ threadId: route.threadId
181
+ });
182
+ case "threads/archive": return handleArchiveThread({
183
+ runtime,
184
+ request,
185
+ threadId: route.threadId
186
+ });
187
+ case "threads/messages": return handleGetThreadMessages({
188
+ runtime,
189
+ request,
190
+ threadId: route.threadId
191
+ });
162
192
  }
163
193
  }
164
194
  async function resolveSingleRoute(request, basePath, pathname) {
@@ -203,9 +233,19 @@ async function resolveSingleRoute(request, basePath, pathname) {
203
233
  }
204
234
  function validateHttpMethod(httpMethod, route) {
205
235
  const method = httpMethod.toUpperCase();
206
- if (route.method === "info" && method === "GET") return null;
207
- if (route.method !== "info" && method === "POST") return null;
208
- return jsonResponse({ error: "Method not allowed" }, 405, { Allow: route.method === "info" ? "GET" : "POST" });
236
+ switch (route.method) {
237
+ case "info":
238
+ case "threads/list":
239
+ case "threads/messages":
240
+ if (method === "GET") return null;
241
+ return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "GET" });
242
+ case "threads/update":
243
+ if (method === "PATCH" || method === "DELETE") return null;
244
+ return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
245
+ default:
246
+ if (method === "POST") return null;
247
+ return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "POST" });
248
+ }
209
249
  }
210
250
  function resolveCorsConfig(cors) {
211
251
  if (!cors) return null;