@copilotkit/runtime 1.69.3 → 1.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/dist/agent/index.cjs +1 -1
  2. package/dist/agent/index.d.mts +1 -1
  3. package/dist/agent/index.mjs +1 -1
  4. package/dist/graphql/resolvers/copilot.resolver.cjs +1 -2
  5. package/dist/graphql/resolvers/copilot.resolver.cjs.map +1 -1
  6. package/dist/graphql/resolvers/copilot.resolver.mjs +1 -2
  7. package/dist/graphql/resolvers/copilot.resolver.mjs.map +1 -1
  8. package/dist/lib/integrations/nest/index.cjs +1 -1
  9. package/dist/lib/integrations/nest/index.cjs.map +1 -1
  10. package/dist/lib/integrations/nest/index.mjs +1 -1
  11. package/dist/lib/integrations/nest/index.mjs.map +1 -1
  12. package/dist/lib/integrations/nextjs/app-router.cjs +1 -1
  13. package/dist/lib/integrations/nextjs/app-router.cjs.map +1 -1
  14. package/dist/lib/integrations/nextjs/app-router.d.cts.map +1 -1
  15. package/dist/lib/integrations/nextjs/app-router.d.mts.map +1 -1
  16. package/dist/lib/integrations/nextjs/app-router.mjs +1 -1
  17. package/dist/lib/integrations/nextjs/app-router.mjs.map +1 -1
  18. package/dist/lib/integrations/nextjs/pages-router.cjs +1 -1
  19. package/dist/lib/integrations/nextjs/pages-router.cjs.map +1 -1
  20. package/dist/lib/integrations/nextjs/pages-router.mjs +1 -1
  21. package/dist/lib/integrations/nextjs/pages-router.mjs.map +1 -1
  22. package/dist/lib/integrations/node-express/index.cjs +1 -1
  23. package/dist/lib/integrations/node-express/index.cjs.map +1 -1
  24. package/dist/lib/integrations/node-express/index.mjs +1 -1
  25. package/dist/lib/integrations/node-express/index.mjs.map +1 -1
  26. package/dist/lib/integrations/node-http/index.cjs +1 -1
  27. package/dist/lib/integrations/node-http/index.cjs.map +1 -1
  28. package/dist/lib/integrations/node-http/index.d.cts.map +1 -1
  29. package/dist/lib/integrations/node-http/index.d.mts.map +1 -1
  30. package/dist/lib/integrations/node-http/index.mjs +1 -1
  31. package/dist/lib/integrations/node-http/index.mjs.map +1 -1
  32. package/dist/lib/integrations/shared.cjs +1 -1
  33. package/dist/lib/integrations/shared.mjs +1 -1
  34. package/dist/lib/runtime/copilot-runtime.cjs +13 -5
  35. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  36. package/dist/lib/runtime/copilot-runtime.d.cts +5 -1
  37. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  38. package/dist/lib/runtime/copilot-runtime.d.mts +5 -1
  39. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  40. package/dist/lib/runtime/copilot-runtime.mjs +13 -5
  41. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  42. package/dist/lib/runtime/telemetry-agent-runner.cjs +4 -3
  43. package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
  44. package/dist/lib/runtime/telemetry-agent-runner.d.cts +4 -0
  45. package/dist/lib/runtime/telemetry-agent-runner.d.cts.map +1 -1
  46. package/dist/lib/runtime/telemetry-agent-runner.d.mts +4 -0
  47. package/dist/lib/runtime/telemetry-agent-runner.d.mts.map +1 -1
  48. package/dist/lib/runtime/telemetry-agent-runner.mjs +4 -3
  49. package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
  50. package/dist/lib/telemetry-disclosure.cjs +4 -4
  51. package/dist/lib/telemetry-disclosure.cjs.map +1 -1
  52. package/dist/lib/telemetry-disclosure.mjs +4 -4
  53. package/dist/lib/telemetry-disclosure.mjs.map +1 -1
  54. package/dist/package.cjs +4 -4
  55. package/dist/package.mjs +4 -4
  56. package/dist/v2/index.d.cts +3 -3
  57. package/dist/v2/index.d.mts +3 -3
  58. package/dist/v2/runtime/core/channel-manager.cjs +24 -8
  59. package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
  60. package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
  61. package/dist/v2/runtime/core/channel-manager.d.mts +1 -1
  62. package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
  63. package/dist/v2/runtime/core/channel-manager.mjs +25 -9
  64. package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
  65. package/dist/v2/runtime/core/fetch-handler.cjs +1 -0
  66. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  67. package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
  68. package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
  69. package/dist/v2/runtime/core/fetch-handler.mjs +1 -0
  70. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  71. package/dist/v2/runtime/core/learning.cjs +7 -0
  72. package/dist/v2/runtime/core/learning.cjs.map +1 -1
  73. package/dist/v2/runtime/core/learning.d.cts +21 -1
  74. package/dist/v2/runtime/core/learning.d.cts.map +1 -1
  75. package/dist/v2/runtime/core/learning.d.mts +21 -1
  76. package/dist/v2/runtime/core/learning.d.mts.map +1 -1
  77. package/dist/v2/runtime/core/learning.mjs +7 -1
  78. package/dist/v2/runtime/core/learning.mjs.map +1 -1
  79. package/dist/v2/runtime/core/runtime.cjs +10 -4
  80. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  81. package/dist/v2/runtime/core/runtime.d.cts +17 -7
  82. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  83. package/dist/v2/runtime/core/runtime.d.mts +17 -7
  84. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  85. package/dist/v2/runtime/core/runtime.mjs +10 -4
  86. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  87. package/dist/v2/runtime/handlers/get-runtime-info.cjs +53 -2
  88. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
  89. package/dist/v2/runtime/handlers/get-runtime-info.mjs +53 -2
  90. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
  91. package/dist/v2/runtime/handlers/handle-connect.cjs +1 -1
  92. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -1
  93. package/dist/v2/runtime/handlers/handle-connect.mjs +1 -1
  94. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -1
  95. package/dist/v2/runtime/handlers/handle-run.cjs +1 -1
  96. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
  97. package/dist/v2/runtime/handlers/handle-run.mjs +1 -1
  98. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
  99. package/dist/v2/runtime/handlers/intelligence/run.cjs +11 -4
  100. package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
  101. package/dist/v2/runtime/handlers/intelligence/run.mjs +12 -5
  102. package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
  103. package/dist/v2/runtime/handlers/shared/sse-response.cjs +4 -4
  104. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  105. package/dist/v2/runtime/handlers/shared/sse-response.mjs +4 -4
  106. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  107. package/dist/v2/runtime/handlers/sse/connect.cjs +1 -0
  108. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  109. package/dist/v2/runtime/handlers/sse/connect.mjs +1 -0
  110. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  111. package/dist/v2/runtime/handlers/sse/run.cjs +1 -0
  112. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  113. package/dist/v2/runtime/handlers/sse/run.mjs +1 -0
  114. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  115. package/dist/v2/runtime/index.d.cts +2 -2
  116. package/dist/v2/runtime/index.d.mts +2 -2
  117. package/dist/v2/runtime/intelligence-platform/client.cjs +170 -3
  118. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  119. package/dist/v2/runtime/intelligence-platform/client.d.cts +22 -3
  120. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  121. package/dist/v2/runtime/intelligence-platform/client.d.mts +22 -3
  122. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  123. package/dist/v2/runtime/intelligence-platform/client.mjs +170 -3
  124. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  125. package/dist/v2/runtime/telemetry/events.d.cts +55 -0
  126. package/dist/v2/runtime/telemetry/events.d.cts.map +1 -0
  127. package/dist/v2/runtime/telemetry/events.d.mts +55 -0
  128. package/dist/v2/runtime/telemetry/events.d.mts.map +1 -0
  129. package/dist/v2/runtime/telemetry/instance-created.cjs +4 -2
  130. package/dist/v2/runtime/telemetry/instance-created.cjs.map +1 -1
  131. package/dist/v2/runtime/telemetry/instance-created.mjs +4 -2
  132. package/dist/v2/runtime/telemetry/instance-created.mjs.map +1 -1
  133. package/dist/v2/runtime/telemetry/telemetry-client.cjs +48 -6
  134. package/dist/v2/runtime/telemetry/telemetry-client.cjs.map +1 -1
  135. package/dist/v2/runtime/telemetry/telemetry-client.d.cts +11 -0
  136. package/dist/v2/runtime/telemetry/telemetry-client.d.cts.map +1 -0
  137. package/dist/v2/runtime/telemetry/telemetry-client.d.mts +11 -0
  138. package/dist/v2/runtime/telemetry/telemetry-client.d.mts.map +1 -0
  139. package/dist/v2/runtime/telemetry/telemetry-client.mjs +50 -7
  140. package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -1
  141. package/dist/v2/runtime/telemetry/telemetry-identity.cjs +13 -0
  142. package/dist/v2/runtime/telemetry/telemetry-identity.cjs.map +1 -0
  143. package/dist/v2/runtime/telemetry/telemetry-identity.mjs +12 -0
  144. package/dist/v2/runtime/telemetry/telemetry-identity.mjs.map +1 -0
  145. package/package.json +7 -7
  146. package/skills/runtime/SKILL.md +1 -1
