{"version":3,"file":"copilot.resolver.mjs","names":[],"sources":["../../../src/graphql/resolvers/copilot.resolver.ts"],"sourcesContent":["import { Arg, Ctx, Mutation, Query, Resolver } from \"type-graphql\";\nimport {\n  ReplaySubject,\n  Subject,\n  Subscription,\n  filter,\n  finalize,\n  firstValueFrom,\n  shareReplay,\n  skipWhile,\n  take,\n  takeWhile,\n  tap,\n} from \"rxjs\";\nimport { GenerateCopilotResponseInput } from \"../inputs/generate-copilot-response.input\";\nimport { CopilotResponse } from \"../types/copilot-response.type\";\nimport {\n  CopilotKitLangGraphInterruptEvent,\n  LangGraphInterruptEvent,\n} from \"../types/meta-events.type\";\nimport { ActionInputAvailability, MessageRole } from \"../types/enums\";\nimport { Repeater } from \"graphql-yoga\";\nimport type {\n  CopilotRequestContextProperties,\n  GraphQLContext,\n} from \"../../lib/integrations\";\nimport {\n  RuntimeEvent,\n  RuntimeEventTypes,\n  RuntimeMetaEventName,\n} from \"../../service-adapters/events\";\nimport {\n  FailedMessageStatus,\n  MessageStatusCode,\n  MessageStatusUnion,\n  SuccessMessageStatus,\n} from \"../types/message-status.type\";\nimport {\n  ResponseStatusUnion,\n  SuccessResponseStatus,\n} from \"../types/response-status.type\";\nimport { GraphQLJSONObject } from \"graphql-scalars\";\nimport { plainToInstance } from \"class-transformer\";\nimport { GuardrailsResult } from \"../types/guardrails-result.type\";\nimport { GraphQLError } from \"graphql\";\nimport {\n  GuardrailsValidationFailureResponse,\n  MessageStreamInterruptedResponse,\n  UnknownErrorResponse,\n} from \"../../utils\";\nimport {\n  ActionExecutionMessage,\n  AgentStateMessage,\n  Message,\n  MessageType,\n  ResultMessage,\n  TextMessage,\n} from \"../types/converted\";\nimport telemetry from \"../../lib/telemetry-client\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { AgentsResponse } from \"../types/agents-response.type\";\nimport { LangGraphEventTypes } from \"../../agents/langgraph/events\";\nimport {\n  CopilotKitError,\n  CopilotKitLowLevelError,\n  isStructuredCopilotKitError,\n} from \"@copilotkit/shared\";\nimport { CopilotRuntime } from \"../../lib\";\n\nconst invokeGuardrails = async ({\n  baseUrl,\n  copilotCloudPublicApiKey,\n  data,\n  onResult,\n  onError,\n}: {\n  baseUrl: string;\n  copilotCloudPublicApiKey: string;\n  data: GenerateCopilotResponseInput;\n  onResult: (result: GuardrailsResult) => void;\n  onError: (err: Error) => void;\n}) => {\n  if (\n    data.messages.length &&\n    data.messages[data.messages.length - 1].textMessage?.role ===\n      MessageRole.user\n  ) {\n    const messages = data.messages\n      .filter(\n        (m) =>\n          m.textMessage !== undefined &&\n          (m.textMessage.role === MessageRole.user ||\n            m.textMessage.role === MessageRole.assistant),\n      )\n      .map((m) => ({\n        role: m.textMessage!.role,\n        content: m.textMessage.content,\n      }));\n\n    const lastMessage = messages[messages.length - 1];\n    const restOfMessages = messages.slice(0, -1);\n\n    const body = {\n      input: lastMessage.content,\n      validTopics: data.cloud.guardrails.inputValidationRules.allowList,\n      invalidTopics: data.cloud.guardrails.inputValidationRules.denyList,\n      messages: restOfMessages,\n    };\n\n    const guardrailsResult = await fetch(`${baseUrl}/guardrails/validate`, {\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n        \"X-CopilotCloud-Public-API-Key\": copilotCloudPublicApiKey,\n      },\n      body: JSON.stringify(body),\n    });\n\n    if (guardrailsResult.ok) {\n      const resultJson: GuardrailsResult = await guardrailsResult.json();\n      onResult(resultJson);\n    } else {\n      onError(await guardrailsResult.json());\n    }\n  }\n};\n\n@Resolver(() => CopilotResponse)\nexport class CopilotResolver {\n  @Query(() => String)\n  async hello() {\n    return \"Hello World\";\n  }\n\n  @Query(() => AgentsResponse)\n  async availableAgents(@Ctx() ctx: GraphQLContext) {\n    let logger = ctx.logger.child({\n      component: \"CopilotResolver.availableAgents\",\n    });\n\n    logger.debug(\"Processing\");\n    const agentsWithEndpoints = [];\n\n    logger.debug(\"Event source created, creating response\");\n\n    return {\n      agents: agentsWithEndpoints.map(\n        ({ endpoint, ...agentWithoutEndpoint }) => agentWithoutEndpoint,\n      ),\n    };\n  }\n\n  @Mutation(() => CopilotResponse)\n  async generateCopilotResponse(\n    @Ctx() ctx: GraphQLContext,\n    @Arg(\"data\") data: GenerateCopilotResponseInput,\n    @Arg(\"properties\", () => GraphQLJSONObject, { nullable: true })\n    properties?: CopilotRequestContextProperties,\n  ) {\n    telemetry.capture(\"oss.runtime.copilot_request_created\", {\n      \"cloud.guardrails.enabled\": data.cloud?.guardrails !== undefined,\n      requestType: data.metadata.requestType,\n      \"cloud.api_key_provided\": !!ctx.request.headers.get(\n        \"x-copilotcloud-public-api-key\",\n      ),\n      ...(ctx.request.headers.get(\"x-copilotcloud-public-api-key\")\n        ? {\n            \"cloud.public_api_key\": ctx.request.headers.get(\n              \"x-copilotcloud-public-api-key\",\n            ),\n          }\n        : {}),\n      ...(ctx._copilotkit.baseUrl\n        ? {\n            \"cloud.base_url\": ctx._copilotkit.baseUrl,\n          }\n        : {\n            \"cloud.base_url\": \"https://api.cloud.copilotkit.ai\",\n          }),\n    });\n\n    let logger = ctx.logger.child({\n      component: \"CopilotResolver.generateCopilotResponse\",\n    });\n    logger.debug({ data }, \"Generating Copilot response\");\n\n    if (properties) {\n      logger.debug(\"Properties provided, merging with context properties\");\n      ctx.properties = { ...ctx.properties, ...properties };\n    }\n\n    const copilotRuntime = ctx._copilotkit.runtime as unknown as CopilotRuntime;\n    const serviceAdapter = ctx._copilotkit.serviceAdapter;\n\n    let copilotCloudPublicApiKey: string | null = null;\n    let copilotCloudBaseUrl: string;\n\n    // Extract publicApiKey from headers for both cloud and non-cloud requests\n    // This enables onTrace functionality regardless of cloud configuration\n    const publicApiKeyFromHeaders = ctx.request.headers.get(\n      \"x-copilotcloud-public-api-key\",\n    );\n    if (publicApiKeyFromHeaders) {\n      copilotCloudPublicApiKey = publicApiKeyFromHeaders;\n    }\n\n    if (data.cloud) {\n      logger = logger.child({ cloud: true });\n      logger.debug(\n        \"Cloud configuration provided, checking for public API key in headers\",\n      );\n\n      if (!copilotCloudPublicApiKey) {\n        logger.error(\"Public API key not found in headers\");\n\n        throw new GraphQLError(\n          \"X-CopilotCloud-Public-API-Key header is required\",\n        );\n      }\n\n      if (process.env.COPILOT_CLOUD_BASE_URL) {\n        copilotCloudBaseUrl = process.env.COPILOT_CLOUD_BASE_URL;\n      } else if (ctx._copilotkit.cloud?.baseUrl) {\n        copilotCloudBaseUrl = ctx._copilotkit.cloud?.baseUrl;\n      } else {\n        copilotCloudBaseUrl = \"https://api.cloud.copilotkit.ai\";\n      }\n\n      logger = logger.child({ copilotCloudBaseUrl });\n    }\n\n    logger.debug(\"Setting up subjects\");\n    const responseStatus$ = new ReplaySubject<typeof ResponseStatusUnion>();\n    const interruptStreaming$ = new ReplaySubject<{\n      reason: string;\n      messageId?: string;\n    }>();\n    const guardrailsResult$ = new ReplaySubject<GuardrailsResult>();\n\n    let outputMessages: Message[] = [];\n    let resolveOutputMessagesPromise: (messages: Message[]) => void;\n    let rejectOutputMessagesPromise: (err: Error) => void;\n\n    const outputMessagesPromise = new Promise<Message[]>((resolve, reject) => {\n      resolveOutputMessagesPromise = resolve;\n      rejectOutputMessagesPromise = reject;\n    });\n\n    if (copilotCloudPublicApiKey) {\n      ctx.properties[\"copilotCloudPublicApiKey\"] = copilotCloudPublicApiKey;\n    }\n\n    logger.debug(\"Processing\");\n    let runtimeResponse;\n\n    const {\n      eventSource,\n      threadId = randomId(),\n      runId,\n      serverSideActions,\n      actionInputsWithoutAgents,\n      extensions,\n    } = runtimeResponse;\n\n    logger.debug(\"Event source created, creating response\");\n    // run and process the event stream\n    const eventStream = eventSource\n      .processRuntimeEvents({\n        serverSideActions,\n        guardrailsResult$: data.cloud?.guardrails ? guardrailsResult$ : null,\n        actionInputsWithoutAgents: actionInputsWithoutAgents.filter(\n          // TODO-AGENTS: do not exclude ALL server side actions\n          (action) =>\n            !serverSideActions.find(\n              (serverSideAction) => serverSideAction.name == action.name,\n            ),\n        ),\n        threadId,\n      })\n      .pipe(\n        // shareReplay() ensures that later subscribers will see the whole stream instead of\n        // just the events that were emitted after the subscriber was added.\n        shareReplay(),\n        finalize(() => {\n          logger.debug(\"Event stream finalized\");\n        }),\n      );\n\n    const response = {\n      threadId,\n      runId,\n      status: firstValueFrom(responseStatus$),\n      extensions,\n      metaEvents: new Repeater(async (push, stop) => {\n        let eventStreamSubscription: Subscription;\n\n        eventStreamSubscription = eventStream.subscribe({\n          next: async (event) => {\n            if (event.type != RuntimeEventTypes.MetaEvent) {\n              return;\n            }\n            switch (event.name) {\n              // @ts-ignore\n              case LangGraphEventTypes.OnInterrupt:\n                push(\n                  plainToInstance(LangGraphInterruptEvent, {\n                    // @ts-ignore\n                    type: event.type,\n                    // @ts-ignore\n                    name: RuntimeMetaEventName.LangGraphInterruptEvent,\n                    // @ts-ignore\n                    value: event.value,\n                  }),\n                );\n                break;\n              case RuntimeMetaEventName.LangGraphInterruptEvent:\n                push(\n                  plainToInstance(LangGraphInterruptEvent, {\n                    type: event.type,\n                    name: event.name,\n                    value: event.value,\n                  }),\n                );\n                break;\n              case RuntimeMetaEventName.CopilotKitLangGraphInterruptEvent:\n                push(\n                  plainToInstance(CopilotKitLangGraphInterruptEvent, {\n                    type: event.type,\n                    name: event.name,\n                    data: {\n                      value: event.data.value,\n                      messages: event.data.messages.map((message) => {\n                        if (\n                          message.type === \"TextMessage\" ||\n                          (\"content\" in message && \"role\" in message)\n                        ) {\n                          return plainToInstance(TextMessage, {\n                            id: message.id,\n                            createdAt: new Date(),\n                            content: [(message as TextMessage).content],\n                            role: (message as TextMessage).role,\n                            status: new SuccessMessageStatus(),\n                          });\n                        }\n                        if (\"arguments\" in message) {\n                          return plainToInstance(ActionExecutionMessage, {\n                            name: message.name,\n                            id: message.id,\n                            arguments: [JSON.stringify(message.arguments)],\n                            createdAt: new Date(),\n                            status: new SuccessMessageStatus(),\n                          });\n                        }\n                        throw new Error(\n                          \"Unknown message in metaEvents copilot resolver\",\n                        );\n                      }),\n                    },\n                  }),\n                );\n                break;\n            }\n          },\n          error: (err) => {\n            // For structured CopilotKit errors, set proper error response status\n            if (\n              err?.name?.includes(\"CopilotKit\") ||\n              err?.extensions?.visibility\n            ) {\n              responseStatus$.next(\n                new UnknownErrorResponse({\n                  description: err.message || \"Agent error occurred\",\n                }),\n              );\n            } else {\n              responseStatus$.next(\n                new UnknownErrorResponse({\n                  description: `An unknown error has occurred in the event stream`,\n                }),\n              );\n            }\n\n            eventStreamSubscription?.unsubscribe();\n            stop();\n          },\n          complete: async () => {\n            logger.debug(\"Meta events stream completed\");\n            responseStatus$.next(new SuccessResponseStatus());\n            eventStreamSubscription?.unsubscribe();\n            stop();\n          },\n        });\n      }),\n      messages: new Repeater(async (pushMessage, stopStreamingMessages) => {\n        logger.debug(\"Messages repeater created\");\n\n        if (data.cloud?.guardrails) {\n          logger = logger.child({ guardrails: true });\n          logger.debug(\"Guardrails is enabled, validating input\");\n\n          invokeGuardrails({\n            baseUrl: copilotCloudBaseUrl,\n            copilotCloudPublicApiKey,\n            data,\n            onResult: (result) => {\n              logger.debug(\n                { status: result.status },\n                \"Guardrails validation done\",\n              );\n              guardrailsResult$.next(result);\n\n              // Guardrails validation failed\n              if (result.status === \"denied\") {\n                // send the reason to the client and interrupt streaming\n                responseStatus$.next(\n                  new GuardrailsValidationFailureResponse({\n                    guardrailsReason: result.reason,\n                  }),\n                );\n                interruptStreaming$.next({\n                  reason: `Interrupted due to Guardrails validation failure. Reason: ${result.reason}`,\n                });\n\n                // resolve messages promise to the middleware\n                outputMessages = [\n                  plainToInstance(TextMessage, {\n                    id: randomId(),\n                    createdAt: new Date(),\n                    content: result.reason,\n                    role: MessageRole.assistant,\n                  }),\n                ];\n                resolveOutputMessagesPromise(outputMessages);\n              }\n            },\n            onError: (err) => {\n              logger.error({ err }, \"Error in guardrails validation\");\n              responseStatus$.next(\n                new UnknownErrorResponse({\n                  description: `An unknown error has occurred in the guardrails validation`,\n                }),\n              );\n              interruptStreaming$.next({\n                reason: `Interrupted due to unknown error in guardrails validation`,\n              });\n\n              // reject the middleware promise\n              rejectOutputMessagesPromise(err);\n            },\n          });\n        }\n\n        let eventStreamSubscription: Subscription;\n\n        logger.debug(\"Event stream created, subscribing to event stream\");\n\n        eventStreamSubscription = eventStream.subscribe({\n          next: async (event) => {\n            switch (event.type) {\n              case RuntimeEventTypes.MetaEvent:\n                break;\n              ////////////////////////////////\n              // TextMessageStart\n              ////////////////////////////////\n              case RuntimeEventTypes.TextMessageStart:\n                // create a sub stream that contains the message content\n                const textMessageContentStream = eventStream.pipe(\n                  // skip until this message start event\n                  skipWhile((e: RuntimeEvent) => e !== event),\n                  // take until the message end event\n                  takeWhile(\n                    (e: RuntimeEvent) =>\n                      !(\n                        e.type === RuntimeEventTypes.TextMessageEnd &&\n                        (e as any).messageId == event.messageId\n                      ),\n                  ),\n                  // filter out any other message events or message ids\n                  filter(\n                    (e: RuntimeEvent) =>\n                      e.type == RuntimeEventTypes.TextMessageContent &&\n                      (e as any).messageId == event.messageId,\n                  ),\n                );\n\n                // signal when we are done streaming\n                const streamingTextStatus = new Subject<\n                  typeof MessageStatusUnion\n                >();\n\n                const messageId = event.messageId;\n                // push the new message\n                pushMessage({\n                  id: messageId,\n                  parentMessageId: event.parentMessageId,\n                  status: firstValueFrom(streamingTextStatus),\n                  createdAt: new Date(),\n                  role: MessageRole.assistant,\n                  content: new Repeater(\n                    async (pushTextChunk, stopStreamingText) => {\n                      logger.debug(\"Text message content repeater created\");\n\n                      const textChunks: string[] = [];\n                      let textSubscription: Subscription;\n\n                      interruptStreaming$\n                        .pipe(\n                          shareReplay(),\n                          take(1),\n                          tap(({ reason, messageId }) => {\n                            logger.debug(\n                              { reason, messageId },\n                              \"Text streaming interrupted\",\n                            );\n\n                            streamingTextStatus.next(\n                              plainToInstance(FailedMessageStatus, { reason }),\n                            );\n\n                            responseStatus$.next(\n                              new MessageStreamInterruptedResponse({\n                                messageId,\n                              }),\n                            );\n                            stopStreamingText();\n                            textSubscription?.unsubscribe();\n                          }),\n                        )\n                        .subscribe();\n\n                      logger.debug(\n                        \"Subscribing to text message content stream\",\n                      );\n\n                      textSubscription = textMessageContentStream.subscribe({\n                        next: async (e: RuntimeEvent) => {\n                          if (e.type == RuntimeEventTypes.TextMessageContent) {\n                            await pushTextChunk(e.content);\n                            textChunks.push(e.content);\n                          }\n                        },\n                        error: (err) => {\n                          logger.error(\n                            { err },\n                            \"Error in text message content stream\",\n                          );\n                          interruptStreaming$.next({\n                            reason: \"Error streaming message content\",\n                            messageId,\n                          });\n                          stopStreamingText();\n                          textSubscription?.unsubscribe();\n                        },\n                        complete: () => {\n                          logger.debug(\"Text message content stream completed\");\n                          streamingTextStatus.next(new SuccessMessageStatus());\n                          stopStreamingText();\n                          textSubscription?.unsubscribe();\n\n                          outputMessages.push(\n                            plainToInstance(TextMessage, {\n                              id: messageId,\n                              createdAt: new Date(),\n                              content: textChunks.join(\"\"),\n                              role: MessageRole.assistant,\n                            }),\n                          );\n                        },\n                      });\n                    },\n                  ),\n                });\n                break;\n              ////////////////////////////////\n              // ActionExecutionStart\n              ////////////////////////////////\n              case RuntimeEventTypes.ActionExecutionStart:\n                logger.debug(\"Action execution start event received\");\n                const actionExecutionArgumentStream = eventStream.pipe(\n                  skipWhile((e: RuntimeEvent) => e !== event),\n                  // take until the action execution end event\n                  takeWhile(\n                    (e: RuntimeEvent) =>\n                      !(\n                        e.type === RuntimeEventTypes.ActionExecutionEnd &&\n                        (e as any).actionExecutionId == event.actionExecutionId\n                      ),\n                  ),\n                  // filter out any other action execution events or action execution ids\n                  filter(\n                    (e: RuntimeEvent) =>\n                      e.type == RuntimeEventTypes.ActionExecutionArgs &&\n                      (e as any).actionExecutionId == event.actionExecutionId,\n                  ),\n                );\n                const streamingArgumentsStatus = new Subject<\n                  typeof MessageStatusUnion\n                >();\n                pushMessage({\n                  id: event.actionExecutionId,\n                  parentMessageId: event.parentMessageId,\n                  status: firstValueFrom(streamingArgumentsStatus),\n                  createdAt: new Date(),\n                  name: event.actionName,\n                  arguments: new Repeater(\n                    async (pushArgumentsChunk, stopStreamingArguments) => {\n                      logger.debug(\"Action execution argument stream created\");\n\n                      const argumentChunks: string[] = [];\n                      let actionExecutionArgumentSubscription: Subscription;\n\n                      actionExecutionArgumentSubscription =\n                        actionExecutionArgumentStream.subscribe({\n                          next: async (e: RuntimeEvent) => {\n                            if (\n                              e.type == RuntimeEventTypes.ActionExecutionArgs\n                            ) {\n                              await pushArgumentsChunk(e.args);\n                              argumentChunks.push(e.args);\n                            }\n                          },\n                          error: (err) => {\n                            logger.error(\n                              { err },\n                              \"Error in action execution argument stream\",\n                            );\n                            streamingArgumentsStatus.next(\n                              plainToInstance(FailedMessageStatus, {\n                                reason:\n                                  \"An unknown error has occurred in the action execution argument stream\",\n                              }),\n                            );\n                            stopStreamingArguments();\n                            actionExecutionArgumentSubscription?.unsubscribe();\n                          },\n                          complete: () => {\n                            logger.debug(\n                              \"Action execution argument stream completed\",\n                            );\n                            streamingArgumentsStatus.next(\n                              new SuccessMessageStatus(),\n                            );\n                            stopStreamingArguments();\n                            actionExecutionArgumentSubscription?.unsubscribe();\n\n                            outputMessages.push(\n                              plainToInstance(ActionExecutionMessage, {\n                                id: event.actionExecutionId,\n                                createdAt: new Date(),\n                                name: event.actionName,\n                                arguments: argumentChunks.join(\"\"),\n                              }),\n                            );\n                          },\n                        });\n                    },\n                  ),\n                });\n                break;\n              ////////////////////////////////\n              // ActionExecutionResult\n              ////////////////////////////////\n              case RuntimeEventTypes.ActionExecutionResult:\n                logger.debug(\n                  { result: event.result },\n                  \"Action execution result event received\",\n                );\n                pushMessage({\n                  id: \"result-\" + event.actionExecutionId,\n                  status: new SuccessMessageStatus(),\n                  createdAt: new Date(),\n                  actionExecutionId: event.actionExecutionId,\n                  actionName: event.actionName,\n                  result: event.result,\n                });\n\n                outputMessages.push(\n                  plainToInstance(ResultMessage, {\n                    id: \"result-\" + event.actionExecutionId,\n                    createdAt: new Date(),\n                    actionExecutionId: event.actionExecutionId,\n                    actionName: event.actionName,\n                    result: event.result,\n                  }),\n                );\n                break;\n              ////////////////////////////////\n              // AgentStateMessage\n              ////////////////////////////////\n              case RuntimeEventTypes.AgentStateMessage:\n                logger.debug({ event }, \"Agent message event received\");\n                pushMessage({\n                  id: randomId(),\n                  status: new SuccessMessageStatus(),\n                  threadId: event.threadId,\n                  agentName: event.agentName,\n                  nodeName: event.nodeName,\n                  runId: event.runId,\n                  active: event.active,\n                  state: event.state,\n                  running: event.running,\n                  role: MessageRole.assistant,\n                  createdAt: new Date(),\n                });\n                outputMessages.push(\n                  plainToInstance(AgentStateMessage, {\n                    id: randomId(),\n                    threadId: event.threadId,\n                    agentName: event.agentName,\n                    nodeName: event.nodeName,\n                    runId: event.runId,\n                    active: event.active,\n                    state: event.state,\n                    running: event.running,\n                    role: MessageRole.assistant,\n                    createdAt: new Date(),\n                  }),\n                );\n                break;\n            }\n          },\n          error: (err) => {\n            // For structured CopilotKit errors, set proper error response status\n            if (\n              err instanceof CopilotKitError ||\n              err instanceof CopilotKitLowLevelError ||\n              (err instanceof Error &&\n                err.name &&\n                err.name.includes(\"CopilotKit\")) ||\n              err?.extensions?.visibility\n            ) {\n              responseStatus$.next(\n                new UnknownErrorResponse({\n                  description: err.message || \"Agent error occurred\",\n                  // Include original error information for frontend to extract\n                  originalError: {\n                    code: err.code || err.extensions?.code,\n                    statusCode: err.statusCode || err.extensions?.statusCode,\n                    severity: err.severity || err.extensions?.severity,\n                    visibility: err.visibility || err.extensions?.visibility,\n                    originalErrorType:\n                      err.originalErrorType ||\n                      err.extensions?.originalErrorType,\n                    extensions: err.extensions,\n                  },\n                }),\n              );\n              eventStreamSubscription?.unsubscribe();\n              rejectOutputMessagesPromise(err);\n              stopStreamingMessages();\n              return;\n            }\n\n            responseStatus$.next(\n              new UnknownErrorResponse({\n                description: `An unknown error has occurred in the event stream`,\n              }),\n            );\n            eventStreamSubscription?.unsubscribe();\n            stopStreamingMessages();\n\n            rejectOutputMessagesPromise(err);\n          },\n          complete: async () => {\n            logger.debug(\"Event stream completed\");\n            if (data.cloud?.guardrails) {\n              logger.debug(\n                \"Guardrails is enabled, waiting for guardrails result\",\n              );\n              await firstValueFrom(guardrailsResult$);\n            }\n            responseStatus$.next(new SuccessResponseStatus());\n            eventStreamSubscription?.unsubscribe();\n            stopStreamingMessages();\n\n            resolveOutputMessagesPromise(outputMessages);\n          },\n        });\n      }),\n    };\n\n    return response;\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,mBAAmB,OAAO,EAC9B,SACA,0BACA,MACA,UACA,cAOI;AACJ,KACE,KAAK,SAAS,UACd,KAAK,SAAS,KAAK,SAAS,SAAS,GAAG,aAAa,SACnD,YAAY,MACd;EACA,MAAM,WAAW,KAAK,SACnB,QACE,MACC,EAAE,gBAAgB,WACjB,EAAE,YAAY,SAAS,YAAY,QAClC,EAAE,YAAY,SAAS,YAAY,WACxC,CACA,KAAK,OAAO;GACX,MAAM,EAAE,YAAa;GACrB,SAAS,EAAE,YAAY;GACxB,EAAE;EAEL,MAAM,cAAc,SAAS,SAAS,SAAS;EAC/C,MAAM,iBAAiB,SAAS,MAAM,GAAG,GAAG;EAE5C,MAAM,OAAO;GACX,OAAO,YAAY;GACnB,aAAa,KAAK,MAAM,WAAW,qBAAqB;GACxD,eAAe,KAAK,MAAM,WAAW,qBAAqB;GAC1D,UAAU;GACX;EAED,MAAM,mBAAmB,MAAM,MAAM,GAAG,QAAQ,uBAAuB;GACrE,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,iCAAiC;IAClC;GACD,MAAM,KAAK,UAAU,KAAK;GAC3B,CAAC;AAEF,MAAI,iBAAiB,GAEnB,UADqC,MAAM,iBAAiB,MAAM,CAC9C;MAEpB,SAAQ,MAAM,iBAAiB,MAAM,CAAC;;;AAMrC,4BAAM,gBAAgB;CAC3B,MACM,QAAQ;AACZ,SAAO;;CAGT,MACM,gBAAgB,AAAO,KAAqB;EAChD,IAAI,SAAS,IAAI,OAAO,M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