import {
  LangGraphEventTypes
} from "./chunk-TBBB7D7O.mjs";
import {
  __name
} from "./chunk-FHD4JECV.mjs";

// src/lib/runtime/langgraph/langgraph-agent.ts
import { EventType } from "@ag-ui/client";
import { map } from "rxjs";
import { LangGraphAgent as AGUILangGraphAgent, LangGraphHttpAgent } from "@ag-ui/langgraph";
var CustomEventNames;
(function(CustomEventNames2) {
  CustomEventNames2["CopilotKitManuallyEmitMessage"] = "copilotkit_manually_emit_message";
  CustomEventNames2["CopilotKitManuallyEmitToolCall"] = "copilotkit_manually_emit_tool_call";
  CustomEventNames2["CopilotKitManuallyEmitIntermediateState"] = "copilotkit_manually_emit_intermediate_state";
  CustomEventNames2["CopilotKitExit"] = "copilotkit_exit";
})(CustomEventNames || (CustomEventNames = {}));
var LangGraphAgent = class extends AGUILangGraphAgent {
  constructor(config) {
    super(config);
  }
  dispatchEvent(event) {
    if (event.type === EventType.CUSTOM) {
      const customEvent = event;
      if (customEvent.name === "copilotkit_manually_emit_message") {
        this.subscriber.next({
          type: EventType.TEXT_MESSAGE_START,
          role: "assistant",
          messageId: customEvent.value.message_id,
          rawEvent: event
        });
        this.subscriber.next({
          type: EventType.TEXT_MESSAGE_CONTENT,
          messageId: customEvent.value.message_id,
          delta: customEvent.value.message,
          rawEvent: event
        });
        this.subscriber.next({
          type: EventType.TEXT_MESSAGE_END,
          messageId: customEvent.value.message_id,
          rawEvent: event
        });
        return true;
      }
      if (customEvent.name === "copilotkit_manually_emit_tool_call") {
        this.subscriber.next({
          type: EventType.TOOL_CALL_START,
          toolCallId: customEvent.value.id,
          toolCallName: customEvent.value.name,
          parentMessageId: customEvent.value.id,
          rawEvent: event
        });
        this.subscriber.next({
          type: EventType.TOOL_CALL_ARGS,
          toolCallId: customEvent.value.id,
          delta: customEvent.value.args,
          rawEvent: event
        });
        this.subscriber.next({
          type: EventType.TOOL_CALL_END,
          toolCallId: customEvent.value.id,
          rawEvent: event
        });
        return true;
      }
      if (customEvent.name === "copilotkit_manually_emit_intermediate_state") {
        this.activeRun.manuallyEmittedState = customEvent.value;
        this.dispatchEvent({
          type: EventType.STATE_SNAPSHOT,
          snapshot: this.getStateSnapshot({
            values: this.activeRun.manuallyEmittedState
          }),
          rawEvent: event
        });
        return true;
      }
      if (customEvent.name === "copilotkit_exit") {
        this.subscriber.next({
          type: EventType.CUSTOM,
          name: "Exit",
          value: true
        });
        return true;
      }
    }
    const rawEvent = event.rawEvent;
    if (!rawEvent) {
      this.subscriber.next(event);
      return true;
    }
    const isMessageEvent = event.type === EventType.TEXT_MESSAGE_START || event.type === EventType.TEXT_MESSAGE_CONTENT || event.type === EventType.TEXT_MESSAGE_END;
    const isToolEvent = event.type === EventType.TOOL_CALL_START || event.type === EventType.TOOL_CALL_ARGS || event.type === EventType.TOOL_CALL_END;
    if ("copilotkit:emit-tool-calls" in (rawEvent.metadata || {})) {
      if (rawEvent.metadata["copilotkit:emit-tool-calls"] === false && isToolEvent) {
        return false;
      }
    }
    if ("copilotkit:emit-messages" in (rawEvent.metadata || {})) {
      if (rawEvent.metadata["copilotkit:emit-messages"] === false && isMessageEvent) {
        return false;
      }
    }
    this.subscriber.next(event);
    return true;
  }
  // @ts-ignore
  run(input) {
    return super.run(input).pipe(map((processedEvent) => {
      var _a, _b, _c, _d, _e;
      if (processedEvent.type === EventType.RAW) {
        const event = processedEvent.event ?? processedEvent.rawEvent;
        const eventType = event.event;
        const toolCallData = (_c = (_b = (_a = event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.tool_call_chunks) == null ? void 0 : _c[0];
        const toolCallUsedToPredictState = (_e = (_d = event.metadata) == null ? void 0 : _d["copilotkit:emit-intermediate-state"]) == null ? void 0 : _e.some((predictStateTool) => predictStateTool.tool === (toolCallData == null ? void 0 : toolCallData.name));
        if (eventType === LangGraphEventTypes.OnChatModelStream && toolCallUsedToPredictState) {
          return {
            type: EventType.CUSTOM,
            name: "PredictState",
            value: event.metadata["copilotkit:emit-intermediate-state"]
          };
        }
      }
      return processedEvent;
    }));
  }
  langGraphDefaultMergeState(state, messages, input) {
    const aguiMergedState = super.langGraphDefaultMergeState(state, messages, input);
    const { tools: returnedTools, "ag-ui": agui } = aguiMergedState;
    const rawCombinedTools = [
      ...returnedTools ?? [],
      ...(agui == null ? void 0 : agui.tools) ?? []
    ];
    const combinedTools = Array.from(new Map(rawCombinedTools.map((t) => [
      (t == null ? void 0 : t.id) ?? (t == null ? void 0 : t.name) ?? (t == null ? void 0 : t.key) ?? JSON.stringify(t),
      t
    ])).values());
    return {
      ...aguiMergedState,
      copilotkit: {
        actions: combinedTools,
        context: (agui == null ? void 0 : agui.context) ?? []
      }
    };
  }
  async getSchemaKeys() {
    const CONSTANT_KEYS = [
      "copilotkit"
    ];
    const schemaKeys = await super.getSchemaKeys();
    return {
      config: schemaKeys.config,
      input: schemaKeys.input ? [
        ...schemaKeys.input,
        ...CONSTANT_KEYS
      ] : null,
      output: schemaKeys.output ? [
        ...schemaKeys.output,
        ...CONSTANT_KEYS
      ] : null,
      context: schemaKeys.context ? [
        ...schemaKeys.context,
        ...CONSTANT_KEYS
      ] : null
    };
  }
};
__name(LangGraphAgent, "LangGraphAgent");

export {
  LangGraphHttpAgent,
  CustomEventNames,
  LangGraphAgent
};
//# sourceMappingURL=chunk-B2QVICDV.mjs.map