@@ -7,12 +7,12 @@ let _ai_sdk_openai = require("@ai-sdk/openai");
7
7
  let _copilotkit_shared = require("@copilotkit/shared");
8
8
  let rxjs = require("rxjs");
9
9
  let _ag_ui_client = require("@ag-ui/client");
10
+ let zod = require("zod");
10
11
  let ai = require("ai");
11
12
  let _ai_sdk_mcp = require("@ai-sdk/mcp");
12
13
  let _ai_sdk_anthropic = require("@ai-sdk/anthropic");
13
14
  let _ai_sdk_google = require("@ai-sdk/google");
14
15
  let _ai_sdk_google_vertex = require("@ai-sdk/google-vertex");
15
- let zod = require("zod");
16
16
  let _modelcontextprotocol_sdk_client_streamableHttp_js = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
17
17
 
18
18
  //#region src/agent/index.ts
@@ -5,8 +5,8 @@ import "./converters/index.mjs";
5
5
  import { InferSchemaOutput, StandardSchemaV1 } from "@copilotkit/shared";
6
6
  import { Observable } from "rxjs";
7
7
  import { AbstractAgent, BaseEvent, Interrupt, Message, ResumeEntry, RunAgentInput } from "@ag-ui/client";
8
- import { LanguageModel, ModelMessage, ToolChoice, ToolSet } from "ai";
9
8
  import { z } from "zod";
