@copilotkit/runtime 1.50.0-beta.9 → 1.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +157 -0
- package/dist/chunk-27JKTS6P.mjs +1704 -0
- package/dist/chunk-27JKTS6P.mjs.map +1 -0
- package/dist/{chunk-FMU55SEU.mjs → chunk-2GPTVDTO.mjs} +2 -2
- package/dist/chunk-3AJVKDZX.mjs +3097 -0
- package/dist/chunk-3AJVKDZX.mjs.map +1 -0
- package/dist/{chunk-BJEYMRDD.mjs → chunk-45RCC3ZS.mjs} +2 -2
- package/dist/chunk-4EHJ4XFJ.mjs +25 -0
- package/dist/chunk-4EHJ4XFJ.mjs.map +1 -0
- package/dist/chunk-4IANB4TC.mjs +25 -0
- package/dist/chunk-4IANB4TC.mjs.map +1 -0
- package/dist/{chunk-Z752VE75.mjs → chunk-4KES76K3.mjs} +2 -2
- package/dist/chunk-4OGE3SLW.mjs +3100 -0
- package/dist/chunk-4OGE3SLW.mjs.map +1 -0
- package/dist/chunk-54YJBMCP.mjs +3097 -0
- package/dist/chunk-54YJBMCP.mjs.map +1 -0
- package/dist/chunk-6ER4SZYH.mjs +74 -0
- package/dist/chunk-6ER4SZYH.mjs.map +1 -0
- package/dist/chunk-6TNSLHVR.mjs +74 -0
- package/dist/chunk-6TNSLHVR.mjs.map +1 -0
- package/dist/chunk-7V4BK7TZ.mjs +25 -0
- package/dist/chunk-7V4BK7TZ.mjs.map +1 -0
- package/dist/chunk-7YZIEXD2.mjs +74 -0
- package/dist/chunk-7YZIEXD2.mjs.map +1 -0
- package/dist/chunk-A4XHOAFU.mjs +25 -0
- package/dist/chunk-A4XHOAFU.mjs.map +1 -0
- package/dist/chunk-A555KEAD.mjs +6020 -0
- package/dist/chunk-A555KEAD.mjs.map +1 -0
- package/dist/chunk-AF73TFTX.mjs +74 -0
- package/dist/chunk-AF73TFTX.mjs.map +1 -0
- package/dist/chunk-AQG2SVCA.mjs +25 -0
- package/dist/chunk-AQG2SVCA.mjs.map +1 -0
- package/dist/chunk-BJZHMXND.mjs +74 -0
- package/dist/chunk-BJZHMXND.mjs.map +1 -0
- package/dist/chunk-CB2OJXF6.mjs +25 -0
- package/dist/chunk-CB2OJXF6.mjs.map +1 -0
- package/dist/chunk-CEOMFPJU.mjs +6020 -0
- package/dist/chunk-CEOMFPJU.mjs.map +1 -0
- package/dist/chunk-CZVLR7CC.mjs +175 -0
- package/dist/chunk-CZVLR7CC.mjs.map +1 -0
- package/dist/{chunk-SBCOROE4.mjs → chunk-DCEEHMLJ.mjs} +16 -1
- package/dist/chunk-DCEEHMLJ.mjs.map +1 -0
- package/dist/chunk-DE3CLKUG.mjs +25 -0
- package/dist/chunk-DE3CLKUG.mjs.map +1 -0
- package/dist/chunk-DTPRUTNV.mjs +25 -0
- package/dist/chunk-DTPRUTNV.mjs.map +1 -0
- package/dist/{chunk-TTUAEJLD.mjs → chunk-ERUOA47O.mjs} +11 -2
- package/dist/chunk-ERUOA47O.mjs.map +1 -0
- package/dist/chunk-ESSRC64W.mjs +74 -0
- package/dist/chunk-ESSRC64W.mjs.map +1 -0
- package/dist/chunk-GRAN6K6N.mjs +25 -0
- package/dist/chunk-GRAN6K6N.mjs.map +1 -0
- package/dist/chunk-I27F2UPA.mjs +175 -0
- package/dist/chunk-I27F2UPA.mjs.map +1 -0
- package/dist/chunk-IAZKTOQW.mjs +25 -0
- package/dist/chunk-IAZKTOQW.mjs.map +1 -0
- package/dist/chunk-J6XZ5MFB.mjs +25 -0
- package/dist/chunk-J6XZ5MFB.mjs.map +1 -0
- package/dist/chunk-JJ32MA4C.mjs +73 -0
- package/dist/chunk-JJ32MA4C.mjs.map +1 -0
- package/dist/chunk-JJY4ZTHQ.mjs +25 -0
- package/dist/chunk-JJY4ZTHQ.mjs.map +1 -0
- package/dist/chunk-KEYLBFU2.mjs +3117 -0
- package/dist/chunk-KEYLBFU2.mjs.map +1 -0
- package/dist/chunk-KQ53L4WZ.mjs +3094 -0
- package/dist/chunk-KQ53L4WZ.mjs.map +1 -0
- package/dist/chunk-KTELVQ67.mjs +3098 -0
- package/dist/chunk-KTELVQ67.mjs.map +1 -0
- package/dist/chunk-LPEPX6NH.mjs +25 -0
- package/dist/chunk-LPEPX6NH.mjs.map +1 -0
- package/dist/chunk-MDXE55DK.mjs +3117 -0
- package/dist/chunk-MDXE55DK.mjs.map +1 -0
- package/dist/chunk-MMFUVOXH.mjs +73 -0
- package/dist/chunk-MMFUVOXH.mjs.map +1 -0
- package/dist/chunk-N3Y4U66N.mjs +253 -0
- package/dist/chunk-N3Y4U66N.mjs.map +1 -0
- package/dist/chunk-O7UYB4MH.mjs +25 -0
- package/dist/chunk-O7UYB4MH.mjs.map +1 -0
- package/dist/chunk-OFNVQHNM.mjs +3089 -0
- package/dist/chunk-OFNVQHNM.mjs.map +1 -0
- package/dist/{chunk-DZV4ZIAR.mjs → chunk-OFSV5GET.mjs} +17 -6
- package/dist/chunk-OFSV5GET.mjs.map +1 -0
- package/dist/chunk-OMRST67R.mjs +25 -0
- package/dist/chunk-OMRST67R.mjs.map +1 -0
- package/dist/chunk-PRZHE74A.mjs +25 -0
- package/dist/chunk-PRZHE74A.mjs.map +1 -0
- package/dist/chunk-PTYRVXXP.mjs +80 -0
- package/dist/chunk-PTYRVXXP.mjs.map +1 -0
- package/dist/chunk-R22B5CCO.mjs +25 -0
- package/dist/chunk-R22B5CCO.mjs.map +1 -0
- package/dist/chunk-SHBDMA63.mjs +141 -0
- package/dist/chunk-SHBDMA63.mjs.map +1 -0
- package/dist/chunk-SPVXBPRA.mjs +74 -0
- package/dist/chunk-SPVXBPRA.mjs.map +1 -0
- package/dist/chunk-T72G46ME.mjs +25 -0
- package/dist/chunk-T72G46ME.mjs.map +1 -0
- package/dist/chunk-TGELROPU.mjs +25 -0
- package/dist/chunk-TGELROPU.mjs.map +1 -0
- package/dist/chunk-UNX4IAAD.mjs +25 -0
- package/dist/chunk-UNX4IAAD.mjs.map +1 -0
- package/dist/chunk-V4DHVC7M.mjs +3085 -0
- package/dist/chunk-V4DHVC7M.mjs.map +1 -0
- package/dist/chunk-VVRFOB66.mjs +25 -0
- package/dist/chunk-VVRFOB66.mjs.map +1 -0
- package/dist/chunk-W6NVBYM6.mjs +80 -0
- package/dist/chunk-W6NVBYM6.mjs.map +1 -0
- package/dist/chunk-W7MBACGC.mjs +74 -0
- package/dist/chunk-W7MBACGC.mjs.map +1 -0
- package/dist/chunk-WMD4XZZS.mjs +25 -0
- package/dist/chunk-WMD4XZZS.mjs.map +1 -0
- package/dist/chunk-WX2ZNCRT.mjs +74 -0
- package/dist/chunk-WX2ZNCRT.mjs.map +1 -0
- package/dist/chunk-Y2Z62E2T.mjs +74 -0
- package/dist/chunk-Y2Z62E2T.mjs.map +1 -0
- package/dist/chunk-YO4I6RVI.mjs +25 -0
- package/dist/chunk-YO4I6RVI.mjs.map +1 -0
- package/dist/chunk-Z6Q5IW6I.mjs +3098 -0
- package/dist/chunk-Z6Q5IW6I.mjs.map +1 -0
- package/dist/chunk-Z726O3G2.mjs +25 -0
- package/dist/chunk-Z726O3G2.mjs.map +1 -0
- package/dist/chunk-ZE4SMZZR.mjs +3097 -0
- package/dist/chunk-ZE4SMZZR.mjs.map +1 -0
- package/dist/chunk-ZULZB33C.mjs +73 -0
- package/dist/chunk-ZULZB33C.mjs.map +1 -0
- package/dist/chunk-ZVRGXMY7.mjs +25 -0
- package/dist/chunk-ZVRGXMY7.mjs.map +1 -0
- package/dist/chunk-ZZ35WBYQ.mjs +25 -0
- package/dist/chunk-ZZ35WBYQ.mjs.map +1 -0
- package/dist/graphql/types/converted/index.d.ts +1 -1
- package/dist/graphql/types/converted/index.js +16 -110
- package/dist/graphql/types/converted/index.js.map +1 -1
- package/dist/graphql/types/converted/index.mjs +2 -3
- package/dist/{groq-adapter-50bc6e4a.d.ts → groq-adapter-540da9c3.d.ts} +6 -1
- package/dist/groq-adapter-a6f5e9d2.d.ts +331 -0
- package/dist/groq-adapter-c8aec5c5.d.ts +321 -0
- package/dist/index-96b330da.d.ts +119 -0
- package/dist/index.d.ts +67 -8
- package/dist/index.js +118 -28
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +120 -31
- package/dist/index.mjs.map +1 -1
- package/dist/langserve-0c6100e3.d.ts +257 -0
- package/dist/langserve-978d5790.d.ts +243 -0
- package/dist/{langserve-74a52292.d.ts → langserve-9fc76ce5.d.ts} +1 -0
- package/dist/lib/index.d.ts +5 -59
- package/dist/lib/index.js +3702 -803
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +20 -18
- package/dist/lib/integrations/index.d.ts +15 -9
- package/dist/lib/integrations/index.js +215 -187
- package/dist/lib/integrations/index.js.map +1 -1
- package/dist/lib/integrations/index.mjs +8 -7
- package/dist/lib/integrations/nest/index.d.ts +5 -6
- package/dist/lib/integrations/nest/index.js +197 -175
- package/dist/lib/integrations/nest/index.js.map +1 -1
- package/dist/lib/integrations/nest/index.mjs +6 -5
- package/dist/lib/integrations/node-express/index.d.ts +5 -6
- package/dist/lib/integrations/node-express/index.js +197 -175
- package/dist/lib/integrations/node-express/index.js.map +1 -1
- package/dist/lib/integrations/node-express/index.mjs +6 -5
- package/dist/lib/integrations/node-http/index.d.ts +5 -6
- package/dist/lib/integrations/node-http/index.js +197 -175
- package/dist/lib/integrations/node-http/index.js.map +1 -1
- package/dist/lib/integrations/node-http/index.mjs +5 -4
- package/dist/service-adapters/index.d.ts +7 -11
- package/dist/service-adapters/index.js +8 -21
- package/dist/service-adapters/index.js.map +1 -1
- package/dist/service-adapters/index.mjs +2 -4
- package/dist/shared-0a7346ce.d.ts +466 -0
- package/dist/{shared-f6d43ef8.d.ts → shared-35c6eb04.d.ts} +3 -1
- package/dist/shared-9ed1dc31.d.ts +414 -0
- package/dist/shared-da5708fe.d.ts +449 -0
- package/package.json +14 -20
- package/src/lib/index.ts +7 -6
- package/src/lib/runtime/copilot-runtime.ts +62 -26
- package/src/lib/runtime/telemetry-agent-runner.ts +139 -0
- package/dist/chunk-DZV4ZIAR.mjs.map +0 -1
- package/dist/chunk-SBCOROE4.mjs.map +0 -1
- package/dist/chunk-TTUAEJLD.mjs.map +0 -1
- /package/dist/{chunk-FMU55SEU.mjs.map → chunk-2GPTVDTO.mjs.map} +0 -0
- /package/dist/{chunk-BJEYMRDD.mjs.map → chunk-45RCC3ZS.mjs.map} +0 -0
- /package/dist/{chunk-Z752VE75.mjs.map → chunk-4KES76K3.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json","../src/lib/integrations/node-http/index.ts","../src/lib/integrations/shared.ts","../src/graphql/resolvers/copilot.resolver.ts","../src/graphql/inputs/generate-copilot-response.input.ts","../src/graphql/inputs/message.input.ts","../src/graphql/inputs/frontend.input.ts","../src/graphql/inputs/action.input.ts","../src/graphql/inputs/cloud.input.ts","../src/graphql/inputs/cloud-guardrails.input.ts","../src/graphql/inputs/forwarded-parameters.input.ts","../src/graphql/inputs/agent-session.input.ts","../src/graphql/inputs/agent-state.input.ts","../src/graphql/inputs/extensions.input.ts","../src/graphql/inputs/meta-event.input.ts","../src/graphql/types/meta-events.type.ts","../src/graphql/types/copilot-response.type.ts","../src/graphql/types/extensions-response.type.ts","../src/graphql/inputs/copilot-context.input.ts","../src/service-adapters/events.ts","../src/lib/telemetry-client.ts","../src/lib/runtime/copilot-runtime.ts","../src/lib/runtime/types.ts","../src/lib/runtime/mcp-tools-utils.ts","../src/lib/runtime/agent-integrations/langgraph.agent.ts","../src/agents/langgraph/events.ts","../src/graphql/types/agents-response.type.ts","../src/lib/logger.ts","../src/graphql/resolvers/state.resolver.ts","../src/graphql/types/load-agent-state-response.type.ts","../src/graphql/inputs/load-agent-state.input.ts"],"sourcesContent":["{\n \"name\": \"@copilotkit/runtime\",\n \"private\": false,\n \"homepage\": \"https://github.com/CopilotKit/CopilotKit\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/CopilotKit/CopilotKit.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"version\": \"1.10.6\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"exports\": {\n \".\": \"./dist/index.js\"\n },\n \"types\": \"./dist/index.d.ts\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"tsup --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"dev\": \"tsup --watch --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"test\": \"jest --passWithNoTests\",\n \"check-types\": \"tsc --noEmit\",\n \"clean\": \"rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next && rm -rf __snapshots__\",\n \"generate-graphql-schema\": \"rm -rf __snapshots__ && ts-node ./scripts/generate-gql-schema.ts\",\n \"link:global\": \"pnpm link --global\",\n \"unlink:global\": \"pnpm unlink --global\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^29.7.0\",\n \"@swc/core\": \"1.5.28\",\n \"@types/express\": \"^4.17.21\",\n \"@types/jest\": \"^29.5.12\",\n \"@types/node\": \"^18.11.17\",\n \"@whatwg-node/server\": \"^0.9.34\",\n \"eslint\": \"^8.56.0\",\n \"eslint-config-custom\": \"workspace:*\",\n \"jest\": \"^29.6.4\",\n \"nodemon\": \"^3.1.3\",\n \"ts-jest\": \"^29.1.1\",\n \"ts-node\": \"^10.9.2\",\n \"tsconfig\": \"workspace:*\",\n \"tsup\": \"^6.7.0\",\n \"typescript\": \"^5.2.3\",\n \"vitest\": \"^3.2.4\",\n \"zod-to-json-schema\": \"^3.23.5\"\n },\n \"dependencies\": {\n \"@anthropic-ai/sdk\": \"^0.57.0\",\n \"@copilotkit/shared\": \"workspace:*\",\n \"@copilotkitnext/agent\": \"^0.0.17\",\n \"@copilotkitnext/runtime\": \"^0.0.17\",\n \"@graphql-yoga/plugin-defer-stream\": \"^3.3.1\",\n \"@langchain/aws\": \"^0.1.9\",\n \"@langchain/community\": \"^0.3.29\",\n \"@langchain/core\": \"^0.3.38\",\n \"@langchain/google-gauth\": \"^0.1.0\",\n \"@langchain/langgraph-sdk\": \"^0.0.70\",\n \"@langchain/openai\": \"^0.4.2\",\n \"@scarf/scarf\": \"^1.3.0\",\n \"class-transformer\": \"^0.5.1\",\n \"class-validator\": \"^0.14.1\",\n \"express\": \"^4.19.2\",\n \"graphql\": \"^16.8.1\",\n \"graphql-scalars\": \"^1.23.0\",\n \"graphql-yoga\": \"^5.3.1\",\n \"groq-sdk\": \"^0.5.0\",\n \"langchain\": \"^0.3.3\",\n \"openai\": \"^4.85.1\",\n \"partial-json\": \"^0.1.7\",\n \"pino\": \"^9.2.0\",\n \"pino-pretty\": \"^11.2.1\",\n \"reflect-metadata\": \"^0.2.2\",\n \"rxjs\": \"7.8.1\",\n \"type-graphql\": \"2.0.0-rc.1\",\n \"zod\": \"^3.23.3\"\n },\n \"peerDependencies\": {\n \"@ag-ui/client\": \">=0.0.39\",\n \"@ag-ui/core\": \">=0.0.39\",\n \"@ag-ui/encoder\": \">=0.0.39\",\n \"@ag-ui/langgraph\": \">=0.0.18\",\n \"@ag-ui/proto\": \">=0.0.39\"\n },\n \"keywords\": [\n \"copilotkit\",\n \"copilot\",\n \"react\",\n \"nextjs\",\n \"nodejs\",\n \"ai\",\n \"assistant\",\n \"javascript\",\n \"automation\",\n \"textarea\"\n ]\n}\n","import { createCopilotEndpoint } from \"@copilotkitnext/runtime\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, { getRuntimeInstanceTelemetryInfo } from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n): ReturnType<typeof createCopilotEndpoint> {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\"oss.runtime.instance_created\", getRuntimeInstanceTelemetryInfo(options));\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n options.runtime.handleServiceAdapter(serviceAdapter);\n\n return createCopilotEndpoint({\n runtime: options.runtime.instance,\n basePath: options.baseUrl,\n });\n}\n","import { YogaInitialContext } from \"graphql-yoga\";\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport { useDeferStream } from \"@graphql-yoga/plugin-defer-stream\";\nimport { CopilotRuntime } from \"../runtime/copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../service-adapters\";\nimport { CopilotCloudOptions } from \"../cloud\";\nimport { LogLevel, createLogger } from \"../../lib/logger\";\nimport { createYoga } from \"graphql-yoga\";\nimport telemetry from \"../telemetry-client\";\nimport { StateResolver } from \"../../graphql/resolvers/state.resolver\";\nimport * as packageJson from \"../../../package.json\";\nimport { CopilotKitError, CopilotKitErrorCode } from \"@copilotkit/shared\";\n\nconst logger = createLogger();\n\nexport const addCustomHeaderPlugin = {\n onResponse({ response }) {\n // Set your custom header; adjust the header name and value as needed\n response.headers.set(\"X-CopilotKit-Runtime-Version\", packageJson.version);\n },\n};\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\nexport type GraphQLContext = YogaInitialContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime;\n serviceAdapter: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n}\n\nexport async function createContext(\n initialContext: YogaInitialContext,\n copilotKitContext: CreateCopilotRuntimeServerOptions,\n contextLogger: typeof logger,\n properties: CopilotRequestContextProperties = {},\n): Promise<Partial<GraphQLContext>> {\n logger.debug({ copilotKitContext }, \"Creating GraphQL context\");\n const ctx: GraphQLContext = {\n ...initialContext,\n _copilotkit: {\n ...copilotKitContext,\n },\n properties: { ...properties },\n logger: contextLogger,\n };\n return ctx;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver, StateResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n schema: ReturnType<typeof buildSchema>;\n plugins: Parameters<typeof createYoga>[0][\"plugins\"];\n context: (ctx: YogaInitialContext) => Promise<Partial<GraphQLContext>>;\n maskedErrors: {\n maskError: (error: any, message: string, isDev?: boolean) => any;\n };\n};\n\nexport function getCommonConfig(options: CreateCopilotRuntimeServerOptions): CommonConfig {\n const logLevel = (process.env.LOG_LEVEL as LogLevel) || (options.logLevel as LogLevel) || \"error\";\n const logger = createLogger({ level: logLevel, component: \"getCommonConfig\" });\n\n const contextLogger = createLogger({ level: logLevel });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter.constructor.name,\n },\n });\n\n // User error codes that should not be logged as server errors\n const userErrorCodes = [\n CopilotKitErrorCode.AGENT_NOT_FOUND,\n CopilotKitErrorCode.API_NOT_FOUND,\n CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND,\n CopilotKitErrorCode.CONFIGURATION_ERROR,\n CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,\n ];\n\n return {\n logging: createLogger({ component: \"Yoga GraphQL\", level: logLevel }),\n schema: buildSchema(),\n plugins: [useDeferStream(), addCustomHeaderPlugin],\n context: (ctx: YogaInitialContext): Promise<Partial<GraphQLContext>> =>\n createContext(ctx, options, contextLogger, options.properties),\n // Suppress logging for user configuration errors\n maskedErrors: {\n maskError: (error: any, message: string, isDev?: boolean) => {\n // Check if this is a user configuration error (could be wrapped in GraphQLError)\n const originalError = error.originalError || error;\n const extensions = error.extensions;\n const errorCode = extensions?.code;\n\n // Suppress logging for user errors based on error code\n if (errorCode && userErrorCodes.includes(errorCode)) {\n // Log user configuration errors at debug level instead\n console.debug(\"User configuration error:\", error.message);\n return error;\n }\n\n // Check if the original error is a user error\n if (\n originalError instanceof CopilotKitError &&\n userErrorCodes.includes(originalError.code)\n ) {\n // Log user configuration errors at debug level instead\n console.debug(\"User configuration error:\", error.message);\n return error;\n }\n\n // For application errors, log normally and mask if needed\n console.error(\"Application error:\", error);\n return error;\n },\n },\n };\n}\n","import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport {\n ReplaySubject,\n Subject,\n Subscription,\n filter,\n finalize,\n firstValueFrom,\n shareReplay,\n skipWhile,\n take,\n takeWhile,\n tap,\n} from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport {\n CopilotKitLangGraphInterruptEvent,\n LangGraphInterruptEvent,\n} from \"../types/meta-events.type\";\nimport { ActionInputAvailability, MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type { CopilotRequestContextProperties, GraphQLContext } from \"../../lib/integrations\";\nimport {\n RuntimeEvent,\n RuntimeEventTypes,\n RuntimeMetaEventName,\n} from \"../../service-adapters/events\";\nimport {\n FailedMessageStatus,\n MessageStatusCode,\n MessageStatusUnion,\n SuccessMessageStatus,\n} from \"../types/message-status.type\";\nimport { ResponseStatusUnion, SuccessResponseStatus } from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\nimport { plainToInstance } from \"class-transformer\";\nimport { GuardrailsResult } from \"../types/guardrails-result.type\";\nimport { GraphQLError } from \"graphql\";\nimport {\n GuardrailsValidationFailureResponse,\n MessageStreamInterruptedResponse,\n UnknownErrorResponse,\n} from \"../../utils\";\nimport {\n ActionExecutionMessage,\n AgentStateMessage,\n Message,\n MessageType,\n ResultMessage,\n TextMessage,\n} from \"../types/converted\";\nimport telemetry from \"../../lib/telemetry-client\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { AgentsResponse } from \"../types/agents-response.type\";\nimport { LangGraphEventTypes } from \"../../agents/langgraph/events\";\nimport {\n CopilotKitError,\n CopilotKitLowLevelError,\n isStructuredCopilotKitError,\n} from \"@copilotkit/shared\";\nimport { CopilotRuntime } from \"../../lib\";\n\nconst invokeGuardrails = async ({\n baseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult,\n onError,\n}: {\n baseUrl: string;\n copilotCloudPublicApiKey: string;\n data: GenerateCopilotResponseInput;\n onResult: (result: GuardrailsResult) => void;\n onError: (err: Error) => void;\n}) => {\n if (\n data.messages.length &&\n data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant),\n )\n .map((m) => ({\n role: m.textMessage!.role,\n content: m.textMessage.content,\n }));\n\n const lastMessage = messages[messages.length - 1];\n const restOfMessages = messages.slice(0, -1);\n\n const body = {\n input: lastMessage.content,\n validTopics: data.cloud.guardrails.inputValidationRules.allowList,\n invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,\n messages: restOfMessages,\n };\n\n const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CopilotCloud-Public-API-Key\": copilotCloudPublicApiKey,\n },\n body: JSON.stringify(body),\n });\n\n if (guardrailsResult.ok) {\n const resultJson: GuardrailsResult = await guardrailsResult.json();\n onResult(resultJson);\n } else {\n onError(await guardrailsResult.json());\n }\n }\n};\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n @Query(() => String)\n async hello() {\n return \"Hello World\";\n }\n\n @Query(() => AgentsResponse)\n async availableAgents(@Ctx() ctx: GraphQLContext) {\n let logger = ctx.logger.child({ component: \"CopilotResolver.availableAgents\" });\n\n logger.debug(\"Processing\");\n const agentsWithEndpoints = [];\n\n logger.debug(\"Event source created, creating response\");\n\n return {\n agents: agentsWithEndpoints.map(\n ({ endpoint, ...agentWithoutEndpoint }) => agentWithoutEndpoint,\n ),\n };\n }\n\n @Mutation(() => CopilotResponse)\n async generateCopilotResponse(\n @Ctx() ctx: GraphQLContext,\n @Arg(\"data\") data: GenerateCopilotResponseInput,\n @Arg(\"properties\", () => GraphQLJSONObject, { nullable: true })\n properties?: CopilotRequestContextProperties,\n ) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": data.cloud?.guardrails !== undefined,\n requestType: data.metadata.requestType,\n \"cloud.api_key_provided\": !!ctx.request.headers.get(\"x-copilotcloud-public-api-key\"),\n ...(ctx.request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": ctx.request.headers.get(\"x-copilotcloud-public-api-key\"),\n }\n : {}),\n ...(ctx._copilotkit.baseUrl\n ? {\n \"cloud.base_url\": ctx._copilotkit.baseUrl,\n }\n : {\n \"cloud.base_url\": \"https://api.cloud.copilotkit.ai\",\n }),\n });\n\n let logger = ctx.logger.child({ component: \"CopilotResolver.generateCopilotResponse\" });\n logger.debug({ data }, \"Generating Copilot response\");\n\n if (properties) {\n logger.debug(\"Properties provided, merging with context properties\");\n ctx.properties = { ...ctx.properties, ...properties };\n }\n\n const copilotRuntime = ctx._copilotkit.runtime as unknown as CopilotRuntime;\n const serviceAdapter = ctx._copilotkit.serviceAdapter;\n\n let copilotCloudPublicApiKey: string | null = null;\n let copilotCloudBaseUrl: string;\n\n // Extract publicApiKey from headers for both cloud and non-cloud requests\n // This enables onTrace functionality regardless of cloud configuration\n const publicApiKeyFromHeaders = ctx.request.headers.get(\"x-copilotcloud-public-api-key\");\n if (publicApiKeyFromHeaders) {\n copilotCloudPublicApiKey = publicApiKeyFromHeaders;\n }\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\"Cloud configuration provided, checking for public API key in headers\");\n\n if (!copilotCloudPublicApiKey) {\n logger.error(\"Public API key not found in headers\");\n\n throw new GraphQLError(\"X-CopilotCloud-Public-API-Key header is required\");\n }\n\n if (process.env.COPILOT_CLOUD_BASE_URL) {\n copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;\n } else if (ctx._copilotkit.cloud?.baseUrl) {\n copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;\n } else {\n copilotCloudBaseUrl = \"https://api.cloud.copilotkit.ai\";\n }\n\n logger = logger.child({ copilotCloudBaseUrl });\n }\n\n logger.debug(\"Setting up subjects\");\n const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();\n const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();\n const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();\n\n let outputMessages: Message[] = [];\n let resolveOutputMessagesPromise: (messages: Message[]) => void;\n let rejectOutputMessagesPromise: (err: Error) => void;\n\n const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {\n resolveOutputMessagesPromise = resolve;\n rejectOutputMessagesPromise = reject;\n });\n\n if (copilotCloudPublicApiKey) {\n ctx.properties[\"copilotCloudPublicApiKey\"] = copilotCloudPublicApiKey;\n }\n\n logger.debug(\"Processing\");\n let runtimeResponse;\n\n const {\n eventSource,\n threadId = randomId(),\n runId,\n serverSideActions,\n actionInputsWithoutAgents,\n extensions,\n } = runtimeResponse;\n\n logger.debug(\"Event source created, creating response\");\n // run and process the event stream\n const eventStream = eventSource\n .processRuntimeEvents({\n serverSideActions,\n guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,\n actionInputsWithoutAgents: actionInputsWithoutAgents.filter(\n // TODO-AGENTS: do not exclude ALL server side actions\n (action) =>\n !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n ),\n threadId,\n })\n .pipe(\n // shareReplay() ensures that later subscribers will see the whole stream instead of\n // just the events that were emitted after the subscriber was added.\n shareReplay(),\n finalize(() => {\n logger.debug(\"Event stream finalized\");\n }),\n );\n\n const response = {\n threadId,\n runId,\n status: firstValueFrom(responseStatus$),\n extensions,\n metaEvents: new Repeater(async (push, stop) => {\n let eventStreamSubscription: Subscription;\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n if (event.type != RuntimeEventTypes.MetaEvent) {\n return;\n }\n switch (event.name) {\n // @ts-ignore\n case LangGraphEventTypes.OnInterrupt:\n push(\n plainToInstance(LangGraphInterruptEvent, {\n // @ts-ignore\n type: event.type,\n // @ts-ignore\n name: RuntimeMetaEventName.LangGraphInterruptEvent,\n // @ts-ignore\n value: event.value,\n }),\n );\n break;\n case RuntimeMetaEventName.LangGraphInterruptEvent:\n push(\n plainToInstance(LangGraphInterruptEvent, {\n type: event.type,\n name: event.name,\n value: event.value,\n }),\n );\n break;\n case RuntimeMetaEventName.CopilotKitLangGraphInterruptEvent:\n push(\n plainToInstance(CopilotKitLangGraphInterruptEvent, {\n type: event.type,\n name: event.name,\n data: {\n value: event.data.value,\n messages: event.data.messages.map((message) => {\n if (\n message.type === \"TextMessage\" ||\n (\"content\" in message && \"role\" in message)\n ) {\n return plainToInstance(TextMessage, {\n id: message.id,\n createdAt: new Date(),\n content: [(message as TextMessage).content],\n role: (message as TextMessage).role,\n status: new SuccessMessageStatus(),\n });\n }\n if (\"arguments\" in message) {\n return plainToInstance(ActionExecutionMessage, {\n name: message.name,\n id: message.id,\n arguments: [JSON.stringify(message.arguments)],\n createdAt: new Date(),\n status: new SuccessMessageStatus(),\n });\n }\n throw new Error(\"Unknown message in metaEvents copilot resolver\");\n }),\n },\n }),\n );\n break;\n }\n },\n error: (err) => {\n // For structured CopilotKit errors, set proper error response status\n if (err?.name?.includes(\"CopilotKit\") || err?.extensions?.visibility) {\n responseStatus$.next(\n new UnknownErrorResponse({\n description: err.message || \"Agent error occurred\",\n }),\n );\n } else {\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n }\n\n eventStreamSubscription?.unsubscribe();\n stop();\n },\n complete: async () => {\n logger.debug(\"Meta events stream completed\");\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stop();\n },\n });\n }),\n messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n logger.debug(\"Messages repeater created\");\n\n if (data.cloud?.guardrails) {\n logger = logger.child({ guardrails: true });\n logger.debug(\"Guardrails is enabled, validating input\");\n\n invokeGuardrails({\n baseUrl: copilotCloudBaseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult: (result) => {\n logger.debug({ status: result.status }, \"Guardrails validation done\");\n guardrailsResult$.next(result);\n\n // Guardrails validation failed\n if (result.status === \"denied\") {\n // send the reason to the client and interrupt streaming\n responseStatus$.next(\n new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,\n });\n\n // resolve messages promise to the middleware\n outputMessages = [\n plainToInstance(TextMessage, {\n id: randomId(),\n createdAt: new Date(),\n content: result.reason,\n role: MessageRole.assistant,\n }),\n ];\n resolveOutputMessagesPromise(outputMessages);\n }\n },\n onError: (err) => {\n logger.error({ err }, \"Error in guardrails validation\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the guardrails validation`,\n }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to unknown error in guardrails validation`,\n });\n\n // reject the middleware promise\n rejectOutputMessagesPromise(err);\n },\n });\n }\n\n let eventStreamSubscription: Subscription;\n\n logger.debug(\"Event stream created, subscribing to event stream\");\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n switch (event.type) {\n case RuntimeEventTypes.MetaEvent:\n break;\n ////////////////////////////////\n // TextMessageStart\n ////////////////////////////////\n case RuntimeEventTypes.TextMessageStart:\n // create a sub stream that contains the message content\n const textMessageContentStream = eventStream.pipe(\n // skip until this message start event\n skipWhile((e: RuntimeEvent) => e !== event),\n // take until the message end event\n takeWhile(\n (e: RuntimeEvent) =>\n !(\n e.type === RuntimeEventTypes.TextMessageEnd &&\n (e as any).messageId == event.messageId\n ),\n ),\n // filter out any other message events or message ids\n filter(\n (e: RuntimeEvent) =>\n e.type == RuntimeEventTypes.TextMessageContent &&\n (e as any).messageId == event.messageId,\n ),\n );\n\n // signal when we are done streaming\n const streamingTextStatus = new Subject<typeof MessageStatusUnion>();\n\n const messageId = event.messageId;\n // push the new message\n pushMessage({\n id: messageId,\n parentMessageId: event.parentMessageId,\n status: firstValueFrom(streamingTextStatus),\n createdAt: new Date(),\n role: MessageRole.assistant,\n content: new Repeater(async (pushTextChunk, stopStreamingText) => {\n logger.debug(\"Text message content repeater created\");\n\n const textChunks: string[] = [];\n let textSubscription: Subscription;\n\n interruptStreaming$\n .pipe(\n shareReplay(),\n take(1),\n tap(({ reason, messageId }) => {\n logger.debug({ reason, messageId }, \"Text streaming interrupted\");\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(new MessageStreamInterruptedResponse({ messageId }));\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\"Subscribing to text message content stream\");\n\n textSubscription = textMessageContentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.TextMessageContent) {\n await pushTextChunk(e.content);\n textChunks.push(e.content);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in text message content stream\");\n interruptStreaming$.next({\n reason: \"Error streaming message content\",\n messageId,\n });\n stopStreamingText();\n textSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Text message content stream completed\");\n streamingTextStatus.next(new SuccessMessageStatus());\n stopStreamingText();\n textSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(TextMessage, {\n id: messageId,\n createdAt: new Date(),\n content: textChunks.join(\"\"),\n role: MessageRole.assistant,\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionStart\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionStart:\n logger.debug(\"Action execution start event received\");\n const actionExecutionArgumentStream = eventStream.pipe(\n skipWhile((e: RuntimeEvent) => e !== event),\n // take until the action execution end event\n takeWhile(\n (e: RuntimeEvent) =>\n !(\n e.type === RuntimeEventTypes.ActionExecutionEnd &&\n (e as any).actionExecutionId == event.actionExecutionId\n ),\n ),\n // filter out any other action execution events or action execution ids\n filter(\n (e: RuntimeEvent) =>\n e.type == RuntimeEventTypes.ActionExecutionArgs &&\n (e as any).actionExecutionId == event.actionExecutionId,\n ),\n );\n const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();\n pushMessage({\n id: event.actionExecutionId,\n parentMessageId: event.parentMessageId,\n status: firstValueFrom(streamingArgumentsStatus),\n createdAt: new Date(),\n name: event.actionName,\n arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.ActionExecutionArgs) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in action execution argument stream\");\n streamingArgumentsStatus.next(\n plainToInstance(FailedMessageStatus, {\n reason:\n \"An unknown error has occurred in the action execution argument stream\",\n }),\n );\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Action execution argument stream completed\");\n streamingArgumentsStatus.next(new SuccessMessageStatus());\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(ActionExecutionMessage, {\n id: event.actionExecutionId,\n createdAt: new Date(),\n name: event.actionName,\n arguments: argumentChunks.join(\"\"),\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug({ result: event.result }, \"Action execution result event received\");\n pushMessage({\n id: \"result-\" + event.actionExecutionId,\n status: new SuccessMessageStatus(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n });\n\n outputMessages.push(\n plainToInstance(ResultMessage, {\n id: \"result-\" + event.actionExecutionId,\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n }),\n );\n break;\n ////////////////////////////////\n // AgentStateMessage\n ////////////////////////////////\n case RuntimeEventTypes.AgentStateMessage:\n logger.debug({ event }, \"Agent message event received\");\n pushMessage({\n id: randomId(),\n status: new SuccessMessageStatus(),\n threadId: event.threadId,\n agentName: event.agentName,\n nodeName: event.nodeName,\n runId: event.runId,\n active: event.active,\n state: event.state,\n running: event.running,\n role: MessageRole.assistant,\n createdAt: new Date(),\n });\n outputMessages.push(\n plainToInstance(AgentStateMessage, {\n id: randomId(),\n threadId: event.threadId,\n agentName: event.agentName,\n nodeName: event.nodeName,\n runId: event.runId,\n active: event.active,\n state: event.state,\n running: event.running,\n role: MessageRole.assistant,\n createdAt: new Date(),\n }),\n );\n break;\n }\n },\n error: (err) => {\n // For structured CopilotKit errors, set proper error response status\n if (\n err instanceof CopilotKitError ||\n err instanceof CopilotKitLowLevelError ||\n (err instanceof Error && err.name && err.name.includes(\"CopilotKit\")) ||\n err?.extensions?.visibility\n ) {\n responseStatus$.next(\n new UnknownErrorResponse({\n description: err.message || \"Agent error occurred\",\n // Include original error information for frontend to extract\n originalError: {\n code: err.code || err.extensions?.code,\n statusCode: err.statusCode || err.extensions?.statusCode,\n severity: err.severity || err.extensions?.severity,\n visibility: err.visibility || err.extensions?.visibility,\n originalErrorType: err.originalErrorType || err.extensions?.originalErrorType,\n extensions: err.extensions,\n },\n }),\n );\n eventStreamSubscription?.unsubscribe();\n rejectOutputMessagesPromise(err);\n stopStreamingMessages();\n return;\n }\n\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n rejectOutputMessagesPromise(err);\n },\n complete: async () => {\n logger.debug(\"Event stream completed\");\n if (data.cloud?.guardrails) {\n logger.debug(\"Guardrails is enabled, waiting for guardrails result\");\n await firstValueFrom(guardrailsResult$);\n }\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n resolveOutputMessagesPromise(outputMessages);\n },\n });\n }),\n };\n\n return response;\n }\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageInput } from \"./message.input\";\nimport { FrontendInput } from \"./frontend.input\";\nimport { CloudInput } from \"./cloud.input\";\nimport { CopilotRequestType } from \"../types/enums\";\nimport { ForwardedParametersInput } from \"./forwarded-parameters.input\";\nimport { AgentSessionInput } from \"./agent-session.input\";\nimport { AgentStateInput } from \"./agent-state.input\";\nimport { ExtensionsInput } from \"./extensions.input\";\nimport { MetaEventInput } from \"./meta-event.input\";\nimport { CopilotContextInput } from \"./copilot-context.input\";\n\n@InputType()\nexport class GenerateCopilotResponseMetadataInput {\n @Field(() => CopilotRequestType, { nullable: true })\n requestType: CopilotRequestType;\n}\n\n@InputType()\nexport class GenerateCopilotResponseInput {\n @Field(() => GenerateCopilotResponseMetadataInput, { nullable: false })\n metadata: GenerateCopilotResponseMetadataInput;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => [MessageInput])\n messages: MessageInput[];\n\n @Field(() => FrontendInput)\n frontend: FrontendInput;\n\n @Field(() => CloudInput, { nullable: true })\n cloud?: CloudInput;\n\n @Field(() => ForwardedParametersInput, { nullable: true })\n forwardedParameters?: ForwardedParametersInput;\n\n @Field(() => AgentSessionInput, { nullable: true })\n agentSession?: AgentSessionInput;\n\n @Field(() => AgentStateInput, { nullable: true })\n agentState?: AgentStateInput;\n\n @Field(() => [AgentStateInput], { nullable: true })\n agentStates?: AgentStateInput[];\n\n @Field(() => ExtensionsInput, { nullable: true })\n extensions?: ExtensionsInput;\n\n @Field(() => [MetaEventInput], { nullable: true })\n metaEvents?: MetaEventInput[];\n\n @Field(() => [CopilotContextInput], { nullable: true })\n context?: CopilotContextInput[];\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageRole } from \"../types/enums\";\nimport { BaseMessageInput } from \"../types/base\";\n\n// GraphQL does not support union types in inputs, so we need to use\n// optional fields for the different subtypes.\n@InputType()\nexport class MessageInput extends BaseMessageInput {\n @Field(() => TextMessageInput, { nullable: true })\n textMessage?: TextMessageInput;\n\n @Field(() => ActionExecutionMessageInput, { nullable: true })\n actionExecutionMessage?: ActionExecutionMessageInput;\n\n @Field(() => ResultMessageInput, { nullable: true })\n resultMessage?: ResultMessageInput;\n\n @Field(() => AgentStateMessageInput, { nullable: true })\n agentStateMessage?: AgentStateMessageInput;\n\n @Field(() => ImageMessageInput, { nullable: true })\n imageMessage?: ImageMessageInput;\n}\n\n@InputType()\nexport class TextMessageInput {\n @Field(() => String)\n content: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n\n@InputType()\nexport class ActionExecutionMessageInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n arguments: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => String, {\n nullable: true,\n deprecationReason: \"This field will be removed in a future version\",\n })\n scope?: String;\n}\n\n@InputType()\nexport class ResultMessageInput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => String)\n result: string;\n}\n\n@InputType()\nexport class AgentStateMessageInput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String)\n state: string;\n\n @Field(() => Boolean)\n running: boolean;\n\n @Field(() => String)\n nodeName: string;\n\n @Field(() => String)\n runId: string;\n\n @Field(() => Boolean)\n active: boolean;\n}\n\n@InputType()\nexport class ImageMessageInput {\n @Field(() => String)\n format: string;\n\n @Field(() => String)\n bytes: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInput } from \"./action.input\";\n\n@InputType()\nexport class FrontendInput {\n @Field(() => String, { nullable: true })\n toDeprecate_fullContext?: string;\n\n @Field(() => [ActionInput])\n actions: ActionInput[];\n\n @Field(() => String, { nullable: true })\n url?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInputAvailability } from \"../types/enums\";\n@InputType()\nexport class ActionInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n jsonSchema: string;\n\n @Field(() => ActionInputAvailability, { nullable: true })\n available?: ActionInputAvailability;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { GuardrailsInput } from \"./cloud-guardrails.input\";\n\n@InputType()\nexport class CloudInput {\n @Field(() => GuardrailsInput, { nullable: true })\n guardrails?: GuardrailsInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class GuardrailsRuleInput {\n @Field(() => [String], { nullable: true })\n allowList?: string[] = [];\n\n @Field(() => [String], { nullable: true })\n denyList?: string[] = [];\n}\n\n@InputType()\nexport class GuardrailsInput {\n @Field(() => GuardrailsRuleInput, { nullable: false })\n inputValidationRules: GuardrailsRuleInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ForwardedParametersInput {\n @Field(() => String, { nullable: true })\n model?: string;\n\n @Field(() => Number, { nullable: true })\n maxTokens?: number;\n\n @Field(() => [String], { nullable: true })\n stop?: string[];\n\n @Field(() => String, { nullable: true })\n toolChoice?: String;\n\n @Field(() => String, { nullable: true })\n toolChoiceFunctionName?: string;\n\n @Field(() => Number, { nullable: true })\n temperature?: number;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class AgentSessionInput {\n @Field(() => String)\n agentName: string;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n nodeName?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class AgentStateInput {\n @Field(() => String)\n agentName: string;\n\n @Field(() => String)\n state: string;\n\n @Field(() => String, { nullable: true })\n config?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n/**\n * The extensions input is used to pass additional information to the copilot runtime, specific to a\n * service adapter or agent framework.\n */\n\n@InputType()\nexport class ExtensionsInput {\n @Field(() => OpenAIApiAssistantAPIInput, { nullable: true })\n openaiAssistantAPI?: OpenAIApiAssistantAPIInput;\n}\n\n@InputType()\nexport class OpenAIApiAssistantAPIInput {\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MetaEventName } from \"../types/meta-events.type\";\nimport { MessageInput } from \"./message.input\";\n\n@InputType()\nexport class MetaEventInput {\n @Field(() => MetaEventName)\n name: MetaEventName;\n\n @Field(() => String)\n value?: string;\n\n @Field(() => String, { nullable: true })\n response?: string;\n\n @Field(() => [MessageInput], { nullable: true })\n messages?: MessageInput[];\n}\n","import { createUnionType, Field, InterfaceType, ObjectType, registerEnumType } from \"type-graphql\";\nimport {\n ActionExecutionMessageOutput,\n AgentStateMessageOutput,\n BaseMessageOutput,\n ResultMessageOutput,\n TextMessageOutput,\n} from \"./copilot-response.type\";\n\nexport enum MetaEventName {\n LangGraphInterruptEvent = \"LangGraphInterruptEvent\",\n CopilotKitLangGraphInterruptEvent = \"CopilotKitLangGraphInterruptEvent\",\n}\n\nregisterEnumType(MetaEventName, {\n name: \"MetaEventName\",\n description: \"Meta event types\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.name === MetaEventName.LangGraphInterruptEvent) {\n return LangGraphInterruptEvent;\n } else if (value.name === MetaEventName.CopilotKitLangGraphInterruptEvent) {\n return CopilotKitLangGraphInterruptEvent;\n }\n return undefined;\n },\n})\n@InterfaceType()\nexport abstract class BaseMetaEvent {\n @Field(() => String)\n type: \"MetaEvent\" = \"MetaEvent\";\n\n @Field(() => MetaEventName)\n name: MetaEventName;\n}\n\n@ObjectType()\nexport class CopilotKitLangGraphInterruptEventData {\n @Field(() => String)\n value: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n}\n\n@ObjectType({ implements: BaseMetaEvent })\nexport class LangGraphInterruptEvent {\n @Field(() => MetaEventName)\n name: MetaEventName.LangGraphInterruptEvent = MetaEventName.LangGraphInterruptEvent;\n\n @Field(() => String)\n value: string;\n\n @Field(() => String, { nullable: true })\n response?: string;\n}\n\n@ObjectType({ implements: BaseMetaEvent })\nexport class CopilotKitLangGraphInterruptEvent {\n @Field(() => MetaEventName)\n name: MetaEventName.CopilotKitLangGraphInterruptEvent =\n MetaEventName.CopilotKitLangGraphInterruptEvent;\n\n @Field(() => CopilotKitLangGraphInterruptEventData)\n data: CopilotKitLangGraphInterruptEventData;\n\n @Field(() => String, { nullable: true })\n response?: string;\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\nimport { ExtensionsResponse } from \"./extensions-response.type\";\nimport { BaseMetaEvent } from \"./meta-events.type\";\n\n@InterfaceType({\n resolveType(value) {\n if (value.hasOwnProperty(\"content\")) {\n return TextMessageOutput;\n } else if (value.hasOwnProperty(\"name\")) {\n return ActionExecutionMessageOutput;\n } else if (value.hasOwnProperty(\"result\")) {\n return ResultMessageOutput;\n } else if (value.hasOwnProperty(\"state\")) {\n return AgentStateMessageOutput;\n } else if (value.hasOwnProperty(\"format\") && value.hasOwnProperty(\"bytes\")) {\n return ImageMessageOutput;\n }\n return undefined;\n },\n})\nexport abstract class BaseMessageOutput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n\n @Field(() => MessageStatusUnion)\n status: typeof MessageStatusUnion;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class TextMessageOutput {\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => [String])\n content: string[];\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ActionExecutionMessageOutput {\n @Field(() => String)\n name: string;\n\n @Field(() => String, {\n nullable: true,\n deprecationReason: \"This field will be removed in a future version\",\n })\n scope?: string;\n\n @Field(() => [String])\n arguments: string[];\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ResultMessageOutput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class AgentStateMessageOutput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n\n @Field(() => String)\n nodeName: string;\n\n @Field(() => String)\n runId: string;\n\n @Field(() => Boolean)\n active: boolean;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String)\n state: string;\n\n @Field(() => Boolean)\n running: boolean;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ImageMessageOutput {\n @Field(() => String)\n format: string;\n\n @Field(() => String)\n bytes: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType()\nexport class CopilotResponse {\n @Field(() => String)\n threadId!: string;\n\n @Field(() => ResponseStatusUnion)\n status: typeof ResponseStatusUnion;\n\n @Field({ nullable: true })\n runId?: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n\n @Field(() => ExtensionsResponse, { nullable: true })\n extensions?: ExtensionsResponse;\n\n @Field(() => [BaseMetaEvent], { nullable: true })\n metaEvents?: (typeof BaseMetaEvent)[];\n}\n","import { Field, ObjectType } from \"type-graphql\";\n\n/**\n * The extensions response is used to receive additional information from the copilot runtime, specific to a\n * service adapter or agent framework.\n *\n * Next time a request to the runtime is made, the extensions response will be included in the request as input.\n */\n\n@ObjectType()\nexport class ExtensionsResponse {\n @Field(() => OpenAIApiAssistantAPIResponse, { nullable: true })\n openaiAssistantAPI?: OpenAIApiAssistantAPIResponse;\n}\n\n@ObjectType()\nexport class OpenAIApiAssistantAPIResponse {\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class CopilotContextInput {\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n value: string;\n}\n","import {\n Action,\n CopilotKitError,\n CopilotKitErrorCode,\n CopilotKitLowLevelError,\n ensureStructuredError,\n randomId,\n Severity,\n} from \"@copilotkit/shared\";\nimport { plainToInstance } from \"class-transformer\";\nimport {\n catchError,\n concat,\n concatMap,\n EMPTY,\n firstValueFrom,\n from,\n of,\n ReplaySubject,\n scan,\n Subject,\n} from \"rxjs\";\nimport { ActionInput } from \"../graphql/inputs/action.input\";\nimport { ActionExecutionMessage, ResultMessage, TextMessage } from \"../graphql/types/converted\";\nimport { GuardrailsResult } from \"../graphql/types/guardrails-result.type\";\nimport { generateHelpfulErrorMessage } from \"../lib/streaming\";\nimport telemetry from \"../lib/telemetry-client\";\nimport { streamLangChainResponse } from \"./langchain/utils\";\n\nexport enum RuntimeEventTypes {\n TextMessageStart = \"TextMessageStart\",\n TextMessageContent = \"TextMessageContent\",\n TextMessageEnd = \"TextMessageEnd\",\n ActionExecutionStart = \"ActionExecutionStart\",\n ActionExecutionArgs = \"ActionExecutionArgs\",\n ActionExecutionEnd = \"ActionExecutionEnd\",\n ActionExecutionResult = \"ActionExecutionResult\",\n AgentStateMessage = \"AgentStateMessage\",\n MetaEvent = \"MetaEvent\",\n RunError = \"RunError\",\n}\n\nexport enum RuntimeMetaEventName {\n LangGraphInterruptEvent = \"LangGraphInterruptEvent\",\n LangGraphInterruptResumeEvent = \"LangGraphInterruptResumeEvent\",\n CopilotKitLangGraphInterruptEvent = \"CopilotKitLangGraphInterruptEvent\",\n}\n\nexport type RunTimeMetaEvent =\n | {\n type: RuntimeEventTypes.MetaEvent;\n name: RuntimeMetaEventName.LangGraphInterruptEvent;\n value: string;\n }\n | {\n type: RuntimeEventTypes.MetaEvent;\n name: RuntimeMetaEventName.CopilotKitLangGraphInterruptEvent;\n data: { value: string; messages: (TextMessage | ActionExecutionMessage | ResultMessage)[] };\n }\n | {\n type: RuntimeEventTypes.MetaEvent;\n name: RuntimeMetaEventName.LangGraphInterruptResumeEvent;\n data: string;\n };\n\nexport type RuntimeErrorEvent = {\n type: RuntimeEventTypes.RunError;\n message: string;\n code?: string;\n};\n\nexport type RuntimeEvent =\n | { type: RuntimeEventTypes.TextMessageStart; messageId: string; parentMessageId?: string }\n | {\n type: RuntimeEventTypes.TextMessageContent;\n messageId: string;\n content: string;\n }\n | { type: RuntimeEventTypes.TextMessageEnd; messageId: string }\n | {\n type: RuntimeEventTypes.ActionExecutionStart;\n actionExecutionId: string;\n actionName: string;\n parentMessageId?: string;\n }\n | { type: RuntimeEventTypes.ActionExecutionArgs; actionExecutionId: string; args: string }\n | { type: RuntimeEventTypes.ActionExecutionEnd; actionExecutionId: string }\n | {\n type: RuntimeEventTypes.ActionExecutionResult;\n actionName: string;\n actionExecutionId: string;\n result: string;\n }\n | {\n type: RuntimeEventTypes.AgentStateMessage;\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: string;\n state: string;\n running: boolean;\n }\n | RunTimeMetaEvent\n | RuntimeErrorEvent;\n\ninterface RuntimeEventWithState {\n event: RuntimeEvent | null;\n callActionServerSide: boolean;\n action: Action<any> | null;\n actionExecutionId: string | null;\n args: string;\n actionExecutionParentMessageId: string | null;\n}\n\ntype EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;\n\nexport class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {\n constructor() {\n super();\n }\n\n sendTextMessageStart({\n messageId,\n parentMessageId,\n }: {\n messageId: string;\n parentMessageId?: string;\n }) {\n this.next({ type: RuntimeEventTypes.TextMessageStart, messageId, parentMessageId });\n }\n\n sendTextMessageContent({ messageId, content }: { messageId: string; content: string }) {\n this.next({ type: RuntimeEventTypes.TextMessageContent, content, messageId });\n }\n\n sendTextMessageEnd({ messageId }: { messageId: string }) {\n this.next({ type: RuntimeEventTypes.TextMessageEnd, messageId });\n }\n\n sendTextMessage(messageId: string, content: string) {\n this.sendTextMessageStart({ messageId });\n this.sendTextMessageContent({ messageId, content });\n this.sendTextMessageEnd({ messageId });\n }\n\n sendActionExecutionStart({\n actionExecutionId,\n actionName,\n parentMessageId,\n }: {\n actionExecutionId: string;\n actionName: string;\n parentMessageId?: string;\n }) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionStart,\n actionExecutionId,\n actionName,\n parentMessageId,\n });\n }\n\n sendActionExecutionArgs({\n actionExecutionId,\n args,\n }: {\n actionExecutionId: string;\n args: string;\n }) {\n this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args, actionExecutionId });\n }\n\n sendActionExecutionEnd({ actionExecutionId }: { actionExecutionId: string }) {\n this.next({ type: RuntimeEventTypes.ActionExecutionEnd, actionExecutionId });\n }\n\n sendActionExecution({\n actionExecutionId,\n actionName,\n args,\n parentMessageId,\n }: {\n actionExecutionId: string;\n actionName: string;\n args: string;\n parentMessageId?: string;\n }) {\n this.sendActionExecutionStart({ actionExecutionId, actionName, parentMessageId });\n this.sendActionExecutionArgs({ actionExecutionId, args });\n this.sendActionExecutionEnd({ actionExecutionId });\n }\n\n sendActionExecutionResult({\n actionExecutionId,\n actionName,\n result,\n error,\n }: {\n actionExecutionId: string;\n actionName: string;\n result?: string;\n error?: { code: string; message: string };\n }) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionResult,\n actionName,\n actionExecutionId,\n result: ResultMessage.encodeResult(result, error),\n });\n }\n\n sendAgentStateMessage({\n threadId,\n agentName,\n nodeName,\n runId,\n active,\n role,\n state,\n running,\n }: {\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: string;\n state: string;\n running: boolean;\n }) {\n this.next({\n type: RuntimeEventTypes.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n active,\n role,\n state,\n running,\n });\n }\n}\n\nexport class RuntimeEventSource {\n private eventStream$ = new RuntimeEventSubject();\n private callback!: EventSourceCallback;\n private errorHandler?: (error: any, context: any) => Promise<void>;\n private errorContext?: any;\n\n constructor(params?: {\n errorHandler?: (error: any, context: any) => Promise<void>;\n errorContext?: any;\n }) {\n this.errorHandler = params?.errorHandler;\n this.errorContext = params?.errorContext;\n }\n\n async stream(callback: EventSourceCallback): Promise<void> {\n this.callback = callback;\n }\n}\n\nfunction convertStreamingErrorToStructured(error: any): CopilotKitError {\n // Determine a more helpful error message based on context\n let helpfulMessage = generateHelpfulErrorMessage(error, \"event streaming connection\");\n\n // For network-related errors, use CopilotKitLowLevelError to preserve the original error\n if (\n error?.message?.includes(\"fetch failed\") ||\n error?.message?.includes(\"ECONNREFUSED\") ||\n error?.message?.includes(\"ENOTFOUND\") ||\n error?.message?.includes(\"ETIMEDOUT\") ||\n error?.message?.includes(\"terminated\") ||\n error?.cause?.code === \"UND_ERR_SOCKET\" ||\n error?.message?.includes(\"other side closed\") ||\n error?.code === \"UND_ERR_SOCKET\"\n ) {\n return new CopilotKitLowLevelError({\n error: error instanceof Error ? error : new Error(String(error)),\n url: \"event streaming connection\",\n message: helpfulMessage,\n });\n }\n\n // For all other errors, preserve the raw error in a basic CopilotKitError\n return new CopilotKitError({\n message: helpfulMessage,\n code: CopilotKitErrorCode.UNKNOWN,\n severity: Severity.CRITICAL,\n });\n}\n","import { TelemetryClient } from \"@copilotkit/shared\";\nimport { createHash } from \"node:crypto\";\nimport { CopilotRuntime, resolveEndpointType } from \"./runtime/copilot-runtime\";\nimport { RuntimeInstanceCreatedInfo } from \"@copilotkit/shared/src/telemetry/events\";\nimport { CreateCopilotRuntimeServerOptions } from \"./integrations/shared\";\nimport { EndpointType, LangGraphPlatformEndpoint } from \"./runtime/types\";\nconst packageJson = require(\"../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport function getRuntimeInstanceTelemetryInfo(\n options: CreateCopilotRuntimeServerOptions,\n): RuntimeInstanceCreatedInfo {\n const runtime = options.runtime;\n const remoteEndpoints = runtime.params?.remoteEndpoints ?? [];\n const endpointsInfo = remoteEndpoints.reduce(\n (acc, endpoint) => {\n let info = { ...acc };\n\n const endpointType = resolveEndpointType(endpoint);\n if (!info.endpointTypes.includes(endpointType)) {\n info = {\n ...info,\n endpointTypes: [...info.endpointTypes, endpointType],\n };\n }\n\n if (endpointType === EndpointType.LangGraphPlatform) {\n // When type is resolved, recreating a const with casting of type\n const ep = endpoint as LangGraphPlatformEndpoint;\n info = {\n ...info,\n agentsAmount: ep.agents.length,\n hashedKey: ep.langsmithApiKey\n ? createHash(\"sha256\").update(ep.langsmithApiKey).digest(\"hex\")\n : null,\n };\n }\n\n return info;\n },\n { endpointTypes: [], agentsAmount: null, hashedKey: null },\n );\n\n // Get public API key from options.cloud.publicApiKey\n const publicApiKey = options.cloud?.publicApiKey;\n const apiKeyProvided = !!publicApiKey && publicApiKey.trim().length > 0;\n\n return {\n actionsAmount: runtime.params?.actions?.length ?? 0,\n endpointsAmount: remoteEndpoints.length,\n endpointTypes: endpointsInfo.endpointTypes,\n agentsAmount: Object.keys(runtime.instance.agents).length,\n hashedLgcKey: endpointsInfo.hashedKey,\n \"cloud.api_key_provided\": apiKeyProvided,\n ...(apiKeyProvided ? { \"cloud.public_api_key\": publicApiKey } : {}),\n ...(options.cloud?.baseUrl ? { \"cloud.base_url\": options.cloud.baseUrl } : {}),\n } as RuntimeInstanceCreatedInfo;\n}\n\nexport default telemetryClient;\n","/**\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 Action,\n CopilotErrorHandler,\n CopilotKitMisuseError,\n MaybePromise,\n NonEmptyRecord,\n Parameter,\n readBody,\n getZodParameters,\n PartialBy,\n} from \"@copilotkit/shared\";\nimport { type RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport { CopilotServiceAdapter, RemoteChainParameters } from \"../../service-adapters\";\nimport {\n CopilotRuntime as CopilotRuntimeVNext,\n CopilotRuntimeOptions,\n CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n InMemoryAgentRunner as InMemoryAgentRunnerVNext,\n} from \"@copilotkitnext/runtime\";\n\nimport { MessageInput } from \"../../graphql/inputs/message.input\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { RuntimeEventSource } from \"../../service-adapters/events\";\nimport { Message } from \"../../graphql/types/converted\";\nimport { ForwardedParametersInput } from \"../../graphql/inputs/forwarded-parameters.input\";\n\nimport {\n EndpointType,\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport { GraphQLContext } from \"../integrations/shared\";\nimport { AgentSessionInput } from \"../../graphql/inputs/agent-session.input\";\nimport { AgentStateInput } from \"../../graphql/inputs/agent-state.input\";\nimport { Agent } from \"../../graphql/types/agents-response.type\";\nimport { ExtensionsInput } from \"../../graphql/inputs/extensions.input\";\nimport { ExtensionsResponse } from \"../../graphql/types/extensions-response.type\";\nimport { MetaEventInput } from \"../../graphql/inputs/meta-event.input\";\nimport {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n LLMErrorData,\n} from \"../observability\";\nimport { AbstractAgent } from \"@ag-ui/client\";\n\n// +++ MCP Imports +++\nimport {\n MCPClient,\n MCPEndpointConfig,\n MCPTool,\n extractParametersFromSchema,\n convertMCPToolsToActions,\n generateMcpToolInstructions,\n} from \"./mcp-tools-utils\";\nimport { LangGraphAgent } from \"./agent-integrations/langgraph.agent\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (config: MCPEndpointConfig) => Promise<MCPClient>;\n// --- MCP Imports ---\n\nimport { CopilotContextInput } from \"../../graphql/inputs/copilot-context.input\";\nimport { BasicAgent, BasicAgentConfiguration } from \"@copilotkitnext/agent\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in (value as object) &&\n typeof (value as { then: unknown }).then === \"function\"\n );\n}\n\nexport interface CopilotRuntimeRequest {\n serviceAdapter: CopilotServiceAdapter;\n messages: MessageInput[];\n actions: ActionInput[];\n agentSession?: AgentSessionInput;\n agentStates?: AgentStateInput[];\n outputMessagesPromise: Promise<Message[]>;\n threadId?: string;\n runId?: string;\n publicApiKey?: string;\n graphqlContext: GraphQLContext;\n forwardedParameters?: ForwardedParametersInput;\n url?: string;\n extensions?: ExtensionsInput;\n metaEvents?: MetaEventInput[];\n context?: CopilotContextInput[];\n}\n\ninterface CopilotRuntimeResponse {\n threadId: string;\n runId?: string;\n eventSource: RuntimeEventSource;\n serverSideActions: Action<any>[];\n actionInputsWithoutAgents: ActionInput[];\n extensions?: ExtensionsResponse;\n}\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 = (options: OnBeforeRequestOptions) => 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 = (options: OnAfterRequestOptions) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (options: OnStopGenerationOptions) => 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\ntype AgentWithEndpoint = Agent & { endpoint: EndpointDefinition };\n\nexport interface CopilotRuntimeConstructorParams_BASE<T extends Parameter[] | [] = []> {\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 * 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\n// (duplicate BASE interface removed)\n\ntype BeforeRequestMiddleware = CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware = CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters = Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends 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 {\n params?: CopilotRuntimeConstructorParams;\n private observability?: CopilotObservabilityConfig;\n // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BasicAgentConfiguration[\"tools\"]> = new Map();\n private runtimeArgs: CopilotRuntimeOptions;\n instance: CopilotRuntimeVNext;\n\n constructor(\n params?: CopilotRuntimeConstructorParams & PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n const agents = params?.agents ?? {};\n this.runtimeArgs = {\n agents: { ...this.assignEndpointsToAgents(params?.remoteEndpoints ?? []), ...agents },\n runner: params?.runner ?? new InMemoryAgentRunnerVNext(),\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware: this.createOnBeforeRequestHandler(params).bind(this),\n afterRequestMiddleware: this.createOnAfterRequestHandler(params).bind(this),\n };\n this.params = params;\n this.observability = params?.observability_c;\n\n this.instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n private assignEndpointsToAgents(endpoints: CopilotRuntimeConstructorParams[\"remoteEndpoints\"]) {\n return endpoints.reduce((acc, endpoint) => {\n if (resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform) {\n let lgAgents = {};\n const lgEndpoint = endpoint as LangGraphPlatformEndpoint;\n lgEndpoint.agents.forEach((agent) => {\n const graphId = agent.assistantId ?? agent.name;\n lgAgents[graphId] = new LangGraphAgent({\n deploymentUrl: lgEndpoint.deploymentUrl,\n langsmithApiKey: lgEndpoint.langsmithApiKey,\n graphId,\n });\n });\n\n return {\n ...acc,\n ...lgAgents,\n };\n }\n\n return acc;\n }, {});\n }\n\n async handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n let agents = (await this.runtimeArgs.agents) ?? {};\n const isAgentsListEmpty = !Object.keys(agents).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent = !illegalServiceAdapterNames.includes(serviceAdapter.name);\n \n if (isAgentsListEmpty && (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)) {\n throw new CopilotKitMisuseError({\n message: \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n agents.default = new BasicAgent({\n model: `${serviceAdapter.provider}/${serviceAdapter.model}`,\n });\n }\n\n if (this.params.actions?.length) {\n const mcpTools = await this.getToolsFromMCP();\n agents = this.assignToolsToAgents(agents, [\n ...this.getToolsFromActions(this.params.actions),\n ...mcpTools,\n ]);\n }\n\n this.instance.agents = agents;\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BasicAgentConfiguration[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\" ? actions({ properties: {}, url: undefined }) : 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 };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BasicAgentConfiguration[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools || tools.length === 0) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n if (!(agent instanceof BasicAgent)) {\n continue;\n }\n\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as BasicAgentConfiguration;\n const existingTools = existingConfig.tools ?? [];\n\n const updatedConfig: BasicAgentConfiguration = {\n ...existingConfig,\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 & PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\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 params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const body = (await readBody(request)) as RunAgentInput;\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 }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams & 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(requestData: LLMRequestData): 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 ? streamedChunks : 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 BasicAgent 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<BasicAgentConfiguration[\"tools\"]> {\n const runtimeMcpServers = (this.params?.mcpServers ?? []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as CreateMCPClientFunction | 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 (options?.properties as { mcpEndpoints?: MCPEndpointConfig[] } | undefined)?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 || (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: BasicAgentConfiguration[\"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: BasicAgentConfiguration[\"tools\"] = Object.entries(toolsMap).map(\n ([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description: tool.description || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n };\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// export class CopilotRuntime<const T extends Parameter[] | [] = []> {\n// public actions: ActionsConfiguration<T>;\n// public agents: Record<string, AbstractAgent>;\n// public remoteEndpointDefinitions: EndpointDefinition[];\n// private langserve: Promise<Action<any>>[] = [];\n// private onBeforeRequest?: OnBeforeRequestHandler;\n// private onAfterRequest?: OnAfterRequestHandler;\n// private onStopGeneration?: OnStopGenerationHandler;\n// private delegateAgentProcessingToServiceAdapter: boolean;\n// private observability?: CopilotObservabilityConfig;\n// private availableAgents: Pick<AgentWithEndpoint, \"name\" | \"id\">[];\n// private onError?: CopilotErrorHandler;\n// private hasWarnedAboutError = false;\n//\n// // +++ MCP Properties +++\n// private readonly mcpServersConfig?: MCPEndpointConfig[];\n// private mcpActionCache = new Map<string, Action<any>[]>();\n// // --- MCP Properties ---\n//\n// // +++ MCP Client Factory +++\n// private readonly createMCPClientImpl?: CreateMCPClientFunction;\n// // --- MCP Client Factory ---\n//\n// constructor(params?: CopilotRuntimeConstructorParams<T>) {\n// if (\n// params?.remoteEndpoints &&\n// params?.remoteEndpoints.some((e) => e.type === EndpointType.LangGraphPlatform)\n// ) {\n// throw new CopilotKitMisuseError({\n// message:\n// \"LangGraph Platform remote endpoints are deprecated in favor of the `agents` property. Refer to https://docs.copilotkit.ai/langgraph for more information.\",\n// });\n// }\n//\n// if (\n// params?.actions &&\n// params?.remoteEndpoints &&\n// params?.remoteEndpoints.some((e) => e.type === EndpointType.LangGraphPlatform)\n// ) {\n// console.warn(\"Actions set in runtime instance will not be available for the agent\");\n// console.warn(\n// `LangGraph Platform remote endpoints are deprecated in favor of the \"agents\" property`,\n// );\n// }\n//\n// // TODO: finalize\n// // if (\n// // params?.agents &&\n// // Object.values(params.agents).some((agent) => {\n// // return agent instanceof AguiLangGraphAgent && !(agent instanceof LangGraphAgent);\n// // })\n// // ) {\n// // console.warn('LangGraph Agent class should be imported from @copilotkit/runtime. ')\n// // }\n//\n// this.actions = params?.actions || [];\n// this.availableAgents = [];\n//\n// for (const chain of params?.langserve || []) {\n// const remoteChain = new RemoteChain(chain);\n// this.langserve.push(remoteChain.toAction());\n// }\n//\n// this.remoteEndpointDefinitions = params?.remoteEndpoints ?? params?.remoteActions ?? [];\n//\n// this.onBeforeRequest = params?.middleware?.onBeforeRequest;\n// this.onAfterRequest = params?.middleware?.onAfterRequest;\n// this.onStopGeneration = params?.onStopGeneration;\n// this.delegateAgentProcessingToServiceAdapter =\n// params?.delegateAgentProcessingToServiceAdapter || false;\n// this.observability = params?.observability_c;\n// const incomingAgents = params?.agents;\n// if (isPromiseLike<Record<string, AbstractAgent>>(incomingAgents)) {\n// this.agents = {};\n// // PromiseLike may not have .catch in the type; attach error handling via then's second arg\n// incomingAgents.then(\n// (resolved) => {\n// this.agents = resolved;\n// },\n// () => {},\n// );\n// } else {\n// this.agents = (incomingAgents as Record<string, AbstractAgent>) ?? {};\n// }\n// this.onError = params?.onError;\n// // +++ MCP Initialization +++\n// this.mcpServersConfig = params?.mcpServers;\n// this.createMCPClientImpl = params?.createMCPClient;\n//\n// // Validate: If mcpServers are provided, createMCPClient must also be provided\n// if (this.mcpServersConfig && this.mcpServersConfig.length > 0 && !this.createMCPClientImpl) {\n// throw new CopilotKitMisuseError({\n// message:\n// \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. \" +\n// \"Please provide an implementation for `createMCPClient`.\",\n// });\n// }\n//\n// // Warning if actions are defined alongside LangGraph platform (potentially MCP too?)\n// if (\n// params?.actions &&\n// (params?.remoteEndpoints?.some((e) => e.type === EndpointType.LangGraphPlatform) ||\n// this.mcpServersConfig?.length)\n// ) {\n// console.warn(\n// \"Local 'actions' defined in CopilotRuntime might not be available to remote agents (LangGraph, MCP). Consider defining actions closer to the agent implementation if needed.\",\n// );\n// }\n// }\n//\n// // +++ MCP Instruction Injection Method +++\n// private injectMCPToolInstructions(\n// messages: MessageInput[],\n// currentActions: Action<any>[],\n// ): MessageInput[] {\n// // Filter the *passed-in* actions for MCP tools\n// const mcpActionsForRequest = currentActions.filter((action) => (action as any)._isMCPTool);\n//\n// if (!mcpActionsForRequest || mcpActionsForRequest.length === 0) {\n// return messages; // No MCP tools for this specific request\n// }\n//\n// // Create a map to deduplicate tools by name (keeping the last one if duplicates exist)\n// const uniqueMcpTools = new Map<string, Action<any>>();\n//\n// // Add all MCP tools to the map with their names as keys\n// mcpActionsForRequest.forEach((action) => {\n// uniqueMcpTools.set(action.name, action);\n// });\n//\n// // Format instructions from the unique tools map\n// // Convert Action objects to MCPTool format for the instruction generator\n// const toolsMap: Record<string, MCPTool> = {};\n// Array.from(uniqueMcpTools.values()).forEach((action) => {\n// toolsMap[action.name] = {\n// description: action.description || \"\",\n// schema: action.parameters\n// ? {\n// parameters: {\n// properties: action.parameters.reduce(\n// (acc, p) => ({\n// ...acc,\n// [p.name]: { type: p.type, description: p.description },\n// }),\n// {},\n// ),\n// required: action.parameters.filter((p) => p.required).map((p) => p.name),\n// },\n// }\n// : {},\n// execute: async () => ({}), // Placeholder, not used for instructions\n// };\n// });\n//\n// // Generate instructions using the exported helper\n// const mcpToolInstructions = generateMcpToolInstructions(toolsMap);\n//\n// if (!mcpToolInstructions) {\n// return messages; // No MCP tools to describe\n// }\n//\n// const instructions =\n// mcpToolInstructions + \"\\nUse them when appropriate to fulfill the user's request.\";\n//\n// const systemMessageIndex = messages.findIndex((msg) => msg.textMessage?.role === \"system\");\n//\n// const newMessages = [...messages]; // Create a mutable copy\n//\n// if (systemMessageIndex !== -1) {\n// const existingMsg = newMessages[systemMessageIndex];\n// if (existingMsg.textMessage) {\n// existingMsg.textMessage.content =\n// (existingMsg.textMessage.content ? existingMsg.textMessage.content + \"\\n\\n\" : \"\") +\n// instructions;\n// }\n// } else {\n// newMessages.unshift({\n// id: randomId(),\n// createdAt: new Date(),\n// textMessage: {\n// role: MessageRole.system,\n// content: instructions,\n// },\n// actionExecutionMessage: undefined,\n// resultMessage: undefined,\n// agentStateMessage: undefined,\n// });\n// }\n//\n// return newMessages;\n// }\n//\n// async processRuntimeRequest(request: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {\n// const {\n// serviceAdapter,\n// messages: rawMessages,\n// actions: clientSideActionsInput,\n// threadId,\n// runId,\n// outputMessagesPromise,\n// graphqlContext,\n// forwardedParameters,\n// url,\n// extensions,\n// agentSession,\n// agentStates,\n// publicApiKey,\n// context,\n// } = request;\n// graphqlContext.request.signal.addEventListener(\n// \"abort\",\n// () =>\n// this.onStopGeneration?.({\n// threadId,\n// runId,\n// url,\n// agentName: agentSession?.agentName,\n// lastMessage: rawMessages[rawMessages.length - 1],\n// }),\n// { once: true }, // optional: fire only once\n// );\n//\n// const eventSource = new RuntimeEventSource({\n// errorHandler: async (error, context) => {\n// await this.error(\"error\", context, error, publicApiKey);\n// },\n// errorContext: {\n// threadId,\n// runId,\n// source: \"runtime\",\n// request: {\n// operation: \"processRuntimeRequest\",\n// method: \"POST\",\n// url: url,\n// startTime: Date.now(),\n// },\n// agent: agentSession ? { name: agentSession.agentName } : undefined,\n// technical: {\n// environment: process.env.NODE_ENV,\n// },\n// },\n// });\n// // Track request start time for logging\n// const requestStartTime = Date.now();\n// // For storing streamed chunks if progressive logging is enabled\n// const streamedChunks: any[] = [];\n//\n// try {\n// if (\n// Object.keys(this.agents).length &&\n// agentSession?.agentName &&\n// !this.delegateAgentProcessingToServiceAdapter\n// ) {\n// this.agents = { [agentSession.agentName]: this.agents[agentSession.agentName] };\n// }\n//\n// if (agentSession && !this.delegateAgentProcessingToServiceAdapter) {\n// return await this.processAgentRequest(request);\n// }\n// if (serviceAdapter instanceof EmptyAdapter) {\n// throw new CopilotKitMisuseError({\n// message: `Invalid adapter configuration: EmptyAdapter is only meant to be used with agent lock mode.\n// For non-agent components like useCopilotChatSuggestions, CopilotTextarea, or CopilotTask,\n// please use an LLM adapter instead.`,\n// });\n// }\n//\n// // +++ Get Server Side Actions (including dynamic MCP) EARLY +++\n// const serverSideActions = await this.getServerSideActions(request);\n// // --- Get Server Side Actions (including dynamic MCP) EARLY ---\n//\n// // Filter raw messages *before* injection\n// const filteredRawMessages = rawMessages.filter((message) => !message.agentStateMessage);\n//\n// // +++ Inject MCP Instructions based on current actions +++\n// const messagesWithInjectedInstructions = this.injectMCPToolInstructions(\n// filteredRawMessages,\n// serverSideActions,\n// );\n// const inputMessages = convertGqlInputToMessages(messagesWithInjectedInstructions);\n// // --- Inject MCP Instructions based on current actions ---\n//\n// // Log LLM request if logging is enabled\n// if (this.observability?.enabled && publicApiKey) {\n// try {\n// const requestData: LLMRequestData = {\n// threadId,\n// runId,\n// model: forwardedParameters?.model,\n// messages: inputMessages,\n// actions: clientSideActionsInput,\n// forwardedParameters,\n// timestamp: requestStartTime,\n// provider: this.detectProvider(serviceAdapter),\n// };\n//\n// await this.observability.hooks.handleRequest(requestData);\n// } catch (error) {\n// console.error(\"Error logging LLM request:\", error);\n// }\n// }\n//\n// const serverSideActionsInput: ActionInput[] = serverSideActions.map((action) => ({\n// name: action.name,\n// description: action.description,\n// jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n// additionalConfig: action.additionalConfig,\n// }));\n//\n// const actionInputs = flattenToolCallsNoDuplicates([\n// ...serverSideActionsInput,\n// ...clientSideActionsInput.filter(\n// // Filter remote actions from CopilotKit core loop\n// (action) => action.available !== ActionInputAvailability.remote,\n// ),\n// ]);\n//\n// await this.onBeforeRequest?.({\n// threadId,\n// runId,\n// inputMessages,\n// properties: graphqlContext.properties,\n// url,\n// });\n//\n// const result = await serviceAdapter.process({\n// messages: inputMessages,\n// actions: actionInputs,\n// threadId,\n// runId,\n// eventSource,\n// forwardedParameters,\n// extensions,\n// agentSession,\n// agentStates,\n// });\n//\n// // for backwards compatibility, we deal with the case that no threadId is provided\n// // by the frontend, by using the threadId from the response\n// const nonEmptyThreadId = threadId ?? result.threadId;\n//\n// outputMessagesPromise\n// .then((outputMessages) => {\n// this.onAfterRequest?.({\n// threadId: nonEmptyThreadId,\n// runId: result.runId,\n// inputMessages,\n// outputMessages,\n// properties: graphqlContext.properties,\n// url,\n// });\n// })\n// .catch((_error) => {});\n//\n// // After getting the response, log it if logging is enabled\n// if (this.observability?.enabled && publicApiKey) {\n// try {\n// outputMessagesPromise\n// .then((outputMessages) => {\n// const responseData: LLMResponseData = {\n// threadId: result.threadId,\n// runId: result.runId,\n// model: forwardedParameters?.model,\n// // Use collected chunks for progressive mode or outputMessages for regular mode\n// output: this.observability.progressive ? streamedChunks : outputMessages,\n// latency: Date.now() - requestStartTime,\n// timestamp: Date.now(),\n// provider: this.detectProvider(serviceAdapter),\n// // Indicate this is the final response\n// isFinalResponse: true,\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// // Add progressive logging if enabled\n// if (this.observability?.enabled && this.observability.progressive && publicApiKey) {\n// // Keep reference to original stream function\n// const originalStream = eventSource.stream.bind(eventSource);\n//\n// // Wrap the stream function to intercept events\n// eventSource.stream = async (callback) => {\n// await originalStream(async (eventStream$) => {\n// // Create subscription to capture streaming events\n// eventStream$.subscribe({\n// next: (event) => {\n// // Only log content chunks\n// if (event.type === RuntimeEventTypes.TextMessageContent) {\n// // Store the chunk\n// streamedChunks.push(event.content);\n//\n// // Log each chunk separately for progressive mode\n// try {\n// const progressiveData: LLMResponseData = {\n// threadId: threadId || \"\",\n// runId,\n// model: forwardedParameters?.model,\n// output: event.content,\n// latency: Date.now() - requestStartTime,\n// timestamp: Date.now(),\n// provider: this.detectProvider(serviceAdapter),\n// isProgressiveChunk: true,\n// };\n//\n// // Use Promise to handle async logger without awaiting\n// Promise.resolve()\n// .then(() => {\n// this.observability.hooks.handleResponse(progressiveData);\n// })\n// .catch((error) => {\n// console.error(\"Error in progressive logging:\", error);\n// });\n// } catch (error) {\n// console.error(\"Error preparing progressive log data:\", error);\n// }\n// }\n// },\n// });\n//\n// // Call the original callback with the event stream\n// await callback(eventStream$);\n// });\n// };\n// }\n//\n// return {\n// threadId: nonEmptyThreadId,\n// runId: result.runId,\n// eventSource,\n// serverSideActions,\n// actionInputsWithoutAgents: actionInputs.filter(\n// (action) =>\n// // TODO-AGENTS: do not exclude ALL server side actions\n// !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n// // !isRemoteAgentAction(\n// // serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n// // ),\n// ),\n// extensions: result.extensions,\n// };\n// } catch (error) {\n// // Log error if logging is enabled\n// if (this.observability?.enabled && publicApiKey) {\n// try {\n// const errorData: LLMErrorData = {\n// threadId,\n// runId,\n// model: forwardedParameters?.model,\n// error: error instanceof Error ? error : String(error),\n// timestamp: Date.now(),\n// latency: Date.now() - requestStartTime,\n// provider: this.detectProvider(serviceAdapter),\n// };\n//\n// await this.observability.hooks.handleError(errorData);\n// } catch (logError) {\n// console.error(\"Error logging LLM error:\", logError);\n// }\n// }\n//\n// let structuredError: CopilotKitError;\n//\n// if (error instanceof CopilotKitError) {\n// structuredError = error;\n// } else {\n// // Convert non-CopilotKitErrors to structured errors, but preserve already structured ones\n// structuredError = ensureStructuredError(error, (err) =>\n// this.convertStreamingErrorToStructured(err),\n// );\n// }\n//\n// // Track the error\n// await this.error(\n// \"error\",\n// {\n// threadId,\n// runId,\n// source: \"runtime\",\n// request: {\n// operation: \"processRuntimeRequest\",\n// method: \"POST\",\n// url: url,\n// startTime: requestStartTime,\n// },\n// response: {\n// endTime: Date.now(),\n// latency: Date.now() - requestStartTime,\n// },\n// agent: agentSession ? { name: agentSession.agentName } : undefined,\n// technical: {\n// environment: process.env.NODE_ENV,\n// stackTrace: error instanceof Error ? error.stack : undefined,\n// },\n// },\n// structuredError,\n// publicApiKey,\n// );\n//\n// throw structuredError;\n// }\n// }\n//\n// async getAllAgents(graphqlContext: GraphQLContext): Promise<(AgentWithEndpoint | Agent)[]> {\n// const agentsWithEndpoints = await this.discoverAgentsFromEndpoints(graphqlContext);\n// const aguiAgents = this.discoverAgentsFromAgui();\n//\n// this.availableAgents = [...agentsWithEndpoints, ...aguiAgents].map((a) => ({\n// name: a.name,\n// id: a.id,\n// }));\n//\n// return [...agentsWithEndpoints, ...aguiAgents];\n// }\n//\n// async discoverAgentsFromEndpoints(graphqlContext: GraphQLContext): Promise<AgentWithEndpoint[]> {\n// const agents: Promise<AgentWithEndpoint[]> = this.remoteEndpointDefinitions.reduce(\n// async (acc: Promise<Agent[]>, endpoint) => {\n// const agents = await acc;\n// if (endpoint.type === EndpointType.LangGraphPlatform) {\n// const propertyHeaders = graphqlContext.properties.authorization\n// ? { authorization: `Bearer ${graphqlContext.properties.authorization}` }\n// : null;\n//\n// const client = new LangGraphClient({\n// apiUrl: endpoint.deploymentUrl,\n// apiKey: endpoint.langsmithApiKey,\n// defaultHeaders: { ...propertyHeaders },\n// });\n// let data: Array<{ assistant_id: string; graph_id: string }> | { detail: string } = [];\n// try {\n// data = await client.assistants.search();\n//\n// if (data && \"detail\" in data && (data.detail as string).toLowerCase() === \"not found\") {\n// throw new CopilotKitAgentDiscoveryError({ availableAgents: this.availableAgents });\n// }\n// } catch (e) {\n// throw new CopilotKitMisuseError({\n// message: `\n// Failed to find or contact remote endpoint at url ${endpoint.deploymentUrl}.\n// Make sure the API is running and that it's indeed a LangGraph platform url.\n//\n// See more: https://docs.copilotkit.ai/troubleshooting/common-issues`,\n// });\n// }\n// const endpointAgents = data.map((entry) => ({\n// name: entry.graph_id,\n// id: entry.assistant_id,\n// description: \"\",\n// endpoint,\n// }));\n// return [...agents, ...endpointAgents];\n// }\n//\n// interface InfoResponse {\n// agents?: Array<{\n// name: string;\n// description: string;\n// }>;\n// }\n// const cpkEndpoint = endpoint as CopilotKitEndpoint;\n// const fetchUrl = `${endpoint.url}/info`;\n// try {\n// const response = await fetchWithRetry(fetchUrl, {\n// method: \"POST\",\n// headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),\n// body: JSON.stringify({ properties: graphqlContext.properties }),\n// });\n// if (!response.ok) {\n// if (response.status === 404) {\n// throw new CopilotKitApiDiscoveryError({ url: fetchUrl });\n// }\n// throw new ResolvedCopilotKitError({\n// status: response.status,\n// url: fetchUrl,\n// isRemoteEndpoint: true,\n// });\n// }\n//\n// const data: InfoResponse = await response.json();\n// const endpointAgents = (data?.agents ?? []).map((agent) => ({\n// name: agent.name,\n// description: agent.description ?? \"\",\n// id: randomId(), // Required by Agent type\n// endpoint,\n// }));\n// return [...agents, ...endpointAgents];\n// } catch (error) {\n// if (error instanceof CopilotKitError) {\n// throw error;\n// }\n// throw new CopilotKitLowLevelError({ error: error as Error, url: fetchUrl });\n// }\n// },\n// Promise.resolve([]),\n// );\n//\n// return agents;\n// }\n//\n// discoverAgentsFromAgui(): Agent[] {\n// return Object.entries(this.agents ?? []).map(([key, agent]: [string, AbstractAgent]) => ({\n// name: (agent as any).agentName ?? key,\n// id: agent.agentId ?? key,\n// description: agent.description ?? \"\",\n// }));\n// }\n//\n// async loadAgentState(\n// graphqlContext: GraphQLContext,\n// threadId: string,\n// agentName: string,\n// ): Promise<LoadAgentStateResponse> {\n// const agents = await this.getAllAgents(graphqlContext);\n//\n// const agent = agents.find((agent) => agent.name === agentName);\n// if (!agent) {\n// throw new Error(\"Agent not found\");\n// }\n//\n// if (\n// \"endpoint\" in agent &&\n// (agent.endpoint.type === EndpointType.CopilotKit || !(\"type\" in agent.endpoint))\n// ) {\n// const cpkEndpoint = agent.endpoint as CopilotKitEndpoint;\n// const fetchUrl = `${cpkEndpoint.url}/agents/state`;\n// try {\n// const response = await fetchWithRetry(fetchUrl, {\n// method: \"POST\",\n// headers: createHeaders(cpkEndpoint.onBeforeRequest, graphqlContext),\n// body: JSON.stringify({\n// properties: graphqlContext.properties,\n// threadId,\n// name: agentName,\n// }),\n// });\n// if (!response.ok) {\n// if (response.status === 404) {\n// throw new CopilotKitApiDiscoveryError({ url: fetchUrl });\n// }\n//\n// // Extract semantic error information from response body\n// let errorMessage = `HTTP ${response.status} error`;\n// try {\n// const errorBody = await response.text();\n// const parsedError = JSON.parse(errorBody);\n// if (parsedError.error && typeof parsedError.error === \"string\") {\n// errorMessage = parsedError.error;\n// }\n// } catch {\n// // If parsing fails, fall back to generic message\n// }\n//\n// throw new ResolvedCopilotKitError({\n// status: response.status,\n// url: fetchUrl,\n// isRemoteEndpoint: true,\n// message: errorMessage,\n// });\n// }\n//\n// const data: LoadAgentStateResponse = await response.json();\n//\n// return {\n// ...data,\n// state: JSON.stringify(data.state),\n// messages: JSON.stringify(data.messages),\n// };\n// } catch (error) {\n// if (error instanceof CopilotKitError) {\n// throw error;\n// }\n// throw new CopilotKitLowLevelError({ error, url: fetchUrl });\n// }\n// }\n//\n// const propertyHeaders = graphqlContext.properties.authorization\n// ? { authorization: `Bearer ${graphqlContext.properties.authorization}` }\n// : null;\n//\n// let state: any = {};\n// try {\n// let client: LangGraphClient | null;\n// if (\"endpoint\" in agent && agent.endpoint.type === EndpointType.LangGraphPlatform) {\n// client = new LangGraphClient({\n// apiUrl: agent.endpoint.deploymentUrl,\n// apiKey: agent.endpoint.langsmithApiKey,\n// defaultHeaders: { ...propertyHeaders },\n// });\n// } else {\n// // @ts-ignore\n// const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent;\n// if (!aguiAgent) {\n// throw new Error(`Agent: ${agent.name} could not be resolved`);\n// }\n// // @ts-expect-error -- both clients are the same\n// client = aguiAgent.client ?? null;\n// }\n//\n// state = client ? ((await client.threads.getState(threadId)).values as any) : {};\n// } catch (error) {\n// // All errors from agent state loading are user configuration issues\n// const errorMessage = error instanceof Error ? error.message : String(error);\n// const errorStatus = error?.response?.status || error?.status;\n//\n// if (errorStatus === 404) {\n// state = {};\n// } else {\n// // Log user configuration errors at debug level to reduce noise\n// console.debug(`Agent '${agentName}' configuration issue: ${errorMessage}`);\n//\n// // Throw a configuration error - all agent state loading failures are user setup issues\n// throw new ResolvedCopilotKitError({\n// status: 400,\n// message: `Agent '${agentName}' failed to execute: ${errorMessage}`,\n// code: CopilotKitErrorCode.CONFIGURATION_ERROR,\n// });\n// }\n// }\n//\n// if (Object.keys(state).length === 0) {\n// return {\n// threadId: threadId || \"\",\n// threadExists: false,\n// state: JSON.stringify({}),\n// messages: JSON.stringify([]),\n// };\n// } else {\n// const { messages, ...stateWithoutMessages } = state;\n// const copilotkitMessages = langchainMessagesToCopilotKit(messages);\n// return {\n// threadId: threadId || \"\",\n// threadExists: true,\n// state: JSON.stringify(stateWithoutMessages),\n// messages: JSON.stringify(copilotkitMessages),\n// };\n// }\n//\n// throw new Error(`Agent: ${agent.name} could not be resolved`);\n// }\n//\n// private async processAgentRequest(\n// request: CopilotRuntimeRequest,\n// ): Promise<CopilotRuntimeResponse> {\n// const {\n// messages: rawMessages,\n// outputMessagesPromise,\n// graphqlContext,\n// agentSession,\n// threadId: threadIdFromRequest,\n// metaEvents,\n// publicApiKey,\n// forwardedParameters,\n// context,\n// } = request;\n// const { agentName, nodeName } = agentSession;\n//\n// // Track request start time for observability\n// const requestStartTime = Date.now();\n// // For storing streamed chunks if progressive logging is enabled\n// const streamedChunks: any[] = [];\n//\n// // for backwards compatibility, deal with the case when no threadId is provided\n// const threadId = threadIdFromRequest ?? agentSession.threadId;\n//\n// // Track agent request start\n// await this.error(\n// \"agent_state\",\n// {\n// threadId,\n// source: \"agent\",\n// request: {\n// operation: \"processAgentRequest\",\n// method: \"POST\",\n// startTime: requestStartTime,\n// },\n// agent: {\n// name: agentName,\n// nodeName: nodeName,\n// },\n// messages: {\n// input: rawMessages,\n// messageCount: rawMessages.length,\n// },\n// technical: {\n// environment: process.env.NODE_ENV,\n// },\n// },\n// undefined,\n// publicApiKey,\n// );\n//\n// const serverSideActions = await this.getServerSideActions(request);\n//\n// const messages = convertGqlInputToMessages(rawMessages);\n//\n// const currentAgent = serverSideActions.find(\n// (action) => action.name === agentName && isRemoteAgentAction(action),\n// ) as RemoteAgentAction;\n//\n// if (!currentAgent) {\n// throw new CopilotKitAgentDiscoveryError({ agentName, availableAgents: this.availableAgents });\n// }\n//\n// // Filter actions to include:\n// // 1. Regular (non-agent) actions\n// // 2. Other agents' actions (but prevent self-calls to avoid infinite loops)\n// const availableActionsForCurrentAgent: ActionInput[] = serverSideActions\n// .filter(\n// (action) =>\n// // Case 1: Keep all regular (non-agent) actions\n// !isRemoteAgentAction(action) ||\n// // Case 2: For agent actions, keep all except self (prevent infinite loops)\n// (isRemoteAgentAction(action) && action.name !== agentName) /* prevent self-calls */,\n// )\n// .map((action) => ({\n// name: action.name,\n// description: action.description,\n// jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n// }));\n//\n// const allAvailableActions = flattenToolCallsNoDuplicates([\n// ...availableActionsForCurrentAgent,\n// ...request.actions,\n// ]);\n//\n// // Log agent request if observability is enabled\n// if (this.observability?.enabled && publicApiKey) {\n// try {\n// const requestData: LLMRequestData = {\n// threadId,\n// runId: undefined,\n// model: forwardedParameters?.model,\n// messages,\n// actions: allAvailableActions,\n// forwardedParameters,\n// timestamp: requestStartTime,\n// provider: \"agent\",\n// agentName, // Add agent-specific context\n// nodeName,\n// };\n//\n// await this.observability.hooks.handleRequest(requestData);\n// } catch (error) {\n// console.error(\"Error logging agent request:\", error);\n// }\n// }\n//\n// await this.onBeforeRequest?.({\n// threadId,\n// runId: undefined,\n// inputMessages: messages,\n// properties: graphqlContext.properties,\n// });\n//\n// try {\n// const eventSource = new RuntimeEventSource({\n// errorHandler: async (error, context) => {\n// await this.error(\"error\", context, error, publicApiKey);\n// },\n// errorContext: {\n// threadId,\n// source: \"agent\",\n// request: {\n// operation: \"processAgentRequest\",\n// method: \"POST\",\n// startTime: requestStartTime,\n// },\n// agent: {\n// name: agentName,\n// nodeName: nodeName,\n// },\n// technical: {\n// environment: process.env.NODE_ENV,\n// },\n// },\n// });\n// const stream = await currentAgent.remoteAgentHandler({\n// name: agentName,\n// threadId,\n// nodeName,\n// metaEvents,\n// actionInputsWithoutAgents: allAvailableActions,\n// });\n//\n// // Add progressive observability if enabled\n// if (this.observability?.enabled && this.observability.progressive && publicApiKey) {\n// // Wrap the stream function to intercept events for observability without changing core logic\n// const originalStream = eventSource.stream.bind(eventSource);\n//\n// eventSource.stream = async (callback) => {\n// await originalStream(async (eventStream$) => {\n// // Create subscription to capture streaming events\n// eventStream$.subscribe({\n// next: (event) => {\n// // Only log content chunks\n// if (event.type === RuntimeEventTypes.TextMessageContent) {\n// // Store the chunk\n// streamedChunks.push(event.content);\n//\n// // Log each chunk separately for progressive mode\n// try {\n// const progressiveData: LLMResponseData = {\n// threadId: threadId || \"\",\n// runId: undefined,\n// model: forwardedParameters?.model,\n// output: event.content,\n// latency: Date.now() - requestStartTime,\n// timestamp: Date.now(),\n// provider: \"agent\",\n// isProgressiveChunk: true,\n// agentName,\n// nodeName,\n// };\n//\n// // Use Promise to handle async logger without awaiting\n// Promise.resolve()\n// .then(() => {\n// this.observability.hooks.handleResponse(progressiveData);\n// })\n// .catch((error) => {\n// console.error(\"Error in progressive agent logging:\", error);\n// });\n// } catch (error) {\n// console.error(\"Error preparing progressive agent log data:\", error);\n// }\n// }\n// },\n// });\n//\n// // Call the original callback with the event stream\n// await callback(eventStream$);\n// });\n// };\n// }\n//\n// eventSource.stream(async (eventStream$) => {\n// from(stream).subscribe({\n// next: (event) => eventStream$.next(event),\n// error: async (err) => {\n// // Log error with observability if enabled\n// if (this.observability?.enabled && publicApiKey) {\n// try {\n// const errorData: LLMErrorData = {\n// threadId,\n// runId: undefined,\n// model: forwardedParameters?.model,\n// error: err instanceof Error ? err : String(err),\n// timestamp: Date.now(),\n// latency: Date.now() - requestStartTime,\n// provider: \"agent\",\n// agentName,\n// nodeName,\n// };\n//\n// this.observability.hooks.handleError(errorData);\n// } catch (logError) {\n// console.error(\"Error logging agent error:\", logError);\n// }\n// }\n//\n// // Preserve structured CopilotKit errors, only convert unstructured errors\n// const structuredError = ensureStructuredError(err, (error) =>\n// this.convertStreamingErrorToStructured(error),\n// );\n//\n// // Track streaming errors\n// await this.error(\n// \"error\",\n// {\n// threadId,\n// source: \"agent\",\n// request: {\n// operation: \"processAgentRequest\",\n// method: \"POST\",\n// startTime: requestStartTime,\n// },\n// response: {\n// endTime: Date.now(),\n// latency: Date.now() - requestStartTime,\n// },\n// agent: {\n// name: agentName,\n// nodeName: nodeName,\n// },\n// technical: {\n// environment: process.env.NODE_ENV,\n// stackTrace: err instanceof Error ? err.stack : undefined,\n// },\n// },\n// structuredError,\n// publicApiKey,\n// );\n//\n// eventStream$.error(structuredError);\n// eventStream$.complete();\n// },\n// complete: () => eventStream$.complete(),\n// });\n// });\n//\n// // Log final agent response when outputs are available\n// if (this.observability?.enabled && publicApiKey) {\n// outputMessagesPromise\n// .then((outputMessages) => {\n// const responseData: LLMResponseData = {\n// threadId,\n// runId: undefined,\n// model: forwardedParameters?.model,\n// // Use collected chunks for progressive mode or outputMessages for regular mode\n// output: this.observability.progressive ? streamedChunks : outputMessages,\n// latency: Date.now() - requestStartTime,\n// timestamp: Date.now(),\n// provider: \"agent\",\n// isFinalResponse: true,\n// agentName,\n// nodeName,\n// };\n//\n// try {\n// this.observability.hooks.handleResponse(responseData);\n// } catch (logError) {\n// console.error(\"Error logging agent response:\", logError);\n// }\n// })\n// .catch((error) => {\n// console.error(\"Failed to get output messages for agent logging:\", error);\n// });\n// }\n//\n// outputMessagesPromise\n// .then((outputMessages) => {\n// this.onAfterRequest?.({\n// threadId,\n// runId: undefined,\n// inputMessages: messages,\n// outputMessages,\n// properties: graphqlContext.properties,\n// });\n// })\n// .catch((_error) => {});\n//\n// return {\n// threadId,\n// runId: undefined,\n// eventSource,\n// serverSideActions,\n// actionInputsWithoutAgents: allAvailableActions,\n// };\n// } catch (error) {\n// // Log error with observability if enabled\n// if (this.observability?.enabled && publicApiKey) {\n// try {\n// const errorData: LLMErrorData = {\n// threadId,\n// runId: undefined,\n// model: forwardedParameters?.model,\n// error: error instanceof Error ? error : String(error),\n// timestamp: Date.now(),\n// latency: Date.now() - requestStartTime,\n// provider: \"agent\",\n// agentName,\n// nodeName,\n// };\n//\n// await this.observability.hooks.handleError(errorData);\n// } catch (logError) {\n// console.error(\"Error logging agent error:\", logError);\n// }\n// }\n//\n// // Ensure error is structured\n// const structuredError = ensureStructuredError(error, (err) =>\n// this.convertStreamingErrorToStructured(err),\n// );\n//\n// // Track the agent error\n// await this.error(\n// \"error\",\n// {\n// threadId,\n// source: \"agent\",\n// request: {\n// operation: \"processAgentRequest\",\n// method: \"POST\",\n// startTime: requestStartTime,\n// },\n// response: {\n// endTime: Date.now(),\n// latency: Date.now() - requestStartTime,\n// },\n// agent: {\n// name: agentName,\n// nodeName: nodeName,\n// },\n// technical: {\n// environment: process.env.NODE_ENV,\n// stackTrace: error instanceof Error ? error.stack : undefined,\n// },\n// },\n// structuredError,\n// publicApiKey,\n// );\n//\n// console.error(\"Error getting response:\", error);\n// throw structuredError;\n// }\n// }\n//\n// private async getServerSideActions(request: CopilotRuntimeRequest): Promise<Action<any>[]> {\n// const { graphqlContext, messages: rawMessages, agentStates, url } = request;\n//\n// // --- Standard Action Fetching (unchanged) ---\n// const inputMessages = convertGqlInputToMessages(rawMessages);\n// const langserveFunctions: Action<any>[] = [];\n// for (const chainPromise of this.langserve) {\n// try {\n// const chain = await chainPromise;\n// langserveFunctions.push(chain);\n// } catch (error) {\n// console.error(\"Error loading langserve chain:\", error);\n// }\n// }\n//\n// const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map(\n// (endpoint) => ({ ...endpoint, type: resolveEndpointType(endpoint) }) as EndpointDefinition,\n// );\n//\n// const remoteActions = await setupRemoteActions({\n// remoteEndpointDefinitions,\n// graphqlContext,\n// messages: inputMessages,\n// agentStates,\n// frontendUrl: url,\n// agents: this.agents,\n// metaEvents: request.metaEvents,\n// nodeName: request.agentSession?.nodeName,\n// context: request.context,\n// });\n//\n// const configuredActions =\n// typeof this.actions === \"function\"\n// ? this.actions({ properties: graphqlContext.properties, url })\n// : this.actions;\n// // --- Standard Action Fetching (unchanged) ---\n//\n// // +++ Dynamic MCP Action Fetching +++\n// const requestSpecificMCPActions: Action<any>[] = [];\n// if (this.createMCPClientImpl) {\n// // 1. Determine effective MCP endpoints for this request\n// const baseEndpoints = this.mcpServersConfig || [];\n// // Assuming frontend passes config via properties.mcpServers\n// const requestEndpoints = (graphqlContext.properties?.mcpServers ||\n// graphqlContext.properties?.mcpEndpoints ||\n// []) as MCPEndpointConfig[];\n//\n// // Merge and deduplicate endpoints based on URL\n// const effectiveEndpointsMap = new Map<string, MCPEndpointConfig>();\n//\n// // First add base endpoints (from runtime configuration)\n// [...baseEndpoints].forEach((ep) => {\n// if (ep && ep.endpoint) {\n// effectiveEndpointsMap.set(ep.endpoint, ep);\n// }\n// });\n//\n// // Then add request endpoints (from frontend), which will override duplicates\n// [...requestEndpoints].forEach((ep) => {\n// if (ep && ep.endpoint) {\n// effectiveEndpointsMap.set(ep.endpoint, ep);\n// }\n// });\n//\n// const effectiveEndpoints = Array.from(effectiveEndpointsMap.values());\n//\n// // 2. Fetch/Cache actions for effective endpoints\n// for (const config of effectiveEndpoints) {\n// const endpointUrl = config.endpoint;\n// let actionsForEndpoint: Action<any>[] | undefined = this.mcpActionCache.get(endpointUrl);\n//\n// if (!actionsForEndpoint) {\n// // Not cached, fetch now\n// let client: MCPClient | null = null;\n// try {\n// client = await this.createMCPClientImpl(config);\n// const tools = await client.tools();\n// actionsForEndpoint = convertMCPToolsToActions(tools, endpointUrl);\n// this.mcpActionCache.set(endpointUrl, actionsForEndpoint); // Store in cache\n// } catch (error) {\n// console.error(\n// `MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`,\n// error,\n// );\n// actionsForEndpoint = []; // Assign empty array on error to prevent re-fetching constantly\n// this.mcpActionCache.set(endpointUrl, actionsForEndpoint); // Cache the failure (empty array)\n// }\n// }\n// requestSpecificMCPActions.push(...(actionsForEndpoint || []));\n// }\n// }\n// // --- Dynamic MCP Action Fetching ---\n//\n// // Combine all action sources, including the dynamically fetched MCP actions\n// return [\n// ...configuredActions,\n// ...langserveFunctions,\n// ...remoteActions,\n// ...requestSpecificMCPActions,\n// ];\n// }\n//\n// // Add helper method to detect provider\n// private detectProvider(serviceAdapter: CopilotServiceAdapter): string | undefined {\n// const adapterName = serviceAdapter.constructor.name;\n// if (adapterName.includes(\"OpenAI\")) return \"openai\";\n// if (adapterName.includes(\"Anthropic\")) return \"anthropic\";\n// if (adapterName.includes(\"Google\")) return \"google\";\n// if (adapterName.includes(\"Groq\")) return \"groq\";\n// if (adapterName.includes(\"LangChain\")) return \"langchain\";\n// return undefined;\n// }\n//\n// private convertStreamingErrorToStructured(error: any): CopilotKitError {\n// // Determine a more helpful error message based on context\n// let helpfulMessage = generateHelpfulErrorMessage(error, \"agent streaming connection\");\n//\n// // For network-related errors, use CopilotKitLowLevelError to preserve the original error\n// if (\n// error?.message?.includes(\"fetch failed\") ||\n// error?.message?.includes(\"ECONNREFUSED\") ||\n// error?.message?.includes(\"ENOTFOUND\") ||\n// error?.message?.includes(\"ETIMEDOUT\") ||\n// error?.message?.includes(\"terminated\") ||\n// error?.cause?.code === \"UND_ERR_SOCKET\" ||\n// error?.message?.includes(\"other side closed\") ||\n// error?.code === \"UND_ERR_SOCKET\"\n// ) {\n// return new CopilotKitLowLevelError({\n// error: error instanceof Error ? error : new Error(String(error)),\n// url: \"agent streaming connection\",\n// message: helpfulMessage,\n// });\n// }\n//\n// // For all other errors, preserve the raw error in a basic CopilotKitError\n// return new CopilotKitError({\n// message: helpfulMessage,\n// code: CopilotKitErrorCode.UNKNOWN,\n// });\n// }\n//\n// private async error(\n// type: CopilotErrorEvent[\"type\"],\n// context: CopilotRequestContext,\n// error?: any,\n// publicApiKey?: string,\n// ): Promise<void> {\n// if (!this.onError) return;\n//\n// // Just check if publicApiKey is defined (regardless of validity)\n// if (!publicApiKey) {\n// if (!this.hasWarnedAboutError) {\n// console.warn(\n// \"CopilotKit: onError handler provided but requires publicApiKey to be defined for error handling to work.\",\n// );\n// this.hasWarnedAboutError = true;\n// }\n// return;\n// }\n//\n// try {\n// const errorEvent: CopilotErrorEvent = {\n// type,\n// timestamp: Date.now(),\n// context,\n// ...(error && { error }),\n// };\n//\n// await this.onError(errorEvent);\n// } catch (errorHandlerError) {\n// // Don't let error handler errors break the main flow\n// console.error(\"Error in onError handler:\", errorHandlerError);\n// }\n// }\n//\n// /**\n// * Public method to handle GraphQL validation errors\n// * This allows the GraphQL resolver to send validation errors through the error system\n// */\n// public async errorGraphQLError(\n// error: { message: string; code: string; type: string },\n// context: {\n// operation: string;\n// cloudConfigPresent: boolean;\n// guardrailsEnabled: boolean;\n// },\n// ): Promise<void> {\n// if (!this.onError) return;\n//\n// try {\n// await this.onError({\n// type: \"error\",\n// timestamp: Date.now(),\n// context: {\n// source: \"runtime\",\n// request: {\n// operation: context.operation,\n// startTime: Date.now(),\n// },\n// technical: {\n// environment: process.env.NODE_ENV,\n// },\n// metadata: {\n// errorType: \"GraphQLValidationError\",\n// cloudConfigPresent: context.cloudConfigPresent,\n// guardrailsEnabled: context.guardrailsEnabled,\n// },\n// },\n// error,\n// });\n// } catch (errorHandlerError) {\n// // Don't let error handler errors break the main flow\n// console.error(\"Error in onError handler:\", errorHandlerError);\n// }\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(config: Omit<CopilotKitEndpoint, \"type\">): 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","import { GraphQLContext } from \"../integrations\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { Message } from \"../../graphql/types/converted\";\nimport { MetaEventInput } from \"../../graphql/inputs/meta-event.input\";\n\nexport interface BaseEndpointDefinition<TActionType extends EndpointType> {\n type?: TActionType;\n}\n\nexport interface CopilotKitEndpoint extends BaseEndpointDefinition<EndpointType.CopilotKit> {\n url: string;\n onBeforeRequest?: ({ ctx }: { ctx: GraphQLContext }) => {\n headers?: Record<string, string> | undefined;\n };\n}\n\nexport interface LangGraphPlatformAgent {\n name: string;\n description: string;\n assistantId?: string;\n}\n\nexport interface LangGraphPlatformEndpoint\n extends BaseEndpointDefinition<EndpointType.LangGraphPlatform> {\n deploymentUrl: string;\n langsmithApiKey?: string | null;\n agents: LangGraphPlatformAgent[];\n}\n\nexport type RemoteActionInfoResponse = {\n actions: any[];\n agents: any[];\n};\n\nexport type RemoteAgentHandlerParams = {\n name: string;\n actionInputsWithoutAgents: ActionInput[];\n threadId?: string;\n nodeName?: string;\n additionalMessages?: Message[];\n metaEvents?: MetaEventInput[];\n};\n\nexport type EndpointDefinition = CopilotKitEndpoint | LangGraphPlatformEndpoint;\n\nexport enum EndpointType {\n CopilotKit = \"copilotKit\",\n LangGraphPlatform = \"langgraph-platform\",\n}\n","import { Action, Parameter } from \"@copilotkit/shared\";\n\n/**\n * Represents a tool provided by an MCP server.\n */\nexport interface MCPTool {\n description?: string;\n /** Schema defining parameters, mirroring the MCP structure. */\n schema?: {\n parameters?: {\n properties?: Record<string, any>;\n required?: string[];\n jsonSchema?: Record<string, any>;\n };\n };\n /** The function to call to execute the tool on the MCP server. */\n execute(params: any): Promise<any>;\n}\n\n/**\n * Defines the contract for *any* MCP client implementation the user might provide.\n */\nexport interface MCPClient {\n /** A method that returns a map of tool names to MCPTool objects available from the connected MCP server. */\n tools(): Promise<Record<string, MCPTool>>;\n /** An optional method for cleanup if the underlying client requires explicit disconnection. */\n close?(): Promise<void>;\n}\n\n/**\n * Configuration for connecting to an MCP endpoint.\n */\nexport interface MCPEndpointConfig {\n endpoint: string;\n apiKey?: string;\n}\n\n/**\n * Extracts CopilotKit-compatible parameters from an MCP tool schema.\n * @param toolOrSchema The schema object from an MCPTool or the full MCPTool object.\n * @returns An array of Parameter objects.\n */\nexport function extractParametersFromSchema(\n toolOrSchema?: MCPTool | MCPTool[\"schema\"],\n): Parameter[] {\n const parameters: Parameter[] = [];\n\n // Handle either full tool object or just schema\n const schema =\n \"schema\" in (toolOrSchema || {})\n ? (toolOrSchema as MCPTool).schema\n : (toolOrSchema as MCPTool[\"schema\"]);\n\n const toolParameters = schema?.parameters?.jsonSchema || schema?.parameters;\n const properties = toolParameters?.properties;\n const requiredParams = new Set(toolParameters?.required || []);\n\n if (!properties) {\n return parameters;\n }\n\n for (const paramName in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, paramName)) {\n const paramDef = properties[paramName];\n\n // Enhanced type extraction with support for complex types\n let type = paramDef.type || \"string\";\n let description = paramDef.description || \"\";\n\n // Handle arrays with items\n if (type === \"array\" && paramDef.items) {\n const itemType = paramDef.items.type || \"object\";\n if (itemType === \"object\" && paramDef.items.properties) {\n // For arrays of objects, describe the structure\n const itemProperties = Object.keys(paramDef.items.properties).join(\", \");\n description =\n description +\n (description ? \" \" : \"\") +\n `Array of objects with properties: ${itemProperties}`;\n } else {\n // For arrays of primitives\n type = `array<${itemType}>`;\n }\n }\n\n // Handle enums\n if (paramDef.enum && Array.isArray(paramDef.enum)) {\n const enumValues = paramDef.enum.join(\" | \");\n description = description + (description ? \" \" : \"\") + `Allowed values: ${enumValues}`;\n }\n\n // Handle objects with properties\n if (type === \"object\" && paramDef.properties) {\n const objectProperties = Object.keys(paramDef.properties).join(\", \");\n description =\n description + (description ? \" \" : \"\") + `Object with properties: ${objectProperties}`;\n }\n\n parameters.push({\n name: paramName,\n type: type,\n description: description,\n required: requiredParams.has(paramName),\n });\n }\n }\n\n return parameters;\n}\n\n/**\n * Converts a map of MCPTools into an array of CopilotKit Actions.\n * @param mcpTools A record mapping tool names to MCPTool objects.\n * @param mcpEndpoint The endpoint URL from which these tools were fetched.\n * @returns An array of Action<any> objects.\n */\nexport function convertMCPToolsToActions(\n mcpTools: Record<string, MCPTool>,\n mcpEndpoint: string,\n): Action<any>[] {\n const actions: Action<any>[] = [];\n\n for (const [toolName, tool] of Object.entries(mcpTools)) {\n const parameters = extractParametersFromSchema(tool);\n\n const handler = async (params: any): Promise<any> => {\n try {\n const result = await tool.execute(params);\n // Ensure the result is a string or stringify it, as required by many LLMs.\n // This might need adjustment depending on how different LLMs handle tool results.\n return typeof result === \"string\" ? result : JSON.stringify(result);\n } catch (error) {\n console.error(\n `Error executing MCP tool '${toolName}' from endpoint ${mcpEndpoint}:`,\n error,\n );\n // Re-throw or format the error for the LLM\n throw new Error(\n `Execution failed for MCP tool '${toolName}': ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n };\n\n actions.push({\n name: toolName,\n description: tool.description || `MCP tool: ${toolName} (from ${mcpEndpoint})`,\n parameters: parameters,\n handler: handler,\n // Add metadata for easier identification/debugging\n _isMCPTool: true,\n _mcpEndpoint: mcpEndpoint,\n } as Action<any> & { _isMCPTool: boolean; _mcpEndpoint: string }); // Type assertion for metadata\n }\n\n return actions;\n}\n\n/**\n * Generate better instructions for using MCP tools\n * This is used to enhance the system prompt with tool documentation\n */\nexport function generateMcpToolInstructions(toolsMap: Record<string, MCPTool>): string {\n if (!toolsMap || Object.keys(toolsMap).length === 0) {\n return \"\";\n }\n\n const toolEntries = Object.entries(toolsMap);\n\n // Generate documentation for each tool\n const toolsDoc = toolEntries\n .map(([name, tool]) => {\n // Extract schema information if available\n let paramsDoc = \" No parameters required\";\n\n try {\n if (tool.schema && typeof tool.schema === \"object\") {\n const schema = tool.schema as any;\n\n // Extract parameters from JSON Schema - check both schema.parameters.properties and schema.properties\n const toolParameters = schema.parameters?.jsonSchema || schema.parameters;\n const properties = toolParameters?.properties || schema.properties;\n const requiredParams = toolParameters?.required || schema.required || [];\n\n if (properties) {\n // Build parameter documentation from properties with enhanced type information\n const paramsList = Object.entries(properties).map(([paramName, propSchema]) => {\n const propDetails = propSchema as any;\n const requiredMark = requiredParams.includes(paramName) ? \"*\" : \"\";\n let typeInfo = propDetails.type || \"any\";\n let description = propDetails.description ? ` - ${propDetails.description}` : \"\";\n\n // Enhanced type display for complex schemas\n if (typeInfo === \"array\" && propDetails.items) {\n const itemType = propDetails.items.type || \"object\";\n if (itemType === \"object\" && propDetails.items.properties) {\n const itemProps = Object.keys(propDetails.items.properties).join(\", \");\n typeInfo = `array<object>`;\n description =\n description +\n (description ? \" \" : \" - \") +\n `Array of objects with properties: ${itemProps}`;\n } else {\n typeInfo = `array<${itemType}>`;\n }\n }\n\n // Handle enums\n if (propDetails.enum && Array.isArray(propDetails.enum)) {\n const enumValues = propDetails.enum.join(\" | \");\n description =\n description + (description ? \" \" : \" - \") + `Allowed values: ${enumValues}`;\n }\n\n // Handle objects\n if (typeInfo === \"object\" && propDetails.properties) {\n const objectProps = Object.keys(propDetails.properties).join(\", \");\n description =\n description +\n (description ? \" \" : \" - \") +\n `Object with properties: ${objectProps}`;\n }\n\n return ` - ${paramName}${requiredMark} (${typeInfo})${description}`;\n });\n\n if (paramsList.length > 0) {\n paramsDoc = paramsList.join(\"\\n\");\n }\n }\n }\n } catch (e) {\n console.error(`Error parsing schema for tool ${name}:`, e);\n }\n\n return `- ${name}: ${tool.description || \"\"}\n${paramsDoc}`;\n })\n .join(\"\\n\\n\");\n\n return `You have access to the following external tools provided by Model Context Protocol (MCP) servers:\n\n${toolsDoc}\n\nWhen using these tools:\n1. Only provide valid parameters according to their type requirements\n2. Required parameters are marked with *\n3. For array parameters, provide data in the correct array format\n4. For object parameters, include all required nested properties\n5. For enum parameters, use only the allowed values listed\n6. Format API calls correctly with the expected parameter structure\n7. Always check tool responses to determine your next action`;\n}\n","import {\n RunAgentInput,\n EventType,\n CustomEvent,\n TextMessageStartEvent,\n TextMessageContentEvent,\n TextMessageEndEvent,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n} from \"@ag-ui/client\";\nimport { map } from \"rxjs\";\nimport { LangGraphEventTypes } from \"../../../agents/langgraph/events\";\nimport { RawEvent } from \"@ag-ui/core\";\nimport {\n LangGraphAgent as AGUILangGraphAgent,\n LangGraphHttpAgent,\n type LangGraphAgentConfig,\n ProcessedEvents,\n SchemaKeys,\n type State,\n StateEnrichment,\n} from \"@ag-ui/langgraph\";\nimport { Message as LangGraphMessage } from \"@langchain/langgraph-sdk/dist/types.messages\";\nimport { ThreadState } from \"@langchain/langgraph-sdk\";\n\ninterface CopilotKitStateEnrichment {\n copilotkit: {\n actions: StateEnrichment[\"ag-ui\"][\"tools\"];\n context: StateEnrichment[\"ag-ui\"][\"context\"];\n };\n}\n\nexport interface PredictStateTool {\n tool: string;\n state_key: string;\n tool_argument: string;\n}\n\nexport type TextMessageEvents =\n | TextMessageStartEvent\n | TextMessageContentEvent\n | TextMessageEndEvent;\n\nexport type ToolCallEvents = ToolCallStartEvent | ToolCallArgsEvent | ToolCallEndEvent;\n\nexport enum CustomEventNames {\n CopilotKitManuallyEmitMessage = \"copilotkit_manually_emit_message\",\n CopilotKitManuallyEmitToolCall = \"copilotkit_manually_emit_tool_call\",\n CopilotKitManuallyEmitIntermediateState = \"copilotkit_manually_emit_intermediate_state\",\n CopilotKitExit = \"copilotkit_exit\",\n}\n\nexport class LangGraphAgent extends AGUILangGraphAgent {\n constructor(config: LangGraphAgentConfig) {\n super(config);\n }\n\n // @ts-ignore\n public clone() {\n return new LangGraphAgent(this.config);\n }\n\n dispatchEvent(event: ProcessedEvents) {\n if (event.type === EventType.CUSTOM) {\n // const event = processedEvent as unknown as CustomEvent;\n const customEvent = event as unknown as CustomEvent;\n\n if (customEvent.name === CustomEventNames.CopilotKitManuallyEmitMessage) {\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_START,\n role: \"assistant\",\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: customEvent.value.message_id,\n delta: customEvent.value.message,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TEXT_MESSAGE_END,\n messageId: customEvent.value.message_id,\n rawEvent: event,\n });\n return true;\n }\n\n if (customEvent.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {\n this.subscriber.next({\n type: EventType.TOOL_CALL_START,\n toolCallId: customEvent.value.id,\n toolCallName: customEvent.value.name,\n parentMessageId: customEvent.value.id,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: customEvent.value.id,\n delta: customEvent.value.args,\n rawEvent: event,\n });\n this.subscriber.next({\n type: EventType.TOOL_CALL_END,\n toolCallId: customEvent.value.id,\n rawEvent: event,\n });\n return true;\n }\n\n if (customEvent.name === CustomEventNames.CopilotKitManuallyEmitIntermediateState) {\n this.activeRun.manuallyEmittedState = customEvent.value;\n this.dispatchEvent({\n type: EventType.STATE_SNAPSHOT,\n snapshot: this.getStateSnapshot({\n values: this.activeRun.manuallyEmittedState,\n } as ThreadState<State>),\n rawEvent: event,\n });\n return true;\n }\n\n if (customEvent.name === CustomEventNames.CopilotKitExit) {\n this.subscriber.next({\n type: EventType.CUSTOM,\n name: \"Exit\",\n value: true,\n });\n return true;\n }\n }\n\n // Intercept all text message and tool call events and check if should disable\n const rawEvent = (event as ToolCallEvents | TextMessageEvents).rawEvent;\n if (!rawEvent) {\n this.subscriber.next(event);\n return true;\n }\n\n const isMessageEvent =\n event.type === EventType.TEXT_MESSAGE_START ||\n event.type === EventType.TEXT_MESSAGE_CONTENT ||\n event.type === EventType.TEXT_MESSAGE_END;\n const isToolEvent =\n event.type === EventType.TOOL_CALL_START ||\n event.type === EventType.TOOL_CALL_ARGS ||\n event.type === EventType.TOOL_CALL_END;\n if (\"copilotkit:emit-tool-calls\" in (rawEvent.metadata || {})) {\n if (rawEvent.metadata[\"copilotkit:emit-tool-calls\"] === false && isToolEvent) {\n return false;\n }\n }\n if (\"copilotkit:emit-messages\" in (rawEvent.metadata || {})) {\n if (rawEvent.metadata[\"copilotkit:emit-messages\"] === false && isMessageEvent) {\n return false;\n }\n }\n\n this.subscriber.next(event);\n return true;\n }\n\n // @ts-ignore\n run(input: RunAgentInput) {\n return super.run(input).pipe(\n map((processedEvent) => {\n // Turn raw event into emit state snapshot from tool call event\n if (processedEvent.type === EventType.RAW) {\n // Get the LangGraph event from the AGUI event.\n const event = (processedEvent as RawEvent).event ?? (processedEvent as RawEvent).rawEvent;\n\n const eventType = event.event;\n const toolCallData = event.data?.chunk?.tool_call_chunks?.[0];\n const toolCallUsedToPredictState = event.metadata?.[\n \"copilotkit:emit-intermediate-state\"\n ]?.some(\n (predictStateTool: PredictStateTool) => predictStateTool.tool === toolCallData?.name,\n );\n\n if (eventType === LangGraphEventTypes.OnChatModelStream && toolCallUsedToPredictState) {\n return {\n type: EventType.CUSTOM,\n name: \"PredictState\",\n value: event.metadata[\"copilotkit:emit-intermediate-state\"],\n };\n }\n }\n\n return processedEvent;\n }),\n );\n }\n\n langGraphDefaultMergeState(\n state: State,\n messages: LangGraphMessage[],\n input: RunAgentInput,\n ): State<StateEnrichment & CopilotKitStateEnrichment> {\n const aguiMergedState = super.langGraphDefaultMergeState(state, messages, input);\n const { tools: returnedTools, \"ag-ui\": agui } = aguiMergedState;\n // tolerate undefined and de-duplicate by stable key (id | name | key)\n const rawCombinedTools = [\n ...((returnedTools as any[]) ?? []),\n ...((agui?.tools as any[]) ?? []),\n ];\n const combinedTools = Array.from(\n new Map(\n rawCombinedTools.map((t: any) => [t?.id ?? t?.name ?? t?.key ?? JSON.stringify(t), t]),\n ).values(),\n );\n\n return {\n ...aguiMergedState,\n copilotkit: {\n actions: combinedTools,\n context: agui?.context ?? [],\n },\n };\n }\n\n async getSchemaKeys(): Promise<SchemaKeys> {\n const CONSTANT_KEYS = [\"copilotkit\"];\n const schemaKeys = await super.getSchemaKeys();\n return {\n config: schemaKeys.config,\n input: schemaKeys.input ? [...schemaKeys.input, ...CONSTANT_KEYS] : null,\n output: schemaKeys.output ? [...schemaKeys.output, ...CONSTANT_KEYS] : null,\n context: schemaKeys.context ? [...schemaKeys.context, ...CONSTANT_KEYS] : null,\n };\n }\n}\n\nexport { LangGraphHttpAgent };\n","import { ActionExecutionMessage, ResultMessage, TextMessage } from \"../../graphql/types/converted\";\n\nexport enum LangGraphEventTypes {\n OnChainStart = \"on_chain_start\",\n OnChainStream = \"on_chain_stream\",\n OnChainEnd = \"on_chain_end\",\n OnChatModelStart = \"on_chat_model_start\",\n OnChatModelStream = \"on_chat_model_stream\",\n OnChatModelEnd = \"on_chat_model_end\",\n OnToolStart = \"on_tool_start\",\n OnToolEnd = \"on_tool_end\",\n OnCopilotKitStateSync = \"on_copilotkit_state_sync\",\n OnCopilotKitEmitMessage = \"on_copilotkit_emit_message\",\n OnCopilotKitEmitToolCall = \"on_copilotkit_emit_tool_call\",\n OnCustomEvent = \"on_custom_event\",\n OnInterrupt = \"on_interrupt\",\n OnCopilotKitInterrupt = \"on_copilotkit_interrupt\",\n OnCopilotKitError = \"on_copilotkit_error\",\n}\n\nexport enum MetaEventNames {\n LangGraphInterruptEvent = \"LangGraphInterruptEvent\",\n CopilotKitLangGraphInterruptEvent = \"CopilotKitLangGraphInterruptEvent\",\n}\n\nexport enum CustomEventNames {\n CopilotKitManuallyEmitMessage = \"copilotkit_manually_emit_message\",\n CopilotKitManuallyEmitToolCall = \"copilotkit_manually_emit_tool_call\",\n CopilotKitManuallyEmitIntermediateState = \"copilotkit_manually_emit_intermediate_state\",\n CopilotKitExit = \"copilotkit_exit\",\n}\n\ntype LangGraphOnCopilotKitStateSyncEvent = {\n event: LangGraphEventTypes.OnCopilotKitStateSync;\n thread_id: string;\n agent_name: string;\n node_name: string;\n run_id: string;\n active: boolean;\n role: string;\n state: any;\n running: boolean;\n};\n\ntype LangGraphOnChainStartEvent = {\n event: LangGraphEventTypes.OnChainStart;\n run_id: string;\n name: string;\n tags: string[];\n metadata: { thread_id: string };\n data: {\n input: any;\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChainEndEvent = {\n event: LangGraphEventTypes.OnChainEnd;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n };\n data: {\n input: any;\n output: any;\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChatModelStartEvent = {\n event: LangGraphEventTypes.OnChatModelStart;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n ls_provider: string;\n ls_model_name: string;\n ls_model_type: string;\n ls_temperature: number;\n };\n data: {\n input: {\n messages: {\n lc: number;\n type: string;\n id: string[];\n kwargs: {\n content: string;\n type: string;\n id: string;\n };\n }[][];\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChatModelStreamEvent = {\n event: LangGraphEventTypes.OnChatModelStream;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n ls_provider: string;\n ls_model_name: string;\n ls_model_type: string;\n ls_temperature: number;\n };\n data: {\n chunk: {\n lc: number;\n type: string;\n id: string;\n kwargs: {\n content: string | { text: string; type: string; index: number }[];\n additional_kwargs: {\n tool_calls: {\n index: number;\n id: string;\n function: { arguments: string; name: string };\n type: string;\n }[];\n };\n type: string;\n id: string;\n tool_calls: { name: string; args: {}; id: string; type: string }[];\n tool_call_chunks: {\n name: string;\n args: string;\n id: string;\n index: number;\n type: string;\n }[];\n invalid_tool_calls: any[];\n };\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChatModelEndEvent = {\n event: LangGraphEventTypes.OnChatModelEnd;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n ls_provider: string;\n ls_model_name: string;\n ls_model_type: string;\n ls_temperature: number;\n };\n data: {\n input: any;\n output: {\n generations: {\n text: string;\n generation_info: {\n finish_reason: string;\n model_name: string;\n system_fingerprint: string;\n };\n type: string;\n message: {\n lc: number;\n type: string;\n id: string[];\n kwargs: {\n content: string;\n additional_kwargs: {\n tool_calls: {\n index: number;\n id: string;\n function: { arguments: string; name: string };\n type: string;\n }[];\n };\n response_metadata: {\n finish_reason: string;\n model_name: string;\n system_fingerprint: string;\n };\n type: string;\n id: string;\n tool_calls: { name: string; args: { query: string }; id: string; type: string }[];\n invalid_tool_calls: any[];\n };\n };\n }[][];\n llm_output: any;\n run: any;\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnChainStreamEvent = {\n event: LangGraphEventTypes.OnChainStream;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step?: number;\n langgraph_node?: string;\n langgraph_triggers?: string[];\n langgraph_task_idx?: number;\n thread_ts?: string;\n };\n data: {\n chunk: {\n messages: {\n lc: number;\n type: string;\n id: string[];\n kwargs: {\n content: string;\n additional_kwargs?: {\n tool_calls?: {\n index: number;\n id: string;\n function: { arguments: string; name: string };\n type: string;\n }[];\n };\n response_metadata?: {\n finish_reason: string;\n model_name: string;\n system_fingerprint: string;\n };\n type: string;\n id: string;\n tool_calls?: { name: string; args: { query: string }; id: string; type: string }[];\n invalid_tool_calls?: any[];\n };\n }[];\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnToolStartEvent = {\n event: LangGraphEventTypes.OnToolStart;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n };\n data: {\n input: {\n query: string;\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnToolEndEvent = {\n event: LangGraphEventTypes.OnToolEnd;\n name: string;\n run_id: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_task_idx: number;\n thread_ts: string;\n };\n data: {\n input: {\n query: string;\n };\n output: {\n lc: number;\n type: string;\n id: string[];\n kwargs: {\n content: string[];\n type: string;\n name: string;\n tool_call_id: string;\n status: string;\n };\n };\n };\n parent_ids: string[];\n};\n\ntype LangGraphOnCustomEvent = {\n event: LangGraphEventTypes.OnCustomEvent;\n run_id: string;\n name: string;\n tags: string[];\n metadata: {\n thread_id: string;\n langgraph_step: number;\n langgraph_node: string;\n langgraph_triggers: string[];\n langgraph_path: [string, string];\n langgraph_checkpoint_ns: string;\n checkpoint_ns: string;\n };\n data: any;\n parent_ids: string[];\n};\n\ninterface LangGraphInterruptEvent {\n event: LangGraphEventTypes.OnInterrupt;\n value: string;\n}\n\ninterface CopilotKitLangGraphInterruptEvent {\n event: LangGraphEventTypes.OnCopilotKitInterrupt;\n data: { value: string; messages: (TextMessage | ActionExecutionMessage | ResultMessage)[] };\n}\n\ninterface CopilotKitLangGraphErrorEvent {\n event: LangGraphEventTypes.OnCopilotKitError;\n data: {\n error: {\n message: string;\n type: string;\n agent_name: string;\n status_code?: number;\n response_data?: any;\n };\n thread_id: string;\n agent_name: string;\n node_name: string;\n };\n}\n\nexport type LangGraphEvent =\n | LangGraphOnChainStartEvent\n | LangGraphOnChainStreamEvent\n | LangGraphOnChainEndEvent\n | LangGraphOnChatModelStartEvent\n | LangGraphOnChatModelStreamEvent\n | LangGraphOnChatModelEndEvent\n | LangGraphOnToolStartEvent\n | LangGraphOnToolEndEvent\n | LangGraphOnCopilotKitStateSyncEvent\n | LangGraphOnCustomEvent\n | LangGraphInterruptEvent\n | CopilotKitLangGraphInterruptEvent\n | CopilotKitLangGraphErrorEvent;\n","import { Field, ObjectType } from \"type-graphql\";\n\n@ObjectType()\nexport class Agent {\n @Field(() => String)\n id: string;\n\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description?: string;\n}\n\n@ObjectType()\nexport class AgentsResponse {\n @Field(() => [Agent])\n agents: Agent[];\n}\n","import createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: { level?: LogLevel; component?: string }) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n","import { Arg, Resolver } from \"type-graphql\";\nimport { Ctx } from \"type-graphql\";\nimport { Query } from \"type-graphql\";\nimport { LoadAgentStateResponse } from \"../types/load-agent-state-response.type\";\nimport type { GraphQLContext } from \"../../lib/integrations\";\nimport { LoadAgentStateInput } from \"../inputs/load-agent-state.input\";\nimport { CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\nimport { CopilotRuntime } from \"../../lib\";\n\n@Resolver(() => LoadAgentStateResponse)\nexport class StateResolver {\n @Query(() => LoadAgentStateResponse)\n async loadAgentState(@Ctx() ctx: GraphQLContext, @Arg(\"data\") data: LoadAgentStateInput) {\n const agents = [];\n const hasAgent = agents.some((agent) => agent.name === data.agentName);\n if (!hasAgent) {\n throw new CopilotKitAgentDiscoveryError({\n agentName: data.agentName,\n availableAgents: agents.map((a) => ({ name: a.name, id: a.name })),\n });\n }\n\n const state = {};\n\n return state;\n }\n}\n","import { Field, ObjectType } from \"type-graphql\";\nimport { BaseMessageOutput } from \"./copilot-response.type\";\n\n@ObjectType()\nexport class LoadAgentStateResponse {\n @Field(() => String)\n threadId: string;\n\n @Field(() => Boolean)\n threadExists: boolean;\n\n @Field(() => String)\n state: string;\n\n @Field(() => String)\n messages: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class LoadAgentStateInput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,UAAY;AAAA,MACZ,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,eAAiB;AAAA,QACf,QAAU;AAAA,MACZ;AAAA,MACA,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,SAAW;AAAA,QACT,KAAK;AAAA,MACP;AAAA,MACA,OAAS;AAAA,MACT,SAAW;AAAA,MACX,SAAW;AAAA,QACT,OAAS;AAAA,QACT,KAAO;AAAA,QACP,MAAQ;AAAA,QACR,eAAe;AAAA,QACf,OAAS;AAAA,QACT,2BAA2B;AAAA,QAC3B,eAAe;AAAA,QACf,iBAAiB;AAAA,MACnB;AAAA,MACA,iBAAmB;AAAA,QACjB,iBAAiB;AAAA,QACjB,aAAa;AAAA,QACb,kBAAkB;AAAA,QAClB,eAAe;AAAA,QACf,eAAe;AAAA,QACf,uBAAuB;AAAA,QACvB,QAAU;AAAA,QACV,wBAAwB;AAAA,QACxB,MAAQ;AAAA,QACR,SAAW;AAAA,QACX,WAAW;AAAA,QACX,WAAW;AAAA,QACX,UAAY;AAAA,QACZ,MAAQ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CAAA;AAEA,OAAIN,aAAQO,eAARP,mBAAoBQ,aAAa;AACnCL,6BAAUC,oBAAoB;MAC5BI,aAAaR,QAAQO,WAAWC;IAClC,CAAA;EACF;AAEAL,2BAAUM,QAAQ,gCAAgCC,gCAAgCV,OAAAA,CAAAA;AAElF,QAAMW,UAASV,aAAaW;AAC5BD,EAAAA,QAAOE,MAAM,6BAAA;AAEb,QAAMC,iBAAiBd,QAAQc;AAC/Bd,UAAQK,QAAQU,qBAAqBD,cAAAA;AAErC,SAAOE,sBAAsB;IAC3BX,SAASL,QAAQK,QAAQY;IACzBC,UAAUlB,QAAQmB;EACpB,CAAA;AACF;AA7BgBpB;","names":["createCopilotEndpoint","buildSchemaSync","Arg","Ctx","Mutation","Query","Resolver","ReplaySubject","Subject","filter","finalize","firstValueFrom","shareReplay","skipWhile","take","takeWhile","tap","Field","InputType","Field","InputType","MessageInput","BaseMessageInput","textMessage","actionExecutionMessage","resultMessage","agentStateMessage","imageMessage","Field","TextMessageInput","nullable","ActionExecutionMessageInput","ResultMessageInput","AgentStateMessageInput","ImageMessageInput","InputType","content","parentMessageId","role","String","MessageRole","name","arguments","scope","deprecationReason","actionExecutionId","actionName","result","threadId","agentName","state","running","nodeName","runId","active","Boolean","format","bytes","Field","InputType","Field","InputType","ActionInput","name","description","jsonSchema","available","Field","String","ActionInputAvailability","nullable","InputType","FrontendInput","toDeprecate_fullContext","actions","url","Field","String","nullable","ActionInput","InputType","Field","InputType","Field","InputType","GuardrailsRuleInput","allowList","denyList","Field","String","nullable","InputType","GuardrailsInput","inputValidationRules","CloudInput","guardrails","Field","GuardrailsInput","nullable","InputType","Field","InputType","ForwardedParametersInput","model","maxTokens","stop","toolChoice","toolChoiceFunctionName","temperature","Field","String","nullable","Number","InputType","Field","InputType","AgentSessionInput","agentName","threadId","nodeName","Field","String","nullable","InputType","Field","InputType","AgentStateInput","agentName","state","config","Field","String","nullable","InputType","Field","InputType","ExtensionsInput","openaiAssistantAPI","Field","OpenAIApiAssistantAPIInput","nullable","InputType","runId","threadId","String","Field","InputType","Field","InterfaceType","ObjectType","registerEnumType","Field","InterfaceType","ObjectType","Field","ObjectType","ExtensionsResponse","openaiAssistantAPI","Field","OpenAIApiAssistantAPIResponse","nullable","ObjectType","runId","threadId","String","BaseMessageOutput","id","createdAt","status","Field","String","Date","MessageStatusUnion","InterfaceType","resolveType","value","hasOwnProperty","TextMessageOutput","ActionExecutionMessageOutput","ResultMessageOutput","AgentStateMessageOutput","ImageMessageOutput","undefined","role","content","parentMessageId","MessageRole","nullable","ObjectType","implements","name","scope","arguments","deprecationReason","actionExecutionId","actionName","result","threadId","agentName","nodeName","runId","active","state","running","Boolean","format","bytes","CopilotResponse","messages","extensions","metaEvents","ResponseStatusUnion","ExtensionsResponse","BaseMetaEvent","MetaEventName","registerEnumType","name","description","BaseMetaEvent","type","Field","String","InterfaceType","resolveType","value","LangGraphInterruptEvent","CopilotKitLangGraphInterruptEvent","undefined","CopilotKitLangGraphInterruptEventData","messages","BaseMessageOutput","ObjectType","response","nullable","implements","data","MetaEventInput","name","value","response","messages","Field","MetaEventName","String","nullable","MessageInput","InputType","Field","InputType","CopilotContextInput","description","value","Field","String","InputType","GenerateCopilotResponseMetadataInput","requestType","Field","CopilotRequestType","nullable","InputType","GenerateCopilotResponseInput","metadata","threadId","runId","messages","frontend","cloud","forwardedParameters","agentSession","agentState","agentStates","extensions","metaEvents","context","String","MessageInput","FrontendInput","CloudInput","ForwardedParametersInput","AgentSessionInput","AgentStateInput","ExtensionsInput","MetaEventInput","CopilotContextInput","Repeater","CopilotKitError","CopilotKitErrorCode","CopilotKitLowLevelError","Severity","ReplaySubject","RuntimeEventTypes","RuntimeMetaEventName","GraphQLJSONObject","plainToInstance","GraphQLError","TelemetryClient","createHash","CopilotKitMisuseError","readBody","getZodParameters","CopilotRuntime","CopilotRuntimeVNext","InMemoryAgentRunner","InMemoryAgentRunnerVNext","EndpointType","extractParametersFromSchema","toolOrSchema","parameters","schema","toolParameters","jsonSchema","properties","requiredParams","Set","required","paramName","Object","prototype","hasOwnProperty","call","paramDef","type","description","items","itemType","itemProperties","keys","join","enum","Array","isArray","enumValues","objectProperties","push","name","has","convertMCPToolsToActions","mcpTools","mcpEndpoint","actions","toolName","tool","entries","handler","params","result","execute","JSON","stringify","error","console","Error","message","String","_isMCPTool","_mcpEndpoint","generateMcpToolInstructions","toolsMap","length","toolEntries","toolsDoc","map","paramsDoc","paramsList","propSchema","propDetails","requiredMark","includes","typeInfo","itemProps","objectProps","e","EventType","map","LangGraphEventTypes","MetaEventNames","CustomEventNames","LangGraphAgent","AGUILangGraphAgent","LangGraphHttpAgent","CustomEventNames","LangGraphAgent","AGUILangGraphAgent","constructor","config","clone","dispatchEvent","event","type","EventType","CUSTOM","customEvent","name","subscriber","next","TEXT_MESSAGE_START","role","messageId","value","message_id","rawEvent","TEXT_MESSAGE_CONTENT","delta","message","TEXT_MESSAGE_END","TOOL_CALL_START","toolCallId","id","toolCallName","parentMessageId","TOOL_CALL_ARGS","args","TOOL_CALL_END","activeRun","manuallyEmittedState","STATE_SNAPSHOT","snapshot","getStateSnapshot","values","isMessageEvent","isToolEvent","metadata","run","input","pipe","map","processedEvent","RAW","eventType","toolCallData","data","chunk","tool_call_chunks","toolCallUsedToPredictState","some","predictStateTool","tool","LangGraphEventTypes","OnChatModelStream","langGraphDefaultMergeState","state","messages","aguiMergedState","tools","returnedTools","agui","rawCombinedTools","combinedTools","Array","from","Map","t","key","JSON","stringify","copilotkit","actions","context","getSchemaKeys","CONSTANT_KEYS","schemaKeys","output","BasicAgent","CopilotRuntime","params","observability","mcpToolsCache","Map","runtimeArgs","instance","constructor","agents","assignEndpointsToAgents","remoteEndpoints","runner","InMemoryAgentRunnerVNext","beforeRequestMiddleware","createOnBeforeRequestHandler","bind","afterRequestMiddleware","createOnAfterRequestHandler","observability_c","CopilotRuntimeVNext","endpoints","reduce","acc","endpoint","resolveEndpointType","EndpointType","LangGraphPlatform","lgAgents","lgEndpoint","forEach","agent","graphId","assistantId","name","LangGraphAgent","deploymentUrl","langsmithApiKey","handleServiceAdapter","serviceAdapter","isAgentsListEmpty","Object","keys","length","hasServiceAdapter","Boolean","illegalServiceAdapterNames","serviceAdapterCanBeUsedForAgent","includes","CopilotKitMisuseError","message","default","BasicAgent","model","provider","actions","mcpTools","getToolsFromMCP","assignToolsToAgents","getToolsFromActions","actionsArray","properties","url","undefined","map","action","zodSchema","getZodParameters","parameters","description","tools","enrichedAgents","agentId","entries","existingConfig","Reflect","get","existingTools","updatedConfig","set","hookParams","middleware","onBeforeRequest","request","runtime","path","body","readBody","gqlMessages","aguiToGQL","messages","msg","role","inputMessages","push","outputMessages","threadId","runId","forwardedProps","onAfterRequest","logObservabilityBeforeRequest","requestData","hooks","handleRequest","error","console","logObservabilityAfterRequest","outputMessagesPromise","baseData","streamedChunks","requestStartTime","publicApiKey","then","responseData","output","progressive","latency","Date","now","timestamp","isFinalResponse","agentName","nodeName","handleResponse","logError","catch","options","runtimeMcpServers","mcpServers","createMCPClient","requestMcpServers","mcpEndpoints","hasAnyServers","effectiveEndpoints","byUrl","ep","Array","from","values","allTools","config","endpointUrl","cached","client","toolsMap","toolDefs","toolName","tool","extractParametersFromSchema","dedupedByName","copilotKitEndpoint","type","CopilotKit","langGraphPlatformEndpoint","packageJson","require","telemetryClient","TelemetryClient","packageName","name","packageVersion","version","getRuntimeInstanceTelemetryInfo","options","runtime","remoteEndpoints","params","endpointsInfo","reduce","acc","endpoint","info","endpointType","resolveEndpointType","endpointTypes","includes","EndpointType","LangGraphPlatform","ep","agentsAmount","agents","length","hashedKey","langsmithApiKey","createHash","update","digest","publicApiKey","cloud","apiKeyProvided","trim","actionsAmount","actions","endpointsAmount","Object","keys","instance","hashedLgcKey","baseUrl","randomId","Field","ObjectType","Agent","id","name","description","Field","String","ObjectType","AgentsResponse","agents","CopilotKitError","CopilotKitLowLevelError","invokeGuardrails","baseUrl","copilotCloudPublicApiKey","data","onResult","onError","messages","length","textMessage","role","MessageRole","user","filter","m","undefined","assistant","map","content","lastMessage","restOfMessages","slice","body","input","validTopics","cloud","guardrails","inputValidationRules","allowList","invalidTopics","denyList","guardrailsResult","fetch","method","headers","JSON","stringify","ok","resultJson","json","CopilotResolver","hello","availableAgents","ctx","logger","child","component","debug","agentsWithEndpoints","agents","endpoint","agentWithoutEndpoint","generateCopilotResponse","properties","telemetry","capture","requestType","metadata","request","get","_copilotkit","copilotRuntime","runtime","serviceAdapter","copilotCloudBaseUrl","publicApiKeyFromHeaders","error","GraphQLError","process","env","COPILOT_CLOUD_BASE_URL","responseStatus$","ReplaySubject","interruptStreaming$","guardrailsResult$","outputMessages","resolveOutputMessagesPromise","rejectOutputMessagesPromise","outputMessagesPromise","Promise","resolve","reject","runtimeResponse","eventSource","threadId","randomId","runId","serverSideActions","actionInputsWithoutAgents","extensions","eventStream","processRuntimeEvents","action","find","serverSideAction","name","pipe","shareReplay","finalize","response","status","firstValueFrom","metaEvents","Repeater","push","stop","eventStreamSubscription","subscribe","next","event","type","RuntimeEventTypes","MetaEvent","LangGraphEventTypes","OnInterrupt","plainToInstance","LangGraphInterruptEvent","RuntimeMetaEventName","value","CopilotKitLangGraphInterruptEvent","message","TextMessage","id","createdAt","Date","SuccessMessageStatus","ActionExecutionMessage","arguments","Error","err","includes","visibility","UnknownErrorResponse","description","unsubscribe","complete","SuccessResponseStatus","pushMessage","stopStreamingMessages","result","GuardrailsValidationFailureResponse","guardrailsReason","reason","TextMessageStart","textMessageContentStream","skipWhile","e","takeWhile","TextMessageEnd","messageId","TextMessageContent","streamingTextStatus","Subject","parentMessageId","pushTextChunk","stopStreamingText","textChunks","textSubscription","take","tap","FailedMessageStatus","MessageStreamInterruptedResponse","join","ActionExecutionStart","actionExecutionArgumentStream","ActionExecutionEnd","actionExecutionId","ActionExecutionArgs","streamingArgumentsStatus","actionName","pushArgumentsChunk","stopStreamingArguments","argumentChunks","actionExecutionArgumentSubscription","args","ActionExecutionResult","ResultMessage","AgentStateMessage","agentName","nodeName","active","state","running","CopilotKitError","CopilotKitLowLevelError","originalError","code","statusCode","severity","originalErrorType","Query","String","AgentsResponse","Ctx","Mutation","CopilotResponse","Arg","GraphQLJSONObject","nullable","Resolver","useDeferStream","createPinoLogger","pretty","createLogger","options","level","component","stream","pretty","colorize","logger","createPinoLogger","process","env","LOG_LEVEL","redact","paths","remove","child","Arg","Resolver","Ctx","Query","Field","ObjectType","LoadAgentStateResponse","threadId","threadExists","state","messages","Field","String","Boolean","ObjectType","Field","InputType","LoadAgentStateInput","threadId","agentName","Field","String","InputType","CopilotKitAgentDiscoveryError","StateResolver","loadAgentState","ctx","data","agents","hasAgent","some","agent","name","agentName","CopilotKitAgentDiscoveryError","availableAgents","map","a","id","state","Query","LoadAgentStateResponse","Ctx","Arg","Resolver","packageJson","CopilotKitError","CopilotKitErrorCode","logger","createLogger","addCustomHeaderPlugin","onResponse","response","headers","set","version","createContext","initialContext","copilotKitContext","contextLogger","properties","debug","ctx","_copilotkit","buildSchema","options","schema","buildSchemaSync","resolvers","CopilotResolver","StateResolver","emitSchemaFile","getCommonConfig","logLevel","process","env","LOG_LEVEL","level","component","cloud","telemetry","setCloudConfiguration","publicApiKey","baseUrl","setGlobalProperties","runtime","serviceAdapter","constructor","name","userErrorCodes","CopilotKitErrorCode","AGENT_NOT_FOUND","API_NOT_FOUND","REMOTE_ENDPOINT_NOT_FOUND","CONFIGURATION_ERROR","MISSING_PUBLIC_API_KEY_ERROR","logging","plugins","useDeferStream","context","maskedErrors","maskError","error","message","isDev","originalError","extensions","errorCode","code","includes","console","CopilotKitError","copilotRuntimeNodeHttpEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","getRuntimeInstanceTelemetryInfo","logger","logging","debug","serviceAdapter","handleServiceAdapter","createCopilotEndpoint","instance","basePath","baseUrl"]}
|