@copilotkit/runtime 1.5.12-next.2 → 1.5.12-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/{chunk-BETLEV37.mjs → chunk-4A5VMMYR.mjs} +2 -2
- package/dist/{chunk-SFLMY3ES.mjs → chunk-JGMDVBJN.mjs} +2 -2
- package/dist/{chunk-FA5DJ2TZ.mjs → chunk-QAUSY7SM.mjs} +2 -2
- package/dist/{chunk-FA5DJ2TZ.mjs.map → chunk-QAUSY7SM.mjs.map} +1 -1
- package/dist/{chunk-ZCU6UPCY.mjs → chunk-VFFEKEC2.mjs} +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/lib/index.js +1 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +4 -4
- package/dist/lib/integrations/index.js +1 -1
- package/dist/lib/integrations/index.js.map +1 -1
- package/dist/lib/integrations/index.mjs +4 -4
- package/dist/lib/integrations/nest/index.js +1 -1
- package/dist/lib/integrations/nest/index.js.map +1 -1
- package/dist/lib/integrations/nest/index.mjs +2 -2
- package/dist/lib/integrations/node-express/index.js +1 -1
- package/dist/lib/integrations/node-express/index.js.map +1 -1
- package/dist/lib/integrations/node-express/index.mjs +2 -2
- package/dist/lib/integrations/node-http/index.js +1 -1
- package/dist/lib/integrations/node-http/index.js.map +1 -1
- package/dist/lib/integrations/node-http/index.mjs +1 -1
- package/package.json +2 -2
- /package/dist/{chunk-BETLEV37.mjs.map → chunk-4A5VMMYR.mjs.map} +0 -0
- /package/dist/{chunk-SFLMY3ES.mjs.map → chunk-JGMDVBJN.mjs.map} +0 -0
- /package/dist/{chunk-ZCU6UPCY.mjs.map → chunk-VFFEKEC2.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../package.json","../../../../src/lib/integrations/node-express/index.ts","../../../../src/lib/integrations/node-http/index.ts","../../../../src/lib/integrations/shared.ts","../../../../src/graphql/resolvers/copilot.resolver.ts","../../../../src/graphql/inputs/generate-copilot-response.input.ts","../../../../src/graphql/inputs/message.input.ts","../../../../src/graphql/types/enums.ts","../../../../src/graphql/types/base/index.ts","../../../../src/graphql/inputs/frontend.input.ts","../../../../src/graphql/inputs/action.input.ts","../../../../src/graphql/inputs/cloud.input.ts","../../../../src/graphql/inputs/cloud-guardrails.input.ts","../../../../src/graphql/inputs/forwarded-parameters.input.ts","../../../../src/graphql/inputs/agent-session.input.ts","../../../../src/graphql/inputs/agent-state.input.ts","../../../../src/graphql/types/copilot-response.type.ts","../../../../src/graphql/types/message-status.type.ts","../../../../src/graphql/types/response-status.type.ts","../../../../src/service-adapters/events.ts","../../../../src/lib/telemetry-client.ts","../../../../src/lib/runtime/remote-actions.ts","../../../../src/lib/runtime/copilot-runtime.ts","../../../../src/graphql/types/converted/index.ts","../../../../src/utils/failed-response-status-reasons.ts","../../../../src/graphql/types/agents-response.type.ts","../../../../src/lib/logger.ts"],"sourcesContent":["{\n \"name\": \"@copilotkit/runtime\",\n \"private\": false,\n \"homepage\": \"https://github.com/CopilotKit/CopilotKit\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/CopilotKit/CopilotKit.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"version\": \"1.5.12-next.2\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"exports\": {\n \".\": \"./dist/index.js\"\n },\n \"types\": \"./dist/index.d.ts\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"tsup --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"dev\": \"tsup --watch --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"test\": \"jest --passWithNoTests\",\n \"check-types\": \"tsc --noEmit\",\n \"clean\": \"rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next && rm -rf __snapshots__\",\n \"generate-graphql-schema\": \"rm -rf __snapshots__ && ts-node ./scripts/generate-gql-schema.ts\",\n \"link:global\": \"pnpm link --global\",\n \"unlink:global\": \"pnpm unlink --global\"\n },\n \"devDependencies\": {\n \"@swc/core\": \"1.5.28\",\n \"@types/express\": \"^4.17.21\",\n \"@types/jest\": \"^29.5.4\",\n \"@types/node\": \"^18.11.17\",\n \"@whatwg-node/server\": \"^0.9.34\",\n \"eslint\": \"^8.56.0\",\n \"eslint-config-custom\": \"workspace:*\",\n \"jest\": \"^29.6.4\",\n \"nodemon\": \"^3.1.3\",\n \"ts-jest\": \"^29.1.1\",\n \"ts-node\": \"^10.9.2\",\n \"tsconfig\": \"workspace:*\",\n \"tsup\": \"^6.7.0\",\n \"typescript\": \"^5.2.3\",\n \"zod-to-json-schema\": \"^3.23.5\"\n },\n \"dependencies\": {\n \"@anthropic-ai/sdk\": \"^0.27.3\",\n \"@copilotkit/shared\": \"workspace:*\",\n \"@graphql-yoga/plugin-defer-stream\": \"^3.3.1\",\n \"@langchain/community\": \"^0.0.53\",\n \"@langchain/core\": \"^0.3.13\",\n \"@langchain/google-gauth\": \"^0.1.0\",\n \"@langchain/langgraph-sdk\": \"^0.0.16\",\n \"@langchain/openai\": \"^0.0.28\",\n \"class-transformer\": \"^0.5.1\",\n \"express\": \"^4.19.2\",\n \"graphql\": \"^16.8.1\",\n \"graphql-scalars\": \"^1.23.0\",\n \"graphql-yoga\": \"^5.3.1\",\n \"groq-sdk\": \"^0.5.0\",\n \"langchain\": \"^0.3.3\",\n \"openai\": \"^4.50.0\",\n \"partial-json\": \"^0.1.7\",\n \"pino\": \"^9.2.0\",\n \"pino-pretty\": \"^11.2.1\",\n \"reflect-metadata\": \"^0.2.2\",\n \"rxjs\": \"^7.8.1\",\n \"type-graphql\": \"2.0.0-rc.1\",\n \"zod\": \"^3.23.3\"\n },\n \"keywords\": [\n \"copilotkit\",\n \"copilot\",\n \"react\",\n \"nextjs\",\n \"nodejs\",\n \"ai\",\n \"assistant\",\n \"javascript\",\n \"automation\",\n \"textarea\"\n ]\n}\n","import { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, { getRuntimeInstanceTelemetryInfo } from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeExpressEndpoint(options: CreateCopilotRuntimeServerOptions) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-express\",\n },\n });\n\n telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options.runtime),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n","import { createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, { getRuntimeInstanceTelemetryInfo } from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeHttpEndpoint(options: CreateCopilotRuntimeServerOptions) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options.runtime),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n });\n\n return yoga;\n}\n","import { YogaInitialContext } from \"graphql-yoga\";\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport { useDeferStream } from \"@graphql-yoga/plugin-defer-stream\";\nimport { CopilotRuntime } from \"../runtime/copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../service-adapters\";\nimport { CopilotCloudOptions } from \"../cloud\";\nimport { LogLevel, createLogger } from \"../../lib/logger\";\nimport { createYoga } from \"graphql-yoga\";\nimport telemetry from \"../telemetry-client\";\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\nexport type GraphQLContext = YogaInitialContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n}\n\nexport async function createContext(\n initialContext: YogaInitialContext,\n copilotKitContext: CreateCopilotRuntimeServerOptions,\n contextLogger: typeof logger,\n properties: CopilotRequestContextProperties = {},\n): Promise<Partial<GraphQLContext>> {\n logger.debug({ copilotKitContext }, \"Creating GraphQL context\");\n const ctx: GraphQLContext = {\n ...initialContext,\n _copilotkit: {\n ...copilotKitContext,\n },\n properties: { ...properties },\n logger: contextLogger,\n };\n return ctx;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n schema: ReturnType<typeof buildSchema>;\n plugins: Parameters<typeof createYoga>[0][\"plugins\"];\n context: (ctx: YogaInitialContext) => Promise<Partial<GraphQLContext>>;\n};\n\nexport function getCommonConfig(options: CreateCopilotRuntimeServerOptions): CommonConfig {\n const logLevel = (process.env.LOG_LEVEL as LogLevel) || (options.logLevel as LogLevel) || \"error\";\n const logger = createLogger({ level: logLevel, component: \"getCommonConfig\" });\n\n const contextLogger = createLogger({ level: logLevel });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter.constructor.name,\n },\n });\n\n return {\n logging: createLogger({ component: \"Yoga GraphQL\", level: logLevel }),\n schema: buildSchema(),\n plugins: [useDeferStream()],\n context: (ctx: YogaInitialContext): Promise<Partial<GraphQLContext>> =>\n createContext(ctx, options, contextLogger, options.properties),\n };\n}\n","import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport {\n ReplaySubject,\n Subject,\n Subscription,\n filter,\n finalize,\n firstValueFrom,\n shareReplay,\n skipWhile,\n take,\n takeWhile,\n tap,\n} from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport { ActionInputAvailability, MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type { CopilotRequestContextProperties, GraphQLContext } from \"../../lib/integrations\";\nimport { RuntimeEvent, RuntimeEventTypes } from \"../../service-adapters/events\";\nimport {\n FailedMessageStatus,\n MessageStatusUnion,\n SuccessMessageStatus,\n} from \"../types/message-status.type\";\nimport { ResponseStatusUnion, SuccessResponseStatus } from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\nimport { plainToInstance } from \"class-transformer\";\nimport { GuardrailsResult } from \"../types/guardrails-result.type\";\nimport { GraphQLError } from \"graphql\";\nimport {\n GuardrailsValidationFailureResponse,\n MessageStreamInterruptedResponse,\n UnknownErrorResponse,\n} from \"../../utils\";\nimport {\n ActionExecutionMessage,\n AgentStateMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../types/converted\";\nimport telemetry from \"../../lib/telemetry-client\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { EndpointType, LangGraphPlatformAgent } from \"../../lib/runtime/remote-actions\";\nimport { AgentsResponse } from \"../types/agents-response.type\";\n\nconst invokeGuardrails = async ({\n baseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult,\n onError,\n}: {\n baseUrl: string;\n copilotCloudPublicApiKey: string;\n data: GenerateCopilotResponseInput;\n onResult: (result: GuardrailsResult) => void;\n onError: (err: Error) => void;\n}) => {\n if (\n data.messages.length &&\n data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant),\n )\n .map((m) => ({\n role: m.textMessage!.role,\n content: m.textMessage.content,\n }));\n\n const lastMessage = messages[messages.length - 1];\n const restOfMessages = messages.slice(0, -1);\n\n const body = {\n input: lastMessage.content,\n validTopics: data.cloud.guardrails.inputValidationRules.allowList,\n invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,\n messages: restOfMessages,\n };\n\n const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CopilotCloud-Public-API-Key\": copilotCloudPublicApiKey,\n },\n body: JSON.stringify(body),\n });\n\n if (guardrailsResult.ok) {\n const resultJson: GuardrailsResult = await guardrailsResult.json();\n onResult(resultJson);\n } else {\n onError(await guardrailsResult.json());\n }\n }\n};\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n @Query(() => String)\n async hello() {\n return \"Hello World\";\n }\n\n @Query(() => AgentsResponse)\n async availableAgents(@Ctx() ctx: GraphQLContext) {\n let logger = ctx.logger.child({ component: \"CopilotResolver.availableAgents\" });\n\n logger.debug(\"Processing\");\n const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);\n\n logger.debug(\"Event source created, creating response\");\n\n return {\n agents,\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 });\n\n let logger = ctx.logger.child({ component: \"CopilotResolver.generateCopilotResponse\" });\n logger.debug({ data }, \"Generating Copilot response\");\n\n if (properties) {\n logger.debug(\"Properties provided, merging with context properties\");\n ctx.properties = { ...ctx.properties, ...properties };\n }\n\n const copilotRuntime = ctx._copilotkit.runtime;\n const serviceAdapter = ctx._copilotkit.serviceAdapter;\n\n let copilotCloudPublicApiKey: string | null = null;\n let copilotCloudBaseUrl: string;\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\"Cloud configuration provided, checking for public API key in headers\");\n const key = ctx.request.headers.get(\"x-copilotcloud-public-api-key\");\n if (key) {\n logger.debug(\"Public API key found in headers\");\n copilotCloudPublicApiKey = key;\n } else {\n logger.error(\"Public API key not found in headers\");\n throw new GraphQLError(\"X-CopilotCloud-Public-API-Key header is required\");\n }\n\n if (process.env.COPILOT_CLOUD_BASE_URL) {\n copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;\n } else if (ctx._copilotkit.cloud?.baseUrl) {\n copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;\n } else {\n copilotCloudBaseUrl = \"https://api.cloud.copilotkit.ai\";\n }\n\n logger = logger.child({ copilotCloudBaseUrl });\n }\n\n logger.debug(\"Setting up subjects\");\n const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();\n const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();\n const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();\n\n let outputMessages: Message[] = [];\n let resolveOutputMessagesPromise: (messages: Message[]) => void;\n let rejectOutputMessagesPromise: (err: Error) => void;\n\n const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {\n resolveOutputMessagesPromise = resolve;\n rejectOutputMessagesPromise = reject;\n });\n\n logger.debug(\"Processing\");\n const {\n eventSource,\n threadId = randomId(),\n runId,\n serverSideActions,\n actionInputsWithoutAgents,\n } = await copilotRuntime.processRuntimeRequest({\n serviceAdapter,\n messages: data.messages,\n actions: data.frontend.actions.filter(\n (action) => action.available !== ActionInputAvailability.disabled,\n ),\n threadId: data.threadId,\n runId: data.runId,\n publicApiKey: undefined,\n outputMessagesPromise,\n graphqlContext: ctx,\n forwardedParameters: data.forwardedParameters,\n agentSession: data.agentSession,\n agentStates: data.agentStates,\n url: data.frontend.url,\n });\n\n logger.debug(\"Event source created, creating response\");\n\n const response = {\n threadId,\n runId,\n status: firstValueFrom(responseStatus$),\n messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n logger.debug(\"Messages repeater created\");\n\n if (data.cloud?.guardrails) {\n logger = logger.child({ guardrails: true });\n logger.debug(\"Guardrails is enabled, validating input\");\n\n invokeGuardrails({\n baseUrl: copilotCloudBaseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult: (result) => {\n logger.debug({ status: result.status }, \"Guardrails validation done\");\n guardrailsResult$.next(result);\n\n // Guardrails validation failed\n if (result.status === \"denied\") {\n // send the reason to the client and interrupt streaming\n responseStatus$.next(\n new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,\n });\n\n // resolve messages promise to the middleware\n outputMessages = [\n plainToInstance(TextMessage, {\n id: randomId(),\n createdAt: new Date(),\n content: result.reason,\n role: MessageRole.assistant,\n }),\n ];\n resolveOutputMessagesPromise(outputMessages);\n }\n },\n onError: (err) => {\n logger.error({ err }, \"Error in guardrails validation\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the guardrails validation`,\n }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to unknown error in guardrails validation`,\n });\n\n // reject the middleware promise\n rejectOutputMessagesPromise(err);\n },\n });\n }\n\n let eventStreamSubscription: Subscription;\n\n // run and process the event stream\n const eventStream = eventSource\n .processRuntimeEvents({\n serverSideActions,\n guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,\n actionInputsWithoutAgents: actionInputsWithoutAgents.filter(\n // TODO-AGENTS: do not exclude ALL server side actions\n (action) =>\n !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n ),\n })\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 logger.debug(\"Event stream created, subscribing to event stream\");\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n switch (event.type) {\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) => e !== event),\n // take until the message end event\n takeWhile(\n (e) =>\n !(\n e.type === RuntimeEventTypes.TextMessageEnd &&\n e.messageId == event.messageId\n ),\n ),\n // filter out any other message events or message ids\n filter(\n (e) =>\n e.type == RuntimeEventTypes.TextMessageContent &&\n e.messageId == event.messageId,\n ),\n );\n\n // signal when we are done streaming\n const streamingTextStatus = new Subject<typeof MessageStatusUnion>();\n\n const messageId = event.messageId;\n // push the new message\n pushMessage({\n id: messageId,\n parentMessageId: event.parentMessageId,\n status: firstValueFrom(streamingTextStatus),\n createdAt: new Date(),\n role: MessageRole.assistant,\n content: new Repeater(async (pushTextChunk, stopStreamingText) => {\n logger.debug(\"Text message content repeater created\");\n\n const textChunks: string[] = [];\n let textSubscription: Subscription;\n\n interruptStreaming$\n .pipe(\n shareReplay(),\n take(1),\n tap(({ reason, messageId }) => {\n logger.debug({ reason, messageId }, \"Text streaming interrupted\");\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(new MessageStreamInterruptedResponse({ messageId }));\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\"Subscribing to text message content stream\");\n\n textSubscription = textMessageContentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.TextMessageContent) {\n await pushTextChunk(e.content);\n textChunks.push(e.content);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in text message content stream\");\n interruptStreaming$.next({\n reason: \"Error streaming message content\",\n messageId,\n });\n stopStreamingText();\n textSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Text message content stream completed\");\n streamingTextStatus.next(new SuccessMessageStatus());\n stopStreamingText();\n textSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(TextMessage, {\n id: messageId,\n createdAt: new Date(),\n content: textChunks.join(\"\"),\n role: MessageRole.assistant,\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionStart\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionStart:\n logger.debug(\"Action execution start event received\");\n const actionExecutionArgumentStream = eventStream.pipe(\n skipWhile((e) => e !== event),\n // take until the action execution end event\n takeWhile(\n (e) =>\n !(\n e.type === RuntimeEventTypes.ActionExecutionEnd &&\n e.actionExecutionId == event.actionExecutionId\n ),\n ),\n // filter out any other action execution events or action execution ids\n filter(\n (e) =>\n e.type == RuntimeEventTypes.ActionExecutionArgs &&\n e.actionExecutionId == event.actionExecutionId,\n ),\n );\n const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();\n pushMessage({\n id: event.actionExecutionId,\n parentMessageId: event.parentMessageId,\n status: firstValueFrom(streamingArgumentsStatus),\n createdAt: new Date(),\n name: event.actionName,\n arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.ActionExecutionArgs) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in action execution argument stream\");\n streamingArgumentsStatus.next(\n plainToInstance(FailedMessageStatus, {\n reason:\n \"An unknown error has occurred in the action execution argument stream\",\n }),\n );\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Action execution argument stream completed\");\n streamingArgumentsStatus.next(new SuccessMessageStatus());\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(ActionExecutionMessage, {\n id: event.actionExecutionId,\n createdAt: new Date(),\n name: event.actionName,\n arguments: argumentChunks.join(\"\"),\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug({ result: event.result }, \"Action execution result event received\");\n pushMessage({\n id: \"result-\" + event.actionExecutionId,\n status: new SuccessMessageStatus(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n });\n\n outputMessages.push(\n plainToInstance(ResultMessage, {\n id: \"result-\" + event.actionExecutionId,\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n }),\n );\n break;\n ////////////////////////////////\n // AgentStateMessage\n ////////////////////////////////\n case RuntimeEventTypes.AgentStateMessage:\n logger.debug({ event }, \"Agent message event received\");\n pushMessage({\n id: randomId(),\n status: new SuccessMessageStatus(),\n threadId: event.threadId,\n agentName: event.agentName,\n nodeName: event.nodeName,\n runId: event.runId,\n active: event.active,\n state: event.state,\n running: event.running,\n role: MessageRole.assistant,\n createdAt: new Date(),\n });\n outputMessages.push(\n plainToInstance(AgentStateMessage, {\n id: randomId(),\n threadId: event.threadId,\n agentName: event.agentName,\n nodeName: event.nodeName,\n runId: event.runId,\n active: event.active,\n state: event.state,\n running: event.running,\n role: MessageRole.assistant,\n createdAt: new Date(),\n }),\n );\n break;\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in event stream\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n rejectOutputMessagesPromise(err);\n },\n complete: async () => {\n logger.debug(\"Event stream completed\");\n if (data.cloud?.guardrails) {\n logger.debug(\"Guardrails is enabled, waiting for guardrails result\");\n await firstValueFrom(guardrailsResult$);\n }\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n resolveOutputMessagesPromise(outputMessages);\n },\n });\n }),\n };\n\n return response;\n }\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageInput } from \"./message.input\";\nimport { FrontendInput } from \"./frontend.input\";\nimport { CloudInput } from \"./cloud.input\";\nimport { CopilotRequestType } from \"../types/enums\";\nimport { ForwardedParametersInput } from \"./forwarded-parameters.input\";\nimport { AgentSessionInput } from \"./agent-session.input\";\nimport { AgentStateInput } from \"./agent-state.input\";\n\n@InputType()\nexport class GenerateCopilotResponseMetadataInput {\n @Field(() => CopilotRequestType, { nullable: true })\n requestType: CopilotRequestType;\n}\n\n@InputType()\nexport class GenerateCopilotResponseInput {\n @Field(() => GenerateCopilotResponseMetadataInput, { nullable: false })\n metadata: GenerateCopilotResponseMetadataInput;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => [MessageInput])\n messages: MessageInput[];\n\n @Field(() => FrontendInput)\n frontend: FrontendInput;\n\n @Field(() => CloudInput, { nullable: true })\n cloud?: CloudInput;\n\n @Field(() => ForwardedParametersInput, { nullable: true })\n forwardedParameters?: ForwardedParametersInput;\n\n @Field(() => AgentSessionInput, { nullable: true })\n agentSession?: AgentSessionInput;\n\n @Field(() => AgentStateInput, { nullable: true })\n agentState?: AgentStateInput;\n\n @Field(() => [AgentStateInput], { nullable: true })\n agentStates?: AgentStateInput[];\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageRole } from \"../types/enums\";\nimport { BaseMessageInput } from \"../types/base\";\n\n// GraphQL does not support union types in inputs, so we need to use\n// optional fields for the different subtypes.\n@InputType()\nexport class MessageInput extends BaseMessageInput {\n @Field(() => TextMessageInput, { nullable: true })\n textMessage?: TextMessageInput;\n\n @Field(() => ActionExecutionMessageInput, { nullable: true })\n actionExecutionMessage?: ActionExecutionMessageInput;\n\n @Field(() => ResultMessageInput, { nullable: true })\n resultMessage?: ResultMessageInput;\n\n @Field(() => AgentStateMessageInput, { nullable: true })\n agentStateMessage?: AgentStateMessageInput;\n}\n\n@InputType()\nexport class TextMessageInput {\n @Field(() => String)\n content: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n\n@InputType()\nexport class ActionExecutionMessageInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n arguments: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => String, {\n nullable: true,\n deprecationReason: \"This field will be removed in a future version\",\n })\n scope?: String;\n}\n\n@InputType()\nexport class ResultMessageInput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => String)\n result: string;\n}\n\n@InputType()\nexport class AgentStateMessageInput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String)\n state: string;\n\n @Field(() => Boolean)\n running: boolean;\n\n @Field(() => String)\n nodeName: string;\n\n @Field(() => String)\n runId: string;\n\n @Field(() => Boolean)\n active: boolean;\n}\n","import { registerEnumType } from \"type-graphql\";\n\nexport enum MessageRole {\n user = \"user\",\n assistant = \"assistant\",\n system = \"system\",\n tool = \"tool\",\n}\n\nexport enum CopilotRequestType {\n Chat = \"Chat\",\n Task = \"Task\",\n TextareaCompletion = \"TextareaCompletion\",\n TextareaPopover = \"TextareaPopover\",\n Suggestion = \"Suggestion\",\n}\n\nexport enum ActionInputAvailability {\n disabled = \"disabled\",\n enabled = \"enabled\",\n remote = \"remote\",\n}\n\nregisterEnumType(MessageRole, {\n name: \"MessageRole\",\n description: \"The role of the message\",\n});\n\nregisterEnumType(CopilotRequestType, {\n name: \"CopilotRequestType\",\n description: \"The type of Copilot request\",\n});\n\nregisterEnumType(ActionInputAvailability, {\n name: \"ActionInputAvailability\",\n description: \"The availability of the frontend action\",\n});\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class BaseMessageInput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInput } from \"./action.input\";\n\n@InputType()\nexport class FrontendInput {\n @Field(() => String, { nullable: true })\n toDeprecate_fullContext?: string;\n\n @Field(() => [ActionInput])\n actions: ActionInput[];\n\n @Field(() => String, { nullable: true })\n url?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInputAvailability } from \"../types/enums\";\n@InputType()\nexport class ActionInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n jsonSchema: string;\n\n @Field(() => ActionInputAvailability, { nullable: true })\n available?: ActionInputAvailability;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { GuardrailsInput } from \"./cloud-guardrails.input\";\n\n@InputType()\nexport class CloudInput {\n @Field(() => GuardrailsInput, { nullable: true })\n guardrails?: GuardrailsInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class GuardrailsRuleInput {\n @Field(() => [String], { nullable: true })\n allowList?: string[] = [];\n\n @Field(() => [String], { nullable: true })\n denyList?: string[] = [];\n}\n\n@InputType()\nexport class GuardrailsInput {\n @Field(() => GuardrailsRuleInput, { nullable: false })\n inputValidationRules: GuardrailsRuleInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ForwardedParametersInput {\n @Field(() => String, { nullable: true })\n model?: string;\n\n @Field(() => Number, { nullable: true })\n maxTokens?: number;\n\n @Field(() => [String], { nullable: true })\n stop?: string[];\n\n @Field(() => String, { nullable: true })\n toolChoice?: String;\n\n @Field(() => String, { nullable: true })\n toolChoiceFunctionName?: string;\n\n @Field(() => Number, { nullable: true })\n temperature?: number;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class AgentSessionInput {\n @Field(() => String)\n agentName: string;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n nodeName?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class AgentStateInput {\n @Field(() => String)\n agentName: string;\n\n @Field(() => String)\n state: string;\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\n\n@InterfaceType({\n resolveType(value) {\n if (value.hasOwnProperty(\"content\")) {\n return TextMessageOutput;\n } else if (value.hasOwnProperty(\"name\")) {\n return ActionExecutionMessageOutput;\n } else if (value.hasOwnProperty(\"result\")) {\n return ResultMessageOutput;\n } else if (value.hasOwnProperty(\"state\")) {\n return AgentStateMessageOutput;\n }\n return undefined;\n },\n})\nabstract class BaseMessageOutput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n\n @Field(() => MessageStatusUnion)\n status: typeof MessageStatusUnion;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class TextMessageOutput {\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => [String])\n content: string[];\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ActionExecutionMessageOutput {\n @Field(() => String)\n name: string;\n\n @Field(() => String, {\n nullable: true,\n deprecationReason: \"This field will be removed in a future version\",\n })\n scope?: string;\n\n @Field(() => [String])\n arguments: string[];\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ResultMessageOutput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class AgentStateMessageOutput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n\n @Field(() => String)\n nodeName: string;\n\n @Field(() => String)\n runId: string;\n\n @Field(() => Boolean)\n active: boolean;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String)\n state: string;\n\n @Field(() => Boolean)\n running: boolean;\n}\n\n@ObjectType()\nexport class CopilotResponse {\n @Field(() => String)\n threadId!: string;\n\n @Field(() => ResponseStatusUnion)\n status: typeof ResponseStatusUnion;\n\n @Field({ nullable: true })\n runId?: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n}\n","import { Field, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum MessageStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(MessageStatusCode, {\n name: \"MessageStatusCode\",\n});\n\n@ObjectType()\nclass BaseMessageStatus {\n @Field(() => MessageStatusCode)\n code: MessageStatusCode;\n}\n\n@ObjectType()\nexport class PendingMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Pending;\n}\n\n@ObjectType()\nexport class SuccessMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Success;\n}\n\n@ObjectType()\nexport class FailedMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Failed;\n\n @Field(() => String)\n reason: string;\n}\n\nexport const MessageStatusUnion = createUnionType({\n name: \"MessageStatus\",\n types: () => [PendingMessageStatus, SuccessMessageStatus, FailedMessageStatus] as const,\n});\n","import { GraphQLJSON } from \"graphql-scalars\";\nimport { Field, InterfaceType, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum ResponseStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(ResponseStatusCode, {\n name: \"ResponseStatusCode\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.code === ResponseStatusCode.Success) {\n return SuccessResponseStatus;\n } else if (value.code === ResponseStatusCode.Failed) {\n return FailedResponseStatus;\n } else if (value.code === ResponseStatusCode.Pending) {\n return PendingResponseStatus;\n }\n return undefined;\n },\n})\n@ObjectType()\nabstract class BaseResponseStatus {\n @Field(() => ResponseStatusCode)\n code: ResponseStatusCode;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class PendingResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Pending;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class SuccessResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Success;\n}\n\nexport enum FailedResponseStatusReason {\n GUARDRAILS_VALIDATION_FAILED = \"GUARDRAILS_VALIDATION_FAILED\",\n MESSAGE_STREAM_INTERRUPTED = \"MESSAGE_STREAM_INTERRUPTED\",\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nregisterEnumType(FailedResponseStatusReason, {\n name: \"FailedResponseStatusReason\",\n});\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class FailedResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Failed;\n\n @Field(() => FailedResponseStatusReason)\n reason: FailedResponseStatusReason;\n\n @Field(() => GraphQLJSON, { nullable: true })\n details?: Record<string, any> = null;\n}\n\nexport const ResponseStatusUnion = createUnionType({\n name: \"ResponseStatus\",\n types: () => [PendingResponseStatus, SuccessResponseStatus, FailedResponseStatus] as const,\n});\n","import { Action, randomId } from \"@copilotkit/shared\";\nimport {\n of,\n concat,\n scan,\n concatMap,\n ReplaySubject,\n Subject,\n firstValueFrom,\n from,\n catchError,\n EMPTY,\n} from \"rxjs\";\nimport { streamLangChainResponse } from \"./langchain/utils\";\nimport { GuardrailsResult } from \"../graphql/types/guardrails-result.type\";\nimport telemetry from \"../lib/telemetry-client\";\nimport { isLangGraphAgentAction } from \"../lib/runtime/remote-actions\";\nimport { ActionInput } from \"../graphql/inputs/action.input\";\nimport { ActionExecutionMessage, ResultMessage } from \"../graphql/types/converted\";\nimport { plainToInstance } from \"class-transformer\";\n\nexport enum RuntimeEventTypes {\n TextMessageStart = \"TextMessageStart\",\n TextMessageContent = \"TextMessageContent\",\n TextMessageEnd = \"TextMessageEnd\",\n ActionExecutionStart = \"ActionExecutionStart\",\n ActionExecutionArgs = \"ActionExecutionArgs\",\n ActionExecutionEnd = \"ActionExecutionEnd\",\n ActionExecutionResult = \"ActionExecutionResult\",\n AgentStateMessage = \"AgentStateMessage\",\n}\n\nexport type RuntimeEvent =\n | { type: RuntimeEventTypes.TextMessageStart; messageId: string; parentMessageId?: string }\n | {\n type: RuntimeEventTypes.TextMessageContent;\n messageId: string;\n content: string;\n }\n | { type: RuntimeEventTypes.TextMessageEnd; messageId: string }\n | {\n type: RuntimeEventTypes.ActionExecutionStart;\n actionExecutionId: string;\n actionName: string;\n parentMessageId?: string;\n }\n | { type: RuntimeEventTypes.ActionExecutionArgs; actionExecutionId: string; args: string }\n | { type: RuntimeEventTypes.ActionExecutionEnd; actionExecutionId: string }\n | {\n type: RuntimeEventTypes.ActionExecutionResult;\n actionName: string;\n actionExecutionId: string;\n result: string;\n }\n | {\n type: RuntimeEventTypes.AgentStateMessage;\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: string;\n state: string;\n running: boolean;\n };\n\ninterface RuntimeEventWithState {\n event: RuntimeEvent | null;\n callActionServerSide: boolean;\n action: Action<any> | null;\n actionExecutionId: string | null;\n args: string;\n actionExecutionParentMessageId: string | null;\n}\n\ntype EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;\n\nexport class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {\n constructor() {\n super();\n }\n\n sendTextMessageStart({\n messageId,\n parentMessageId,\n }: {\n messageId: string;\n parentMessageId?: string;\n }) {\n this.next({ type: RuntimeEventTypes.TextMessageStart, messageId, parentMessageId });\n }\n\n sendTextMessageContent({ messageId, content }: { messageId: string; content: string }) {\n this.next({ type: RuntimeEventTypes.TextMessageContent, content, messageId });\n }\n\n sendTextMessageEnd({ messageId }: { messageId: string }) {\n this.next({ type: RuntimeEventTypes.TextMessageEnd, messageId });\n }\n\n sendTextMessage(messageId: string, content: string) {\n this.sendTextMessageStart({ messageId });\n this.sendTextMessageContent({ messageId, content });\n this.sendTextMessageEnd({ messageId });\n }\n\n sendActionExecutionStart({\n actionExecutionId,\n actionName,\n parentMessageId,\n }: {\n actionExecutionId: string;\n actionName: string;\n parentMessageId?: string;\n }) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionStart,\n actionExecutionId,\n actionName,\n parentMessageId,\n });\n }\n\n sendActionExecutionArgs({\n actionExecutionId,\n args,\n }: {\n actionExecutionId: string;\n args: string;\n }) {\n this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args, actionExecutionId });\n }\n\n sendActionExecutionEnd({ actionExecutionId }: { actionExecutionId: string }) {\n this.next({ type: RuntimeEventTypes.ActionExecutionEnd, actionExecutionId });\n }\n\n sendActionExecution({\n actionExecutionId,\n actionName,\n args,\n parentMessageId,\n }: {\n actionExecutionId: string;\n actionName: string;\n args: string;\n parentMessageId?: string;\n }) {\n this.sendActionExecutionStart({ actionExecutionId, actionName, parentMessageId });\n this.sendActionExecutionArgs({ actionExecutionId, args });\n this.sendActionExecutionEnd({ actionExecutionId });\n }\n\n sendActionExecutionResult({\n actionExecutionId,\n actionName,\n result,\n error,\n }: {\n actionExecutionId: string;\n actionName: string;\n result?: string;\n error?: { code: string; message: string };\n }) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionResult,\n actionName,\n actionExecutionId,\n result: ResultMessage.encodeResult(result, error),\n });\n }\n\n sendAgentStateMessage({\n threadId,\n agentName,\n nodeName,\n runId,\n active,\n role,\n state,\n running,\n }: {\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: string;\n state: string;\n running: boolean;\n }) {\n this.next({\n type: RuntimeEventTypes.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n active,\n role,\n state,\n running,\n });\n }\n}\n\nexport class RuntimeEventSource {\n private eventStream$ = new RuntimeEventSubject();\n private callback!: EventSourceCallback;\n\n async stream(callback: EventSourceCallback): Promise<void> {\n this.callback = callback;\n }\n\n sendErrorMessageToChat(message = \"An error occurred. Please try again.\") {\n const errorMessage = `❌ ${message}`;\n if (!this.callback) {\n this.stream(async (eventStream$) => {\n eventStream$.sendTextMessage(randomId(), errorMessage);\n });\n } else {\n this.eventStream$.sendTextMessage(randomId(), errorMessage);\n }\n }\n\n processRuntimeEvents({\n serverSideActions,\n guardrailsResult$,\n actionInputsWithoutAgents,\n }: {\n serverSideActions: Action<any>[];\n guardrailsResult$?: Subject<GuardrailsResult>;\n actionInputsWithoutAgents: ActionInput[];\n }) {\n this.callback(this.eventStream$).catch((error) => {\n console.error(\"Error in event source callback\", error);\n this.sendErrorMessageToChat();\n this.eventStream$.complete();\n });\n return this.eventStream$.pipe(\n // track state\n scan(\n (acc, event) => {\n // It seems like this is needed so that rxjs recognizes the object has changed\n // This fixes an issue where action were executed multiple times\n // Not investigating further for now (Markus)\n acc = { ...acc };\n\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n acc.callActionServerSide =\n serverSideActions.find((action) => action.name === event.actionName) !== undefined;\n acc.args = \"\";\n acc.actionExecutionId = event.actionExecutionId;\n if (acc.callActionServerSide) {\n acc.action = serverSideActions.find((action) => action.name === event.actionName);\n }\n acc.actionExecutionParentMessageId = event.parentMessageId;\n } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {\n acc.args += event.args;\n }\n\n acc.event = event;\n\n return acc;\n },\n {\n event: null,\n callActionServerSide: false,\n args: \"\",\n actionExecutionId: null,\n action: null,\n actionExecutionParentMessageId: null,\n } as RuntimeEventWithState,\n ),\n concatMap((eventWithState) => {\n if (\n eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&\n eventWithState.callActionServerSide\n ) {\n const toolCallEventStream$ = new RuntimeEventSubject();\n executeAction(\n toolCallEventStream$,\n guardrailsResult$ ? guardrailsResult$ : null,\n eventWithState.action!,\n eventWithState.args,\n eventWithState.actionExecutionParentMessageId,\n eventWithState.actionExecutionId,\n actionInputsWithoutAgents,\n ).catch((error) => {\n console.error(error);\n });\n\n telemetry.capture(\"oss.runtime.server_action_executed\", {});\n return concat(of(eventWithState.event!), toolCallEventStream$).pipe(\n catchError((error) => {\n console.error(\"Error in tool call stream\", error);\n this.sendErrorMessageToChat();\n return EMPTY;\n }),\n );\n } else {\n return of(eventWithState.event!);\n }\n }),\n );\n }\n}\n\nasync function executeAction(\n eventStream$: RuntimeEventSubject,\n guardrailsResult$: Subject<GuardrailsResult> | null,\n action: Action<any>,\n actionArguments: string,\n actionExecutionParentMessageId: string | null,\n actionExecutionId: string,\n actionInputsWithoutAgents: ActionInput[],\n) {\n if (guardrailsResult$) {\n const { status } = await firstValueFrom(guardrailsResult$);\n\n if (status === \"denied\") {\n eventStream$.complete();\n return;\n }\n }\n\n // Prepare arguments for function calling\n let args: Record<string, any>[] = [];\n if (actionArguments) {\n try {\n args = JSON.parse(actionArguments);\n } catch (e) {\n console.error(\"Action argument unparsable\", { actionArguments });\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: \"INVALID_ARGUMENTS\",\n message: \"Failed to parse action arguments\",\n },\n });\n return;\n }\n }\n\n // handle LangGraph agents\n if (isLangGraphAgentAction(action)) {\n const result = `${action.name} agent started`;\n\n const agentExecution = plainToInstance(ActionExecutionMessage, {\n id: actionExecutionId,\n createdAt: new Date(),\n name: action.name,\n arguments: JSON.parse(actionArguments),\n parentMessageId: actionExecutionParentMessageId ?? actionExecutionId,\n });\n\n const agentExecutionResult = plainToInstance(ResultMessage, {\n id: \"result-\" + actionExecutionId,\n createdAt: new Date(),\n actionExecutionId,\n actionName: action.name,\n result,\n });\n\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n result,\n });\n\n const stream = await action.langGraphAgentHandler({\n name: action.name,\n actionInputsWithoutAgents,\n additionalMessages: [agentExecution, agentExecutionResult],\n });\n\n // forward to eventStream$\n from(stream).subscribe({\n next: (event) => eventStream$.next(event),\n error: (err) => {\n console.error(\"Error in stream\", err);\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: \"STREAM_ERROR\",\n message: err.message,\n },\n });\n eventStream$.complete();\n },\n complete: () => eventStream$.complete(),\n });\n } else {\n // call the function\n try {\n const result = await action.handler?.(args);\n await streamLangChainResponse({\n result,\n eventStream$,\n actionExecution: {\n name: action.name,\n id: actionExecutionId,\n },\n });\n } catch (e) {\n console.error(\"Error in action handler\", e);\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: \"HANDLER_ERROR\",\n message: e.message,\n },\n });\n eventStream$.complete();\n }\n }\n}\n","import { TelemetryClient } from \"@copilotkit/shared\";\nimport { EndpointType, LangGraphPlatformEndpoint } from \"./runtime/remote-actions\";\nimport { createHash } from \"node:crypto\";\nimport { CopilotRuntime, resolveEndpointType } from \"./runtime/copilot-runtime\";\nimport { RuntimeInstanceCreatedInfo } from \"@copilotkit/shared/src/telemetry/events\";\nconst packageJson = require(\"../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport function getRuntimeInstanceTelemetryInfo(\n runtime: CopilotRuntime,\n): RuntimeInstanceCreatedInfo {\n const endpointsInfo = runtime.remoteEndpointDefinitions.reduce(\n (acc, endpoint) => {\n let info = { ...acc };\n\n const endpointType = resolveEndpointType(endpoint);\n if (!info.endpointTypes.includes(endpointType)) {\n info = {\n ...info,\n endpointTypes: [...info.endpointTypes, endpointType],\n };\n }\n\n if (endpointType === EndpointType.LangGraphPlatform) {\n // When type is resolved, recreating a const with casting of type\n const ep = endpoint as LangGraphPlatformEndpoint;\n info = {\n ...info,\n agentsAmount: ep.agents.length,\n hashedKey: createHash(\"sha256\").update(ep.langsmithApiKey).digest(\"hex\"),\n };\n }\n\n return info;\n },\n { endpointTypes: [], agentsAmount: null, hashedKey: null },\n );\n\n return {\n actionsAmount: runtime.actions.length,\n endpointsAmount: runtime.remoteEndpointDefinitions.length,\n endpointTypes: endpointsInfo.endpointTypes,\n agentsAmount: endpointsInfo.agentsAmount,\n hashedLgcKey: endpointsInfo.hashedKey,\n };\n}\n\nexport default telemetryClient;\n","import { Action } from \"@copilotkit/shared\";\nimport { GraphQLContext } from \"../integrations/shared\";\nimport { Logger } from \"pino\";\nimport { Message } from \"../../graphql/types/converted\";\nimport { RuntimeEvent } from \"../../service-adapters/events\";\nimport { Observable } from \"rxjs\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { AgentStateInput } from \"../../graphql/inputs/agent-state.input\";\nimport {\n constructLGCRemoteAction,\n constructRemoteActions,\n createHeaders,\n} from \"./remote-action-constructors\";\n\nexport type EndpointDefinition = CopilotKitEndpoint | LangGraphPlatformEndpoint;\n\nexport enum EndpointType {\n CopilotKit = \"copilotKit\",\n LangGraphPlatform = \"langgraph-platform\",\n}\n\nexport interface BaseEndpointDefinition<TActionType extends EndpointType> {\n type?: TActionType;\n}\n\nexport interface CopilotKitEndpoint extends BaseEndpointDefinition<EndpointType.CopilotKit> {\n url: string;\n onBeforeRequest?: ({ ctx }: { ctx: GraphQLContext }) => {\n headers?: Record<string, string> | undefined;\n };\n}\n\nexport interface LangGraphPlatformAgent {\n name: string;\n description: string;\n assistantId?: string;\n}\n\nexport interface LangGraphPlatformEndpoint\n extends BaseEndpointDefinition<EndpointType.LangGraphPlatform> {\n deploymentUrl: string;\n langsmithApiKey: string;\n agents: LangGraphPlatformAgent[];\n}\n\nexport type RemoteActionInfoResponse = {\n actions: any[];\n agents: any[];\n};\n\nexport type LangGraphAgentHandlerParams = {\n name: string;\n actionInputsWithoutAgents: ActionInput[];\n threadId?: string;\n nodeName?: string;\n additionalMessages?: Message[];\n};\n\nexport type LangGraphAgentAction = Action<any> & {\n langGraphAgentHandler: (params: LangGraphAgentHandlerParams) => Promise<Observable<RuntimeEvent>>;\n};\n\nexport function isLangGraphAgentAction(action: Action<any>): action is LangGraphAgentAction {\n if (!action) {\n return false;\n }\n return typeof (action as LangGraphAgentAction).langGraphAgentHandler === \"function\";\n}\n\nasync function fetchRemoteInfo({\n url,\n onBeforeRequest,\n graphqlContext,\n logger,\n frontendUrl,\n}: {\n url: string;\n onBeforeRequest?: CopilotKitEndpoint[\"onBeforeRequest\"];\n graphqlContext: GraphQLContext;\n logger: Logger;\n frontendUrl?: string;\n}): Promise<RemoteActionInfoResponse> {\n logger.debug({ url }, \"Fetching actions from url\");\n const headers = createHeaders(onBeforeRequest, graphqlContext);\n\n try {\n const response = await fetch(`${url}/info`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ properties: graphqlContext.properties, frontendUrl }),\n });\n\n if (!response.ok) {\n logger.error(\n { url, status: response.status, body: await response.text() },\n \"Failed to fetch actions from url\",\n );\n return { actions: [], agents: [] };\n }\n\n const json = await response.json();\n logger.debug({ json }, \"Fetched actions from url\");\n return json;\n } catch (error) {\n logger.error(\n { error: error.message ? error.message : error + \"\" },\n \"Failed to fetch actions from url\",\n );\n return { actions: [], agents: [] };\n }\n}\n\nexport async function setupRemoteActions({\n remoteEndpointDefinitions,\n graphqlContext,\n messages,\n agentStates,\n frontendUrl,\n}: {\n remoteEndpointDefinitions: EndpointDefinition[];\n graphqlContext: GraphQLContext;\n messages: Message[];\n agentStates?: AgentStateInput[];\n frontendUrl?: string;\n}): Promise<Action[]> {\n const logger = graphqlContext.logger.child({ component: \"remote-actions.fetchRemoteActions\" });\n logger.debug({ remoteEndpointDefinitions }, \"Fetching from remote endpoints\");\n\n // Remove duplicates of remoteEndpointDefinitions.url\n const filtered = remoteEndpointDefinitions.filter((value, index, self) => {\n if (value.type === EndpointType.LangGraphPlatform) {\n return value;\n }\n return index === self.findIndex((t: CopilotKitEndpoint) => t.url === value.url);\n });\n\n const result = await Promise.all(\n filtered.map(async (endpoint) => {\n // Check for properties that can distinguish LG platform from other actions\n if (endpoint.type === EndpointType.LangGraphPlatform) {\n return constructLGCRemoteAction({\n endpoint,\n messages,\n graphqlContext,\n logger: logger.child({\n component: \"remote-actions.constructLGCRemoteAction\",\n endpoint,\n }),\n agentStates,\n });\n }\n\n const json = await fetchRemoteInfo({\n url: endpoint.url,\n onBeforeRequest: endpoint.onBeforeRequest,\n graphqlContext,\n logger: logger.child({ component: \"remote-actions.fetchActionsFromUrl\", endpoint }),\n frontendUrl,\n });\n\n return constructRemoteActions({\n json,\n messages,\n url: endpoint.url,\n onBeforeRequest: endpoint.onBeforeRequest,\n graphqlContext,\n logger: logger.child({ component: \"remote-actions.constructActions\", endpoint }),\n agentStates,\n });\n }),\n );\n\n return result.flat();\n}\n","/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/concepts/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport { Action, actionParametersToJsonSchema, Parameter, randomId } from \"@copilotkit/shared\";\nimport { CopilotServiceAdapter, RemoteChain, RemoteChainParameters } from \"../../service-adapters\";\nimport { MessageInput } from \"../../graphql/inputs/message.input\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { RuntimeEventSource } from \"../../service-adapters/events\";\nimport { convertGqlInputToMessages } from \"../../service-adapters/conversion\";\nimport { Message } from \"../../graphql/types/converted\";\nimport { ForwardedParametersInput } from \"../../graphql/inputs/forwarded-parameters.input\";\nimport {\n isLangGraphAgentAction,\n LangGraphAgentAction,\n EndpointType,\n setupRemoteActions,\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./remote-actions\";\nimport { GraphQLContext } from \"../integrations/shared\";\nimport { AgentSessionInput } from \"../../graphql/inputs/agent-session.input\";\nimport { from } from \"rxjs\";\nimport { AgentStateInput } from \"../../graphql/inputs/agent-state.input\";\nimport { ActionInputAvailability } from \"../../graphql/types/enums\";\nimport { createHeaders } from \"./remote-action-constructors\";\nimport { Agent } from \"../../graphql/types/agents-response.type\";\n\ninterface CopilotRuntimeRequest {\n serviceAdapter: CopilotServiceAdapter;\n messages: MessageInput[];\n actions: ActionInput[];\n agentSession?: AgentSessionInput;\n agentStates?: AgentStateInput[];\n outputMessagesPromise: Promise<Message[]>;\n threadId?: string;\n runId?: string;\n publicApiKey?: string;\n graphqlContext: GraphQLContext;\n forwardedParameters?: ForwardedParametersInput;\n url?: string;\n}\n\ninterface CopilotRuntimeResponse {\n threadId: string;\n runId?: string;\n eventSource: RuntimeEventSource;\n serverSideActions: Action<any>[];\n actionInputsWithoutAgents: ActionInput[];\n}\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (options: OnBeforeRequestOptions) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (options: OnAfterRequestOptions) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed.\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n}\n\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n public actions: ActionsConfiguration<T>;\n public remoteEndpointDefinitions: EndpointDefinition[];\n private langserve: Promise<Action<any>>[] = [];\n private onBeforeRequest?: OnBeforeRequestHandler;\n private onAfterRequest?: OnAfterRequestHandler;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n this.actions = params?.actions || [];\n\n for (const chain of params?.langserve || []) {\n const remoteChain = new RemoteChain(chain);\n this.langserve.push(remoteChain.toAction());\n }\n\n this.remoteEndpointDefinitions = params?.remoteEndpoints ?? params?.remoteActions ?? [];\n\n this.onBeforeRequest = params?.middleware?.onBeforeRequest;\n this.onAfterRequest = params?.middleware?.onAfterRequest;\n }\n\n async processRuntimeRequest(request: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {\n const {\n serviceAdapter,\n messages: rawMessages,\n actions: clientSideActionsInput,\n threadId,\n runId,\n outputMessagesPromise,\n graphqlContext,\n forwardedParameters,\n agentSession,\n url,\n } = request;\n\n const eventSource = new RuntimeEventSource();\n\n try {\n if (agentSession) {\n return await this.processAgentRequest(request);\n }\n\n const messages = rawMessages.filter((message) => !message.agentStateMessage);\n\n const inputMessages = convertGqlInputToMessages(messages);\n const serverSideActions = await this.getServerSideActions(request);\n\n const serverSideActionsInput: ActionInput[] = serverSideActions.map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n }));\n\n const actionInputs = flattenToolCallsNoDuplicates([\n ...serverSideActionsInput,\n ...clientSideActionsInput.filter(\n // Filter remote actions from CopilotKit core loop\n (action) => action.available !== ActionInputAvailability.remote,\n ),\n ]);\n\n await this.onBeforeRequest?.({\n threadId,\n runId,\n inputMessages,\n properties: graphqlContext.properties,\n url,\n });\n\n const result = await serviceAdapter.process({\n messages: inputMessages,\n actions: actionInputs,\n threadId,\n runId,\n eventSource,\n forwardedParameters,\n });\n\n outputMessagesPromise\n .then((outputMessages) => {\n this.onAfterRequest?.({\n threadId: result.threadId,\n runId: result.runId,\n inputMessages,\n outputMessages,\n properties: graphqlContext.properties,\n url,\n });\n })\n .catch((_error) => {});\n\n return {\n threadId: result.threadId,\n runId: result.runId,\n eventSource,\n serverSideActions,\n actionInputsWithoutAgents: actionInputs.filter(\n (action) =>\n // TODO-AGENTS: do not exclude ALL server side actions\n !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n // !isLangGraphAgentAction(\n // serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n // ),\n ),\n };\n } catch (error) {\n console.error(\"Error getting response:\", error);\n eventSource.sendErrorMessageToChat();\n throw error;\n }\n }\n\n async discoverAgentsFromEndpoints(graphqlContext: GraphQLContext): Promise<Agent[]> {\n const headers = createHeaders(null, graphqlContext);\n const agents = this.remoteEndpointDefinitions.reduce(\n async (acc: Promise<Agent[]>, endpoint) => {\n const agents = await acc;\n if (endpoint.type === EndpointType.LangGraphPlatform) {\n const response = await fetch(\n `${(endpoint as LangGraphPlatformEndpoint).deploymentUrl}/assistants/search`,\n {\n method: \"POST\",\n headers,\n },\n );\n\n const data: Array<{ assistant_id: string; graph_id: string }> = await response.json();\n const endpointAgents = (data ?? []).map((entry) => ({\n name: entry.graph_id,\n id: entry.assistant_id,\n }));\n return [...agents, ...endpointAgents];\n }\n\n interface InfoResponse {\n agents?: Array<{\n name: string;\n description: string;\n }>;\n }\n\n const response = await fetch(`${(endpoint as CopilotKitEndpoint).url}/info`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ properties: graphqlContext.properties }),\n });\n const data: InfoResponse = await response.json();\n const endpointAgents = (data?.agents ?? []).map((agent) => ({\n name: agent.name,\n description: agent.description,\n id: randomId(), // Required by Agent type\n }));\n return [...agents, ...endpointAgents];\n },\n Promise.resolve([]),\n );\n\n return agents;\n }\n\n private async processAgentRequest(\n request: CopilotRuntimeRequest,\n ): Promise<CopilotRuntimeResponse> {\n const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession } = request;\n const { threadId, agentName, nodeName } = agentSession;\n const serverSideActions = await this.getServerSideActions(request);\n\n const messages = convertGqlInputToMessages(rawMessages);\n\n const agent = serverSideActions.find(\n (action) => action.name === agentName && isLangGraphAgentAction(action),\n ) as LangGraphAgentAction;\n\n if (!agent) {\n throw new Error(`Agent ${agentName} not found`);\n }\n\n const serverSideActionsInput: ActionInput[] = serverSideActions\n .filter((action) => !isLangGraphAgentAction(action))\n .map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n }));\n\n const actionInputsWithoutAgents = flattenToolCallsNoDuplicates([\n ...serverSideActionsInput,\n ...request.actions,\n ]);\n\n await this.onBeforeRequest?.({\n threadId,\n runId: undefined,\n inputMessages: messages,\n properties: graphqlContext.properties,\n });\n try {\n const eventSource = new RuntimeEventSource();\n const stream = await agent.langGraphAgentHandler({\n name: agentName,\n threadId,\n nodeName,\n actionInputsWithoutAgents,\n });\n\n eventSource.stream(async (eventStream$) => {\n from(stream).subscribe({\n next: (event) => eventStream$.next(event),\n error: (err) => {\n console.error(\"Error in stream\", err);\n eventStream$.error(err);\n eventStream$.complete();\n },\n complete: () => eventStream$.complete(),\n });\n });\n\n outputMessagesPromise\n .then((outputMessages) => {\n this.onAfterRequest?.({\n threadId,\n runId: undefined,\n inputMessages: messages,\n outputMessages,\n properties: graphqlContext.properties,\n });\n })\n .catch((_error) => {});\n\n return {\n threadId,\n runId: undefined,\n eventSource,\n serverSideActions: [],\n actionInputsWithoutAgents,\n };\n } catch (error) {\n console.error(\"Error getting response:\", error);\n throw error;\n }\n }\n\n private async getServerSideActions(request: CopilotRuntimeRequest): Promise<Action<any>[]> {\n const { messages: rawMessages, graphqlContext, agentStates, url } = request;\n const inputMessages = convertGqlInputToMessages(rawMessages);\n const langserveFunctions: Action<any>[] = [];\n\n for (const chainPromise of this.langserve) {\n try {\n const chain = await chainPromise;\n langserveFunctions.push(chain);\n } catch (error) {\n console.error(\"Error loading langserve chain:\", error);\n }\n }\n\n const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map(\n (endpoint) =>\n ({\n ...endpoint,\n type: resolveEndpointType(endpoint),\n }) as EndpointDefinition,\n );\n\n const remoteActions = await setupRemoteActions({\n remoteEndpointDefinitions,\n graphqlContext,\n messages: inputMessages,\n agentStates,\n frontendUrl: url,\n });\n\n const configuredActions =\n typeof this.actions === \"function\"\n ? this.actions({ properties: graphqlContext.properties, url })\n : this.actions;\n\n return [...configuredActions, ...langserveFunctions, ...remoteActions];\n }\n}\n\nexport function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {\n let allTools: ActionInput[] = [];\n const allToolNames: string[] = [];\n for (const tool of toolsByPriority) {\n if (!allToolNames.includes(tool.name)) {\n allTools.push(tool);\n allToolNames.push(tool.name);\n }\n }\n return allTools;\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(config: Omit<CopilotKitEndpoint, \"type\">): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"langsmithApiKey\" in endpoint && \"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n","import {\n ActionExecutionMessageInput,\n ResultMessageInput,\n TextMessageInput,\n AgentStateMessageInput,\n} from \"../../inputs/message.input\";\nimport { BaseMessageInput } from \"../base\";\nimport { MessageRole } from \"../enums\";\n\nexport type MessageType =\n | \"TextMessage\"\n | \"ActionExecutionMessage\"\n | \"ResultMessage\"\n | \"AgentStateMessage\";\n\nexport class Message extends BaseMessageInput {\n type: MessageType;\n\n isTextMessage(): this is TextMessage {\n return this.type === \"TextMessage\";\n }\n\n isActionExecutionMessage(): this is ActionExecutionMessage {\n return this.type === \"ActionExecutionMessage\";\n }\n\n isResultMessage(): this is ResultMessage {\n return this.type === \"ResultMessage\";\n }\n\n isAgentStateMessage(): this is AgentStateMessage {\n return this.type === \"AgentStateMessage\";\n }\n}\n\nexport class TextMessage extends Message implements TextMessageInput {\n type: MessageType = \"TextMessage\";\n content: string;\n role: MessageRole;\n parentMessageId?: string;\n}\n\nexport class ActionExecutionMessage\n extends Message\n implements Omit<ActionExecutionMessageInput, \"arguments\" | \"scope\">\n{\n type: MessageType = \"ActionExecutionMessage\";\n name: string;\n arguments: Record<string, any>;\n parentMessageId?: string;\n}\n\nexport class ResultMessage extends Message implements ResultMessageInput {\n type: MessageType = \"ResultMessage\";\n actionExecutionId: string;\n actionName: string;\n result: string;\n\n static encodeResult(\n result: any,\n error?: { code: string; message: string } | string | Error,\n ): string {\n const errorObj = error\n ? typeof error === \"string\"\n ? { code: \"ERROR\", message: error }\n : error instanceof Error\n ? { code: \"ERROR\", message: error.message }\n : error\n : undefined;\n\n if (errorObj) {\n return JSON.stringify({\n error: errorObj,\n result: result || \"\",\n });\n }\n if (result === undefined) {\n return \"\";\n }\n return typeof result === \"string\" ? result : JSON.stringify(result);\n }\n\n static decodeResult(result: string): {\n error?: { code: string; message: string };\n result: string;\n } {\n if (!result) {\n return { result: \"\" };\n }\n try {\n const parsed = JSON.parse(result);\n if (parsed && typeof parsed === \"object\") {\n if (\"error\" in parsed) {\n return {\n error: parsed.error,\n result: parsed.result || \"\",\n };\n }\n return { result: JSON.stringify(parsed) };\n }\n return { result };\n } catch (e) {\n return { result };\n }\n }\n\n hasError(): boolean {\n try {\n const { error } = ResultMessage.decodeResult(this.result);\n return !!error;\n } catch {\n return false;\n }\n }\n\n getError(): { code: string; message: string } | undefined {\n try {\n const { error } = ResultMessage.decodeResult(this.result);\n return error;\n } catch {\n return undefined;\n }\n }\n}\n\nexport class AgentStateMessage extends Message implements Omit<AgentStateMessageInput, \"state\"> {\n type: MessageType = \"AgentStateMessage\";\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: MessageRole;\n state: any;\n running: boolean;\n}\n","import {\n FailedResponseStatus,\n FailedResponseStatusReason,\n} from \"../graphql/types/response-status.type\";\n\nexport class GuardrailsValidationFailureResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.GUARDRAILS_VALIDATION_FAILED;\n declare details: {\n guardrailsReason: string;\n };\n\n constructor({ guardrailsReason }) {\n super();\n this.details = {\n guardrailsReason,\n };\n }\n}\n\nexport class MessageStreamInterruptedResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.MESSAGE_STREAM_INTERRUPTED;\n declare details: {\n messageId: string;\n description: string;\n };\n\n constructor({ messageId }: { messageId: string }) {\n super();\n this.details = {\n messageId,\n description: \"Check the message for mode details\",\n };\n }\n}\n\nexport class UnknownErrorResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.UNKNOWN_ERROR;\n declare details: {\n description?: string;\n };\n\n constructor({ description }: { description?: string }) {\n super();\n this.details = {\n description,\n };\n }\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\n\n@ObjectType()\nexport class Agent {\n @Field(() => String)\n id: string;\n\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description?: string;\n}\n\n@ObjectType()\nexport class AgentsResponse {\n @Field(() => [Agent])\n agents: Agent[];\n}\n","import createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: { level?: LogLevel; component?: string }) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,0BAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,UAAY;AAAA,MACZ,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,eAAiB;AAAA,QACf,QAAU;AAAA,MACZ;AAAA,MACA,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,SAAW;AAAA,QACT,KAAK;AAAA,MACP;AAAA,MACA,OAAS;AAAA,MACT,SAAW;AAAA,MACX,SAAW;AAAA,QACT,OAAS;AAAA,QACT,K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AAAA;AACxC;AAZgBD;","names":["module","import_graphql_yoga","import_type_graphql","import_type_graphql","import_rxjs","import_type_graphql","import_type_graphql","MessageRole","CopilotRequestType","ActionInputAvailability","registerEnumType","name","description","import_type_graphql","BaseMessageInput","id","createdAt","Field","String","Date","InputType","MessageInput","BaseMessageInput","textMessage","actionExecutionMessage","resultMessage","agentStateMessage","Field","TextMessageInput","nullable","ActionExecutionMessageInput","ResultMessageInput","AgentStateMessageInput","InputType","content","parentMessageId","role","String","MessageRole","name","arguments","scope","deprecationReason","actionExecutionId","actionName","result","threadId","agentName","state","running","nodeName","runId","active","Boolean","import_type_graphql","import_type_graphql","ActionInput","name","description","jsonSchema","available","Field","String","ActionInputAvailability","nullable","InputType","FrontendInput","toDeprecate_fullContext","actions","url","Field","String","nullable","ActionInput","InputType","import_type_graphql","import_type_graphql","GuardrailsRuleInput","allowList","denyList","Field","String","nullable","InputType","GuardrailsInput","inputValidationRules","CloudInput","guardrails","Field","GuardrailsInput","nullable","InputType","import_type_graphql","ForwardedParametersInput","model","maxTokens","stop","toolChoice","toolChoiceFunctionName","temperature","Field","String","nullable","Number","InputType","import_type_graphql","AgentSessionInput","agentName","threadId","nodeName","Field","String","nullable","InputType","import_type_graphql","AgentStateInput","agentName","state","Field","String","InputType","GenerateCopilotResponseMetadataInput","requestType","Field","CopilotRequestType","nullable","InputType","GenerateCopilotResponseInput","metadata","threadId","runId","messages","frontend","cloud","forwardedParameters","agentSession","agentState","agentStates","String","MessageInput","FrontendInput","CloudInput","ForwardedParametersInput","AgentSessionInput","AgentStateInput","import_type_graphql","import_type_graphql","MessageStatusCode","registerEnumType","name","BaseMessageStatus","code","Field","ObjectType","PendingMessageStatus","SuccessMessageStatus","FailedMessageStatus","reason","String","MessageStatusUnion","createUnionType","types","import_type_graphql","ResponseStatusCode","registerEnumType","name","BaseResponseStatus","code","Field","InterfaceType","resolveType","value","SuccessResponseStatus","FailedResponseStatus","PendingResponseStatus","undefined","ObjectType","implements","FailedResponseStatusReason","reason","details","GraphQLJSON","nullable","ResponseStatusUnion","createUnionType","types","BaseMessageOutput","id","createdAt","status","Field","String","Date","MessageStatusUnion","InterfaceType","resolveType","value","hasOwnProperty","TextMessageOutput","ActionExecutionMessageOutput","ResultMessageOutput","AgentStateMessageOutput","undefined","role","content","parentMessageId","MessageRole","nullable","ObjectType","implements","name","scope","arguments","deprecationReason","actionExecutionId","actionName","result","threadId","agentName","nodeName","runId","active","state","running","Boolean","CopilotResponse","messages","ResponseStatusUnion","import_shared","import_rxjs","import_shared","EndpointType","Message","BaseMessageInput","type","isTextMessage","isActionExecutionMessage","isResultMessage","isAgentStateMessage","TextMessage","content","role","parentMessageId","ActionExecutionMessage","name","arguments","ResultMessage","actionExecutionId","actionName","result","encodeResult","error","errorObj","code","message","Error","undefined","JSON","stringify","decodeResult","parsed","parse","e","hasError","getError","AgentStateMessage","threadId","agentName","nodeName","runId","active","state","running","resolveEndpointType","endpoint","type","EndpointType","LangGraphPlatform","CopilotKit","packageJson","require","telemetryClient","TelemetryClient","packageName","name","packageVersion","version","getRuntimeInstanceTelemetryInfo","runtime","endpointsInfo","remoteEndpointDefinitions","reduce","acc","endpoint","info","endpointType","resolveEndpointType","endpointTypes","includes","EndpointType","LangGraphPlatform","ep","agentsAmount","agents","length","hashedKey","createHash","update","langsmithApiKey","digest","actionsAmount","actions","endpointsAmount","hashedLgcKey","RuntimeEventTypes","import_graphql_scalars","import_class_transformer","GuardrailsValidationFailureResponse","FailedResponseStatus","reason","FailedResponseStatusReason","GUARDRAILS_VALIDATION_FAILED","constructor","guardrailsReason","details","MessageStreamInterruptedResponse","MESSAGE_STREAM_INTERRUPTED","messageId","description","UnknownErrorResponse","UNKNOWN_ERROR","import_shared","import_type_graphql","Agent","id","name","description","Field","String","ObjectType","AgentsResponse","agents","invokeGuardrails","baseUrl","copilotCloudPublicApiKey","data","onResult","onError","messages","length","textMessage","role","MessageRole","user","filter","m","undefined","assistant","map","content","lastMessage","restOfMessages","slice","body","input","validTopics","cloud","guardrails","inputValidationRules","allowList","invalidTopics","denyList","guardrailsResult","fetch","method","headers","JSON","stringify","ok","resultJson","json","CopilotResolver","hello","availableAgents","ctx","logger","child","component","debug","agents","_copilotkit","runtime","discoverAgentsFromEndpoints","generateCopilotResponse","properties","telemetry","capture","requestType","metadata","copilotRuntime","serviceAdapter","copilotCloudBaseUrl","key","request","get","error","GraphQLError","process","env","COPILOT_CLOUD_BASE_URL","responseStatus$","ReplaySubject","interruptStreaming$","guardrailsResult$","outputMessages","resolveOutputMessagesPromise","rejectOutputMessagesPromise","outputMessagesPromise","Promise","resolve","reject","eventSource","threadId","randomId","runId","serverSideActions","actionInputsWithoutAgents","processRuntimeRequest","actions","frontend","action","available","ActionInputAvailability","disabled","publicApiKey","graphqlContext","forwardedParameters","agentSession","agentStates","url","response","status","firstValueFrom","Repeater","pushMessage","stopStreamingMessages","result","next","GuardrailsValidationFailureResponse","guardrailsReason","reason","plainToInstance","TextMessage","id","createdAt","Date","err","UnknownErrorResponse","description","eventStreamSubscription","eventStream","processRuntimeEvents","find","serverSideAction","name","pipe","shareReplay","finalize","subscribe","event","type","RuntimeEventTypes","TextMessageStart","textMessageContentStream","skipWhile","e","takeWhile","TextMessageEnd","messageId","TextMessageContent","streamingTextStatus","Subject","parentMessageId","pushTextChunk","stopStreamingText","textChunks","textSubscription","take","tap","FailedMessageStatus","MessageStreamInterruptedResponse","unsubscribe","push","complete","SuccessMessageStatus","join","ActionExecutionStart","actionExecutionArgumentStream","ActionExecutionEnd","actionExecutionId","ActionExecutionArgs","streamingArgumentsStatus","actionName","arguments","pushArgumentsChunk","stopStreamingArguments","argumentChunks","actionExecutionArgumentSubscription","args","ActionExecutionMessage","ActionExecutionResult","ResultMessage","AgentStateMessage","agentName","nodeName","active","state","running","SuccessResponseStatus","Query","String","AgentsResponse","Ctx","Mutation","CopilotResponse","Arg","GraphQLJSONObject","nullable","Resolver","createLogger","options","level","component","stream","pretty","colorize","logger","createPinoLogger","process","env","LOG_LEVEL","redact","paths","remove","child","logger","createLogger","createContext","initialContext","copilotKitContext","contextLogger","properties","debug","ctx","_copilotkit","buildSchema","options","schema","buildSchemaSync","resolvers","CopilotResolver","emitSchemaFile","getCommonConfig","logLevel","process","env","LOG_LEVEL","level","component","cloud","telemetry","setCloudConfiguration","publicApiKey","baseUrl","setGlobalProperties","runtime","serviceAdapter","constructor","name","logging","plugins","useDeferStream","context","copilotRuntimeNodeHttpEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","getRuntimeInstanceTelemetryInfo","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","copilotRuntimeNodeExpressEndpoint","options","telemetry","setGlobalProperties","runtime","framework","capture","getRuntimeInstanceTelemetryInfo","copilotRuntimeNodeHttpEndpoint"]}
|
|
1
|
+
{"version":3,"sources":["../../../../package.json","../../../../src/lib/integrations/node-express/index.ts","../../../../src/lib/integrations/node-http/index.ts","../../../../src/lib/integrations/shared.ts","../../../../src/graphql/resolvers/copilot.resolver.ts","../../../../src/graphql/inputs/generate-copilot-response.input.ts","../../../../src/graphql/inputs/message.input.ts","../../../../src/graphql/types/enums.ts","../../../../src/graphql/types/base/index.ts","../../../../src/graphql/inputs/frontend.input.ts","../../../../src/graphql/inputs/action.input.ts","../../../../src/graphql/inputs/cloud.input.ts","../../../../src/graphql/inputs/cloud-guardrails.input.ts","../../../../src/graphql/inputs/forwarded-parameters.input.ts","../../../../src/graphql/inputs/agent-session.input.ts","../../../../src/graphql/inputs/agent-state.input.ts","../../../../src/graphql/types/copilot-response.type.ts","../../../../src/graphql/types/message-status.type.ts","../../../../src/graphql/types/response-status.type.ts","../../../../src/service-adapters/events.ts","../../../../src/lib/telemetry-client.ts","../../../../src/lib/runtime/remote-actions.ts","../../../../src/lib/runtime/copilot-runtime.ts","../../../../src/graphql/types/converted/index.ts","../../../../src/utils/failed-response-status-reasons.ts","../../../../src/graphql/types/agents-response.type.ts","../../../../src/lib/logger.ts"],"sourcesContent":["{\n \"name\": \"@copilotkit/runtime\",\n \"private\": false,\n \"homepage\": \"https://github.com/CopilotKit/CopilotKit\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/CopilotKit/CopilotKit.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"version\": \"1.5.12-next.3\",\n \"sideEffects\": false,\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"exports\": {\n \".\": \"./dist/index.js\"\n },\n \"types\": \"./dist/index.d.ts\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"tsup --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"dev\": \"tsup --watch --onSuccess \\\"pnpm run generate-graphql-schema\\\"\",\n \"test\": \"jest --passWithNoTests\",\n \"check-types\": \"tsc --noEmit\",\n \"clean\": \"rm -rf .turbo && rm -rf node_modules && rm -rf dist && rm -rf .next && rm -rf __snapshots__\",\n \"generate-graphql-schema\": \"rm -rf __snapshots__ && ts-node ./scripts/generate-gql-schema.ts\",\n \"link:global\": \"pnpm link --global\",\n \"unlink:global\": \"pnpm unlink --global\"\n },\n \"devDependencies\": {\n \"@swc/core\": \"1.5.28\",\n \"@types/express\": \"^4.17.21\",\n \"@types/jest\": \"^29.5.4\",\n \"@types/node\": \"^18.11.17\",\n \"@whatwg-node/server\": \"^0.9.34\",\n \"eslint\": \"^8.56.0\",\n \"eslint-config-custom\": \"workspace:*\",\n \"jest\": \"^29.6.4\",\n \"nodemon\": \"^3.1.3\",\n \"ts-jest\": \"^29.1.1\",\n \"ts-node\": \"^10.9.2\",\n \"tsconfig\": \"workspace:*\",\n \"tsup\": \"^6.7.0\",\n \"typescript\": \"^5.2.3\",\n \"zod-to-json-schema\": \"^3.23.5\"\n },\n \"dependencies\": {\n \"@anthropic-ai/sdk\": \"^0.27.3\",\n \"@copilotkit/shared\": \"workspace:*\",\n \"@graphql-yoga/plugin-defer-stream\": \"^3.3.1\",\n \"@langchain/community\": \"^0.0.53\",\n \"@langchain/core\": \"^0.3.13\",\n \"@langchain/google-gauth\": \"^0.1.0\",\n \"@langchain/langgraph-sdk\": \"^0.0.16\",\n \"@langchain/openai\": \"^0.0.28\",\n \"class-transformer\": \"^0.5.1\",\n \"express\": \"^4.19.2\",\n \"graphql\": \"^16.8.1\",\n \"graphql-scalars\": \"^1.23.0\",\n \"graphql-yoga\": \"^5.3.1\",\n \"groq-sdk\": \"^0.5.0\",\n \"langchain\": \"^0.3.3\",\n \"openai\": \"^4.50.0\",\n \"partial-json\": \"^0.1.7\",\n \"pino\": \"^9.2.0\",\n \"pino-pretty\": \"^11.2.1\",\n \"reflect-metadata\": \"^0.2.2\",\n \"rxjs\": \"^7.8.1\",\n \"type-graphql\": \"2.0.0-rc.1\",\n \"zod\": \"^3.23.3\"\n },\n \"keywords\": [\n \"copilotkit\",\n \"copilot\",\n \"react\",\n \"nextjs\",\n \"nodejs\",\n \"ai\",\n \"assistant\",\n \"javascript\",\n \"automation\",\n \"textarea\"\n ]\n}\n","import { CreateCopilotRuntimeServerOptions } from \"../shared\";\nimport { copilotRuntimeNodeHttpEndpoint } from \"../node-http\";\nimport telemetry, { getRuntimeInstanceTelemetryInfo } from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeExpressEndpoint(options: CreateCopilotRuntimeServerOptions) {\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-express\",\n },\n });\n\n telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options.runtime),\n );\n return copilotRuntimeNodeHttpEndpoint(options);\n}\n","import { createYoga } from \"graphql-yoga\";\nimport { CreateCopilotRuntimeServerOptions, getCommonConfig } from \"../shared\";\nimport telemetry, { getRuntimeInstanceTelemetryInfo } from \"../../telemetry-client\";\n\nexport function copilotRuntimeNodeHttpEndpoint(options: CreateCopilotRuntimeServerOptions) {\n const commonConfig = getCommonConfig(options);\n\n telemetry.setGlobalProperties({\n runtime: {\n framework: \"node-http\",\n },\n });\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: options.properties._copilotkit,\n });\n }\n\n telemetry.capture(\n \"oss.runtime.instance_created\",\n getRuntimeInstanceTelemetryInfo(options.runtime),\n );\n\n const logger = commonConfig.logging;\n logger.debug(\"Creating Node HTTP endpoint\");\n\n const yoga = createYoga({\n ...commonConfig,\n graphqlEndpoint: options.endpoint,\n });\n\n return yoga;\n}\n","import { YogaInitialContext } from \"graphql-yoga\";\nimport { buildSchemaSync } from \"type-graphql\";\nimport { CopilotResolver } from \"../../graphql/resolvers/copilot.resolver\";\nimport { useDeferStream } from \"@graphql-yoga/plugin-defer-stream\";\nimport { CopilotRuntime } from \"../runtime/copilot-runtime\";\nimport { CopilotServiceAdapter } from \"../../service-adapters\";\nimport { CopilotCloudOptions } from \"../cloud\";\nimport { LogLevel, createLogger } from \"../../lib/logger\";\nimport { createYoga } from \"graphql-yoga\";\nimport telemetry from \"../telemetry-client\";\n\nconst logger = createLogger();\n\ntype AnyPrimitive = string | boolean | number | null;\nexport type CopilotRequestContextProperties = Record<\n string,\n AnyPrimitive | Record<string, AnyPrimitive>\n>;\n\nexport type GraphQLContext = YogaInitialContext & {\n _copilotkit: CreateCopilotRuntimeServerOptions;\n properties: CopilotRequestContextProperties;\n logger: typeof logger;\n};\n\nexport interface CreateCopilotRuntimeServerOptions {\n runtime: CopilotRuntime<any>;\n serviceAdapter: CopilotServiceAdapter;\n endpoint: string;\n baseUrl?: string;\n cloud?: CopilotCloudOptions;\n properties?: CopilotRequestContextProperties;\n logLevel?: LogLevel;\n}\n\nexport async function createContext(\n initialContext: YogaInitialContext,\n copilotKitContext: CreateCopilotRuntimeServerOptions,\n contextLogger: typeof logger,\n properties: CopilotRequestContextProperties = {},\n): Promise<Partial<GraphQLContext>> {\n logger.debug({ copilotKitContext }, \"Creating GraphQL context\");\n const ctx: GraphQLContext = {\n ...initialContext,\n _copilotkit: {\n ...copilotKitContext,\n },\n properties: { ...properties },\n logger: contextLogger,\n };\n return ctx;\n}\n\nexport function buildSchema(\n options: {\n emitSchemaFile?: string;\n } = {},\n) {\n logger.debug(\"Building GraphQL schema...\");\n const schema = buildSchemaSync({\n resolvers: [CopilotResolver],\n emitSchemaFile: options.emitSchemaFile,\n });\n logger.debug(\"GraphQL schema built successfully\");\n return schema;\n}\n\nexport type CommonConfig = {\n logging: typeof logger;\n schema: ReturnType<typeof buildSchema>;\n plugins: Parameters<typeof createYoga>[0][\"plugins\"];\n context: (ctx: YogaInitialContext) => Promise<Partial<GraphQLContext>>;\n};\n\nexport function getCommonConfig(options: CreateCopilotRuntimeServerOptions): CommonConfig {\n const logLevel = (process.env.LOG_LEVEL as LogLevel) || (options.logLevel as LogLevel) || \"error\";\n const logger = createLogger({ level: logLevel, component: \"getCommonConfig\" });\n\n const contextLogger = createLogger({ level: logLevel });\n\n if (options.cloud) {\n telemetry.setCloudConfiguration({\n publicApiKey: options.cloud.publicApiKey,\n baseUrl: options.cloud.baseUrl,\n });\n }\n\n if (options.properties?._copilotkit) {\n telemetry.setGlobalProperties({\n _copilotkit: {\n ...(options.properties._copilotkit as Record<string, any>),\n },\n });\n }\n\n telemetry.setGlobalProperties({\n runtime: {\n serviceAdapter: options.serviceAdapter.constructor.name,\n },\n });\n\n return {\n logging: createLogger({ component: \"Yoga GraphQL\", level: logLevel }),\n schema: buildSchema(),\n plugins: [useDeferStream()],\n context: (ctx: YogaInitialContext): Promise<Partial<GraphQLContext>> =>\n createContext(ctx, options, contextLogger, options.properties),\n };\n}\n","import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport {\n ReplaySubject,\n Subject,\n Subscription,\n filter,\n finalize,\n firstValueFrom,\n shareReplay,\n skipWhile,\n take,\n takeWhile,\n tap,\n} from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport { ActionInputAvailability, MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type { CopilotRequestContextProperties, GraphQLContext } from \"../../lib/integrations\";\nimport { RuntimeEvent, RuntimeEventTypes } from \"../../service-adapters/events\";\nimport {\n FailedMessageStatus,\n MessageStatusUnion,\n SuccessMessageStatus,\n} from \"../types/message-status.type\";\nimport { ResponseStatusUnion, SuccessResponseStatus } from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\nimport { plainToInstance } from \"class-transformer\";\nimport { GuardrailsResult } from \"../types/guardrails-result.type\";\nimport { GraphQLError } from \"graphql\";\nimport {\n GuardrailsValidationFailureResponse,\n MessageStreamInterruptedResponse,\n UnknownErrorResponse,\n} from \"../../utils\";\nimport {\n ActionExecutionMessage,\n AgentStateMessage,\n Message,\n ResultMessage,\n TextMessage,\n} from \"../types/converted\";\nimport telemetry from \"../../lib/telemetry-client\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { EndpointType, LangGraphPlatformAgent } from \"../../lib/runtime/remote-actions\";\nimport { AgentsResponse } from \"../types/agents-response.type\";\n\nconst invokeGuardrails = async ({\n baseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult,\n onError,\n}: {\n baseUrl: string;\n copilotCloudPublicApiKey: string;\n data: GenerateCopilotResponseInput;\n onResult: (result: GuardrailsResult) => void;\n onError: (err: Error) => void;\n}) => {\n if (\n data.messages.length &&\n data.messages[data.messages.length - 1].textMessage?.role === MessageRole.user\n ) {\n const messages = data.messages\n .filter(\n (m) =>\n m.textMessage !== undefined &&\n (m.textMessage.role === MessageRole.user || m.textMessage.role === MessageRole.assistant),\n )\n .map((m) => ({\n role: m.textMessage!.role,\n content: m.textMessage.content,\n }));\n\n const lastMessage = messages[messages.length - 1];\n const restOfMessages = messages.slice(0, -1);\n\n const body = {\n input: lastMessage.content,\n validTopics: data.cloud.guardrails.inputValidationRules.allowList,\n invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,\n messages: restOfMessages,\n };\n\n const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-CopilotCloud-Public-API-Key\": copilotCloudPublicApiKey,\n },\n body: JSON.stringify(body),\n });\n\n if (guardrailsResult.ok) {\n const resultJson: GuardrailsResult = await guardrailsResult.json();\n onResult(resultJson);\n } else {\n onError(await guardrailsResult.json());\n }\n }\n};\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n @Query(() => String)\n async hello() {\n return \"Hello World\";\n }\n\n @Query(() => AgentsResponse)\n async availableAgents(@Ctx() ctx: GraphQLContext) {\n let logger = ctx.logger.child({ component: \"CopilotResolver.availableAgents\" });\n\n logger.debug(\"Processing\");\n const agents = await ctx._copilotkit.runtime.discoverAgentsFromEndpoints(ctx);\n\n logger.debug(\"Event source created, creating response\");\n\n return {\n agents,\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 });\n\n let logger = ctx.logger.child({ component: \"CopilotResolver.generateCopilotResponse\" });\n logger.debug({ data }, \"Generating Copilot response\");\n\n if (properties) {\n logger.debug(\"Properties provided, merging with context properties\");\n ctx.properties = { ...ctx.properties, ...properties };\n }\n\n const copilotRuntime = ctx._copilotkit.runtime;\n const serviceAdapter = ctx._copilotkit.serviceAdapter;\n\n let copilotCloudPublicApiKey: string | null = null;\n let copilotCloudBaseUrl: string;\n\n if (data.cloud) {\n logger = logger.child({ cloud: true });\n logger.debug(\"Cloud configuration provided, checking for public API key in headers\");\n const key = ctx.request.headers.get(\"x-copilotcloud-public-api-key\");\n if (key) {\n logger.debug(\"Public API key found in headers\");\n copilotCloudPublicApiKey = key;\n } else {\n logger.error(\"Public API key not found in headers\");\n throw new GraphQLError(\"X-CopilotCloud-Public-API-Key header is required\");\n }\n\n if (process.env.COPILOT_CLOUD_BASE_URL) {\n copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;\n } else if (ctx._copilotkit.cloud?.baseUrl) {\n copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;\n } else {\n copilotCloudBaseUrl = \"https://api.cloud.copilotkit.ai\";\n }\n\n logger = logger.child({ copilotCloudBaseUrl });\n }\n\n logger.debug(\"Setting up subjects\");\n const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();\n const interruptStreaming$ = new ReplaySubject<{ reason: string; messageId?: string }>();\n const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();\n\n let outputMessages: Message[] = [];\n let resolveOutputMessagesPromise: (messages: Message[]) => void;\n let rejectOutputMessagesPromise: (err: Error) => void;\n\n const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {\n resolveOutputMessagesPromise = resolve;\n rejectOutputMessagesPromise = reject;\n });\n\n logger.debug(\"Processing\");\n const {\n eventSource,\n threadId = randomId(),\n runId,\n serverSideActions,\n actionInputsWithoutAgents,\n } = await copilotRuntime.processRuntimeRequest({\n serviceAdapter,\n messages: data.messages,\n actions: data.frontend.actions.filter(\n (action) => action.available !== ActionInputAvailability.disabled,\n ),\n threadId: data.threadId,\n runId: data.runId,\n publicApiKey: undefined,\n outputMessagesPromise,\n graphqlContext: ctx,\n forwardedParameters: data.forwardedParameters,\n agentSession: data.agentSession,\n agentStates: data.agentStates,\n url: data.frontend.url,\n });\n\n logger.debug(\"Event source created, creating response\");\n\n const response = {\n threadId,\n runId,\n status: firstValueFrom(responseStatus$),\n messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n logger.debug(\"Messages repeater created\");\n\n if (data.cloud?.guardrails) {\n logger = logger.child({ guardrails: true });\n logger.debug(\"Guardrails is enabled, validating input\");\n\n invokeGuardrails({\n baseUrl: copilotCloudBaseUrl,\n copilotCloudPublicApiKey,\n data,\n onResult: (result) => {\n logger.debug({ status: result.status }, \"Guardrails validation done\");\n guardrailsResult$.next(result);\n\n // Guardrails validation failed\n if (result.status === \"denied\") {\n // send the reason to the client and interrupt streaming\n responseStatus$.next(\n new GuardrailsValidationFailureResponse({ guardrailsReason: result.reason }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,\n });\n\n // resolve messages promise to the middleware\n outputMessages = [\n plainToInstance(TextMessage, {\n id: randomId(),\n createdAt: new Date(),\n content: result.reason,\n role: MessageRole.assistant,\n }),\n ];\n resolveOutputMessagesPromise(outputMessages);\n }\n },\n onError: (err) => {\n logger.error({ err }, \"Error in guardrails validation\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the guardrails validation`,\n }),\n );\n interruptStreaming$.next({\n reason: `Interrupted due to unknown error in guardrails validation`,\n });\n\n // reject the middleware promise\n rejectOutputMessagesPromise(err);\n },\n });\n }\n\n let eventStreamSubscription: Subscription;\n\n // run and process the event stream\n const eventStream = eventSource\n .processRuntimeEvents({\n serverSideActions,\n guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,\n actionInputsWithoutAgents: actionInputsWithoutAgents.filter(\n // TODO-AGENTS: do not exclude ALL server side actions\n (action) =>\n !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n ),\n })\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 logger.debug(\"Event stream created, subscribing to event stream\");\n\n eventStreamSubscription = eventStream.subscribe({\n next: async (event) => {\n switch (event.type) {\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) => e !== event),\n // take until the message end event\n takeWhile(\n (e) =>\n !(\n e.type === RuntimeEventTypes.TextMessageEnd &&\n e.messageId == event.messageId\n ),\n ),\n // filter out any other message events or message ids\n filter(\n (e) =>\n e.type == RuntimeEventTypes.TextMessageContent &&\n e.messageId == event.messageId,\n ),\n );\n\n // signal when we are done streaming\n const streamingTextStatus = new Subject<typeof MessageStatusUnion>();\n\n const messageId = event.messageId;\n // push the new message\n pushMessage({\n id: messageId,\n parentMessageId: event.parentMessageId,\n status: firstValueFrom(streamingTextStatus),\n createdAt: new Date(),\n role: MessageRole.assistant,\n content: new Repeater(async (pushTextChunk, stopStreamingText) => {\n logger.debug(\"Text message content repeater created\");\n\n const textChunks: string[] = [];\n let textSubscription: Subscription;\n\n interruptStreaming$\n .pipe(\n shareReplay(),\n take(1),\n tap(({ reason, messageId }) => {\n logger.debug({ reason, messageId }, \"Text streaming interrupted\");\n\n streamingTextStatus.next(\n plainToInstance(FailedMessageStatus, { reason }),\n );\n\n responseStatus$.next(new MessageStreamInterruptedResponse({ messageId }));\n stopStreamingText();\n textSubscription?.unsubscribe();\n }),\n )\n .subscribe();\n\n logger.debug(\"Subscribing to text message content stream\");\n\n textSubscription = textMessageContentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.TextMessageContent) {\n await pushTextChunk(e.content);\n textChunks.push(e.content);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in text message content stream\");\n interruptStreaming$.next({\n reason: \"Error streaming message content\",\n messageId,\n });\n stopStreamingText();\n textSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Text message content stream completed\");\n streamingTextStatus.next(new SuccessMessageStatus());\n stopStreamingText();\n textSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(TextMessage, {\n id: messageId,\n createdAt: new Date(),\n content: textChunks.join(\"\"),\n role: MessageRole.assistant,\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionStart\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionStart:\n logger.debug(\"Action execution start event received\");\n const actionExecutionArgumentStream = eventStream.pipe(\n skipWhile((e) => e !== event),\n // take until the action execution end event\n takeWhile(\n (e) =>\n !(\n e.type === RuntimeEventTypes.ActionExecutionEnd &&\n e.actionExecutionId == event.actionExecutionId\n ),\n ),\n // filter out any other action execution events or action execution ids\n filter(\n (e) =>\n e.type == RuntimeEventTypes.ActionExecutionArgs &&\n e.actionExecutionId == event.actionExecutionId,\n ),\n );\n const streamingArgumentsStatus = new Subject<typeof MessageStatusUnion>();\n pushMessage({\n id: event.actionExecutionId,\n parentMessageId: event.parentMessageId,\n status: firstValueFrom(streamingArgumentsStatus),\n createdAt: new Date(),\n name: event.actionName,\n arguments: new Repeater(async (pushArgumentsChunk, stopStreamingArguments) => {\n logger.debug(\"Action execution argument stream created\");\n\n const argumentChunks: string[] = [];\n let actionExecutionArgumentSubscription: Subscription;\n\n actionExecutionArgumentSubscription = actionExecutionArgumentStream.subscribe({\n next: async (e: RuntimeEvent) => {\n if (e.type == RuntimeEventTypes.ActionExecutionArgs) {\n await pushArgumentsChunk(e.args);\n argumentChunks.push(e.args);\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in action execution argument stream\");\n streamingArgumentsStatus.next(\n plainToInstance(FailedMessageStatus, {\n reason:\n \"An unknown error has occurred in the action execution argument stream\",\n }),\n );\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n },\n complete: () => {\n logger.debug(\"Action execution argument stream completed\");\n streamingArgumentsStatus.next(new SuccessMessageStatus());\n stopStreamingArguments();\n actionExecutionArgumentSubscription?.unsubscribe();\n\n outputMessages.push(\n plainToInstance(ActionExecutionMessage, {\n id: event.actionExecutionId,\n createdAt: new Date(),\n name: event.actionName,\n arguments: argumentChunks.join(\"\"),\n }),\n );\n },\n });\n }),\n });\n break;\n ////////////////////////////////\n // ActionExecutionResult\n ////////////////////////////////\n case RuntimeEventTypes.ActionExecutionResult:\n logger.debug({ result: event.result }, \"Action execution result event received\");\n pushMessage({\n id: \"result-\" + event.actionExecutionId,\n status: new SuccessMessageStatus(),\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n });\n\n outputMessages.push(\n plainToInstance(ResultMessage, {\n id: \"result-\" + event.actionExecutionId,\n createdAt: new Date(),\n actionExecutionId: event.actionExecutionId,\n actionName: event.actionName,\n result: event.result,\n }),\n );\n break;\n ////////////////////////////////\n // AgentStateMessage\n ////////////////////////////////\n case RuntimeEventTypes.AgentStateMessage:\n logger.debug({ event }, \"Agent message event received\");\n pushMessage({\n id: randomId(),\n status: new SuccessMessageStatus(),\n threadId: event.threadId,\n agentName: event.agentName,\n nodeName: event.nodeName,\n runId: event.runId,\n active: event.active,\n state: event.state,\n running: event.running,\n role: MessageRole.assistant,\n createdAt: new Date(),\n });\n outputMessages.push(\n plainToInstance(AgentStateMessage, {\n id: randomId(),\n threadId: event.threadId,\n agentName: event.agentName,\n nodeName: event.nodeName,\n runId: event.runId,\n active: event.active,\n state: event.state,\n running: event.running,\n role: MessageRole.assistant,\n createdAt: new Date(),\n }),\n );\n break;\n }\n },\n error: (err) => {\n logger.error({ err }, \"Error in event stream\");\n responseStatus$.next(\n new UnknownErrorResponse({\n description: `An unknown error has occurred in the event stream`,\n }),\n );\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n rejectOutputMessagesPromise(err);\n },\n complete: async () => {\n logger.debug(\"Event stream completed\");\n if (data.cloud?.guardrails) {\n logger.debug(\"Guardrails is enabled, waiting for guardrails result\");\n await firstValueFrom(guardrailsResult$);\n }\n responseStatus$.next(new SuccessResponseStatus());\n eventStreamSubscription?.unsubscribe();\n stopStreamingMessages();\n\n resolveOutputMessagesPromise(outputMessages);\n },\n });\n }),\n };\n\n return response;\n }\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageInput } from \"./message.input\";\nimport { FrontendInput } from \"./frontend.input\";\nimport { CloudInput } from \"./cloud.input\";\nimport { CopilotRequestType } from \"../types/enums\";\nimport { ForwardedParametersInput } from \"./forwarded-parameters.input\";\nimport { AgentSessionInput } from \"./agent-session.input\";\nimport { AgentStateInput } from \"./agent-state.input\";\n\n@InputType()\nexport class GenerateCopilotResponseMetadataInput {\n @Field(() => CopilotRequestType, { nullable: true })\n requestType: CopilotRequestType;\n}\n\n@InputType()\nexport class GenerateCopilotResponseInput {\n @Field(() => GenerateCopilotResponseMetadataInput, { nullable: false })\n metadata: GenerateCopilotResponseMetadataInput;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n runId?: string;\n\n @Field(() => [MessageInput])\n messages: MessageInput[];\n\n @Field(() => FrontendInput)\n frontend: FrontendInput;\n\n @Field(() => CloudInput, { nullable: true })\n cloud?: CloudInput;\n\n @Field(() => ForwardedParametersInput, { nullable: true })\n forwardedParameters?: ForwardedParametersInput;\n\n @Field(() => AgentSessionInput, { nullable: true })\n agentSession?: AgentSessionInput;\n\n @Field(() => AgentStateInput, { nullable: true })\n agentState?: AgentStateInput;\n\n @Field(() => [AgentStateInput], { nullable: true })\n agentStates?: AgentStateInput[];\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { MessageRole } from \"../types/enums\";\nimport { BaseMessageInput } from \"../types/base\";\n\n// GraphQL does not support union types in inputs, so we need to use\n// optional fields for the different subtypes.\n@InputType()\nexport class MessageInput extends BaseMessageInput {\n @Field(() => TextMessageInput, { nullable: true })\n textMessage?: TextMessageInput;\n\n @Field(() => ActionExecutionMessageInput, { nullable: true })\n actionExecutionMessage?: ActionExecutionMessageInput;\n\n @Field(() => ResultMessageInput, { nullable: true })\n resultMessage?: ResultMessageInput;\n\n @Field(() => AgentStateMessageInput, { nullable: true })\n agentStateMessage?: AgentStateMessageInput;\n}\n\n@InputType()\nexport class TextMessageInput {\n @Field(() => String)\n content: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n}\n\n@InputType()\nexport class ActionExecutionMessageInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n arguments: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => String, {\n nullable: true,\n deprecationReason: \"This field will be removed in a future version\",\n })\n scope?: String;\n}\n\n@InputType()\nexport class ResultMessageInput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n\n @Field(() => String)\n result: string;\n}\n\n@InputType()\nexport class AgentStateMessageInput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String)\n state: string;\n\n @Field(() => Boolean)\n running: boolean;\n\n @Field(() => String)\n nodeName: string;\n\n @Field(() => String)\n runId: string;\n\n @Field(() => Boolean)\n active: boolean;\n}\n","import { registerEnumType } from \"type-graphql\";\n\nexport enum MessageRole {\n user = \"user\",\n assistant = \"assistant\",\n system = \"system\",\n tool = \"tool\",\n}\n\nexport enum CopilotRequestType {\n Chat = \"Chat\",\n Task = \"Task\",\n TextareaCompletion = \"TextareaCompletion\",\n TextareaPopover = \"TextareaPopover\",\n Suggestion = \"Suggestion\",\n}\n\nexport enum ActionInputAvailability {\n disabled = \"disabled\",\n enabled = \"enabled\",\n remote = \"remote\",\n}\n\nregisterEnumType(MessageRole, {\n name: \"MessageRole\",\n description: \"The role of the message\",\n});\n\nregisterEnumType(CopilotRequestType, {\n name: \"CopilotRequestType\",\n description: \"The type of Copilot request\",\n});\n\nregisterEnumType(ActionInputAvailability, {\n name: \"ActionInputAvailability\",\n description: \"The availability of the frontend action\",\n});\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class BaseMessageInput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInput } from \"./action.input\";\n\n@InputType()\nexport class FrontendInput {\n @Field(() => String, { nullable: true })\n toDeprecate_fullContext?: string;\n\n @Field(() => [ActionInput])\n actions: ActionInput[];\n\n @Field(() => String, { nullable: true })\n url?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { ActionInputAvailability } from \"../types/enums\";\n@InputType()\nexport class ActionInput {\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description: string;\n\n @Field(() => String)\n jsonSchema: string;\n\n @Field(() => ActionInputAvailability, { nullable: true })\n available?: ActionInputAvailability;\n}\n","import { Field, InputType } from \"type-graphql\";\nimport { GuardrailsInput } from \"./cloud-guardrails.input\";\n\n@InputType()\nexport class CloudInput {\n @Field(() => GuardrailsInput, { nullable: true })\n guardrails?: GuardrailsInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class GuardrailsRuleInput {\n @Field(() => [String], { nullable: true })\n allowList?: string[] = [];\n\n @Field(() => [String], { nullable: true })\n denyList?: string[] = [];\n}\n\n@InputType()\nexport class GuardrailsInput {\n @Field(() => GuardrailsRuleInput, { nullable: false })\n inputValidationRules: GuardrailsRuleInput;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class ForwardedParametersInput {\n @Field(() => String, { nullable: true })\n model?: string;\n\n @Field(() => Number, { nullable: true })\n maxTokens?: number;\n\n @Field(() => [String], { nullable: true })\n stop?: string[];\n\n @Field(() => String, { nullable: true })\n toolChoice?: String;\n\n @Field(() => String, { nullable: true })\n toolChoiceFunctionName?: string;\n\n @Field(() => Number, { nullable: true })\n temperature?: number;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class AgentSessionInput {\n @Field(() => String)\n agentName: string;\n\n @Field(() => String, { nullable: true })\n threadId?: string;\n\n @Field(() => String, { nullable: true })\n nodeName?: string;\n}\n","import { Field, InputType } from \"type-graphql\";\n\n@InputType()\nexport class AgentStateInput {\n @Field(() => String)\n agentName: string;\n\n @Field(() => String)\n state: string;\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\n\n@InterfaceType({\n resolveType(value) {\n if (value.hasOwnProperty(\"content\")) {\n return TextMessageOutput;\n } else if (value.hasOwnProperty(\"name\")) {\n return ActionExecutionMessageOutput;\n } else if (value.hasOwnProperty(\"result\")) {\n return ResultMessageOutput;\n } else if (value.hasOwnProperty(\"state\")) {\n return AgentStateMessageOutput;\n }\n return undefined;\n },\n})\nabstract class BaseMessageOutput {\n @Field(() => String)\n id: string;\n\n @Field(() => Date)\n createdAt: Date;\n\n @Field(() => MessageStatusUnion)\n status: typeof MessageStatusUnion;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class TextMessageOutput {\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => [String])\n content: string[];\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ActionExecutionMessageOutput {\n @Field(() => String)\n name: string;\n\n @Field(() => String, {\n nullable: true,\n deprecationReason: \"This field will be removed in a future version\",\n })\n scope?: string;\n\n @Field(() => [String])\n arguments: string[];\n\n @Field(() => String, { nullable: true })\n parentMessageId?: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class ResultMessageOutput {\n @Field(() => String)\n actionExecutionId: string;\n\n @Field(() => String)\n actionName: string;\n\n @Field(() => String)\n result: string;\n}\n\n@ObjectType({ implements: BaseMessageOutput })\nexport class AgentStateMessageOutput {\n @Field(() => String)\n threadId: string;\n\n @Field(() => String)\n agentName: string;\n\n @Field(() => String)\n nodeName: string;\n\n @Field(() => String)\n runId: string;\n\n @Field(() => Boolean)\n active: boolean;\n\n @Field(() => MessageRole)\n role: MessageRole;\n\n @Field(() => String)\n state: string;\n\n @Field(() => Boolean)\n running: boolean;\n}\n\n@ObjectType()\nexport class CopilotResponse {\n @Field(() => String)\n threadId!: string;\n\n @Field(() => ResponseStatusUnion)\n status: typeof ResponseStatusUnion;\n\n @Field({ nullable: true })\n runId?: string;\n\n @Field(() => [BaseMessageOutput])\n messages: (typeof BaseMessageOutput)[];\n}\n","import { Field, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum MessageStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(MessageStatusCode, {\n name: \"MessageStatusCode\",\n});\n\n@ObjectType()\nclass BaseMessageStatus {\n @Field(() => MessageStatusCode)\n code: MessageStatusCode;\n}\n\n@ObjectType()\nexport class PendingMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Pending;\n}\n\n@ObjectType()\nexport class SuccessMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Success;\n}\n\n@ObjectType()\nexport class FailedMessageStatus extends BaseMessageStatus {\n code: MessageStatusCode = MessageStatusCode.Failed;\n\n @Field(() => String)\n reason: string;\n}\n\nexport const MessageStatusUnion = createUnionType({\n name: \"MessageStatus\",\n types: () => [PendingMessageStatus, SuccessMessageStatus, FailedMessageStatus] as const,\n});\n","import { GraphQLJSON } from \"graphql-scalars\";\nimport { Field, InterfaceType, ObjectType, createUnionType, registerEnumType } from \"type-graphql\";\n\nexport enum ResponseStatusCode {\n Pending = \"pending\",\n Success = \"success\",\n Failed = \"failed\",\n}\n\nregisterEnumType(ResponseStatusCode, {\n name: \"ResponseStatusCode\",\n});\n\n@InterfaceType({\n resolveType(value) {\n if (value.code === ResponseStatusCode.Success) {\n return SuccessResponseStatus;\n } else if (value.code === ResponseStatusCode.Failed) {\n return FailedResponseStatus;\n } else if (value.code === ResponseStatusCode.Pending) {\n return PendingResponseStatus;\n }\n return undefined;\n },\n})\n@ObjectType()\nabstract class BaseResponseStatus {\n @Field(() => ResponseStatusCode)\n code: ResponseStatusCode;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class PendingResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Pending;\n}\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class SuccessResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Success;\n}\n\nexport enum FailedResponseStatusReason {\n GUARDRAILS_VALIDATION_FAILED = \"GUARDRAILS_VALIDATION_FAILED\",\n MESSAGE_STREAM_INTERRUPTED = \"MESSAGE_STREAM_INTERRUPTED\",\n UNKNOWN_ERROR = \"UNKNOWN_ERROR\",\n}\n\nregisterEnumType(FailedResponseStatusReason, {\n name: \"FailedResponseStatusReason\",\n});\n\n@ObjectType({ implements: BaseResponseStatus })\nexport class FailedResponseStatus extends BaseResponseStatus {\n code: ResponseStatusCode = ResponseStatusCode.Failed;\n\n @Field(() => FailedResponseStatusReason)\n reason: FailedResponseStatusReason;\n\n @Field(() => GraphQLJSON, { nullable: true })\n details?: Record<string, any> = null;\n}\n\nexport const ResponseStatusUnion = createUnionType({\n name: \"ResponseStatus\",\n types: () => [PendingResponseStatus, SuccessResponseStatus, FailedResponseStatus] as const,\n});\n","import { Action, randomId } from \"@copilotkit/shared\";\nimport {\n of,\n concat,\n scan,\n concatMap,\n ReplaySubject,\n Subject,\n firstValueFrom,\n from,\n catchError,\n EMPTY,\n} from \"rxjs\";\nimport { streamLangChainResponse } from \"./langchain/utils\";\nimport { GuardrailsResult } from \"../graphql/types/guardrails-result.type\";\nimport telemetry from \"../lib/telemetry-client\";\nimport { isLangGraphAgentAction } from \"../lib/runtime/remote-actions\";\nimport { ActionInput } from \"../graphql/inputs/action.input\";\nimport { ActionExecutionMessage, ResultMessage } from \"../graphql/types/converted\";\nimport { plainToInstance } from \"class-transformer\";\n\nexport enum RuntimeEventTypes {\n TextMessageStart = \"TextMessageStart\",\n TextMessageContent = \"TextMessageContent\",\n TextMessageEnd = \"TextMessageEnd\",\n ActionExecutionStart = \"ActionExecutionStart\",\n ActionExecutionArgs = \"ActionExecutionArgs\",\n ActionExecutionEnd = \"ActionExecutionEnd\",\n ActionExecutionResult = \"ActionExecutionResult\",\n AgentStateMessage = \"AgentStateMessage\",\n}\n\nexport type RuntimeEvent =\n | { type: RuntimeEventTypes.TextMessageStart; messageId: string; parentMessageId?: string }\n | {\n type: RuntimeEventTypes.TextMessageContent;\n messageId: string;\n content: string;\n }\n | { type: RuntimeEventTypes.TextMessageEnd; messageId: string }\n | {\n type: RuntimeEventTypes.ActionExecutionStart;\n actionExecutionId: string;\n actionName: string;\n parentMessageId?: string;\n }\n | { type: RuntimeEventTypes.ActionExecutionArgs; actionExecutionId: string; args: string }\n | { type: RuntimeEventTypes.ActionExecutionEnd; actionExecutionId: string }\n | {\n type: RuntimeEventTypes.ActionExecutionResult;\n actionName: string;\n actionExecutionId: string;\n result: string;\n }\n | {\n type: RuntimeEventTypes.AgentStateMessage;\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: string;\n state: string;\n running: boolean;\n };\n\ninterface RuntimeEventWithState {\n event: RuntimeEvent | null;\n callActionServerSide: boolean;\n action: Action<any> | null;\n actionExecutionId: string | null;\n args: string;\n actionExecutionParentMessageId: string | null;\n}\n\ntype EventSourceCallback = (eventStream$: RuntimeEventSubject) => Promise<void>;\n\nexport class RuntimeEventSubject extends ReplaySubject<RuntimeEvent> {\n constructor() {\n super();\n }\n\n sendTextMessageStart({\n messageId,\n parentMessageId,\n }: {\n messageId: string;\n parentMessageId?: string;\n }) {\n this.next({ type: RuntimeEventTypes.TextMessageStart, messageId, parentMessageId });\n }\n\n sendTextMessageContent({ messageId, content }: { messageId: string; content: string }) {\n this.next({ type: RuntimeEventTypes.TextMessageContent, content, messageId });\n }\n\n sendTextMessageEnd({ messageId }: { messageId: string }) {\n this.next({ type: RuntimeEventTypes.TextMessageEnd, messageId });\n }\n\n sendTextMessage(messageId: string, content: string) {\n this.sendTextMessageStart({ messageId });\n this.sendTextMessageContent({ messageId, content });\n this.sendTextMessageEnd({ messageId });\n }\n\n sendActionExecutionStart({\n actionExecutionId,\n actionName,\n parentMessageId,\n }: {\n actionExecutionId: string;\n actionName: string;\n parentMessageId?: string;\n }) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionStart,\n actionExecutionId,\n actionName,\n parentMessageId,\n });\n }\n\n sendActionExecutionArgs({\n actionExecutionId,\n args,\n }: {\n actionExecutionId: string;\n args: string;\n }) {\n this.next({ type: RuntimeEventTypes.ActionExecutionArgs, args, actionExecutionId });\n }\n\n sendActionExecutionEnd({ actionExecutionId }: { actionExecutionId: string }) {\n this.next({ type: RuntimeEventTypes.ActionExecutionEnd, actionExecutionId });\n }\n\n sendActionExecution({\n actionExecutionId,\n actionName,\n args,\n parentMessageId,\n }: {\n actionExecutionId: string;\n actionName: string;\n args: string;\n parentMessageId?: string;\n }) {\n this.sendActionExecutionStart({ actionExecutionId, actionName, parentMessageId });\n this.sendActionExecutionArgs({ actionExecutionId, args });\n this.sendActionExecutionEnd({ actionExecutionId });\n }\n\n sendActionExecutionResult({\n actionExecutionId,\n actionName,\n result,\n error,\n }: {\n actionExecutionId: string;\n actionName: string;\n result?: string;\n error?: { code: string; message: string };\n }) {\n this.next({\n type: RuntimeEventTypes.ActionExecutionResult,\n actionName,\n actionExecutionId,\n result: ResultMessage.encodeResult(result, error),\n });\n }\n\n sendAgentStateMessage({\n threadId,\n agentName,\n nodeName,\n runId,\n active,\n role,\n state,\n running,\n }: {\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: string;\n state: string;\n running: boolean;\n }) {\n this.next({\n type: RuntimeEventTypes.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n active,\n role,\n state,\n running,\n });\n }\n}\n\nexport class RuntimeEventSource {\n private eventStream$ = new RuntimeEventSubject();\n private callback!: EventSourceCallback;\n\n async stream(callback: EventSourceCallback): Promise<void> {\n this.callback = callback;\n }\n\n sendErrorMessageToChat(message = \"An error occurred. Please try again.\") {\n const errorMessage = `❌ ${message}`;\n if (!this.callback) {\n this.stream(async (eventStream$) => {\n eventStream$.sendTextMessage(randomId(), errorMessage);\n });\n } else {\n this.eventStream$.sendTextMessage(randomId(), errorMessage);\n }\n }\n\n processRuntimeEvents({\n serverSideActions,\n guardrailsResult$,\n actionInputsWithoutAgents,\n }: {\n serverSideActions: Action<any>[];\n guardrailsResult$?: Subject<GuardrailsResult>;\n actionInputsWithoutAgents: ActionInput[];\n }) {\n this.callback(this.eventStream$).catch((error) => {\n console.error(\"Error in event source callback\", error);\n this.sendErrorMessageToChat();\n this.eventStream$.complete();\n });\n return this.eventStream$.pipe(\n // track state\n scan(\n (acc, event) => {\n // It seems like this is needed so that rxjs recognizes the object has changed\n // This fixes an issue where action were executed multiple times\n // Not investigating further for now (Markus)\n acc = { ...acc };\n\n if (event.type === RuntimeEventTypes.ActionExecutionStart) {\n acc.callActionServerSide =\n serverSideActions.find((action) => action.name === event.actionName) !== undefined;\n acc.args = \"\";\n acc.actionExecutionId = event.actionExecutionId;\n if (acc.callActionServerSide) {\n acc.action = serverSideActions.find((action) => action.name === event.actionName);\n }\n acc.actionExecutionParentMessageId = event.parentMessageId;\n } else if (event.type === RuntimeEventTypes.ActionExecutionArgs) {\n acc.args += event.args;\n }\n\n acc.event = event;\n\n return acc;\n },\n {\n event: null,\n callActionServerSide: false,\n args: \"\",\n actionExecutionId: null,\n action: null,\n actionExecutionParentMessageId: null,\n } as RuntimeEventWithState,\n ),\n concatMap((eventWithState) => {\n if (\n eventWithState.event!.type === RuntimeEventTypes.ActionExecutionEnd &&\n eventWithState.callActionServerSide\n ) {\n const toolCallEventStream$ = new RuntimeEventSubject();\n executeAction(\n toolCallEventStream$,\n guardrailsResult$ ? guardrailsResult$ : null,\n eventWithState.action!,\n eventWithState.args,\n eventWithState.actionExecutionParentMessageId,\n eventWithState.actionExecutionId,\n actionInputsWithoutAgents,\n ).catch((error) => {\n console.error(error);\n });\n\n telemetry.capture(\"oss.runtime.server_action_executed\", {});\n return concat(of(eventWithState.event!), toolCallEventStream$).pipe(\n catchError((error) => {\n console.error(\"Error in tool call stream\", error);\n this.sendErrorMessageToChat();\n return EMPTY;\n }),\n );\n } else {\n return of(eventWithState.event!);\n }\n }),\n );\n }\n}\n\nasync function executeAction(\n eventStream$: RuntimeEventSubject,\n guardrailsResult$: Subject<GuardrailsResult> | null,\n action: Action<any>,\n actionArguments: string,\n actionExecutionParentMessageId: string | null,\n actionExecutionId: string,\n actionInputsWithoutAgents: ActionInput[],\n) {\n if (guardrailsResult$) {\n const { status } = await firstValueFrom(guardrailsResult$);\n\n if (status === \"denied\") {\n eventStream$.complete();\n return;\n }\n }\n\n // Prepare arguments for function calling\n let args: Record<string, any>[] = [];\n if (actionArguments) {\n try {\n args = JSON.parse(actionArguments);\n } catch (e) {\n console.error(\"Action argument unparsable\", { actionArguments });\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: \"INVALID_ARGUMENTS\",\n message: \"Failed to parse action arguments\",\n },\n });\n return;\n }\n }\n\n // handle LangGraph agents\n if (isLangGraphAgentAction(action)) {\n const result = `${action.name} agent started`;\n\n const agentExecution = plainToInstance(ActionExecutionMessage, {\n id: actionExecutionId,\n createdAt: new Date(),\n name: action.name,\n arguments: JSON.parse(actionArguments),\n parentMessageId: actionExecutionParentMessageId ?? actionExecutionId,\n });\n\n const agentExecutionResult = plainToInstance(ResultMessage, {\n id: \"result-\" + actionExecutionId,\n createdAt: new Date(),\n actionExecutionId,\n actionName: action.name,\n result,\n });\n\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n result,\n });\n\n const stream = await action.langGraphAgentHandler({\n name: action.name,\n actionInputsWithoutAgents,\n additionalMessages: [agentExecution, agentExecutionResult],\n });\n\n // forward to eventStream$\n from(stream).subscribe({\n next: (event) => eventStream$.next(event),\n error: (err) => {\n console.error(\"Error in stream\", err);\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: \"STREAM_ERROR\",\n message: err.message,\n },\n });\n eventStream$.complete();\n },\n complete: () => eventStream$.complete(),\n });\n } else {\n // call the function\n try {\n const result = await action.handler?.(args);\n await streamLangChainResponse({\n result,\n eventStream$,\n actionExecution: {\n name: action.name,\n id: actionExecutionId,\n },\n });\n } catch (e) {\n console.error(\"Error in action handler\", e);\n eventStream$.sendActionExecutionResult({\n actionExecutionId,\n actionName: action.name,\n error: {\n code: \"HANDLER_ERROR\",\n message: e.message,\n },\n });\n eventStream$.complete();\n }\n }\n}\n","import { TelemetryClient } from \"@copilotkit/shared\";\nimport { EndpointType, LangGraphPlatformEndpoint } from \"./runtime/remote-actions\";\nimport { createHash } from \"node:crypto\";\nimport { CopilotRuntime, resolveEndpointType } from \"./runtime/copilot-runtime\";\nimport { RuntimeInstanceCreatedInfo } from \"@copilotkit/shared/src/telemetry/events\";\nconst packageJson = require(\"../../package.json\");\n\nconst telemetryClient = new TelemetryClient({\n packageName: packageJson.name,\n packageVersion: packageJson.version,\n});\n\nexport function getRuntimeInstanceTelemetryInfo(\n runtime: CopilotRuntime,\n): RuntimeInstanceCreatedInfo {\n const endpointsInfo = runtime.remoteEndpointDefinitions.reduce(\n (acc, endpoint) => {\n let info = { ...acc };\n\n const endpointType = resolveEndpointType(endpoint);\n if (!info.endpointTypes.includes(endpointType)) {\n info = {\n ...info,\n endpointTypes: [...info.endpointTypes, endpointType],\n };\n }\n\n if (endpointType === EndpointType.LangGraphPlatform) {\n // When type is resolved, recreating a const with casting of type\n const ep = endpoint as LangGraphPlatformEndpoint;\n info = {\n ...info,\n agentsAmount: ep.agents.length,\n hashedKey: createHash(\"sha256\").update(ep.langsmithApiKey).digest(\"hex\"),\n };\n }\n\n return info;\n },\n { endpointTypes: [], agentsAmount: null, hashedKey: null },\n );\n\n return {\n actionsAmount: runtime.actions.length,\n endpointsAmount: runtime.remoteEndpointDefinitions.length,\n endpointTypes: endpointsInfo.endpointTypes,\n agentsAmount: endpointsInfo.agentsAmount,\n hashedLgcKey: endpointsInfo.hashedKey,\n };\n}\n\nexport default telemetryClient;\n","import { Action } from \"@copilotkit/shared\";\nimport { GraphQLContext } from \"../integrations/shared\";\nimport { Logger } from \"pino\";\nimport { Message } from \"../../graphql/types/converted\";\nimport { RuntimeEvent } from \"../../service-adapters/events\";\nimport { Observable } from \"rxjs\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { AgentStateInput } from \"../../graphql/inputs/agent-state.input\";\nimport {\n constructLGCRemoteAction,\n constructRemoteActions,\n createHeaders,\n} from \"./remote-action-constructors\";\n\nexport type EndpointDefinition = CopilotKitEndpoint | LangGraphPlatformEndpoint;\n\nexport enum EndpointType {\n CopilotKit = \"copilotKit\",\n LangGraphPlatform = \"langgraph-platform\",\n}\n\nexport interface BaseEndpointDefinition<TActionType extends EndpointType> {\n type?: TActionType;\n}\n\nexport interface CopilotKitEndpoint extends BaseEndpointDefinition<EndpointType.CopilotKit> {\n url: string;\n onBeforeRequest?: ({ ctx }: { ctx: GraphQLContext }) => {\n headers?: Record<string, string> | undefined;\n };\n}\n\nexport interface LangGraphPlatformAgent {\n name: string;\n description: string;\n assistantId?: string;\n}\n\nexport interface LangGraphPlatformEndpoint\n extends BaseEndpointDefinition<EndpointType.LangGraphPlatform> {\n deploymentUrl: string;\n langsmithApiKey: string;\n agents: LangGraphPlatformAgent[];\n}\n\nexport type RemoteActionInfoResponse = {\n actions: any[];\n agents: any[];\n};\n\nexport type LangGraphAgentHandlerParams = {\n name: string;\n actionInputsWithoutAgents: ActionInput[];\n threadId?: string;\n nodeName?: string;\n additionalMessages?: Message[];\n};\n\nexport type LangGraphAgentAction = Action<any> & {\n langGraphAgentHandler: (params: LangGraphAgentHandlerParams) => Promise<Observable<RuntimeEvent>>;\n};\n\nexport function isLangGraphAgentAction(action: Action<any>): action is LangGraphAgentAction {\n if (!action) {\n return false;\n }\n return typeof (action as LangGraphAgentAction).langGraphAgentHandler === \"function\";\n}\n\nasync function fetchRemoteInfo({\n url,\n onBeforeRequest,\n graphqlContext,\n logger,\n frontendUrl,\n}: {\n url: string;\n onBeforeRequest?: CopilotKitEndpoint[\"onBeforeRequest\"];\n graphqlContext: GraphQLContext;\n logger: Logger;\n frontendUrl?: string;\n}): Promise<RemoteActionInfoResponse> {\n logger.debug({ url }, \"Fetching actions from url\");\n const headers = createHeaders(onBeforeRequest, graphqlContext);\n\n try {\n const response = await fetch(`${url}/info`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ properties: graphqlContext.properties, frontendUrl }),\n });\n\n if (!response.ok) {\n logger.error(\n { url, status: response.status, body: await response.text() },\n \"Failed to fetch actions from url\",\n );\n return { actions: [], agents: [] };\n }\n\n const json = await response.json();\n logger.debug({ json }, \"Fetched actions from url\");\n return json;\n } catch (error) {\n logger.error(\n { error: error.message ? error.message : error + \"\" },\n \"Failed to fetch actions from url\",\n );\n return { actions: [], agents: [] };\n }\n}\n\nexport async function setupRemoteActions({\n remoteEndpointDefinitions,\n graphqlContext,\n messages,\n agentStates,\n frontendUrl,\n}: {\n remoteEndpointDefinitions: EndpointDefinition[];\n graphqlContext: GraphQLContext;\n messages: Message[];\n agentStates?: AgentStateInput[];\n frontendUrl?: string;\n}): Promise<Action[]> {\n const logger = graphqlContext.logger.child({ component: \"remote-actions.fetchRemoteActions\" });\n logger.debug({ remoteEndpointDefinitions }, \"Fetching from remote endpoints\");\n\n // Remove duplicates of remoteEndpointDefinitions.url\n const filtered = remoteEndpointDefinitions.filter((value, index, self) => {\n if (value.type === EndpointType.LangGraphPlatform) {\n return value;\n }\n return index === self.findIndex((t: CopilotKitEndpoint) => t.url === value.url);\n });\n\n const result = await Promise.all(\n filtered.map(async (endpoint) => {\n // Check for properties that can distinguish LG platform from other actions\n if (endpoint.type === EndpointType.LangGraphPlatform) {\n return constructLGCRemoteAction({\n endpoint,\n messages,\n graphqlContext,\n logger: logger.child({\n component: \"remote-actions.constructLGCRemoteAction\",\n endpoint,\n }),\n agentStates,\n });\n }\n\n const json = await fetchRemoteInfo({\n url: endpoint.url,\n onBeforeRequest: endpoint.onBeforeRequest,\n graphqlContext,\n logger: logger.child({ component: \"remote-actions.fetchActionsFromUrl\", endpoint }),\n frontendUrl,\n });\n\n return constructRemoteActions({\n json,\n messages,\n url: endpoint.url,\n onBeforeRequest: endpoint.onBeforeRequest,\n graphqlContext,\n logger: logger.child({ component: \"remote-actions.constructActions\", endpoint }),\n agentStates,\n });\n }),\n );\n\n return result.flat();\n}\n","/**\n * <Callout type=\"info\">\n * This is the reference for the `CopilotRuntime` class. For more information and example code snippets, please see [Concept: Copilot Runtime](/concepts/copilot-runtime).\n * </Callout>\n *\n * ## Usage\n *\n * ```tsx\n * import { CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const copilotKit = new CopilotRuntime();\n * ```\n */\n\nimport { Action, actionParametersToJsonSchema, Parameter, randomId } from \"@copilotkit/shared\";\nimport { CopilotServiceAdapter, RemoteChain, RemoteChainParameters } from \"../../service-adapters\";\nimport { MessageInput } from \"../../graphql/inputs/message.input\";\nimport { ActionInput } from \"../../graphql/inputs/action.input\";\nimport { RuntimeEventSource } from \"../../service-adapters/events\";\nimport { convertGqlInputToMessages } from \"../../service-adapters/conversion\";\nimport { Message } from \"../../graphql/types/converted\";\nimport { ForwardedParametersInput } from \"../../graphql/inputs/forwarded-parameters.input\";\nimport {\n isLangGraphAgentAction,\n LangGraphAgentAction,\n EndpointType,\n setupRemoteActions,\n EndpointDefinition,\n CopilotKitEndpoint,\n LangGraphPlatformEndpoint,\n} from \"./remote-actions\";\nimport { GraphQLContext } from \"../integrations/shared\";\nimport { AgentSessionInput } from \"../../graphql/inputs/agent-session.input\";\nimport { from } from \"rxjs\";\nimport { AgentStateInput } from \"../../graphql/inputs/agent-state.input\";\nimport { ActionInputAvailability } from \"../../graphql/types/enums\";\nimport { createHeaders } from \"./remote-action-constructors\";\nimport { Agent } from \"../../graphql/types/agents-response.type\";\n\ninterface CopilotRuntimeRequest {\n serviceAdapter: CopilotServiceAdapter;\n messages: MessageInput[];\n actions: ActionInput[];\n agentSession?: AgentSessionInput;\n agentStates?: AgentStateInput[];\n outputMessagesPromise: Promise<Message[]>;\n threadId?: string;\n runId?: string;\n publicApiKey?: string;\n graphqlContext: GraphQLContext;\n forwardedParameters?: ForwardedParametersInput;\n url?: string;\n}\n\ninterface CopilotRuntimeResponse {\n threadId: string;\n runId?: string;\n eventSource: RuntimeEventSource;\n serverSideActions: Action<any>[];\n actionInputsWithoutAgents: ActionInput[];\n}\n\ntype ActionsConfiguration<T extends Parameter[] | [] = []> =\n | Action<T>[]\n | ((ctx: { properties: any; url?: string }) => Action<T>[]);\n\ninterface OnBeforeRequestOptions {\n threadId?: string;\n runId?: string;\n inputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnBeforeRequestHandler = (options: OnBeforeRequestOptions) => void | Promise<void>;\n\ninterface OnAfterRequestOptions {\n threadId: string;\n runId?: string;\n inputMessages: Message[];\n outputMessages: Message[];\n properties: any;\n url?: string;\n}\n\ntype OnAfterRequestHandler = (options: OnAfterRequestOptions) => void | Promise<void>;\n\ninterface Middleware {\n /**\n * A function that is called before the request is processed.\n */\n onBeforeRequest?: OnBeforeRequestHandler;\n\n /**\n * A function that is called after the request is processed.\n */\n onAfterRequest?: OnAfterRequestHandler;\n}\n\nexport interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []> {\n /**\n * Middleware to be used by the runtime.\n *\n * ```ts\n * onBeforeRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n *\n * ```ts\n * onAfterRequest: (options: {\n * threadId?: string;\n * runId?: string;\n * inputMessages: Message[];\n * outputMessages: Message[];\n * properties: any;\n * }) => void | Promise<void>;\n * ```\n */\n middleware?: Middleware;\n\n /*\n * A list of server side actions that can be executed.\n */\n actions?: ActionsConfiguration<T>;\n\n /*\n * Deprecated: Use `remoteEndpoints`.\n */\n remoteActions?: CopilotKitEndpoint[];\n\n /*\n * A list of remote actions that can be executed.\n */\n remoteEndpoints?: EndpointDefinition[];\n\n /*\n * An array of LangServer URLs.\n */\n langserve?: RemoteChainParameters[];\n}\n\nexport class CopilotRuntime<const T extends Parameter[] | [] = []> {\n public actions: ActionsConfiguration<T>;\n public remoteEndpointDefinitions: EndpointDefinition[];\n private langserve: Promise<Action<any>>[] = [];\n private onBeforeRequest?: OnBeforeRequestHandler;\n private onAfterRequest?: OnAfterRequestHandler;\n\n constructor(params?: CopilotRuntimeConstructorParams<T>) {\n this.actions = params?.actions || [];\n\n for (const chain of params?.langserve || []) {\n const remoteChain = new RemoteChain(chain);\n this.langserve.push(remoteChain.toAction());\n }\n\n this.remoteEndpointDefinitions = params?.remoteEndpoints ?? params?.remoteActions ?? [];\n\n this.onBeforeRequest = params?.middleware?.onBeforeRequest;\n this.onAfterRequest = params?.middleware?.onAfterRequest;\n }\n\n async processRuntimeRequest(request: CopilotRuntimeRequest): Promise<CopilotRuntimeResponse> {\n const {\n serviceAdapter,\n messages: rawMessages,\n actions: clientSideActionsInput,\n threadId,\n runId,\n outputMessagesPromise,\n graphqlContext,\n forwardedParameters,\n agentSession,\n url,\n } = request;\n\n const eventSource = new RuntimeEventSource();\n\n try {\n if (agentSession) {\n return await this.processAgentRequest(request);\n }\n\n const messages = rawMessages.filter((message) => !message.agentStateMessage);\n\n const inputMessages = convertGqlInputToMessages(messages);\n const serverSideActions = await this.getServerSideActions(request);\n\n const serverSideActionsInput: ActionInput[] = serverSideActions.map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n }));\n\n const actionInputs = flattenToolCallsNoDuplicates([\n ...serverSideActionsInput,\n ...clientSideActionsInput.filter(\n // Filter remote actions from CopilotKit core loop\n (action) => action.available !== ActionInputAvailability.remote,\n ),\n ]);\n\n await this.onBeforeRequest?.({\n threadId,\n runId,\n inputMessages,\n properties: graphqlContext.properties,\n url,\n });\n\n const result = await serviceAdapter.process({\n messages: inputMessages,\n actions: actionInputs,\n threadId,\n runId,\n eventSource,\n forwardedParameters,\n });\n\n outputMessagesPromise\n .then((outputMessages) => {\n this.onAfterRequest?.({\n threadId: result.threadId,\n runId: result.runId,\n inputMessages,\n outputMessages,\n properties: graphqlContext.properties,\n url,\n });\n })\n .catch((_error) => {});\n\n return {\n threadId: result.threadId,\n runId: result.runId,\n eventSource,\n serverSideActions,\n actionInputsWithoutAgents: actionInputs.filter(\n (action) =>\n // TODO-AGENTS: do not exclude ALL server side actions\n !serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n // !isLangGraphAgentAction(\n // serverSideActions.find((serverSideAction) => serverSideAction.name == action.name),\n // ),\n ),\n };\n } catch (error) {\n console.error(\"Error getting response:\", error);\n eventSource.sendErrorMessageToChat();\n throw error;\n }\n }\n\n async discoverAgentsFromEndpoints(graphqlContext: GraphQLContext): Promise<Agent[]> {\n const headers = createHeaders(null, graphqlContext);\n const agents = this.remoteEndpointDefinitions.reduce(\n async (acc: Promise<Agent[]>, endpoint) => {\n const agents = await acc;\n if (endpoint.type === EndpointType.LangGraphPlatform) {\n const response = await fetch(\n `${(endpoint as LangGraphPlatformEndpoint).deploymentUrl}/assistants/search`,\n {\n method: \"POST\",\n headers,\n },\n );\n\n const data: Array<{ assistant_id: string; graph_id: string }> = await response.json();\n const endpointAgents = (data ?? []).map((entry) => ({\n name: entry.graph_id,\n id: entry.assistant_id,\n }));\n return [...agents, ...endpointAgents];\n }\n\n interface InfoResponse {\n agents?: Array<{\n name: string;\n description: string;\n }>;\n }\n\n const response = await fetch(`${(endpoint as CopilotKitEndpoint).url}/info`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ properties: graphqlContext.properties }),\n });\n const data: InfoResponse = await response.json();\n const endpointAgents = (data?.agents ?? []).map((agent) => ({\n name: agent.name,\n description: agent.description,\n id: randomId(), // Required by Agent type\n }));\n return [...agents, ...endpointAgents];\n },\n Promise.resolve([]),\n );\n\n return agents;\n }\n\n private async processAgentRequest(\n request: CopilotRuntimeRequest,\n ): Promise<CopilotRuntimeResponse> {\n const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession } = request;\n const { threadId, agentName, nodeName } = agentSession;\n const serverSideActions = await this.getServerSideActions(request);\n\n const messages = convertGqlInputToMessages(rawMessages);\n\n const agent = serverSideActions.find(\n (action) => action.name === agentName && isLangGraphAgentAction(action),\n ) as LangGraphAgentAction;\n\n if (!agent) {\n throw new Error(`Agent ${agentName} not found`);\n }\n\n const serverSideActionsInput: ActionInput[] = serverSideActions\n .filter((action) => !isLangGraphAgentAction(action))\n .map((action) => ({\n name: action.name,\n description: action.description,\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters)),\n }));\n\n const actionInputsWithoutAgents = flattenToolCallsNoDuplicates([\n ...serverSideActionsInput,\n ...request.actions,\n ]);\n\n await this.onBeforeRequest?.({\n threadId,\n runId: undefined,\n inputMessages: messages,\n properties: graphqlContext.properties,\n });\n try {\n const eventSource = new RuntimeEventSource();\n const stream = await agent.langGraphAgentHandler({\n name: agentName,\n threadId,\n nodeName,\n actionInputsWithoutAgents,\n });\n\n eventSource.stream(async (eventStream$) => {\n from(stream).subscribe({\n next: (event) => eventStream$.next(event),\n error: (err) => {\n console.error(\"Error in stream\", err);\n eventStream$.error(err);\n eventStream$.complete();\n },\n complete: () => eventStream$.complete(),\n });\n });\n\n outputMessagesPromise\n .then((outputMessages) => {\n this.onAfterRequest?.({\n threadId,\n runId: undefined,\n inputMessages: messages,\n outputMessages,\n properties: graphqlContext.properties,\n });\n })\n .catch((_error) => {});\n\n return {\n threadId,\n runId: undefined,\n eventSource,\n serverSideActions: [],\n actionInputsWithoutAgents,\n };\n } catch (error) {\n console.error(\"Error getting response:\", error);\n throw error;\n }\n }\n\n private async getServerSideActions(request: CopilotRuntimeRequest): Promise<Action<any>[]> {\n const { messages: rawMessages, graphqlContext, agentStates, url } = request;\n const inputMessages = convertGqlInputToMessages(rawMessages);\n const langserveFunctions: Action<any>[] = [];\n\n for (const chainPromise of this.langserve) {\n try {\n const chain = await chainPromise;\n langserveFunctions.push(chain);\n } catch (error) {\n console.error(\"Error loading langserve chain:\", error);\n }\n }\n\n const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map(\n (endpoint) =>\n ({\n ...endpoint,\n type: resolveEndpointType(endpoint),\n }) as EndpointDefinition,\n );\n\n const remoteActions = await setupRemoteActions({\n remoteEndpointDefinitions,\n graphqlContext,\n messages: inputMessages,\n agentStates,\n frontendUrl: url,\n });\n\n const configuredActions =\n typeof this.actions === \"function\"\n ? this.actions({ properties: graphqlContext.properties, url })\n : this.actions;\n\n return [...configuredActions, ...langserveFunctions, ...remoteActions];\n }\n}\n\nexport function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {\n let allTools: ActionInput[] = [];\n const allToolNames: string[] = [];\n for (const tool of toolsByPriority) {\n if (!allToolNames.includes(tool.name)) {\n allTools.push(tool);\n allToolNames.push(tool.name);\n }\n }\n return allTools;\n}\n\n// The two functions below are \"factory functions\", meant to create the action objects that adhere to the expected interfaces\nexport function copilotKitEndpoint(config: Omit<CopilotKitEndpoint, \"type\">): CopilotKitEndpoint {\n return {\n ...config,\n type: EndpointType.CopilotKit,\n };\n}\n\nexport function langGraphPlatformEndpoint(\n config: Omit<LangGraphPlatformEndpoint, \"type\">,\n): LangGraphPlatformEndpoint {\n return {\n ...config,\n type: EndpointType.LangGraphPlatform,\n };\n}\n\nexport function resolveEndpointType(endpoint: EndpointDefinition) {\n if (!endpoint.type) {\n if (\"langsmithApiKey\" in endpoint && \"deploymentUrl\" in endpoint && \"agents\" in endpoint) {\n return EndpointType.LangGraphPlatform;\n } else {\n return EndpointType.CopilotKit;\n }\n }\n\n return endpoint.type;\n}\n","import {\n ActionExecutionMessageInput,\n ResultMessageInput,\n TextMessageInput,\n AgentStateMessageInput,\n} from \"../../inputs/message.input\";\nimport { BaseMessageInput } from \"../base\";\nimport { MessageRole } from \"../enums\";\n\nexport type MessageType =\n | \"TextMessage\"\n | \"ActionExecutionMessage\"\n | \"ResultMessage\"\n | \"AgentStateMessage\";\n\nexport class Message extends BaseMessageInput {\n type: MessageType;\n\n isTextMessage(): this is TextMessage {\n return this.type === \"TextMessage\";\n }\n\n isActionExecutionMessage(): this is ActionExecutionMessage {\n return this.type === \"ActionExecutionMessage\";\n }\n\n isResultMessage(): this is ResultMessage {\n return this.type === \"ResultMessage\";\n }\n\n isAgentStateMessage(): this is AgentStateMessage {\n return this.type === \"AgentStateMessage\";\n }\n}\n\nexport class TextMessage extends Message implements TextMessageInput {\n type: MessageType = \"TextMessage\";\n content: string;\n role: MessageRole;\n parentMessageId?: string;\n}\n\nexport class ActionExecutionMessage\n extends Message\n implements Omit<ActionExecutionMessageInput, \"arguments\" | \"scope\">\n{\n type: MessageType = \"ActionExecutionMessage\";\n name: string;\n arguments: Record<string, any>;\n parentMessageId?: string;\n}\n\nexport class ResultMessage extends Message implements ResultMessageInput {\n type: MessageType = \"ResultMessage\";\n actionExecutionId: string;\n actionName: string;\n result: string;\n\n static encodeResult(\n result: any,\n error?: { code: string; message: string } | string | Error,\n ): string {\n const errorObj = error\n ? typeof error === \"string\"\n ? { code: \"ERROR\", message: error }\n : error instanceof Error\n ? { code: \"ERROR\", message: error.message }\n : error\n : undefined;\n\n if (errorObj) {\n return JSON.stringify({\n error: errorObj,\n result: result || \"\",\n });\n }\n if (result === undefined) {\n return \"\";\n }\n return typeof result === \"string\" ? result : JSON.stringify(result);\n }\n\n static decodeResult(result: string): {\n error?: { code: string; message: string };\n result: string;\n } {\n if (!result) {\n return { result: \"\" };\n }\n try {\n const parsed = JSON.parse(result);\n if (parsed && typeof parsed === \"object\") {\n if (\"error\" in parsed) {\n return {\n error: parsed.error,\n result: parsed.result || \"\",\n };\n }\n return { result: JSON.stringify(parsed) };\n }\n return { result };\n } catch (e) {\n return { result };\n }\n }\n\n hasError(): boolean {\n try {\n const { error } = ResultMessage.decodeResult(this.result);\n return !!error;\n } catch {\n return false;\n }\n }\n\n getError(): { code: string; message: string } | undefined {\n try {\n const { error } = ResultMessage.decodeResult(this.result);\n return error;\n } catch {\n return undefined;\n }\n }\n}\n\nexport class AgentStateMessage extends Message implements Omit<AgentStateMessageInput, \"state\"> {\n type: MessageType = \"AgentStateMessage\";\n threadId: string;\n agentName: string;\n nodeName: string;\n runId: string;\n active: boolean;\n role: MessageRole;\n state: any;\n running: boolean;\n}\n","import {\n FailedResponseStatus,\n FailedResponseStatusReason,\n} from \"../graphql/types/response-status.type\";\n\nexport class GuardrailsValidationFailureResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.GUARDRAILS_VALIDATION_FAILED;\n declare details: {\n guardrailsReason: string;\n };\n\n constructor({ guardrailsReason }) {\n super();\n this.details = {\n guardrailsReason,\n };\n }\n}\n\nexport class MessageStreamInterruptedResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.MESSAGE_STREAM_INTERRUPTED;\n declare details: {\n messageId: string;\n description: string;\n };\n\n constructor({ messageId }: { messageId: string }) {\n super();\n this.details = {\n messageId,\n description: \"Check the message for mode details\",\n };\n }\n}\n\nexport class UnknownErrorResponse extends FailedResponseStatus {\n reason = FailedResponseStatusReason.UNKNOWN_ERROR;\n declare details: {\n description?: string;\n };\n\n constructor({ description }: { description?: string }) {\n super();\n this.details = {\n description,\n };\n }\n}\n","import { Field, InterfaceType, ObjectType } from \"type-graphql\";\nimport { MessageRole } from \"./enums\";\nimport { MessageStatusUnion } from \"./message-status.type\";\nimport { ResponseStatusUnion } from \"./response-status.type\";\n\n@ObjectType()\nexport class Agent {\n @Field(() => String)\n id: string;\n\n @Field(() => String)\n name: string;\n\n @Field(() => String)\n description?: string;\n}\n\n@ObjectType()\nexport class AgentsResponse {\n @Field(() => [Agent])\n agents: Agent[];\n}\n","import createPinoLogger from \"pino\";\nimport pretty from \"pino-pretty\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type CopilotRuntimeLogger = ReturnType<typeof createLogger>;\n\nexport function createLogger(options?: { level?: LogLevel; component?: string }) {\n const { level, component } = options || {};\n const stream = pretty({ colorize: true });\n\n const logger = createPinoLogger(\n {\n level: process.env.LOG_LEVEL || level || \"error\",\n redact: {\n paths: [\"pid\", \"hostname\"],\n remove: true,\n },\n },\n stream,\n );\n\n if (component) {\n return logger.child({ component });\n } else {\n return logger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,0BAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,UAAY;AAAA,MACZ,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,eAAiB;AAAA,QACf,QAAU;AAAA,MACZ;AAAA,MACA,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,QAAU;AAAA,MACV,SAAW;AAAA,QACT,KAAK;AAAA,MACP;AAAA,MACA,OAAS;AAAA,MACT,SAAW;AAAA,MACX,SAAW;AAAA,QACT,OAAS;AAAA,QACT,KAAO;AAAA,QACP,MAAQ;AAAA,QACR,eAAe;AAAA,QACf,OAAS;AAAA,QACT,2BAA2B;AAAA,QAC3B,eAAe;AAAA,QACf,iBAAiB;AAAA,MACnB;AAAA,MACA,iBAAmB;AAAA,QACjB,aAAa;AAAA,QACb,kBAAkB;AAAA,QAClB,eAAe;AAAA,QACf,eAAe;AAAA,QACf,uBAAuB;AAAA,QACvB,QAAU;AAAA,QACV,wBAAwB;AAAA,QACxB,MAAQ;AAAA,QACR,SAAW;AAAA,QACX,WAAW;AAAA,QACX,WAAW;AAAA,QACX,UAAY;AAAA,QACZ,MAAQ;AAAA,QACR,YAAc;AAAA,QACd,sBAAsB;AAAA,MACxB;AAAA,MACA,cAAgB;AAAA,QACd,qBAAqB;AAAA,QACrB,sBAAsB;AAAA,QACtB,qCAAqC;AAAA,QACrC,wBAAwB;AAAA,QACxB,mBAAmB;AAAA,QACnB,2BAA2B;AAAA,QAC3B,4BAA4B;AAAA,QAC5B,qBAAqB;AAAA,QACrB,qBAAqB;AAAA,QACrB,SAAW;AAAA,QAC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oBAAoB;IAC5BC,SAAS;MACPC,WAAW;IACb;EACF,CAAA;AAEA,OAAIN,aAAQO,eAARP,mBAAoBQ,aAAa;AACnCL,6BAAUC,oBAAoB;MAC5BI,aAAaR,QAAQO,WAAWC;IAClC,CAAA;EACF;AAEAL,2BAAUM,QACR,gCACAC,gCAAgCV,QAAQK,OAAO,CAAA;AAGjD,QAAMM,UAASV,aAAaW;AAC5BD,EAAAA,QAAOE,MAAM,6BAAA;AAEb,QAAMC,WAAOC,iCAAW;IACtB,GAAGd;IACHe,iBAAiBhB,QAAQiB;EAC3B,CAAA;AAEA,SAAOH;AACT;AA7BgBf;;;ADAT,SAASmB,kCAAkCC,SAA0C;AAC1FC,2BAAUC,oBAAoB;IAC5BC,SAAS;MACPC,WAAW;IACb;EACF,CAAA;AAEAH,2BAAUI,QACR,gCACAC,gCAAgCN,QAAQG,OAAO,CAAA;AAEjD,SAAOI,+BAA+BP,OAAAA;AACxC;AAZgBD;","names":["module","import_graphql_yoga","import_type_graphql","import_type_graphql","import_rxjs","import_type_graphql","import_type_graphql","MessageRole","CopilotRequestType","ActionInputAvailability","registerEnumType","name","description","import_type_graphql","BaseMessageInput","id","createdAt","Field","String","Date","InputType","MessageInput","BaseMessageInput","textMessage","actionExecutionMessage","resultMessage","agentStateMessage","Field","TextMessageInput","nullable","ActionExecutionMessageInput","ResultMessageInput","AgentStateMessageInput","InputType","content","parentMessageId","role","String","MessageRole","name","arguments","scope","deprecationReason","actionExecutionId","actionName","result","threadId","agentName","state","running","nodeName","runId","active","Boolean","import_type_graphql","import_type_graphql","ActionInput","name","description","jsonSchema","available","Field","String","ActionInputAvailability","nullable","InputType","FrontendInput","toDeprecate_fullContext","actions","url","Field","String","nullable","ActionInput","InputType","import_type_graphql","import_type_graphql","GuardrailsRuleInput","allowList","denyList","Field","String","nullable","InputType","GuardrailsInput","inputValidationRules","CloudInput","guardrails","Field","GuardrailsInput","nullable","InputType","import_type_graphql","ForwardedParametersInput","model","maxTokens","stop","toolChoice","toolChoiceFunctionName","temperature","Field","String","nullable","Number","InputType","import_type_graphql","AgentSessionInput","agentName","threadId","nodeName","Field","String","nullable","InputType","import_type_graphql","AgentStateInput","agentName","state","Field","String","InputType","GenerateCopilotResponseMetadataInput","requestType","Field","CopilotRequestType","nullable","InputType","GenerateCopilotResponseInput","metadata","threadId","runId","messages","frontend","cloud","forwardedParameters","agentSession","agentState","agentStates","String","MessageInput","FrontendInput","CloudInput","ForwardedParametersInput","AgentSessionInput","AgentStateInput","import_type_graphql","import_type_graphql","MessageStatusCode","registerEnumType","name","BaseMessageStatus","code","Field","ObjectType","PendingMessageStatus","SuccessMessageStatus","FailedMessageStatus","reason","String","MessageStatusUnion","createUnionType","types","import_type_graphql","ResponseStatusCode","registerEnumType","name","BaseResponseStatus","code","Field","InterfaceType","resolveType","value","SuccessResponseStatus","FailedResponseStatus","PendingResponseStatus","undefined","ObjectType","implements","FailedResponseStatusReason","reason","details","GraphQLJSON","nullable","ResponseStatusUnion","createUnionType","types","BaseMessageOutput","id","createdAt","status","Field","String","Date","MessageStatusUnion","InterfaceType","resolveType","value","hasOwnProperty","TextMessageOutput","ActionExecutionMessageOutput","ResultMessageOutput","AgentStateMessageOutput","undefined","role","content","parentMessageId","MessageRole","nullable","ObjectType","implements","name","scope","arguments","deprecationReason","actionExecutionId","actionName","result","threadId","agentName","nodeName","runId","active","state","running","Boolean","CopilotResponse","messages","ResponseStatusUnion","import_shared","import_rxjs","import_shared","EndpointType","Message","BaseMessageInput","type","isTextMessage","isActionExecutionMessage","isResultMessage","isAgentStateMessage","TextMessage","content","role","parentMessageId","ActionExecutionMessage","name","arguments","ResultMessage","actionExecutionId","actionName","result","encodeResult","error","errorObj","code","message","Error","undefined","JSON","stringify","decodeResult","parsed","parse","e","hasError","getError","AgentStateMessage","threadId","agentName","nodeName","runId","active","state","running","resolveEndpointType","endpoint","type","EndpointType","LangGraphPlatform","CopilotKit","packageJson","require","telemetryClient","TelemetryClient","packageName","name","packageVersion","version","getRuntimeInstanceTelemetryInfo","runtime","endpointsInfo","remoteEndpointDefinitions","reduce","acc","endpoint","info","endpointType","resolveEndpointType","endpointTypes","includes","EndpointType","LangGraphPlatform","ep","agentsAmount","agents","length","hashedKey","createHash","update","langsmithApiKey","digest","actionsAmount","actions","endpointsAmount","hashedLgcKey","RuntimeEventTypes","import_graphql_scalars","import_class_transformer","GuardrailsValidationFailureResponse","FailedResponseStatus","reason","FailedResponseStatusReason","GUARDRAILS_VALIDATION_FAILED","constructor","guardrailsReason","details","MessageStreamInterruptedResponse","MESSAGE_STREAM_INTERRUPTED","messageId","description","UnknownErrorResponse","UNKNOWN_ERROR","import_shared","import_type_graphql","Agent","id","name","description","Field","String","ObjectType","AgentsResponse","agents","invokeGuardrails","baseUrl","copilotCloudPublicApiKey","data","onResult","onError","messages","length","textMessage","role","MessageRole","user","filter","m","undefined","assistant","map","content","lastMessage","restOfMessages","slice","body","input","validTopics","cloud","guardrails","inputValidationRules","allowList","invalidTopics","denyList","guardrailsResult","fetch","method","headers","JSON","stringify","ok","resultJson","json","CopilotResolver","hello","availableAgents","ctx","logger","child","component","debug","agents","_copilotkit","runtime","discoverAgentsFromEndpoints","generateCopilotResponse","properties","telemetry","capture","requestType","metadata","copilotRuntime","serviceAdapter","copilotCloudBaseUrl","key","request","get","error","GraphQLError","process","env","COPILOT_CLOUD_BASE_URL","responseStatus$","ReplaySubject","interruptStreaming$","guardrailsResult$","outputMessages","resolveOutputMessagesPromise","rejectOutputMessagesPromise","outputMessagesPromise","Promise","resolve","reject","eventSource","threadId","randomId","runId","serverSideActions","actionInputsWithoutAgents","processRuntimeRequest","actions","frontend","action","available","ActionInputAvailability","disabled","publicApiKey","graphqlContext","forwardedParameters","agentSession","agentStates","url","response","status","firstValueFrom","Repeater","pushMessage","stopStreamingMessages","result","next","GuardrailsValidationFailureResponse","guardrailsReason","reason","plainToInstance","TextMessage","id","createdAt","Date","err","UnknownErrorResponse","description","eventStreamSubscription","eventStream","processRuntimeEvents","find","serverSideAction","name","pipe","shareReplay","finalize","subscribe","event","type","RuntimeEventTypes","TextMessageStart","textMessageContentStream","skipWhile","e","takeWhile","TextMessageEnd","messageId","TextMessageContent","streamingTextStatus","Subject","parentMessageId","pushTextChunk","stopStreamingText","textChunks","textSubscription","take","tap","FailedMessageStatus","MessageStreamInterruptedResponse","unsubscribe","push","complete","SuccessMessageStatus","join","ActionExecutionStart","actionExecutionArgumentStream","ActionExecutionEnd","actionExecutionId","ActionExecutionArgs","streamingArgumentsStatus","actionName","arguments","pushArgumentsChunk","stopStreamingArguments","argumentChunks","actionExecutionArgumentSubscription","args","ActionExecutionMessage","ActionExecutionResult","ResultMessage","AgentStateMessage","agentName","nodeName","active","state","running","SuccessResponseStatus","Query","String","AgentsResponse","Ctx","Mutation","CopilotResponse","Arg","GraphQLJSONObject","nullable","Resolver","createLogger","options","level","component","stream","pretty","colorize","logger","createPinoLogger","process","env","LOG_LEVEL","redact","paths","remove","child","logger","createLogger","createContext","initialContext","copilotKitContext","contextLogger","properties","debug","ctx","_copilotkit","buildSchema","options","schema","buildSchemaSync","resolvers","CopilotResolver","emitSchemaFile","getCommonConfig","logLevel","process","env","LOG_LEVEL","level","component","cloud","telemetry","setCloudConfiguration","publicApiKey","baseUrl","setGlobalProperties","runtime","serviceAdapter","constructor","name","logging","plugins","useDeferStream","context","copilotRuntimeNodeHttpEndpoint","options","commonConfig","getCommonConfig","telemetry","setGlobalProperties","runtime","framework","properties","_copilotkit","capture","getRuntimeInstanceTelemetryInfo","logger","logging","debug","yoga","createYoga","graphqlEndpoint","endpoint","copilotRuntimeNodeExpressEndpoint","options","telemetry","setGlobalProperties","runtime","framework","capture","getRuntimeInstanceTelemetryInfo","copilotRuntimeNodeHttpEndpoint"]}
|