9
+ import { LanguageModel, ModelMessage, ToolChoice, ToolSet } from "ai";
10
10
  import { StreamableHTTPClientTransportOptions } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
11
11
  import { AgentCapabilities } from "@ag-ui/core";
12
12
 
@@ -6,12 +6,12 @@ import { createOpenAI } from "@ai-sdk/openai";
6
6
  import { randomUUID, safeParseToolArgs, schemaToJsonSchema } from "@copilotkit/shared";
7
7
  import { Observable } from "rxjs";
8
8
  import { AbstractAgent, EventType } from "@ag-ui/client";
9
+ import { z } from "zod";
9
10
  import { jsonSchema, stepCountIs, streamText, tool } from "ai";
10
11
  import { createMCPClient } from "@ai-sdk/mcp";
11
12
  import { createAnthropic } from "@ai-sdk/anthropic";
12
13
  import { createGoogleGenerativeAI } from "@ai-sdk/google";
13
14
  import { createVertex } from "@ai-sdk/google-vertex";
14
- import { z } from "zod";
15
15
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
16
16
 
17
17
  //#region src/agent/index.ts
@@ -11,7 +11,6 @@ const require_generate_copilot_response_input = require('../inputs/generate-copi
11
11
  const require_index = require('../types/converted/index.cjs');
12
12
  const require_events = require('../../service-adapters/events.cjs');
13
13
  const require_failed_response_status_reasons = require('../../utils/failed-response-status-reasons.cjs');
14
- const require_telemetry_client = require('../../lib/telemetry-client.cjs');
15
14
  const require_resolve_message_id = require('./resolve-message-id.cjs');
16
15
  const require_agents_response_type = require('../types/agents-response.type.cjs');
17
16
  const require_events$1 = require('../../agents/langgraph/events.cjs');
@@ -64,7 +63,7 @@ let CopilotResolver = class CopilotResolver {
64
63
  return { agents: agentsWithEndpoints.map(({ endpoint, ...agentWithoutEndpoint }) => agentWithoutEndpoint) };
65
64
  }
66
65
  async generateCopilotResponse(ctx, data, properties) {
67
- require_telemetry_client.default.capture("oss.runtime.copilot_request_created", {
66
+ ctx._copilotkit.runtime.telemetry.capture("oss.runtime.copilot_request_created", {
68
67
  "cloud.guardrails.enabled": data.cloud?.guardrails !== void 0,
69
68
  requestType: data.metadata.requestType,
70
69
  "cloud.api_key_provided": !!ctx.request.headers.get("x-copilotcloud-public-api-key"),
@@ -1 +1 @@
1
- {"version":3,"file":"copilot.resolver.cjs","names":["MessageRole","GraphQLError","ReplaySubject","Repeater","RuntimeEventTypes","LangGraphEventTypes","LangGraphInterruptEvent","RuntimeMetaEventName","CopilotKitLangGraphInterruptEvent","TextMessage","SuccessMessageStatus","ActionExecutionMessage","UnknownErrorResponse","SuccessResponseStatus","GuardrailsValidationFailureResponse","Subject","resolveMessageId","FailedMessageStatus","MessageStreamInterruptedResponse","ResultMessage","AgentStateMessage","CopilotKitError","CopilotKitLowLevelError","AgentsResponse","CopilotResponse","GraphQLJSONObject"],"sources":["../../../../src/v1-deprecated/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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AiBZC,8CAAgB;iEAExB;gEACD,OAAO;gEACP,oBAAoBC,mCAAmB,EAAE,UAAU,MAAM,CAAC;;;;;;;;;gFA7BnDD,8CAAgB"}
1
+ {"version":3,"file":"copilot.resolver.cjs","names":["MessageRole","GraphQLError","ReplaySubject","Repeater","RuntimeEventTypes","LangGraphEventTypes","LangGraphInterruptEvent","RuntimeMetaEventName","CopilotKitLangGraphInterruptEvent","TextMessage","SuccessMessageStatus","ActionExecutionMessage","UnknownErrorResponse","SuccessResponseStatus","GuardrailsValidationFailureResponse","Subject","resolveMessageId","FailedMessageStatus","MessageStreamInterruptedResponse","ResultMessage","AgentStateMessage","CopilotKitError","CopilotKitLowLevelError","AgentsResponse","CopilotResponse","GraphQLJSONObject"],"sources":["../../../../src/v1-deprecated/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 { 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 ctx._copilotkit.runtime.telemetry.capture(\n \"oss.runtime.copilot_request_created\",\n {\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\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,mBAAmB,OAAO,EAC9B,SACA,0BACA,MACA,UACA,cAOI;AACJ,KACE,KAAK,SAAS,UACd,KAAK,SAAS,KAAK,SAAS,SAAS,GAAG,aAAa,SACnDA,0BAAY,MACd;EACA,MAAM,WAAW,KAAK,SACnB,QACE,MACC,EAAE,gBAAgB,WACjB,EAAE,YAAY,SAASA,0BAAY,QAClC,EAAE,YAAY,SAASA,0BAAY,WACxC,CACA,KAAK,OAAO;GACX,MAAM,EAAE,YAAa;GACrB,SAAS,EAAE,YAAY;GACxB,EAAE;EAEL,MAAM,cAAc,SAAS,S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B,KACd,IAAIV,4DAAqB;QACvB,aAAa,IAAI,WAAW;QAE5B,eAAe;SACb,MAAM,IAAI,QAAQ,IAAI,YAAY;SAClC,YAAY,IAAI,cAAc,IAAI,YAAY;SAC9C,UAAU,IAAI,YAAY,IAAI,YAAY;SAC1C,YAAY,IAAI,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,IAAIA,4DAAqB,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,sCAAqB,kBAAkB;;AAEzC,sBAAgB,KAAK,IAAIC,oDAAuB,CAAC;AACjD,+BAAyB,aAAa;AACtC,6BAAuB;AAEvB,mCAA6B,eAAe;;KAE/C,CAAC;KACF;GACH;;;;+BA7oBU,OAAO;;;;;;+BAKPU,4CAAe;iEACA;;;;;;kCAiBZC,8CAAgB;iEAExB;gEACD,OAAO;gEACP,oBAAoBC,mCAAmB,EAAE,UAAU,MAAM,CAAC;;;;;;;;;gFA7BnDD,8CAAgB"}
@@ -10,7 +10,6 @@ import { GenerateCopilotResponseInput } from "../inputs/generate-copilot-respons
10
10
  import { ActionExecutionMessage, AgentStateMessage, ResultMessage, TextMessage } from "../types/converted/index.mjs";
11
11
  import { RuntimeEventTypes, RuntimeMetaEventName } from "../../service-adapters/events.mjs";
12
12
  import { GuardrailsValidationFailureResponse, MessageStreamInterruptedResponse, UnknownErrorResponse } from "../../utils/failed-response-status-reasons.mjs";
13
- import telemetryClient from "../../lib/telemetry-client.mjs";
14
13
  import { resolveMessageId } from "./resolve-message-id.mjs";
15
14
  import { AgentsResponse } from "../types/agents-response.type.mjs";
16
15
  import { LangGraphEventTypes } from "../../agents/langgraph/events.mjs";
@@ -63,7 +62,7 @@ let CopilotResolver = class CopilotResolver {
63
62
  return { agents: agentsWithEndpoints.map(({ endpoint, ...agentWithoutEndpoint }) => agentWithoutEndpoint) };
64
63
  }
65
64
  async generateCopilotResponse(ctx, data, properties) {
66
- telemetryClient.capture("oss.runtime.copilot_request_created", {
65
+ ctx._copilotkit.runtime.telemetry.capture("oss.runtime.copilot_request_created", {
67
66
  "cloud.guardrails.enabled": data.cloud?.guardrails !== void 0,
68
67
  requestType: data.metadata.requestType,
69
68
  "cloud.api_key_provided": !!ctx.request.headers.get("x-copilotcloud-public-api-key"),
@@ -1 +1 @@
1
- {"version":3,"file":"copilot.resolver.mjs","names":[],"sources":["../../../../src/v1-deprecated/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;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,EAA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Ae,2BACd,eAAe,SACd,IAAI,QACJ,IAAI,KAAK,SAAS,aAAa,IACjC,KAAK,YAAY,YACjB;AACA,uBAAgB,KACd,IAAI,qBAAqB;QACvB,aAAa,IAAI,WAAW;QAE5B,eAAe;SACb,MAAM,IAAI,QAAQ,IAAI,YAAY;SAClC,YAAY,IAAI,cAAc,IAAI,YAAY;SAC9C,UAAU,IAAI,YAAY,IAAI,YAAY;SAC1C,YAAY,IAAI,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/v1-deprecated/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 { 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 ctx._copilotkit.runtime.telemetry.capture(\n \"oss.runtime.copilot_request_created\",\n {\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\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":";;;;;;;;;;;;;;;;;;;;;;;;;;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,uBAAuB;GACrE,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,iCAAiC;IAClC;GACD,MAAM,KAAK,UAAU,KAAK;GAC3B,CAAC;AAEF,MAAI,iBAAiB,GAEnB,UADqC,MAAM,iBAAiB,MAAM,CAC9C;MAEpB,SAAQ,MAAM,iBAAiB,MAAM,CAAC;;;AAMrC,4BAAM,gBAAgB;CAC3B,MACM,QAAQ;AACZ,SAAO;;CAGT,MACM,gBAAgB,AAAO,KAAqB;EAChD,IAAI,SAAS,IAAI,OAAO,MAAM,EAC5B,WAAW,mCACZ,CAAC;AAEF,SAAO,MAAM,aAAa;EAC1B,MAAM,sBAAsB,EAAE;A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eAAe,kBAAkB;;AAEzC,sBAAgB,KAAK,IAAI,uBAAuB,CAAC;AACjD,+BAAyB,aAAa;AACtC,6BAAuB;AAEvB,mCAA6B,eAAe;;KAE/C,CAAC;KACF;GACH;;;;CA7oBF,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"}
@@ -5,7 +5,7 @@ const require_index = require('../node-http/index.cjs');
5
5
  //#region src/v1-deprecated/lib/integrations/nest/index.ts
6
6
  function copilotRuntimeNestEndpoint(options) {
7
7
  require_telemetry_client.default.setGlobalProperties({ runtime: { framework: "nest" } });
8
- require_telemetry_client.default.capture("oss.runtime.instance_created", require_telemetry_client.getRuntimeInstanceTelemetryInfo(options));
8
+ options.runtime.telemetry.capture("oss.runtime.instance_created", require_telemetry_client.getRuntimeInstanceTelemetryInfo(options));
9
9
  return require_index.copilotRuntimeNodeHttpEndpoint(options);
10
10
  }
11
11
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getRuntimeInstanceTelemetryInfo","copilotRuntimeNodeHttpEndpoint"],"sources":["../../../../../src/v1-deprecated/lib/integrations/nest/index.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotRuntimeNestEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\n\nexport function copilotRuntimeNestEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nest\",\n },\n });\n\n telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;AAyBA,SAAgB,2BACd,SACA;AACA,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,QACZ,EACF,CAAC;AAEF,kCAAU,QACR,gCACAA,yDAAgC,QAAQ,CACzC;AACD,QAAOC,6CAA+B,QAAQ"}
1
+ {"version":3,"file":"index.cjs","names":["getRuntimeInstanceTelemetryInfo","copilotRuntimeNodeHttpEndpoint"],"sources":["../../../../../src/v1-deprecated/lib/integrations/nest/index.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotRuntimeNestEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\n\nexport function copilotRuntimeNestEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nest\",\n },\n });\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;AAyBA,SAAgB,2BACd,SACA;AACA,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,QACZ,EACF,CAAC;AAEF,SAAQ,QAAQ,UAAU,QACxB,gCACAA,yDAAgC,QAAQ,CACzC;AACD,QAAOC,6CAA+B,QAAQ"}
@@ -5,7 +5,7 @@ import { copilotRuntimeNodeHttpEndpoint } from "../node-http/index.mjs";
5
5
  //#region src/v1-deprecated/lib/integrations/nest/index.ts
6
6
  function copilotRuntimeNestEndpoint(options) {
7
7
  telemetryClient.setGlobalProperties({ runtime: { framework: "nest" } });
8
- telemetryClient.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
8
+ options.runtime.telemetry.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
9
9
  return copilotRuntimeNodeHttpEndpoint(options);
10
10
  }
11
11
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nest/index.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotRuntimeNestEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\n\nexport function copilotRuntimeNestEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nest\",\n },\n });\n\n telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;AAyBA,SAAgB,2BACd,SACA;AACA,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,QACZ,EACF,CAAC;AAEF,iBAAU,QACR,gCACA,gCAAgC,QAAQ,CACzC;AACD,QAAO,+BAA+B,QAAQ"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nest/index.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotRuntimeNestEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\n\nexport function copilotRuntimeNestEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nest\",\n },\n });\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n"],"mappings":";;;;;AAyBA,SAAgB,2BACd,SACA;AACA,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,QACZ,EACF,CAAC;AAEF,SAAQ,QAAQ,UAAU,QACxB,gCACA,gCAAgC,QAAQ,CACzC;AACD,QAAO,+BAA+B,QAAQ"}
@@ -10,7 +10,7 @@ function copilotRuntimeNextJSAppRouterEndpoint(options) {
10
10
  const commonConfig = require_shared.getCommonConfig(options);
11
11
  require_telemetry_client.default.setGlobalProperties({ runtime: { framework: "nextjs-app-router" } });
12
12
  if (options.properties?._copilotkit) require_telemetry_client.default.setGlobalProperties({ _copilotkit: options.properties._copilotkit });
13
- require_telemetry_client.default.capture("oss.runtime.instance_created", require_telemetry_client.getRuntimeInstanceTelemetryInfo(options));
13
+ options.runtime.telemetry.capture("oss.runtime.instance_created", require_telemetry_client.getRuntimeInstanceTelemetryInfo(options));
14
14
  commonConfig.logging.debug("Creating NextJS App Router endpoint");
15
15
  const serviceAdapter = options.serviceAdapter;
16
16
  if (serviceAdapter) options.runtime.handleServiceAdapter(serviceAdapter);
@@ -1 +1 @@
1
- {"version":3,"file":"app-router.cjs","names":["getCommonConfig","getRuntimeInstanceTelemetryInfo","createCopilotEndpointSingleRoute"],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotRuntimeNextJSAppRouterEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { handle } from \"hono/vercel\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\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 NextJS App Router 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 copilotRoute = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handleRequest = handle(copilotRoute as any);\n return { handleRequest };\n}\n"],"mappings":";;;;;;;;AA0BA,SAAgB,sCACd,SACA;CACA,MAAM,eAAeA,+BAAgB,QAAQ;AAE7C,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,qBACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,kCAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,kCAAU,QACR,gCACAC,yDAAgC,QAAQ,CACzC;AAGD,CADe,aAAa,QACrB,MAAM,sCAAsC;CAEnD,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;AAWtD,QAAO,EAAE,uCAPYC,qDAAiC;EACpD,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ,CAEwC,EACzB"}
1
+ {"version":3,"file":"app-router.cjs","names":["getCommonConfig","getRuntimeInstanceTelemetryInfo","createCopilotEndpointSingleRoute"],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotRuntimeNextJSAppRouterEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { handle } from \"hono/vercel\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS App Router 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 copilotRoute = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handleRequest = handle(copilotRoute as any);\n return { handleRequest };\n}\n"],"mappings":";;;;;;;;AA2BA,SAAgB,sCACd,SACA;CACA,MAAM,eAAeA,+BAAgB,QAAQ;AAE7C,kCAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,qBACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,kCAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,SAAQ,QAAQ,UAAU,QACxB,gCACAC,yDAAgC,QAAQ,CACzC;AAGD,CADe,aAAa,QACrB,MAAM,sCAAsC;CAEnD,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;AAWtD,QAAO,EAAE,uCAPYC,qDAAiC;EACpD,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ,CAEwC,EACzB"}
@@ -1 +1 @@
1
- {"version":3,"file":"app-router.d.cts","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.ts"],"mappings":";;;;iBA0BgB,qCAAA,CACd,OAAA,EAAS,iCAAA"}
1
+ {"version":3,"file":"app-router.d.cts","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.ts"],"mappings":";;;;iBA2BgB,qCAAA,CACd,OAAA,EAAS,iCAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"app-router.d.mts","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.ts"],"mappings":";;;;iBA0BgB,qCAAA,CACd,OAAA,EAAS,iCAAA"}
1
+ {"version":3,"file":"app-router.d.mts","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.ts"],"mappings":";;;;iBA2BgB,qCAAA,CACd,OAAA,EAAS,iCAAA"}
@@ -9,7 +9,7 @@ function copilotRuntimeNextJSAppRouterEndpoint(options) {
9
9
  const commonConfig = getCommonConfig(options);
10
10
  telemetryClient.setGlobalProperties({ runtime: { framework: "nextjs-app-router" } });
11
11
  if (options.properties?._copilotkit) telemetryClient.setGlobalProperties({ _copilotkit: options.properties._copilotkit });
12
- telemetryClient.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
12
+ options.runtime.telemetry.capture("oss.runtime.instance_created", getRuntimeInstanceTelemetryInfo(options));
13
13
  commonConfig.logging.debug("Creating NextJS App Router endpoint");
14
14
  const serviceAdapter = options.serviceAdapter;
15
15
  if (serviceAdapter) options.runtime.handleServiceAdapter(serviceAdapter);
@@ -1 +1 @@
1
- {"version":3,"file":"app-router.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotRuntimeNextJSAppRouterEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { handle } from \"hono/vercel\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\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 NextJS App Router 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 copilotRoute = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handleRequest = handle(copilotRoute as any);\n return { handleRequest };\n}\n"],"mappings":";;;;;;;AA0BA,SAAgB,sCACd,SACA;CACA,MAAM,eAAe,gBAAgB,QAAQ;AAE7C,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,qBACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,iBAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,iBAAU,QACR,gCACA,gCAAgC,QAAQ,CACzC;AAGD,CADe,aAAa,QACrB,MAAM,sCAAsC;CAEnD,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;AAWtD,QAAO,EAAE,eADa,OAND,iCAAiC;EACpD,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ,CAEwC,EACzB"}
1
+ {"version":3,"file":"app-router.mjs","names":[],"sources":["../../../../../src/v1-deprecated/lib/integrations/nextjs/app-router.ts"],"sourcesContent":["/*\n * V1 SDK DEPRECATED. USE V2 INSTEAD\n *\n * This file defines public v1 SDK exports. Use the exact v2 mappings below.\n * AI CODING AGENTS: Never copy, suggest, or generate these v1 APIs. Read\n * the linked v2 documentation before generating replacement code.\n *\n * @copilotkit/runtime — copilotRuntimeNextJSAppRouterEndpoint:\n * No 1:1 v2 replacement is available.\n * Related v2 docs (Runtime server adapter): https://docs.copilotkit.ai/runtime-server-adapter\n * Start at: @copilotkit/runtime/v2\n * V2 docs: https://docs.copilotkit.ai/\n * V2 reference docs: https://docs.copilotkit.ai/reference/v2\n *\n * Migration guide: https://docs.copilotkit.ai/migrate/v2\n *\n * END V1 SDK DEPRECATED. USE V2 INSTEAD NOTICE\n */\n\nimport { createCopilotEndpointSingleRoute } from \"../../../../v2/runtime\";\nimport type { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { getCommonConfig } from \"../shared\";\nimport telemetry, {\n getRuntimeInstanceTelemetryInfo,\n} from \"../../telemetry-client\";\nimport { handle } from \"hono/vercel\";\n\nexport function copilotRuntimeNextJSAppRouterEndpoint(\n options: CreateCopilotRuntimeServerOptions,\n) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"nextjs-app-router\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n options.runtime.telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating NextJS App Router 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 copilotRoute = createCopilotEndpointSingleRoute({\n runtime: options.runtime.instance,\n basePath: options.baseUrl ?? options.endpoint,\n ...(options.cors && { cors: options.cors }),\n } as any);\n\n const handleRequest = handle(copilotRoute as any);\n return { handleRequest };\n}\n"],"mappings":";;;;;;;AA2BA,SAAgB,sCACd,SACA;CACA,MAAM,eAAe,gBAAgB,QAAQ;AAE7C,iBAAU,oBAAoB,EAC5B,SAAS,EACP,WAAW,qBACZ,EACF,CAAC;AAEF,KAAI,QAAQ,YAAY,YACtB,iBAAU,oBAAoB,EAC5B,aAAa,QAAQ,WAAW,aACjC,CAAC;AAGJ,SAAQ,QAAQ,UAAU,QACxB,gCACA,gCAAgC,QAAQ,CACzC;AAGD,CADe,aAAa,QACrB,MAAM,sCAAsC;CAEnD,MAAM,iBAAiB,QAAQ;AAC/B,KAAI,eACF,SAAQ,QAAQ,qBAAqB,eAAe;AAWtD,QAAO,EAAE,eADa,OAND,iCAAiC;EACpD,SAAS,QAAQ,QAAQ;EACzB,UAAU,QAAQ,WAAW,QAAQ;EACrC,GAAI,QAAQ,QAAQ,EAAE,MAAM,QAAQ,MAAM;EAC3C,CAAQ,CAEwC,EACzB"}