@copilotkit/runtime 1.56.0 → 1.56.2-canary.pin-to-send
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/dist/agent/index.cjs +2 -2
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +2 -2
- package/dist/agent/index.mjs.map +1 -1
- package/dist/graphql/resolvers/copilot.resolver.cjs +2 -1
- package/dist/graphql/resolvers/copilot.resolver.cjs.map +1 -1
- package/dist/graphql/resolvers/copilot.resolver.mjs +2 -1
- package/dist/graphql/resolvers/copilot.resolver.mjs.map +1 -1
- package/dist/graphql/resolvers/resolve-message-id.cjs +19 -0
- package/dist/graphql/resolvers/resolve-message-id.cjs.map +1 -0
- package/dist/graphql/resolvers/resolve-message-id.mjs +18 -0
- package/dist/graphql/resolvers/resolve-message-id.mjs.map +1 -0
- package/dist/lib/integrations/node-http/index.cjs +4 -1
- package/dist/lib/integrations/node-http/index.cjs.map +1 -1
- package/dist/lib/integrations/node-http/index.d.cts.map +1 -1
- package/dist/lib/integrations/node-http/index.d.mts.map +1 -1
- package/dist/lib/integrations/node-http/index.mjs +4 -1
- package/dist/lib/integrations/node-http/index.mjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.cjs +15 -3
- package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs +15 -3
- package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
- package/dist/lib/runtime/mcp-tools-utils.cjs +21 -4
- package/dist/lib/runtime/mcp-tools-utils.cjs.map +1 -1
- package/dist/lib/runtime/mcp-tools-utils.d.cts.map +1 -1
- package/dist/lib/runtime/mcp-tools-utils.d.mts.map +1 -1
- package/dist/lib/runtime/mcp-tools-utils.mjs +21 -4
- package/dist/lib/runtime/mcp-tools-utils.mjs.map +1 -1
- package/dist/package.cjs +2 -2
- package/dist/package.mjs +2 -2
- package/dist/service-adapters/anthropic/anthropic-adapter.cjs +11 -3
- package/dist/service-adapters/anthropic/anthropic-adapter.cjs.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.d.cts +6 -0
- package/dist/service-adapters/anthropic/anthropic-adapter.d.cts.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.d.mts +6 -0
- package/dist/service-adapters/anthropic/anthropic-adapter.d.mts.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.mjs +11 -3
- package/dist/service-adapters/anthropic/anthropic-adapter.mjs.map +1 -1
- package/dist/service-adapters/anthropic/utils.cjs +27 -1
- package/dist/service-adapters/anthropic/utils.cjs.map +1 -1
- package/dist/service-adapters/anthropic/utils.mjs +27 -1
- package/dist/service-adapters/anthropic/utils.mjs.map +1 -1
- package/dist/service-adapters/langchain/utils.cjs +1 -1
- package/dist/service-adapters/langchain/utils.cjs.map +1 -1
- package/dist/service-adapters/langchain/utils.mjs +1 -1
- package/dist/service-adapters/langchain/utils.mjs.map +1 -1
- package/dist/service-adapters/openai/openai-adapter.cjs +2 -1
- package/dist/service-adapters/openai/openai-adapter.cjs.map +1 -1
- package/dist/service-adapters/openai/openai-adapter.d.cts +6 -0
- package/dist/service-adapters/openai/openai-adapter.d.cts.map +1 -1
- package/dist/service-adapters/openai/openai-adapter.d.mts +6 -0
- package/dist/service-adapters/openai/openai-adapter.d.mts.map +1 -1
- package/dist/service-adapters/openai/openai-adapter.mjs +2 -1
- package/dist/service-adapters/openai/openai-adapter.mjs.map +1 -1
- package/dist/v2/runtime/core/debug-event-bus.cjs +36 -0
- package/dist/v2/runtime/core/debug-event-bus.cjs.map +1 -0
- package/dist/v2/runtime/core/debug-event-bus.d.cts +19 -0
- package/dist/v2/runtime/core/debug-event-bus.d.cts.map +1 -0
- package/dist/v2/runtime/core/debug-event-bus.d.mts +19 -0
- package/dist/v2/runtime/core/debug-event-bus.d.mts.map +1 -0
- package/dist/v2/runtime/core/debug-event-bus.mjs +35 -0
- package/dist/v2/runtime/core/debug-event-bus.mjs.map +1 -0
- package/dist/v2/runtime/core/fetch-handler.cjs +6 -0
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +6 -0
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.cjs +1 -0
- package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.mjs +1 -0
- package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
- package/dist/v2/runtime/core/hooks.cjs.map +1 -1
- package/dist/v2/runtime/core/hooks.d.cts +2 -0
- package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
- package/dist/v2/runtime/core/hooks.d.mts +2 -0
- package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
- package/dist/v2/runtime/core/hooks.mjs.map +1 -1
- package/dist/v2/runtime/core/middleware-sse-parser.cjs +5 -2
- package/dist/v2/runtime/core/middleware-sse-parser.cjs.map +1 -1
- package/dist/v2/runtime/core/middleware-sse-parser.mjs +5 -2
- package/dist/v2/runtime/core/middleware-sse-parser.mjs.map +1 -1
- package/dist/v2/runtime/core/runtime.cjs +5 -0
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +5 -0
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +5 -0
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs +5 -0
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-connect.cjs +2 -0
- package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-connect.mjs +2 -0
- package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-debug-events.cjs +33 -0
- package/dist/v2/runtime/handlers/handle-debug-events.cjs.map +1 -0
- package/dist/v2/runtime/handlers/handle-debug-events.mjs +32 -0
- package/dist/v2/runtime/handlers/handle-debug-events.mjs.map +1 -0
- package/dist/v2/runtime/handlers/handle-run.cjs +1 -0
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +1 -0
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/connect.cjs +32 -2
- package/dist/v2/runtime/handlers/intelligence/connect.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/connect.mjs +31 -2
- package/dist/v2/runtime/handlers/intelligence/connect.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +5 -1
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +5 -1
- package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/sse-response.cjs +21 -1
- package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/sse-response.mjs +21 -1
- package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/connect.cjs +3 -1
- package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/connect.mjs +3 -1
- package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/run.cjs +3 -1
- package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/sse/run.mjs +3 -1
- package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +2 -7
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +1 -4
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +1 -4
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +2 -7
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/v2/runtime/runner/intelligence.cjs +17 -5
- package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.cts +1 -0
- package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.mts +1 -0
- package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.mjs +17 -5
- package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
- package/package.json +3 -3
- package/src/agent/__tests__/provider-id-collision.test.ts +195 -0
- package/src/agent/index.ts +19 -11
- package/src/agents/langgraph/__tests__/event-source.test.ts +256 -0
- package/src/graphql/resolvers/__tests__/resolve-message-id.test.ts +25 -0
- package/src/graphql/resolvers/copilot.resolver.ts +2 -1
- package/src/graphql/resolvers/resolve-message-id.ts +14 -0
- package/src/lib/integrations/node-http/__tests__/request-duck-type.test.ts +66 -0
- package/src/lib/integrations/node-http/index.ts +15 -1
- package/src/lib/runtime/__tests__/handle-service-adapter.test.ts +108 -0
- package/src/lib/runtime/__tests__/mcp-tools-utils.test.ts +30 -1
- package/src/lib/runtime/__tests__/on-after-request.test.ts +122 -0
- package/src/lib/runtime/__tests__/retry-utils.test.ts +137 -0
- package/src/lib/runtime/agent-integrations/langgraph/__tests__/dispatch-event-filtering.test.ts +190 -0
- package/src/lib/runtime/copilot-runtime.ts +36 -7
- package/src/lib/runtime/mcp-tools-utils.ts +41 -6
- package/src/lib/runtime/retry-utils.ts +41 -1
- package/src/service-adapters/anthropic/anthropic-adapter.ts +22 -2
- package/src/service-adapters/anthropic/utils.ts +60 -1
- package/src/service-adapters/langchain/utils.ts +1 -1
- package/src/service-adapters/openai/openai-adapter.ts +14 -1
- package/src/v2/runtime/__tests__/fetch-router.test.ts +22 -0
- package/src/v2/runtime/__tests__/handle-connect.test.ts +58 -5
- package/src/v2/runtime/__tests__/handle-run.test.ts +31 -4
- package/src/v2/runtime/__tests__/handle-threads.test.ts +66 -4
- package/src/v2/runtime/__tests__/integration/node-servers.integration.test.ts +19 -0
- package/src/v2/runtime/__tests__/integration/suites/debug-events.suite.ts +253 -0
- package/src/v2/runtime/__tests__/middleware-sse-parser.test.ts +50 -0
- package/src/v2/runtime/__tests__/runtime.test.ts +3 -1
- package/src/v2/runtime/core/__tests__/debug-event-bus.test.ts +156 -0
- package/src/v2/runtime/core/debug-event-bus.ts +45 -0
- package/src/v2/runtime/core/fetch-handler.ts +4 -0
- package/src/v2/runtime/core/fetch-router.ts +11 -0
- package/src/v2/runtime/core/hooks.ts +2 -1
- package/src/v2/runtime/core/middleware-sse-parser.ts +12 -2
- package/src/v2/runtime/core/runtime.ts +12 -0
- package/src/v2/runtime/handlers/__tests__/handle-debug-events.test.ts +176 -0
- package/src/v2/runtime/handlers/handle-connect.ts +2 -0
- package/src/v2/runtime/handlers/handle-debug-events.ts +52 -0
- package/src/v2/runtime/handlers/handle-run.ts +1 -0
- package/src/v2/runtime/handlers/intelligence/connect.ts +58 -1
- package/src/v2/runtime/handlers/shared/resolve-intelligence-user.ts +4 -1
- package/src/v2/runtime/handlers/shared/sse-response.ts +46 -0
- package/src/v2/runtime/handlers/sse/__tests__/sse-connect-agent-id.test.ts +71 -0
- package/src/v2/runtime/handlers/sse/connect.ts +6 -0
- package/src/v2/runtime/handlers/sse/run.ts +4 -0
- package/src/v2/runtime/intelligence-platform/__tests__/client.test.ts +13 -11
- package/src/v2/runtime/intelligence-platform/client.ts +3 -11
- package/src/v2/runtime/runner/__tests__/intelligence-runner.test.ts +51 -1
- package/src/v2/runtime/runner/intelligence.ts +27 -9
- package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +268 -0
- package/tests/service-adapters/anthropic/utils-token-trimming.test.ts +301 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot.resolver.mjs","names":[],"sources":["../../../src/graphql/resolvers/copilot.resolver.ts"],"sourcesContent":["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 {\n CopilotRequestContextProperties,\n GraphQLContext,\n} 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 {\n ResponseStatusUnion,\n SuccessResponseStatus,\n} 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 ===\n MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user ||\n 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({\n component: \"CopilotResolver.availableAgents\",\n });\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(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(ctx.request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": ctx.request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\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({\n component: \"CopilotResolver.generateCopilotResponse\",\n });\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(\n \"x-copilotcloud-public-api-key\",\n );\n if (publicApiKeyFromHeaders) {\n copilotCloudPublicApiKey = publicApiKeyFromHeaders;\n }\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\n \"Cloud configuration provided, checking for public API key in headers\",\n );\n\n if (!copilotCloudPublicApiKey) {\n logger.error(\"Public API key not found in headers\");\n\n throw new GraphQLError(\n \"X-CopilotCloud-Public-API-Key header is required\",\n );\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<{\n reason: string;\n messageId?: string;\n }>();\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(\n (serverSideAction) => serverSideAction.name == action.name,\n ),\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(\n \"Unknown message in metaEvents copilot resolver\",\n );\n }),\n },\n }),\n );\n break;\n }\n },\n error: (err) => {\n // For structured CopilotKit errors, set proper error response status\n if (\n err?.name?.includes(\"CopilotKit\") ||\n err?.extensions?.visibility\n ) {\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(\n { status: result.status },\n \"Guardrails validation done\",\n );\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({\n guardrailsReason: result.reason,\n }),\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<\n typeof MessageStatusUnion\n >();\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(\n 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(\n { reason, messageId },\n \"Text streaming interrupted\",\n );\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(\n new MessageStreamInterruptedResponse({\n messageId,\n }),\n );\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\n \"Subscribing to text message content stream\",\n );\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(\n { err },\n \"Error in text message content stream\",\n );\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 });\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<\n typeof MessageStatusUnion\n >();\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(\n async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription =\n actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (\n e.type == RuntimeEventTypes.ActionExecutionArgs\n ) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error(\n { err },\n \"Error in action execution argument stream\",\n );\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(\n \"Action execution argument stream completed\",\n );\n streamingArgumentsStatus.next(\n new SuccessMessageStatus(),\n );\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 });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug(\n { result: event.result },\n \"Action execution result event received\",\n );\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 &&\n err.name &&\n 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:\n err.originalErrorType ||\n 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(\n \"Guardrails is enabled, waiting for guardrails result\",\n );\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,mBAAmB,OAAO,EAC9B,SACA,0BACA,MACA,UACA,cAOI;AACJ,KACE,KAAK,SAAS,UACd,KAAK,SAAS,KAAK,SAAS,SAAS,GAAG,aAAa,SACnD,YAAY,MACd;EACA,MAAM,WAAW,KAAK,SACnB,QACE,MACC,EAAE,gBAAgB,WACjB,EAAE,YAAY,SAAS,YAAY,QAClC,EAAE,YAAY,SAAS,YAAY,WACxC,CACA,KAAK,OAAO;GACX,MAAM,EAAE,YAAa;GACrB,SAAS,EAAE,YAAY;GACxB,EAAE;EAEL,MAAM,cAAc,SAAS,SAAS,SAAS;EAC/C,MAAM,iBAAiB,SAAS,MAAM,GAAG,GAAG;EAE5C,MAAM,OAAO;GACX,OAAO,YAAY;GACnB,aAAa,KAAK,MAAM,WAAW,qBAAqB;GACxD,eAAe,KAAK,MAAM,WAAW,qBAAqB;GAC1D,UAAU;GACX;EAED,MAAM,mBAAmB,MAAM,MAAM,GAAG,QAAQ,uBA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cAAc,IAAI,YAAY;SAC9C,mBACE,IAAI,qBACJ,IAAI,YAAY;SAClB,YAAY,IAAI;SACjB;QACF,CAAC,CACH;AACD,gCAAyB,aAAa;AACtC,mCAA4B,IAAI;AAChC,8BAAuB;AACvB;;AAGF,sBAAgB,KACd,IAAI,qBAAqB,EACvB,aAAa,qDACd,CAAC,CACH;AACD,+BAAyB,aAAa;AACtC,6BAAuB;AAEvB,kCAA4B,IAAI;;KAElC,UAAU,YAAY;AACpB,aAAO,MAAM,yBAAyB;AACtC,UAAI,KAAK,OAAO,YAAY;AAC1B,cAAO,MACL,uDACD;AACD,aAAM,eAAe,kBAAkB;;AAEzC,sBAAgB,KAAK,IAAI,uBAAuB,CAAC;AACjD,+BAAyB,aAAa;AACtC,6BAAuB;AAEvB,mCAA6B,eAAe;;KAE/C,CAAC;KACF;GACH;;;;CA1oBF,YAAY,OAAO;;;;;;CAKnB,YAAY,eAAe;oBACL,KAAK;;;;;;CAiB3B,eAAe,gBAAgB;oBAE7B,KAAK;oBACL,IAAI,OAAO;oBACX,IAAI,oBAAoB,mBAAmB,EAAE,UAAU,MAAM,CAAC;;;;;;;;;8BA7BlE,eAAe,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"copilot.resolver.mjs","names":[],"sources":["../../../src/graphql/resolvers/copilot.resolver.ts"],"sourcesContent":["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 {\n CopilotRequestContextProperties,\n GraphQLContext,\n} 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 {\n ResponseStatusUnion,\n SuccessResponseStatus,\n} 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 { resolveMessageId } from \"./resolve-message-id\";\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 ===\n MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user ||\n 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({\n component: \"CopilotResolver.availableAgents\",\n });\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(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(ctx.request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": ctx.request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\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({\n component: \"CopilotResolver.generateCopilotResponse\",\n });\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(\n \"x-copilotcloud-public-api-key\",\n );\n if (publicApiKeyFromHeaders) {\n copilotCloudPublicApiKey = publicApiKeyFromHeaders;\n }\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\n \"Cloud configuration provided, checking for public API key in headers\",\n );\n\n if (!copilotCloudPublicApiKey) {\n logger.error(\"Public API key not found in headers\");\n\n throw new GraphQLError(\n \"X-CopilotCloud-Public-API-Key header is required\",\n );\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<{\n reason: string;\n messageId?: string;\n }>();\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(\n (serverSideAction) => serverSideAction.name == action.name,\n ),\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(\n \"Unknown message in metaEvents copilot resolver\",\n );\n }),\n },\n }),\n );\n break;\n }\n },\n error: (err) => {\n // For structured CopilotKit errors, set proper error response status\n if (\n err?.name?.includes(\"CopilotKit\") ||\n err?.extensions?.visibility\n ) {\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(\n { status: result.status },\n \"Guardrails validation done\",\n );\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({\n guardrailsReason: result.reason,\n }),\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<\n typeof MessageStatusUnion\n >();\n\n const messageId = resolveMessageId(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(\n 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(\n { reason, messageId },\n \"Text streaming interrupted\",\n );\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(\n new MessageStreamInterruptedResponse({\n messageId,\n }),\n );\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\n \"Subscribing to text message content stream\",\n );\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(\n { err },\n \"Error in text message content stream\",\n );\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 });\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<\n typeof MessageStatusUnion\n >();\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(\n async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription =\n actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (\n e.type == RuntimeEventTypes.ActionExecutionArgs\n ) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error(\n { err },\n \"Error in action execution argument stream\",\n );\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(\n \"Action execution argument stream completed\",\n );\n streamingArgumentsStatus.next(\n new SuccessMessageStatus(),\n );\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 });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug(\n { result: event.result },\n \"Action execution result event received\",\n );\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 &&\n err.name &&\n 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:\n err.originalErrorType ||\n 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(\n \"Guardrails is enabled, waiting for guardrails result\",\n );\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,MAAM,mBAAmB,OAAO,EAC9B,SACA,0BACA,MACA,UACA,cAOI;A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,EAAE,UAAU,MAAM,CAAC;;;;;;;;;8BA7BlE,eAAe,gBAAgB"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
require("reflect-metadata");
|
|
2
|
+
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
|
+
|
|
5
|
+
//#region src/graphql/resolvers/resolve-message-id.ts
|
|
6
|
+
/**
|
|
7
|
+
* Resolve the id to use for a streamed TextMessageOutput.
|
|
8
|
+
*
|
|
9
|
+
* Upstream events occasionally arrive with `messageId` missing, null, or an
|
|
10
|
+
* empty string. We fall back to a freshly generated id in those cases so the
|
|
11
|
+
* resulting output never surfaces a null id to the GraphQL client (#2118).
|
|
12
|
+
*/
|
|
13
|
+
function resolveMessageId(eventMessageId) {
|
|
14
|
+
return eventMessageId || (0, _copilotkit_shared.randomId)();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
//#endregion
|
|
18
|
+
exports.resolveMessageId = resolveMessageId;
|
|
19
|
+
//# sourceMappingURL=resolve-message-id.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-message-id.cjs","names":[],"sources":["../../../src/graphql/resolvers/resolve-message-id.ts"],"sourcesContent":["import { randomId } from \"@copilotkit/shared\";\n\n/**\n * Resolve the id to use for a streamed TextMessageOutput.\n *\n * Upstream events occasionally arrive with `messageId` missing, null, or an\n * empty string. We fall back to a freshly generated id in those cases so the\n * resulting output never surfaces a null id to the GraphQL client (#2118).\n */\nexport function resolveMessageId(\n eventMessageId: string | null | undefined,\n): string {\n return eventMessageId || randomId();\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,iBACd,gBACQ;AACR,QAAO,oDAA4B"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import { randomId } from "@copilotkit/shared";
|
|
3
|
+
|
|
4
|
+
//#region src/graphql/resolvers/resolve-message-id.ts
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the id to use for a streamed TextMessageOutput.
|
|
7
|
+
*
|
|
8
|
+
* Upstream events occasionally arrive with `messageId` missing, null, or an
|
|
9
|
+
* empty string. We fall back to a freshly generated id in those cases so the
|
|
10
|
+
* resulting output never surfaces a null id to the GraphQL client (#2118).
|
|
11
|
+
*/
|
|
12
|
+
function resolveMessageId(eventMessageId) {
|
|
13
|
+
return eventMessageId || randomId();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
//#endregion
|
|
17
|
+
export { resolveMessageId };
|
|
18
|
+
//# sourceMappingURL=resolve-message-id.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-message-id.mjs","names":[],"sources":["../../../src/graphql/resolvers/resolve-message-id.ts"],"sourcesContent":["import { randomId } from \"@copilotkit/shared\";\n\n/**\n * Resolve the id to use for a streamed TextMessageOutput.\n *\n * Upstream events occasionally arrive with `messageId` missing, null, or an\n * empty string. We fall back to a freshly generated id in those cases so the\n * resulting output never surfaces a null id to the GraphQL client (#2118).\n */\nexport function resolveMessageId(\n eventMessageId: string | null | undefined,\n): string {\n return eventMessageId || randomId();\n}\n"],"mappings":";;;;;;;;;;;AASA,SAAgB,iBACd,gBACQ;AACR,QAAO,kBAAkB,UAAU"}
|
|
@@ -72,8 +72,11 @@ function copilotRuntimeNodeHttpEndpoint(options) {
|
|
|
72
72
|
if (response.body) require_request_handler.readableStreamToNodeStream(response.body).pipe(res);
|
|
73
73
|
else res.end();
|
|
74
74
|
};
|
|
75
|
+
function isRequestLike(obj) {
|
|
76
|
+
return obj instanceof Request || typeof obj === "object" && obj !== null && "url" in obj && "method" in obj && "headers" in obj && typeof obj.url === "string" && typeof obj.method === "string";
|
|
77
|
+
}
|
|
75
78
|
return function(reqOrRequest, res) {
|
|
76
|
-
if (reqOrRequest
|
|
79
|
+
if (isRequestLike(reqOrRequest) && !res) return honoApp.fetch(reqOrRequest);
|
|
77
80
|
if (!res) throw new TypeError("ServerResponse is required for Node HTTP requests");
|
|
78
81
|
return handle(reqOrRequest, res);
|
|
79
82
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["getCommonConfig","getRuntimeInstanceTelemetryInfo","createCopilotEndpointSingleRoute","getFullUrl","toHeaders","isStreamConsumed","nodeStreamToReadableStream","synthesizeBodyFromParsedBody","isDisturbedOrLockedError"],"sources":["../../../../src/lib/integrations/node-http/index.ts"],"sourcesContent":["import { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { createCopilotEndpointSingleRoute } from \"../../../v2/runtime\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport {\n getFullUrl,\n IncomingWithBody,\n isDisturbedOrLockedError,\n isStreamConsumed,\n nodeStreamToReadableStream,\n readableStreamToNodeStream,\n synthesizeBodyFromParsedBody,\n toHeaders,\n} from \"./request-handler\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\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(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const honoApp = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handle = async function handler(\n req: IncomingWithBody,\n res: ServerResponse,\n ) {\n const url = getFullUrl(req);\n const hasBody = req.method !== \"GET\" && req.method !== \"HEAD\";\n\n const baseHeaders = toHeaders(req.headers);\n const parsedBody = req.body;\n\n const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;\n const canStream = hasBody && !streamConsumed;\n\n let requestBody: BodyInit | null | undefined = undefined;\n let useDuplex = false;\n\n if (hasBody && canStream) {\n requestBody = nodeStreamToReadableStream(req);\n useDuplex = true;\n }\n\n if (hasBody && streamConsumed) {\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n baseHeaders,\n );\n requestBody = synthesized.body ?? undefined;\n baseHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n baseHeaders.set(\"content-type\", synthesized.contentType);\n }\n\n logger.debug(\n \"Request stream already consumed; using parsed req.body to rebuild request.\",\n );\n } else {\n logger.warn(\n \"Request stream consumed with no available body; sending empty payload.\",\n );\n requestBody = undefined;\n }\n }\n\n const buildRequest = (\n body: BodyInit | null | undefined,\n headers: Headers,\n duplex: boolean,\n ) =>\n new Request(url, {\n method: req.method,\n headers,\n body,\n duplex: duplex ? \"half\" : undefined,\n } as RequestInit);\n\n let response: Response;\n try {\n response = await honoApp.fetch(\n buildRequest(requestBody, baseHeaders, useDuplex),\n );\n } catch (error) {\n if (isDisturbedOrLockedError(error) && hasBody) {\n logger.warn(\n \"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.\",\n );\n\n const fallbackHeaders = new Headers(baseHeaders);\n let fallbackBody: BodyInit | null | undefined;\n\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n fallbackHeaders,\n );\n fallbackBody = synthesized.body ?? undefined;\n fallbackHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n fallbackHeaders.set(\"content-type\", synthesized.contentType);\n }\n } else {\n fallbackBody = undefined;\n }\n\n response = await honoApp.fetch(\n buildRequest(fallbackBody, fallbackHeaders, false),\n );\n } else {\n throw error;\n }\n }\n\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (response.body) {\n readableStreamToNodeStream(response.body).pipe(res);\n } else {\n res.end();\n }\n };\n\n return function (\n reqOrRequest: IncomingMessage | Request,\n res?: ServerResponse,\n ): Promise<void> | Promise<Response> | Response {\n if (reqOrRequest
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["getCommonConfig","getRuntimeInstanceTelemetryInfo","createCopilotEndpointSingleRoute","getFullUrl","toHeaders","isStreamConsumed","nodeStreamToReadableStream","synthesizeBodyFromParsedBody","isDisturbedOrLockedError"],"sources":["../../../../src/lib/integrations/node-http/index.ts"],"sourcesContent":["import { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { createCopilotEndpointSingleRoute } from \"../../../v2/runtime\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport {\n getFullUrl,\n IncomingWithBody,\n isDisturbedOrLockedError,\n isStreamConsumed,\n nodeStreamToReadableStream,\n readableStreamToNodeStream,\n synthesizeBodyFromParsedBody,\n toHeaders,\n} from \"./request-handler\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\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(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const honoApp = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handle = async function handler(\n req: IncomingWithBody,\n res: ServerResponse,\n ) {\n const url = getFullUrl(req);\n const hasBody = req.method !== \"GET\" && req.method !== \"HEAD\";\n\n const baseHeaders = toHeaders(req.headers);\n const parsedBody = req.body;\n\n const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;\n const canStream = hasBody && !streamConsumed;\n\n let requestBody: BodyInit | null | undefined = undefined;\n let useDuplex = false;\n\n if (hasBody && canStream) {\n requestBody = nodeStreamToReadableStream(req);\n useDuplex = true;\n }\n\n if (hasBody && streamConsumed) {\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n baseHeaders,\n );\n requestBody = synthesized.body ?? undefined;\n baseHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n baseHeaders.set(\"content-type\", synthesized.contentType);\n }\n\n logger.debug(\n \"Request stream already consumed; using parsed req.body to rebuild request.\",\n );\n } else {\n logger.warn(\n \"Request stream consumed with no available body; sending empty payload.\",\n );\n requestBody = undefined;\n }\n }\n\n const buildRequest = (\n body: BodyInit | null | undefined,\n headers: Headers,\n duplex: boolean,\n ) =>\n new Request(url, {\n method: req.method,\n headers,\n body,\n duplex: duplex ? \"half\" : undefined,\n } as RequestInit);\n\n let response: Response;\n try {\n response = await honoApp.fetch(\n buildRequest(requestBody, baseHeaders, useDuplex),\n );\n } catch (error) {\n if (isDisturbedOrLockedError(error) && hasBody) {\n logger.warn(\n \"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.\",\n );\n\n const fallbackHeaders = new Headers(baseHeaders);\n let fallbackBody: BodyInit | null | undefined;\n\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n fallbackHeaders,\n );\n fallbackBody = synthesized.body ?? undefined;\n fallbackHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n fallbackHeaders.set(\"content-type\", synthesized.contentType);\n }\n } else {\n fallbackBody = undefined;\n }\n\n response = await honoApp.fetch(\n buildRequest(fallbackBody, fallbackHeaders, false),\n );\n } else {\n throw error;\n }\n }\n\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (response.body) {\n readableStreamToNodeStream(response.body).pipe(res);\n } else {\n res.end();\n }\n };\n\n // Duck-type check for Request-like objects (handles polyfilled Request from @hono/node-server)\n function isRequestLike(obj: unknown): obj is Request {\n return (\n obj instanceof Request ||\n (typeof obj === \"object\" &&\n obj !== null &&\n \"url\" in obj &&\n \"method\" in obj &&\n \"headers\" in obj &&\n typeof (obj as any).url === \"string\" &&\n typeof (obj as any).method === \"string\")\n );\n }\n\n return function (\n reqOrRequest: IncomingMessage | Request,\n res?: ServerResponse,\n ): Promise<void> | Promise<Response> | Response {\n if (isRequestLike(reqOrRequest) && !res) {\n return honoApp.fetch(reqOrRequest as Request);\n }\n if (!res) {\n throw new TypeError(\"ServerResponse is required for Node HTTP requests\");\n }\n return handle(reqOrRequest as IncomingMessage, res);\n };\n}\n"],"mappings":";;;;;;;AAiBA,SAAgB,+BACd,SACA;CACA,MAAM,eAAeA,+BAAgB,QAAQ;AAE7C,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,aACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,kCAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,kCAAU,QACR,gCACAC,yDAAgC,QAAQ,CACzC;CAED,MAAM,SAAS,aAAa;AAC5B,QAAO,MAAM,8BAA8B;CAE3C,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;CAItD,MAAM,UAAUC,qDAAiC;EAC/C,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ;CAET,MAAM,SAA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S;AAC1B,WAAS,QAAQ,SAAS,OAAO,QAAQ;AACvC,OAAI,UAAU,KAAK,MAAM;IACzB;AAEF,MAAI,SAAS,KACX,oDAA2B,SAAS,KAAK,CAAC,KAAK,IAAI;MAEnD,KAAI,KAAK;;CAKb,SAAS,cAAc,KAA8B;AACnD,SACE,eAAe,WACd,OAAO,QAAQ,YACd,QAAQ,QACR,SAAS,OACT,YAAY,OACZ,aAAa,OACb,OAAQ,IAAY,QAAQ,YAC5B,OAAQ,IAAY,WAAW;;AAIrC,QAAO,SACL,cACA,KAC8C;AAC9C,MAAI,cAAc,aAAa,IAAI,CAAC,IAClC,QAAO,QAAQ,MAAM,aAAwB;AAE/C,MAAI,CAAC,IACH,OAAM,IAAI,UAAU,oDAAoD;AAE1E,SAAO,OAAO,cAAiC,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../../src/lib/integrations/node-http/index.ts"],"mappings":";;;;;iBAiBgB,8BAAA,CACd,OAAA,EAAS,iCAAA,
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../../src/lib/integrations/node-http/index.ts"],"mappings":";;;;;iBAiBgB,8BAAA,CACd,OAAA,EAAS,iCAAA,IA6JP,YAAA,EAAc,eAAA,GAAkB,OAAA,EAChC,GAAA,GAAM,cAAA,KACL,OAAA,SAAgB,OAAA,CAAQ,QAAA,IAAY,QAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../src/lib/integrations/node-http/index.ts"],"mappings":";;;;;iBAiBgB,8BAAA,CACd,OAAA,EAAS,iCAAA,
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../src/lib/integrations/node-http/index.ts"],"mappings":";;;;;iBAiBgB,8BAAA,CACd,OAAA,EAAS,iCAAA,IA6JP,YAAA,EAAc,eAAA,GAAkB,OAAA,EAChC,GAAA,GAAM,cAAA,KACL,OAAA,SAAgB,OAAA,CAAQ,QAAA,IAAY,QAAA"}
|
|
@@ -72,8 +72,11 @@ function copilotRuntimeNodeHttpEndpoint(options) {
|
|
|
72
72
|
if (response.body) readableStreamToNodeStream(response.body).pipe(res);
|
|
73
73
|
else res.end();
|
|
74
74
|
};
|
|
75
|
+
function isRequestLike(obj) {
|
|
76
|
+
return obj instanceof Request || typeof obj === "object" && obj !== null && "url" in obj && "method" in obj && "headers" in obj && typeof obj.url === "string" && typeof obj.method === "string";
|
|
77
|
+
}
|
|
75
78
|
return function(reqOrRequest, res) {
|
|
76
|
-
if (reqOrRequest
|
|
79
|
+
if (isRequestLike(reqOrRequest) && !res) return honoApp.fetch(reqOrRequest);
|
|
77
80
|
if (!res) throw new TypeError("ServerResponse is required for Node HTTP requests");
|
|
78
81
|
return handle(reqOrRequest, res);
|
|
79
82
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/lib/integrations/node-http/index.ts"],"sourcesContent":["import { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { createCopilotEndpointSingleRoute } from \"../../../v2/runtime\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport {\n getFullUrl,\n IncomingWithBody,\n isDisturbedOrLockedError,\n isStreamConsumed,\n nodeStreamToReadableStream,\n readableStreamToNodeStream,\n synthesizeBodyFromParsedBody,\n toHeaders,\n} from \"./request-handler\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\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(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const honoApp = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handle = async function handler(\n req: IncomingWithBody,\n res: ServerResponse,\n ) {\n const url = getFullUrl(req);\n const hasBody = req.method !== \"GET\" && req.method !== \"HEAD\";\n\n const baseHeaders = toHeaders(req.headers);\n const parsedBody = req.body;\n\n const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;\n const canStream = hasBody && !streamConsumed;\n\n let requestBody: BodyInit | null | undefined = undefined;\n let useDuplex = false;\n\n if (hasBody && canStream) {\n requestBody = nodeStreamToReadableStream(req);\n useDuplex = true;\n }\n\n if (hasBody && streamConsumed) {\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n baseHeaders,\n );\n requestBody = synthesized.body ?? undefined;\n baseHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n baseHeaders.set(\"content-type\", synthesized.contentType);\n }\n\n logger.debug(\n \"Request stream already consumed; using parsed req.body to rebuild request.\",\n );\n } else {\n logger.warn(\n \"Request stream consumed with no available body; sending empty payload.\",\n );\n requestBody = undefined;\n }\n }\n\n const buildRequest = (\n body: BodyInit | null | undefined,\n headers: Headers,\n duplex: boolean,\n ) =>\n new Request(url, {\n method: req.method,\n headers,\n body,\n duplex: duplex ? \"half\" : undefined,\n } as RequestInit);\n\n let response: Response;\n try {\n response = await honoApp.fetch(\n buildRequest(requestBody, baseHeaders, useDuplex),\n );\n } catch (error) {\n if (isDisturbedOrLockedError(error) && hasBody) {\n logger.warn(\n \"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.\",\n );\n\n const fallbackHeaders = new Headers(baseHeaders);\n let fallbackBody: BodyInit | null | undefined;\n\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n fallbackHeaders,\n );\n fallbackBody = synthesized.body ?? undefined;\n fallbackHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n fallbackHeaders.set(\"content-type\", synthesized.contentType);\n }\n } else {\n fallbackBody = undefined;\n }\n\n response = await honoApp.fetch(\n buildRequest(fallbackBody, fallbackHeaders, false),\n );\n } else {\n throw error;\n }\n }\n\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (response.body) {\n readableStreamToNodeStream(response.body).pipe(res);\n } else {\n res.end();\n }\n };\n\n return function (\n reqOrRequest: IncomingMessage | Request,\n res?: ServerResponse,\n ): Promise<void> | Promise<Response> | Response {\n if (reqOrRequest
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/lib/integrations/node-http/index.ts"],"sourcesContent":["import { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { createCopilotEndpointSingleRoute } from \"../../../v2/runtime\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport {\n getFullUrl,\n IncomingWithBody,\n isDisturbedOrLockedError,\n isStreamConsumed,\n nodeStreamToReadableStream,\n readableStreamToNodeStream,\n synthesizeBodyFromParsedBody,\n toHeaders,\n} from \"./request-handler\";\n\nexport function copilotRuntimeNodeHttpEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\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(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const serviceAdapter = options.serviceAdapter;\n if (serviceAdapter) {\n options.runtime.handleServiceAdapter(serviceAdapter);\n }\n\n // Note: cors option requires @copilotkit/runtime with credentials support\n const honoApp = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handle = async function handler(\n req: IncomingWithBody,\n res: ServerResponse,\n ) {\n const url = getFullUrl(req);\n const hasBody = req.method !== \"GET\" && req.method !== \"HEAD\";\n\n const baseHeaders = toHeaders(req.headers);\n const parsedBody = req.body;\n\n const streamConsumed = isStreamConsumed(req) || parsedBody !== undefined;\n const canStream = hasBody && !streamConsumed;\n\n let requestBody: BodyInit | null | undefined = undefined;\n let useDuplex = false;\n\n if (hasBody && canStream) {\n requestBody = nodeStreamToReadableStream(req);\n useDuplex = true;\n }\n\n if (hasBody && streamConsumed) {\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n baseHeaders,\n );\n requestBody = synthesized.body ?? undefined;\n baseHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n baseHeaders.set(\"content-type\", synthesized.contentType);\n }\n\n logger.debug(\n \"Request stream already consumed; using parsed req.body to rebuild request.\",\n );\n } else {\n logger.warn(\n \"Request stream consumed with no available body; sending empty payload.\",\n );\n requestBody = undefined;\n }\n }\n\n const buildRequest = (\n body: BodyInit | null | undefined,\n headers: Headers,\n duplex: boolean,\n ) =>\n new Request(url, {\n method: req.method,\n headers,\n body,\n duplex: duplex ? \"half\" : undefined,\n } as RequestInit);\n\n let response: Response;\n try {\n response = await honoApp.fetch(\n buildRequest(requestBody, baseHeaders, useDuplex),\n );\n } catch (error) {\n if (isDisturbedOrLockedError(error) && hasBody) {\n logger.warn(\n \"Encountered disturbed/locked request body; rebuilding request using parsed body or empty payload.\",\n );\n\n const fallbackHeaders = new Headers(baseHeaders);\n let fallbackBody: BodyInit | null | undefined;\n\n if (parsedBody !== undefined) {\n const synthesized = synthesizeBodyFromParsedBody(\n parsedBody,\n fallbackHeaders,\n );\n fallbackBody = synthesized.body ?? undefined;\n fallbackHeaders.delete(\"content-length\");\n\n if (synthesized.contentType) {\n fallbackHeaders.set(\"content-type\", synthesized.contentType);\n }\n } else {\n fallbackBody = undefined;\n }\n\n response = await honoApp.fetch(\n buildRequest(fallbackBody, fallbackHeaders, false),\n );\n } else {\n throw error;\n }\n }\n\n res.statusCode = response.status;\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (response.body) {\n readableStreamToNodeStream(response.body).pipe(res);\n } else {\n res.end();\n }\n };\n\n // Duck-type check for Request-like objects (handles polyfilled Request from @hono/node-server)\n function isRequestLike(obj: unknown): obj is Request {\n return (\n obj instanceof Request ||\n (typeof obj === \"object\" &&\n obj !== null &&\n \"url\" in obj &&\n \"method\" in obj &&\n \"headers\" in obj &&\n typeof (obj as any).url === \"string\" &&\n typeof (obj as any).method === \"string\")\n );\n }\n\n return function (\n reqOrRequest: IncomingMessage | Request,\n res?: ServerResponse,\n ): Promise<void> | Promise<Response> | Response {\n if (isRequestLike(reqOrRequest) && !res) {\n return honoApp.fetch(reqOrRequest as Request);\n }\n if (!res) {\n throw new TypeError(\"ServerResponse is required for Node HTTP requests\");\n }\n return handle(reqOrRequest as IncomingMessage, res);\n };\n}\n"],"mappings":";;;;;;;AAiBA,SAAgB,+BACd,SACA;CACA,MAAM,eAAe,gBAAgB,QAAQ;AAE7C,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,aACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,iBAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,iBAAU,QACR,gCACA,gCAAgC,QAAQ,CACzC;CAED,MAAM,SAAS,aAAa;AAC5B,QAAO,MAAM,8BAA8B;CAE3C,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ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,iBAAiB;AAExC,SAAI,YAAY,YACd,iBAAgB,IAAI,gBAAgB,YAAY,YAAY;UAG9D,gBAAe;AAGjB,eAAW,MAAM,QAAQ,MACvB,aAAa,cAAc,iBAAiB,MAAM,CACnD;SAED,OAAM;;AAIV,MAAI,aAAa,SAAS;AAC1B,WAAS,QAAQ,SAAS,OAAO,QAAQ;AACvC,OAAI,UAAU,KAAK,MAAM;IACzB;AAEF,MAAI,SAAS,KACX,4BAA2B,SAAS,KAAK,CAAC,KAAK,IAAI;MAEnD,KAAI,KAAK;;CAKb,SAAS,cAAc,KAA8B;AACnD,SACE,eAAe,WACd,OAAO,QAAQ,YACd,QAAQ,QACR,SAAS,OACT,YAAY,OACZ,aAAa,OACb,OAAQ,IAAY,QAAQ,YAC5B,OAAQ,IAAY,WAAW;;AAIrC,QAAO,SACL,cACA,KAC8C;AAC9C,MAAI,cAAc,aAAa,IAAI,CAAC,IAClC,QAAO,QAAQ,MAAM,aAAwB;AAE/C,MAAI,CAAC,IACH,OAAM,IAAI,UAAU,oDAAoD;AAE1E,SAAO,OAAO,cAAiC,IAAI"}
|
|
@@ -77,8 +77,10 @@ var CopilotRuntime = class {
|
|
|
77
77
|
const serviceAdapterCanBeUsedForAgent = !["EmptyAdapter"].includes(serviceAdapter.name);
|
|
78
78
|
if (isAgentsListEmpty && (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)) throw new _copilotkit_shared.CopilotKitMisuseError({ message: "No default agent provided. Please provide a default agent in the runtime config." });
|
|
79
79
|
if (isAgentsListEmpty) {
|
|
80
|
-
const
|
|
81
|
-
agentsList.default = new require_index.BuiltInAgent({ model });
|
|
80
|
+
const languageModel = serviceAdapter.getLanguageModel?.();
|
|
81
|
+
if (languageModel) agentsList.default = new require_index.BuiltInAgent({ model: languageModel });
|
|
82
|
+
else if (serviceAdapter.provider && serviceAdapter.model) agentsList.default = new require_index.BuiltInAgent({ model: `${serviceAdapter.provider}/${serviceAdapter.model}` });
|
|
83
|
+
else throw new _copilotkit_shared.CopilotKitMisuseError({ message: `Service adapter "${serviceAdapter.name ?? "unknown"}" does not provide model information. When using adapters like LangChainAdapter without an explicit agents list, please provide a default agent in the runtime config. Example:\n new CopilotRuntime({\n agents: { default: new BuiltInAgent({ model: "openai/gpt-4o" }) }\n })` });
|
|
82
84
|
}
|
|
83
85
|
const actions = this.params?.actions;
|
|
84
86
|
if (actions) {
|
|
@@ -159,7 +161,17 @@ var CopilotRuntime = class {
|
|
|
159
161
|
createOnAfterRequestHandler(params) {
|
|
160
162
|
return async (hookParams) => {
|
|
161
163
|
params?.afterRequestMiddleware?.(hookParams);
|
|
162
|
-
if (params?.middleware?.onAfterRequest)
|
|
164
|
+
if (params?.middleware?.onAfterRequest) {
|
|
165
|
+
const messages = hookParams.messages ?? [];
|
|
166
|
+
params.middleware.onAfterRequest({
|
|
167
|
+
threadId: hookParams.threadId ?? "",
|
|
168
|
+
runId: hookParams.runId,
|
|
169
|
+
inputMessages: messages.filter((m) => "role" in m && m.role === "user"),
|
|
170
|
+
outputMessages: messages.filter((m) => "role" in m && m.role !== "user"),
|
|
171
|
+
properties: {},
|
|
172
|
+
url: hookParams.path
|
|
173
|
+
});
|
|
174
|
+
}
|
|
163
175
|
};
|
|
164
176
|
}
|
|
165
177
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"copilot-runtime.cjs","names":["InMemoryAgentRunner","TelemetryAgentRunner","CopilotRuntimeVNext","EndpointType","CopilotKitMisuseError","BuiltInAgent","aguiToGQL","extractParametersFromSchema"],"sources":["../../../src/lib/runtime/copilot-runtime.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/concepts/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n type Action,\n type CopilotErrorHandler,\n CopilotKitMisuseError,\n type MaybePromise,\n type NonEmptyRecord,\n type Parameter,\n readBody,\n getZodParameters,\n type PartialBy,\n isTelemetryDisabled,\n type DebugConfig,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport {\n CopilotRuntime as CopilotRuntimeVNext,\n type CopilotRuntimeOptions,\n type CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n type AgentRunner,\n type AgentsConfig,\n type AgentsFactory,\n type AgentFactoryContext,\n InMemoryAgentRunner,\n} from \"../../v2/runtime\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport { TelemetryAgentRunner } from \"./telemetry-agent-runner\";\nimport telemetry from \"../telemetry-client\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport {\n EndpointType,\n type EndpointDefinition,\n type CopilotKitEndpoint,\n type LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\n\n// +++ MCP Imports +++\nimport {\n type MCPClient,\n type MCPEndpointConfig,\n type MCPTool,\n extractParametersFromSchema,\n} from \"./mcp-tools-utils\";\nimport { BuiltInAgent, type BuiltInAgentClassicConfig } from \"../../agent\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n * Requires publicApiKey from CopilotKit component to be set:\n *\n * ```tsx\n * <CopilotKit publicApiKey=\"ck_pub_...\" />\n * ```\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * **Requires publicApiKey**: Error handling only works when requests include a valid publicApiKey.\n * This is a premium Copilot Cloud feature.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n /**\n * Enable debug logging for the runtime event pipeline.\n * Pass `true` for full output, or an object for granular control:\n *\n * ```ts\n * const runtime = new CopilotRuntime({\n * debug: true,\n * // or: debug: { events: true, lifecycle: true, verbose: false }\n * });\n * ```\n */\n debug?: DebugConfig;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n}\n\n/**\n * Central runtime object passed to all request handlers.\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BuiltInAgentClassicConfig[\"tools\"]> =\n new Map();\n private runtimeArgs: CopilotRuntimeOptions;\n private _instance: CopilotRuntimeVNext;\n\n constructor(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Merge endpoint agents with user-provided agents.\n // When agents is a factory function, wrap it so endpoint agents are merged\n // at resolution time (spreading a function produces {} — silent data loss).\n let mergedAgents: AgentsConfig;\n if (typeof agents === \"function\") {\n mergedAgents = async (ctx) => {\n const resolved = await agents(ctx);\n return { ...endpointAgents, ...resolved };\n };\n } else {\n mergedAgents = Promise.resolve(agents).then((resolved) => ({\n ...endpointAgents,\n ...resolved,\n }));\n }\n\n // Determine the base runner (user-provided or default)\n const baseRunner = params?.runner ?? new InMemoryAgentRunner();\n\n // Wrap with TelemetryAgentRunner unless telemetry is disabled\n // This ensures we always capture agent execution telemetry when enabled,\n // even if the user provides their own custom runner\n const runner = isTelemetryDisabled()\n ? baseRunner\n : new TelemetryAgentRunner({ runner: baseRunner });\n\n this.runtimeArgs = {\n agents: mergedAgents,\n runner,\n licenseToken: params?.licenseToken,\n debug: params?.debug,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n };\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n this.runtimeArgs.agents = Promise.resolve(\n this.runtimeArgs.agents ?? {},\n ).then(async (agents) => {\n let agentsList = agents;\n const isAgentsListEmpty = !Object.keys(agents).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const model =\n serviceAdapter.getLanguageModel?.() ??\n `${serviceAdapter.provider}/${serviceAdapter.model}`;\n agentsList.default = new BuiltInAgent({ model });\n }\n\n const actions = this.params?.actions;\n if (actions) {\n const mcpTools = await this.getToolsFromMCP();\n agentsList = this.assignToolsToAgents(agents, [\n ...this.getToolsFromActions(actions),\n ...mcpTools,\n ]);\n }\n\n return agentsList;\n });\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: {}, url: undefined })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig = existingConfig as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...tools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // Capture telemetry for copilot request creation\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n const body = (await readBody(request)) as RunAgentInput;\n\n const forwardedProps = body?.forwardedProps as\n | {\n cloud?: { guardrails?: unknown };\n metadata?: { requestType?: string };\n }\n | undefined;\n\n // Get cloud base URL from environment or default\n const cloudBaseUrl =\n process.env.COPILOT_CLOUD_BASE_URL || \"https://api.cloud.copilotkit.ai\";\n\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\":\n forwardedProps?.cloud?.guardrails !== undefined,\n requestType: forwardedProps?.metadata?.requestType ?? \"unknown\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n \"cloud.base_url\": cloudBaseUrl,\n });\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n // TODO: provide old expected params here when available\n // @ts-expect-error -- missing arguments.\n params.middleware.onAfterRequest({});\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<BuiltInAgentClassicConfig[\"tools\"]> {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const allTools: BuiltInAgentClassicConfig[\"tools\"] = [];\n\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n // Return cached tool definitions when available\n const cached = this.mcpToolsCache.get(endpointUrl);\n if (cached) {\n allTools.push(...cached);\n continue;\n }\n\n try {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n\n // Cache per endpoint and add to aggregate\n this.mcpToolsCache.set(endpointUrl, toolDefs);\n allTools.push(...toolDefs);\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`,\n error,\n );\n // Cache empty to prevent repeated attempts within lifecycle\n this.mcpToolsCache.set(endpointUrl, []);\n }\n }\n\n // Dedupe tools by name while preserving last-in wins (request overrides)\n const dedupedByName = new Map<string, (typeof allTools)[number]>();\n for (const tool of allTools) {\n dedupedByName.set(tool.name, tool);\n }\n\n return Array.from(dedupedByName.values());\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyVA,IAAa,iBAAb,MAAmE;CASjE,YACE,QAEA;uCAPA,IAAI,KAAK;EAQT,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAKD,IAAI;AACJ,MAAI,OAAO,WAAW,WACpB,gBAAe,OAAO,QAAQ;GAC5B,MAAM,WAAW,MAAM,OAAO,IAAI;AAClC,UAAO;IAAE,GAAG;IAAgB,GAA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AErC,MAAM,WAA+C,OAAO,QAC1D,SACD,CAAC,KAAK,CAAC,UAAU,UAA6B;KAE7C,MAAM,qDADsBG,oDAA4B,KAAK,CACnB;AAC1C,YAAO;MACL,MAAM;MACN,aACE,KAAK,eAAe,aAAa,SAAS,SAAS,YAAY;MACjE,YAAY;MACZ,eAAe,QAAQ,SAAS;MACjC;MACD;AAGF,SAAK,cAAc,IAAI,aAAa,SAAS;AAC7C,aAAS,KAAK,GAAG,SAAS;YACnB,OAAO;AACd,YAAQ,MACN,4CAA4C,YAAY,qBACxD,MACD;AAED,SAAK,cAAc,IAAI,aAAa,EAAE,CAAC;;;EAK3C,MAAM,gCAAgB,IAAI,KAAwC;AAClE,OAAK,MAAM,QAAQ,SACjB,eAAc,IAAI,KAAK,MAAM,KAAK;AAGpC,SAAO,MAAM,KAAK,cAAc,QAAQ,CAAC;;;AAK7C,SAAgB,mBACd,QACoB;AACpB,QAAO;EACL,GAAG;EACH,MAAMJ,2BAAa;EACpB;;AAGH,SAAgB,0BACd,QAC2B;AAC3B,QAAO;EACL,GAAG;EACH,MAAMA,2BAAa;EACpB;;AAGH,SAAgB,oBAAoB,UAA8B;AAChE,KAAI,CAAC,SAAS,KACZ,KAAI,mBAAmB,YAAY,YAAY,SAC7C,QAAOA,2BAAa;KAEpB,QAAOA,2BAAa;AAIxB,QAAO,SAAS"}
|
|
1
|
+
{"version":3,"file":"copilot-runtime.cjs","names":["InMemoryAgentRunner","TelemetryAgentRunner","CopilotRuntimeVNext","EndpointType","CopilotKitMisuseError","BuiltInAgent","aguiToGQL","extractParametersFromSchema"],"sources":["../../../src/lib/runtime/copilot-runtime.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/concepts/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport {\n type Action,\n type CopilotErrorHandler,\n CopilotKitMisuseError,\n type MaybePromise,\n type NonEmptyRecord,\n type Parameter,\n readBody,\n getZodParameters,\n type PartialBy,\n isTelemetryDisabled,\n type DebugConfig,\n} from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/core\";\nimport { aguiToGQL } from \"../../graphql/message-conversion/agui-to-gql\";\nimport type {\n CopilotServiceAdapter,\n RemoteChainParameters,\n} from \"../../service-adapters\";\nimport {\n CopilotRuntime as CopilotRuntimeVNext,\n type CopilotRuntimeOptions,\n type CopilotRuntimeOptions as CopilotRuntimeOptionsVNext,\n type AgentRunner,\n type AgentsConfig,\n type AgentsFactory,\n type AgentFactoryContext,\n InMemoryAgentRunner,\n} from \"../../v2/runtime\";\n\nexport type { AgentsConfig, AgentsFactory, AgentFactoryContext };\nimport { TelemetryAgentRunner } from \"./telemetry-agent-runner\";\nimport telemetry from \"../telemetry-client\";\n\nimport type { MessageInput } from \"../../graphql/inputs/message.input\";\nimport type { Message } from \"../../graphql/types/converted\";\n\nimport {\n EndpointType,\n type EndpointDefinition,\n type CopilotKitEndpoint,\n type LangGraphPlatformEndpoint,\n} from \"./types\";\n\nimport type {\n CopilotObservabilityConfig,\n LLMRequestData,\n LLMResponseData,\n} from \"../observability\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\n\n// +++ MCP Imports +++\nimport {\n type MCPClient,\n type MCPEndpointConfig,\n type MCPTool,\n extractParametersFromSchema,\n} from \"./mcp-tools-utils\";\nimport { BuiltInAgent, type BuiltInAgentClassicConfig } from \"../../agent\";\n// Define the function type alias here or import if defined elsewhere\ntype CreateMCPClientFunction = (\n config: MCPEndpointConfig,\n) => Promise<MCPClient>;\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (\n options: OnBeforeRequestOptions,\n) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (\n options: OnAfterRequestOptions,\n) => void | Promise<void>;\n\ninterface OnStopGenerationOptions {\n threadId: string;\n runId?: string;\n url?: string;\n agentName?: string;\n lastMessage: MessageInput;\n}\ntype OnStopGenerationHandler = (\n options: OnStopGenerationOptions,\n) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams_BASE<\n T extends Parameter[] | [] = [],\n> {\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n /**\n * @deprecated This middleware hook is deprecated and will be removed in a future version.\n * Use updated middleware integration methods in CopilotRuntimeVNext instead.\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed. Will be ignored when remoteActions are set\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n\n /**\n * Optional agent runner to use for SSE runtime.\n */\n runner?: AgentRunner;\n\n /*\n * A map of agent names to AGUI agents.\n * Example agent config:\n * ```ts\n * import { AbstractAgent } from \"@ag-ui/client\";\n * // ...\n * agents: {\n * \"support\": new CustomerSupportAgent(),\n * \"technical\": new TechnicalAgent()\n * }\n * ```\n */\n agents?: Record<string, AbstractAgent>;\n\n /*\n * Delegates agent state processing to the service adapter.\n *\n * When enabled, individual agent state requests will not be processed by the agent itself.\n * Instead, all processing will be handled by the service adapter.\n */\n delegateAgentProcessingToServiceAdapter?: boolean;\n\n /**\n * Configuration for LLM request/response logging.\n * Requires publicApiKey from CopilotKit component to be set:\n *\n * ```tsx\n * <CopilotKit publicApiKey=\"ck_pub_...\" />\n * ```\n *\n * Example logging config:\n * ```ts\n * logging: {\n * enabled: true, // Enable or disable logging\n * progressive: true, // Set to false for buffered logging\n * logger: {\n * logRequest: (data) => langfuse.trace({ name: \"LLM Request\", input: data }),\n * logResponse: (data) => langfuse.trace({ name: \"LLM Response\", output: data }),\n * logError: (errorData) => langfuse.trace({ name: \"LLM Error\", metadata: errorData }),\n * },\n * }\n * ```\n */\n observability_c?: CopilotObservabilityConfig;\n\n /**\n * Configuration for connecting to Model Context Protocol (MCP) servers.\n * Allows fetching and using tools defined on external MCP-compliant servers.\n * Requires providing the `createMCPClient` function during instantiation.\n * @experimental\n */\n mcpServers?: MCPEndpointConfig[];\n\n /**\n * A function that creates an MCP client instance for a given endpoint configuration.\n * This function is responsible for using the appropriate MCP client library\n * (e.g., `@copilotkit/runtime`, `ai`) to establish a connection.\n * Required if `mcpServers` is provided.\n *\n * ```typescript\n * import { experimental_createMCPClient } from \"ai\"; // Import from vercel ai library\n * // ...\n * const runtime = new CopilotRuntime({\n * mcpServers: [{ endpoint: \"...\" }],\n * async createMCPClient(config) {\n * return await experimental_createMCPClient({\n * transport: {\n * type: \"sse\",\n * url: config.endpoint,\n * headers: config.apiKey\n * ? { Authorization: `Bearer ${config.apiKey}` }\n * : undefined,\n * },\n * });\n * }\n * });\n * ```\n */\n createMCPClient?: CreateMCPClientFunction;\n\n /**\n * Optional error handler for comprehensive debugging and observability.\n *\n * **Requires publicApiKey**: Error handling only works when requests include a valid publicApiKey.\n * This is a premium Copilot Cloud feature.\n *\n * @param errorEvent - Structured error event with rich debugging context\n *\n * @example\n * ```typescript\n * const runtime = new CopilotRuntime({\n * onError: (errorEvent) => {\n * debugDashboard.capture(errorEvent);\n * }\n * });\n * ```\n */\n onError?: CopilotErrorHandler;\n\n onStopGeneration?: OnStopGenerationHandler;\n\n /**\n * Enable debug logging for the runtime event pipeline.\n * Pass `true` for full output, or an object for granular control:\n *\n * ```ts\n * const runtime = new CopilotRuntime({\n * debug: true,\n * // or: debug: { events: true, lifecycle: true, verbose: false }\n * });\n * ```\n */\n debug?: DebugConfig;\n\n // /** Optional transcription service for audio processing. */\n // transcriptionService?: CopilotRuntimeOptionsVNext[\"transcriptionService\"];\n // /** Optional *before* middleware – callback function or webhook URL. */\n // beforeRequestMiddleware?: CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\n // /** Optional *after* middleware – callback function or webhook URL. */\n // afterRequestMiddleware?: CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\n}\n\ntype BeforeRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"beforeRequestMiddleware\"];\ntype AfterRequestMiddleware =\n CopilotRuntimeOptionsVNext[\"afterRequestMiddleware\"];\ntype BeforeRequestMiddlewareFn = Exclude<BeforeRequestMiddleware, string>;\ntype BeforeRequestMiddlewareFnParameters =\n Parameters<BeforeRequestMiddlewareFn>;\ntype BeforeRequestMiddlewareFnResult = ReturnType<BeforeRequestMiddlewareFn>;\ntype AfterRequestMiddlewareFn = Exclude<AfterRequestMiddleware, string>;\ntype AfterRequestMiddlewareFnParameters = Parameters<AfterRequestMiddlewareFn>;\n\ninterface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []>\n extends\n Omit<CopilotRuntimeConstructorParams_BASE<T>, \"agents\">,\n Omit<CopilotRuntimeOptionsVNext, \"agents\" | \"transcriptionService\"> {\n /**\n * TODO: un-omit `transcriptionService` above once it's supported\n *\n * This satisfies...\n * – the optional constraint in `CopilotRuntimeConstructorParams_BASE`\n * – the `MaybePromise<NonEmptyRecord<T>>` constraint in `CopilotRuntimeOptionsVNext`\n * – the `Record<string, AbstractAgent>` constraint in `both\n */\n agents?: AgentsConfig;\n}\n\n/**\n * Central runtime object passed to all request handlers.\n */\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n params?: CopilotRuntimeConstructorParams<T>;\n private observability?: CopilotObservabilityConfig;\n // Cache MCP tools per endpoint to avoid re-fetching repeatedly\n private mcpToolsCache: Map<string, BuiltInAgentClassicConfig[\"tools\"]> =\n new Map();\n private runtimeArgs: CopilotRuntimeOptions;\n private _instance: CopilotRuntimeVNext;\n\n constructor(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n const agents = params?.agents ?? {};\n const endpointAgents = this.assignEndpointsToAgents(\n params?.remoteEndpoints ?? [],\n );\n\n // Merge endpoint agents with user-provided agents.\n // When agents is a factory function, wrap it so endpoint agents are merged\n // at resolution time (spreading a function produces {} — silent data loss).\n let mergedAgents: AgentsConfig;\n if (typeof agents === \"function\") {\n mergedAgents = async (ctx) => {\n const resolved = await agents(ctx);\n return { ...endpointAgents, ...resolved };\n };\n } else {\n mergedAgents = Promise.resolve(agents).then((resolved) => ({\n ...endpointAgents,\n ...resolved,\n }));\n }\n\n // Determine the base runner (user-provided or default)\n const baseRunner = params?.runner ?? new InMemoryAgentRunner();\n\n // Wrap with TelemetryAgentRunner unless telemetry is disabled\n // This ensures we always capture agent execution telemetry when enabled,\n // even if the user provides their own custom runner\n const runner = isTelemetryDisabled()\n ? baseRunner\n : new TelemetryAgentRunner({ runner: baseRunner });\n\n this.runtimeArgs = {\n agents: mergedAgents,\n runner,\n licenseToken: params?.licenseToken,\n debug: params?.debug,\n // TODO: add support for transcriptionService from CopilotRuntimeOptionsVNext once it is ready\n // transcriptionService: params?.transcriptionService,\n\n beforeRequestMiddleware:\n this.createOnBeforeRequestHandler(params).bind(this),\n ...(params?.afterRequestMiddleware || params?.middleware?.onAfterRequest\n ? {\n afterRequestMiddleware:\n this.createOnAfterRequestHandler(params).bind(this),\n }\n : {}),\n a2ui: params?.a2ui,\n mcpApps: params?.mcpApps,\n openGenerativeUI: params?.openGenerativeUI,\n };\n this.params = params;\n this.observability = params?.observability_c;\n }\n\n get instance() {\n if (!this._instance) {\n this._instance = new CopilotRuntimeVNext(this.runtimeArgs);\n }\n\n return this._instance;\n }\n\n private assignEndpointsToAgents(\n endpoints: CopilotRuntimeConstructorParams<T>[\"remoteEndpoints\"],\n ): Record<string, AbstractAgent> {\n let result: Record<string, AbstractAgent> = {};\n\n if (\n endpoints.some(\n (endpoint) =>\n resolveEndpointType(endpoint) == EndpointType.LangGraphPlatform,\n )\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"LangGraphPlatformEndpoint in remoteEndpoints is deprecated. \" +\n 'Please use the \"agents\" option instead with LangGraphAgent from \"@copilotkit/runtime/langgraph\". ' +\n 'Example: agents: { myAgent: new LangGraphAgent({ deploymentUrl: \"...\", graphId: \"...\" }) }',\n });\n }\n\n return result;\n }\n\n handleServiceAdapter(serviceAdapter: CopilotServiceAdapter) {\n this.runtimeArgs.agents = Promise.resolve(\n this.runtimeArgs.agents ?? {},\n ).then(async (agents) => {\n let agentsList = agents;\n const isAgentsListEmpty = !Object.keys(agents).length;\n const hasServiceAdapter = Boolean(serviceAdapter);\n const illegalServiceAdapterNames = [\"EmptyAdapter\"];\n const serviceAdapterCanBeUsedForAgent =\n !illegalServiceAdapterNames.includes(serviceAdapter.name);\n\n if (\n isAgentsListEmpty &&\n (!hasServiceAdapter || !serviceAdapterCanBeUsedForAgent)\n ) {\n throw new CopilotKitMisuseError({\n message:\n \"No default agent provided. Please provide a default agent in the runtime config.\",\n });\n }\n\n if (isAgentsListEmpty) {\n const languageModel = serviceAdapter.getLanguageModel?.();\n if (languageModel) {\n // Adapter exposes a pre-configured LanguageModel (e.g. OpenAI/Anthropic adapters)\n agentsList.default = new BuiltInAgent({ model: languageModel });\n } else if (serviceAdapter.provider && serviceAdapter.model) {\n // Adapter exposes provider/model strings\n agentsList.default = new BuiltInAgent({\n model: `${serviceAdapter.provider}/${serviceAdapter.model}`,\n });\n } else {\n throw new CopilotKitMisuseError({\n message:\n `Service adapter \"${serviceAdapter.name ?? \"unknown\"}\" does not provide model information. ` +\n `When using adapters like LangChainAdapter without an explicit agents list, ` +\n `please provide a default agent in the runtime config. Example:\\n` +\n ` new CopilotRuntime({\\n` +\n ` agents: { default: new BuiltInAgent({ model: \"openai/gpt-4o\" }) }\\n` +\n ` })`,\n });\n }\n }\n\n const actions = this.params?.actions;\n if (actions) {\n const mcpTools = await this.getToolsFromMCP();\n agentsList = this.assignToolsToAgents(agents, [\n ...this.getToolsFromActions(actions),\n ...mcpTools,\n ]);\n }\n\n return agentsList;\n });\n }\n\n // Receive this.params.action and turn it into the AbstractAgent tools\n private getToolsFromActions(\n actions: ActionsConfiguration<any>,\n ): BuiltInAgentClassicConfig[\"tools\"] {\n // Resolve actions to an array (handle function case)\n const actionsArray =\n typeof actions === \"function\"\n ? actions({ properties: {}, url: undefined })\n : actions;\n\n // Convert each Action to a ToolDefinition\n return actionsArray.map((action) => {\n // Convert JSON schema to Zod schema\n const zodSchema = getZodParameters(action.parameters || []);\n\n return {\n name: action.name,\n description: action.description || \"\",\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n }\n\n private assignToolsToAgents(\n agents: Record<string, AbstractAgent>,\n tools: BuiltInAgentClassicConfig[\"tools\"],\n ): Record<string, AbstractAgent> {\n if (!tools?.length) {\n return agents;\n }\n\n const enrichedAgents: Record<string, AbstractAgent> = { ...agents };\n\n for (const [agentId, agent] of Object.entries(enrichedAgents)) {\n const existingConfig = (Reflect.get(agent, \"config\") ?? {}) as Record<\n string,\n unknown\n >;\n\n // Skip factory-mode agents — they don't have a tools property\n if (\"factory\" in existingConfig) {\n continue;\n }\n\n const classicConfig = existingConfig as BuiltInAgentClassicConfig;\n const existingTools = classicConfig.tools ?? [];\n\n const updatedConfig: BuiltInAgentClassicConfig = {\n ...classicConfig,\n tools: [...existingTools, ...tools],\n };\n\n Reflect.set(agent, \"config\", updatedConfig);\n enrichedAgents[agentId] = agent;\n }\n\n return enrichedAgents;\n }\n\n private createOnBeforeRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: BeforeRequestMiddlewareFnParameters[0]) => {\n const { request } = hookParams;\n\n // Capture telemetry for copilot request creation\n const publicApiKey = request.headers.get(\"x-copilotcloud-public-api-key\");\n const body = (await readBody(request)) as RunAgentInput;\n\n const forwardedProps = body?.forwardedProps as\n | {\n cloud?: { guardrails?: unknown };\n metadata?: { requestType?: string };\n }\n | undefined;\n\n // Get cloud base URL from environment or default\n const cloudBaseUrl =\n process.env.COPILOT_CLOUD_BASE_URL || \"https://api.cloud.copilotkit.ai\";\n\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\":\n forwardedProps?.cloud?.guardrails !== undefined,\n requestType: forwardedProps?.metadata?.requestType ?? \"unknown\",\n \"cloud.api_key_provided\": !!publicApiKey,\n ...(publicApiKey ? { \"cloud.public_api_key\": publicApiKey } : {}),\n \"cloud.base_url\": cloudBaseUrl,\n });\n\n // We do not process middleware for the internal GET requests\n if (request.method === \"GET\" || !body) return;\n\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && this.params.publicApiKey) {\n // this.logObservabilityBeforeRequest()\n // }\n\n // TODO: replace hooksParams top argument type with BeforeRequestMiddlewareParameters when exported\n const middlewareResult =\n await params?.beforeRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onBeforeRequest) {\n const { request, runtime, path } = hookParams;\n const gqlMessages = (aguiToGQL(body.messages) as Message[]).reduce(\n (acc, msg) => {\n if (\"role\" in msg && msg.role === \"user\") {\n acc.inputMessages.push(msg);\n } else {\n acc.outputMessages.push(msg);\n }\n return acc;\n },\n { inputMessages: [] as Message[], outputMessages: [] as Message[] },\n );\n const { inputMessages, outputMessages } = gqlMessages;\n params.middleware.onBeforeRequest({\n threadId: body.threadId,\n runId: body.runId,\n inputMessages,\n properties: body.forwardedProps,\n url: request.url,\n } satisfies OnBeforeRequestOptions);\n }\n\n return middlewareResult;\n };\n }\n\n private createOnAfterRequestHandler(\n params?: CopilotRuntimeConstructorParams<T> &\n PartialBy<CopilotRuntimeOptions, \"agents\">,\n ) {\n return async (hookParams: AfterRequestMiddlewareFnParameters[0]) => {\n // TODO: get public api key and run with expected data\n // if (this.observability?.enabled && publicApiKey) {\n // this.logObservabilityAfterRequest()\n // }\n\n // TODO: replace hooksParams top argument type with AfterRequestMiddlewareParameters when exported\n params?.afterRequestMiddleware?.(hookParams);\n\n if (params?.middleware?.onAfterRequest) {\n const messages = hookParams.messages ?? [];\n params.middleware.onAfterRequest({\n threadId: hookParams.threadId ?? \"\",\n runId: hookParams.runId,\n inputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role === \"user\",\n ) as unknown as Message[],\n outputMessages: messages.filter(\n (m): m is typeof m & { role: string } =>\n \"role\" in m && m.role !== \"user\",\n ) as unknown as Message[],\n // TODO: forward actual properties once the after-request hook has access to the request body\n properties: {},\n url: hookParams.path,\n } satisfies OnAfterRequestOptions);\n }\n };\n }\n\n // Observability Methods\n\n /**\n * Log LLM request if observability is enabled\n */\n private async logObservabilityBeforeRequest(\n requestData: LLMRequestData,\n ): Promise<void> {\n try {\n await this.observability.hooks.handleRequest(requestData);\n } catch (error) {\n console.error(\"Error logging LLM request:\", error);\n }\n }\n\n /**\n * Log final LLM response after request completes\n */\n private logObservabilityAfterRequest(\n outputMessagesPromise: Promise<Message[]>,\n baseData: {\n threadId: string;\n runId?: string;\n model?: string;\n provider?: string;\n agentName?: string;\n nodeName?: string;\n },\n streamedChunks: any[],\n requestStartTime: number,\n publicApiKey?: string,\n ): void {\n try {\n outputMessagesPromise\n .then((outputMessages) => {\n const responseData: LLMResponseData = {\n threadId: baseData.threadId,\n runId: baseData.runId,\n model: baseData.model,\n // Use collected chunks for progressive mode or outputMessages for regular mode\n output: this.observability.progressive\n ? streamedChunks\n : outputMessages,\n latency: Date.now() - requestStartTime,\n timestamp: Date.now(),\n provider: baseData.provider,\n isFinalResponse: true,\n agentName: baseData.agentName,\n nodeName: baseData.nodeName,\n };\n\n try {\n this.observability.hooks.handleResponse(responseData);\n } catch (logError) {\n console.error(\"Error logging LLM response:\", logError);\n }\n })\n .catch((error) => {\n console.error(\"Failed to get output messages for logging:\", error);\n });\n } catch (error) {\n console.error(\"Error setting up logging for LLM response:\", error);\n }\n }\n\n // Resolve MCP tools to BuiltInAgent tool definitions\n // Optionally accepts request-scoped properties to merge request-provided mcpServers\n private async getToolsFromMCP(options?: {\n properties?: Record<string, unknown>;\n }): Promise<BuiltInAgentClassicConfig[\"tools\"]> {\n const runtimeMcpServers = (this.params?.mcpServers ??\n []) as MCPEndpointConfig[];\n const createMCPClient = this.params?.createMCPClient as\n | CreateMCPClientFunction\n | undefined;\n\n // If no runtime config and no request overrides, nothing to do\n const requestMcpServers = ((\n options?.properties as { mcpServers?: MCPEndpointConfig[] } | undefined\n )?.mcpServers ??\n (\n options?.properties as\n | { mcpEndpoints?: MCPEndpointConfig[] }\n | undefined\n )?.mcpEndpoints ??\n []) as MCPEndpointConfig[];\n\n const hasAnyServers =\n (runtimeMcpServers?.length ?? 0) > 0 ||\n (requestMcpServers?.length ?? 0) > 0;\n if (!hasAnyServers) {\n return [];\n }\n\n if (!createMCPClient) {\n // Mirror legacy behavior: when servers are provided without a factory, treat as misconfiguration\n throw new CopilotKitMisuseError({\n message:\n \"MCP Integration Error: `mcpServers` were provided, but the `createMCPClient` function was not passed to the CopilotRuntime constructor. Please provide an implementation for `createMCPClient`.\",\n });\n }\n\n // Merge and dedupe endpoints by URL; request-level overrides take precedence\n const effectiveEndpoints = (() => {\n const byUrl = new Map<string, MCPEndpointConfig>();\n for (const ep of runtimeMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n for (const ep of requestMcpServers) {\n if (ep?.endpoint) byUrl.set(ep.endpoint, ep);\n }\n return Array.from(byUrl.values());\n })();\n\n const allTools: BuiltInAgentClassicConfig[\"tools\"] = [];\n\n for (const config of effectiveEndpoints) {\n const endpointUrl = config.endpoint;\n // Return cached tool definitions when available\n const cached = this.mcpToolsCache.get(endpointUrl);\n if (cached) {\n allTools.push(...cached);\n continue;\n }\n\n try {\n const client = await createMCPClient(config);\n const toolsMap = await client.tools();\n\n const toolDefs: BuiltInAgentClassicConfig[\"tools\"] = Object.entries(\n toolsMap,\n ).map(([toolName, tool]: [string, MCPTool]) => {\n const params: Parameter[] = extractParametersFromSchema(tool);\n const zodSchema = getZodParameters(params);\n return {\n name: toolName,\n description:\n tool.description || `MCP tool: ${toolName} (from ${endpointUrl})`,\n parameters: zodSchema,\n execute: () => Promise.resolve(),\n };\n });\n\n // Cache per endpoint and add to aggregate\n this.mcpToolsCache.set(endpointUrl, toolDefs);\n allTools.push(...toolDefs);\n } catch (error) {\n console.error(\n `MCP: Failed to fetch tools from endpoint ${endpointUrl}. Skipping. Error:`,\n error,\n );\n // Cache empty to prevent repeated attempts within lifecycle\n this.mcpToolsCache.set(endpointUrl, []);\n }\n }\n\n // Dedupe tools by name while preserving last-in wins (request overrides)\n const dedupedByName = new Map<string, (typeof allTools)[number]>();\n for (const tool of allTools) {\n dedupedByName.set(tool.name, tool);\n }\n\n return Array.from(dedupedByName.values());\n }\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(\n config: Omit<CopilotKitEndpoint, \"type\">,\n): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyVA,IAAa,iBAAb,MAAmE;CASjE,YACE,QAEA;uCAPA,IAAI,KAAK;EAQT,MAAM,SAAS,QAAQ,UAAU,EAAE;EACnC,MAAM,iBAAiB,KAAK,wBAC1B,QAAQ,mBAAmB,EAAE,CAC9B;EAKD,IAAI;AACJ,MAAI,OAAO,WAAW,WACpB,gBAAe,OAAO,QAAQ;GAC5B,MAAM,WAAW,MAAM,OAAO,IAAI;AAClC,UAAO;IAAE,GAAG;IAAgB,GAAG;IAAU;;MAG3C,gBAAe,QAAQ,QAAQ,OAAO,CAAC,MAAM,cAAc;GACzD,GAAG;GACH,GAAG;GACJ,EAAE;EAIL,MAAM,aAAa,QAAQ,UAAU,IAAIA,uCAAqB;EAK9D,MAAM,sDAA8B,GAChC,aACA,IAAIC,oDAAqB,EAAE,QAAQ,YAAY,CAAC;AAEpD,OAAK,cAAc;GACjB,QAAQ;GACR;GACA,cAAc,QAAQ;GACtB,OAAO,QAAQ;GAIf,yBACE,KAAK,6BAA6B,OAAO,CAAC,KAAK,KAAK;GACtD,GAAI,QAAQ,0BAA0B,QAAQ,YAAY,iBACtD,EACE,wBACE,KAAK,4BAA4B,OAAO,CAAC,KAAK,KAAK,EACtD,GACD,EAAE;GACN,MAAM,QAAQ;GACd,SAAS,QAAQ;GACjB,kBAAkB,QAAQ;GAC3B;AACD,OAAK,SAAS;AACd,OAAK,gBAAgB,QA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