var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/graphql/message-conversion/index.ts
var message_conversion_exports = {};
__export(message_conversion_exports, {
  aguiMessageWithImageToGQLMessage: () => aguiMessageWithImageToGQLMessage,
  aguiMessageWithRenderToGQL: () => aguiMessageWithRenderToGQL,
  aguiTextMessageToGQLMessage: () => aguiTextMessageToGQLMessage,
  aguiToGQL: () => aguiToGQL,
  aguiToolCallToGQLActionExecution: () => aguiToolCallToGQLActionExecution,
  aguiToolMessageToGQLResultMessage: () => aguiToolMessageToGQLResultMessage,
  gqlActionExecutionMessageToAGUIMessage: () => gqlActionExecutionMessageToAGUIMessage,
  gqlImageMessageToAGUIMessage: () => gqlImageMessageToAGUIMessage,
  gqlResultMessageToAGUIMessage: () => gqlResultMessageToAGUIMessage,
  gqlTextMessageToAGUIMessage: () => gqlTextMessageToAGUIMessage,
  gqlToAGUI: () => gqlToAGUI
});
module.exports = __toCommonJS(message_conversion_exports);

// src/graphql/types/converted/index.ts
var import_shared = require("@copilotkit/shared");

// src/graphql/types/enums.ts
var import_type_graphql = require("type-graphql");
var MessageRole;
(function(MessageRole2) {
  MessageRole2["assistant"] = "assistant";
  MessageRole2["developer"] = "developer";
  MessageRole2["system"] = "system";
  MessageRole2["tool"] = "tool";
  MessageRole2["user"] = "user";
})(MessageRole || (MessageRole = {}));
var CopilotRequestType;
(function(CopilotRequestType2) {
  CopilotRequestType2["Chat"] = "Chat";
  CopilotRequestType2["Task"] = "Task";
  CopilotRequestType2["TextareaCompletion"] = "TextareaCompletion";
  CopilotRequestType2["TextareaPopover"] = "TextareaPopover";
  CopilotRequestType2["Suggestion"] = "Suggestion";
})(CopilotRequestType || (CopilotRequestType = {}));
var ActionInputAvailability;
(function(ActionInputAvailability2) {
  ActionInputAvailability2["disabled"] = "disabled";
  ActionInputAvailability2["enabled"] = "enabled";
  ActionInputAvailability2["remote"] = "remote";
})(ActionInputAvailability || (ActionInputAvailability = {}));
(0, import_type_graphql.registerEnumType)(MessageRole, {
  name: "MessageRole",
  description: "The role of the message"
});
(0, import_type_graphql.registerEnumType)(CopilotRequestType, {
  name: "CopilotRequestType",
  description: "The type of Copilot request"
});
(0, import_type_graphql.registerEnumType)(ActionInputAvailability, {
  name: "ActionInputAvailability",
  description: "The availability of the frontend action"
});

// src/graphql/types/message-status.type.ts
var import_type_graphql2 = require("type-graphql");
function _ts_decorate(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}
__name(_ts_decorate, "_ts_decorate");
function _ts_metadata(k, v) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(k, v);
}
__name(_ts_metadata, "_ts_metadata");
var MessageStatusCode;
(function(MessageStatusCode2) {
  MessageStatusCode2["Pending"] = "pending";
  MessageStatusCode2["Success"] = "success";
  MessageStatusCode2["Failed"] = "failed";
})(MessageStatusCode || (MessageStatusCode = {}));
(0, import_type_graphql2.registerEnumType)(MessageStatusCode, {
  name: "MessageStatusCode"
});
var BaseMessageStatus = class {
  code;
};
__name(BaseMessageStatus, "BaseMessageStatus");
_ts_decorate([
  (0, import_type_graphql2.Field)(() => MessageStatusCode),
  _ts_metadata("design:type", String)
], BaseMessageStatus.prototype, "code", void 0);
BaseMessageStatus = _ts_decorate([
  (0, import_type_graphql2.ObjectType)()
], BaseMessageStatus);
var PendingMessageStatus = class extends BaseMessageStatus {
  code = "pending";
};
__name(PendingMessageStatus, "PendingMessageStatus");
PendingMessageStatus = _ts_decorate([
  (0, import_type_graphql2.ObjectType)()
], PendingMessageStatus);
var SuccessMessageStatus = class extends BaseMessageStatus {
  code = "success";
};
__name(SuccessMessageStatus, "SuccessMessageStatus");
SuccessMessageStatus = _ts_decorate([
  (0, import_type_graphql2.ObjectType)()
], SuccessMessageStatus);
var FailedMessageStatus = class extends BaseMessageStatus {
  code = "failed";
  reason;
};
__name(FailedMessageStatus, "FailedMessageStatus");
_ts_decorate([
  (0, import_type_graphql2.Field)(() => String),
  _ts_metadata("design:type", String)
], FailedMessageStatus.prototype, "reason", void 0);
FailedMessageStatus = _ts_decorate([
  (0, import_type_graphql2.ObjectType)()
], FailedMessageStatus);
var MessageStatusUnion = (0, import_type_graphql2.createUnionType)({
  name: "MessageStatus",
  types: () => [
    PendingMessageStatus,
    SuccessMessageStatus,
    FailedMessageStatus
  ]
});

// src/graphql/types/converted/index.ts
var Message = class {
  type;
  id;
  createdAt;
  status;
  constructor(props) {
    props.id ?? (props.id = (0, import_shared.randomId)());
    props.status ?? (props.status = {
      code: MessageStatusCode.Success
    });
    props.createdAt ?? (props.createdAt = /* @__PURE__ */ new Date());
    Object.assign(this, props);
  }
  isTextMessage() {
    return this.type === "TextMessage";
  }
  isActionExecutionMessage() {
    return this.type === "ActionExecutionMessage";
  }
  isResultMessage() {
    return this.type === "ResultMessage";
  }
  isAgentStateMessage() {
    return this.type === "AgentStateMessage";
  }
  isImageMessage() {
    return this.type === "ImageMessage";
  }
};
__name(Message, "Message");
var Role = MessageRole;
var TextMessage = class extends Message {
  content;
  parentMessageId;
  role;
  type = "TextMessage";
  constructor(props) {
    super(props);
    this.type = "TextMessage";
  }
};
__name(TextMessage, "TextMessage");
var ActionExecutionMessage = class extends Message {
  type = "ActionExecutionMessage";
  name;
  arguments;
  parentMessageId;
};
__name(ActionExecutionMessage, "ActionExecutionMessage");
var ResultMessage = class extends Message {
  type = "ResultMessage";
  actionExecutionId;
  actionName;
  result;
  static encodeResult(result, error) {
    const errorObj = error ? typeof error === "string" ? {
      code: "ERROR",
      message: error
    } : error instanceof Error ? {
      code: "ERROR",
      message: error.message
    } : error : void 0;
    if (errorObj) {
      return JSON.stringify({
        error: errorObj,
        result: result || ""
      });
    }
    if (result === void 0) {
      return "";
    }
    return typeof result === "string" ? result : JSON.stringify(result);
  }
  static decodeResult(result) {
    if (!result) {
      return {
        result: ""
      };
    }
    try {
      const parsed = JSON.parse(result);
      if (parsed && typeof parsed === "object") {
        if ("error" in parsed) {
          return {
            error: parsed.error,
            result: parsed.result || ""
          };
        }
        return {
          result: JSON.stringify(parsed)
        };
      }
      return {
        result
      };
    } catch (e) {
      return {
        result
      };
    }
  }
  hasError() {
    try {
      const { error } = ResultMessage.decodeResult(this.result);
      return !!error;
    } catch {
      return false;
    }
  }
  getError() {
    try {
      const { error } = ResultMessage.decodeResult(this.result);
      return error;
    } catch {
      return void 0;
    }
  }
};
__name(ResultMessage, "ResultMessage");
var AgentStateMessage = class extends Message {
  type = "AgentStateMessage";
  threadId;
  agentName;
  nodeName;
  runId;
  active;
  role;
  state;
  running;
};
__name(AgentStateMessage, "AgentStateMessage");
var ImageMessage = class extends Message {
  type = "ImageMessage";
  format;
  bytes;
  role;
  parentMessageId;
};
__name(ImageMessage, "ImageMessage");

// src/graphql/message-conversion/agui-to-gql.ts
function extractAgentName(message) {
  if (message.role !== "assistant") {
    throw new Error(`Cannot extract agent name from message with role ${message.role}`);
  }
  return message.agentName || "unknown";
}
__name(extractAgentName, "extractAgentName");
function isAgentStateMessage(message) {
  return message.role === "assistant" && "agentName" in message && "state" in message;
}
__name(isAgentStateMessage, "isAgentStateMessage");
function hasImageProperty(message) {
  const canContainImage = message.role === "assistant" || message.role === "user";
  if (!canContainImage || message.image === void 0) {
    return false;
  }
  const isMalformed = message.image.format === void 0 || message.image.bytes === void 0;
  if (isMalformed) {
    return false;
  }
  return true;
}
__name(hasImageProperty, "hasImageProperty");
function aguiToGQL(messages, actions, coAgentStateRenders) {
  const gqlMessages = [];
  messages = Array.isArray(messages) ? messages : [
    messages
  ];
  const toolCallNames = {};
  for (const message of messages) {
    if (isAgentStateMessage(message)) {
      const agentName = extractAgentName(message);
      const state = "state" in message && message.state ? message.state : {};
      gqlMessages.push(new AgentStateMessage({
        id: message.id,
        agentName,
        state,
        role: Role.assistant
      }));
      if ("generativeUI" in message && message.generativeUI && coAgentStateRenders) {
        coAgentStateRenders[agentName] = {
          name: agentName,
          render: message.generativeUI
        };
      }
      continue;
    }
    if (hasImageProperty(message)) {
      gqlMessages.push(aguiMessageWithImageToGQLMessage(message));
      continue;
    }
    if (message.role === "assistant" && message.toolCalls) {
      gqlMessages.push(aguiTextMessageToGQLMessage(message));
      for (const toolCall of message.toolCalls) {
        toolCallNames[toolCall.id] = toolCall.function.name;
        const actionExecMsg = aguiToolCallToGQLActionExecution(toolCall, message.id);
        if ("generativeUI" in message && message.generativeUI && actions) {
          const actionName = toolCall.function.name;
          const specificAction = Object.values(actions).find((action) => action.name === actionName);
          const wildcardAction = Object.values(actions).find((action) => action.name === "*");
          if (specificAction) {
            specificAction.render = message.generativeUI;
          } else if (wildcardAction) {
            wildcardAction.render = message.generativeUI;
          }
        }
        gqlMessages.push(actionExecMsg);
      }
      continue;
    }
    if (message.role === "developer" || message.role === "system" || message.role === "assistant" || message.role === "user") {
      gqlMessages.push(aguiTextMessageToGQLMessage(message));
      continue;
    }
    if (message.role === "tool") {
      gqlMessages.push(aguiToolMessageToGQLResultMessage(message, toolCallNames));
      continue;
    }
    throw new Error(`Unknown message role: "${message.role}" in message with id: ${message.id}`);
  }
  return gqlMessages;
}
__name(aguiToGQL, "aguiToGQL");
function aguiTextMessageToGQLMessage(message) {
  if (message.role !== "developer" && message.role !== "system" && message.role !== "assistant" && message.role !== "user") {
    throw new Error(`Cannot convert message with role ${message.role} to TextMessage`);
  }
  let roleValue;
  if (message.role === "developer") {
    roleValue = Role.developer;
  } else if (message.role === "system") {
    roleValue = Role.system;
  } else if (message.role === "assistant") {
    roleValue = Role.assistant;
  } else {
    roleValue = Role.user;
  }
  return new TextMessage({
    id: message.id,
    content: message.content || "",
    role: roleValue
  });
}
__name(aguiTextMessageToGQLMessage, "aguiTextMessageToGQLMessage");
function aguiToolCallToGQLActionExecution(toolCall, parentMessageId) {
  if (toolCall.type !== "function") {
    throw new Error(`Unsupported tool call type: ${toolCall.type}`);
  }
  let argumentsObj;
  if (typeof toolCall.function.arguments === "string") {
    try {
      argumentsObj = JSON.parse(toolCall.function.arguments);
    } catch (error) {
      console.warn(`Failed to parse tool call arguments for ${toolCall.function.name}:`, error);
      argumentsObj = {};
    }
  } else if (typeof toolCall.function.arguments === "object" && toolCall.function.arguments !== null) {
    argumentsObj = toolCall.function.arguments;
  } else {
    console.warn(`Invalid tool call arguments type for ${toolCall.function.name}:`, typeof toolCall.function.arguments);
    argumentsObj = {};
  }
  return new ActionExecutionMessage({
    id: toolCall.id,
    name: toolCall.function.name,
    arguments: argumentsObj,
    parentMessageId
  });
}
__name(aguiToolCallToGQLActionExecution, "aguiToolCallToGQLActionExecution");
function aguiToolMessageToGQLResultMessage(message, toolCallNames) {
  if (message.role !== "tool") {
    throw new Error(`Cannot convert message with role ${message.role} to ResultMessage`);
  }
  if (!message.toolCallId) {
    throw new Error("Tool message must have a toolCallId");
  }
  const actionName = toolCallNames[message.toolCallId] || "unknown";
  let resultContent;
  const messageContent = message.content || "";
  if (typeof messageContent === "string") {
    resultContent = messageContent;
  } else if (typeof messageContent === "object" && messageContent !== null) {
    try {
      resultContent = JSON.stringify(messageContent);
    } catch (error) {
      console.warn(`Failed to stringify tool result for ${actionName}:`, error);
      resultContent = String(messageContent);
    }
  } else {
    resultContent = String(messageContent);
  }
  return new ResultMessage({
    id: message.id,
    result: resultContent,
    actionExecutionId: message.toolCallId,
    actionName: message.toolName || actionName
  });
}
__name(aguiToolMessageToGQLResultMessage, "aguiToolMessageToGQLResultMessage");
function aguiMessageWithRenderToGQL(message, actions, coAgentStateRenders) {
  if (message.role === "assistant" && "generativeUI" in message && message.generativeUI && !message.toolCalls) {
    const gqlMessages = [];
    gqlMessages.push(new AgentStateMessage({
      id: message.id,
      agentName: "unknown",
      state: {},
      role: Role.assistant
    }));
    if (coAgentStateRenders) {
      coAgentStateRenders.unknown = {
        name: "unknown",
        render: message.generativeUI
      };
    }
    return gqlMessages;
  }
  return aguiToGQL([
    message
  ], actions, coAgentStateRenders);
}
__name(aguiMessageWithRenderToGQL, "aguiMessageWithRenderToGQL");
function aguiMessageWithImageToGQLMessage(message) {
  if (!hasImageProperty(message)) {
    throw new Error(`Cannot convert message to ImageMessage: missing format or bytes`);
  }
  let roleValue;
  if (message.role === "assistant") {
    roleValue = Role.assistant;
  } else {
    roleValue = Role.user;
  }
  if (message.role !== "assistant" && message.role !== "user") {
    throw new Error(`Cannot convert message with role ${message.role} to ImageMessage`);
  }
  return new ImageMessage({
    id: message.id,
    format: message.image.format,
    bytes: message.image.bytes,
    role: roleValue
  });
}
__name(aguiMessageWithImageToGQLMessage, "aguiMessageWithImageToGQLMessage");

// src/graphql/message-conversion/gql-to-agui.ts
var VALID_IMAGE_FORMATS = [
  "jpeg",
  "png",
  "webp",
  "gif"
];
function validateImageFormat(format) {
  return VALID_IMAGE_FORMATS.includes(format);
}
__name(validateImageFormat, "validateImageFormat");
function gqlToAGUI(messages, actions, coAgentStateRenders) {
  let aguiMessages = [];
  messages = Array.isArray(messages) ? messages : [
    messages
  ];
  const actionResults = /* @__PURE__ */ new Map();
  for (const message of messages) {
    if (message.isResultMessage()) {
      actionResults.set(message.actionExecutionId, message.result);
    }
  }
  for (const message of messages) {
    if (message.isTextMessage()) {
      aguiMessages.push(gqlTextMessageToAGUIMessage(message));
    } else if (message.isResultMessage()) {
      aguiMessages.push(gqlResultMessageToAGUIMessage(message));
    } else if (message.isActionExecutionMessage()) {
      aguiMessages.push(gqlActionExecutionMessageToAGUIMessage(message, actions, actionResults));
    } else if (message.isAgentStateMessage()) {
      aguiMessages.push(gqlAgentStateMessageToAGUIMessage(message, coAgentStateRenders));
    } else if (message.isImageMessage()) {
      aguiMessages.push(gqlImageMessageToAGUIMessage(message));
    } else {
      throw new Error("Unknown message type");
    }
  }
  return aguiMessages;
}
__name(gqlToAGUI, "gqlToAGUI");
function gqlActionExecutionMessageToAGUIMessage(message, actions, actionResults) {
  const hasSpecificAction = actions && Object.values(actions).some((action2) => action2.name === message.name);
  const hasWildcardAction = actions && Object.values(actions).some((action2) => action2.name === "*");
  if (!actions || !hasSpecificAction && !hasWildcardAction) {
    return {
      id: message.id,
      role: "assistant",
      toolCalls: [
        actionExecutionMessageToAGUIMessage(message)
      ],
      name: message.name
    };
  }
  const action = Object.values(actions).find((action2) => action2.name === message.name) || Object.values(actions).find((action2) => action2.name === "*");
  const createRenderWrapper = /* @__PURE__ */ __name((originalRender) => {
    if (!originalRender)
      return void 0;
    return (props) => {
      var _a;
      let actionResult = actionResults == null ? void 0 : actionResults.get(message.id);
      let status = "inProgress";
      if (actionResult !== void 0) {
        status = "complete";
      } else if (((_a = message.status) == null ? void 0 : _a.code) !== MessageStatusCode.Pending) {
        status = "executing";
      }
      if (typeof (props == null ? void 0 : props.result) === "string") {
        try {
          props.result = JSON.parse(props.result);
        } catch (e) {
        }
      }
      if (typeof actionResult === "string") {
        try {
          actionResult = JSON.parse(actionResult);
        } catch (e) {
        }
      }
      const baseProps = {
        status: (props == null ? void 0 : props.status) || status,
        args: message.arguments || {},
        result: (props == null ? void 0 : props.result) || actionResult || void 0,
        messageId: message.id
      };
      if (action.name === "*") {
        return originalRender({
          ...baseProps,
          ...props,
          name: message.name
        });
      } else {
        const respond = (props == null ? void 0 : props.respond) ?? (() => {
        });
        return originalRender({
          ...baseProps,
          ...props,
          respond
        });
      }
    };
  }, "createRenderWrapper");
  return {
    id: message.id,
    role: "assistant",
    content: "",
    toolCalls: [
      actionExecutionMessageToAGUIMessage(message)
    ],
    generativeUI: createRenderWrapper(action.render),
    name: message.name
  };
}
__name(gqlActionExecutionMessageToAGUIMessage, "gqlActionExecutionMessageToAGUIMessage");
function gqlAgentStateMessageToAGUIMessage(message, coAgentStateRenders) {
  if (coAgentStateRenders && Object.values(coAgentStateRenders).some((render) => render.name === message.agentName)) {
    const render = Object.values(coAgentStateRenders).find((render2) => render2.name === message.agentName);
    const createRenderWrapper = /* @__PURE__ */ __name((originalRender) => {
      if (!originalRender)
        return void 0;
      return (props) => {
        const state = message.state;
        const renderProps = {
          state
        };
        return originalRender(renderProps);
      };
    }, "createRenderWrapper");
    return {
      id: message.id,
      role: "assistant",
      generativeUI: createRenderWrapper(render.render),
      agentName: message.agentName,
      state: message.state
    };
  }
  return {
    id: message.id,
    role: "assistant",
    agentName: message.agentName,
    state: message.state
  };
}
__name(gqlAgentStateMessageToAGUIMessage, "gqlAgentStateMessageToAGUIMessage");
function actionExecutionMessageToAGUIMessage(actionExecutionMessage) {
  return {
    id: actionExecutionMessage.id,
    function: {
      name: actionExecutionMessage.name,
      arguments: JSON.stringify(actionExecutionMessage.arguments)
    },
    type: "function"
  };
}
__name(actionExecutionMessageToAGUIMessage, "actionExecutionMessageToAGUIMessage");
function gqlTextMessageToAGUIMessage(message) {
  switch (message.role) {
    case Role.developer:
      return {
        id: message.id,
        role: "developer",
        content: message.content
      };
    case Role.system:
      return {
        id: message.id,
        role: "system",
        content: message.content
      };
    case Role.assistant:
      return {
        id: message.id,
        role: "assistant",
        content: message.content
      };
    case Role.user:
      return {
        id: message.id,
        role: "user",
        content: message.content
      };
    default:
      throw new Error("Unknown message role");
  }
}
__name(gqlTextMessageToAGUIMessage, "gqlTextMessageToAGUIMessage");
function gqlResultMessageToAGUIMessage(message) {
  return {
    id: message.id,
    role: "tool",
    content: message.result,
    toolCallId: message.actionExecutionId,
    toolName: message.actionName
  };
}
__name(gqlResultMessageToAGUIMessage, "gqlResultMessageToAGUIMessage");
function gqlImageMessageToAGUIMessage(message) {
  if (!validateImageFormat(message.format)) {
    throw new Error(`Invalid image format: ${message.format}. Supported formats are: ${VALID_IMAGE_FORMATS.join(", ")}`);
  }
  if (!message.bytes || typeof message.bytes !== "string" || message.bytes.trim() === "") {
    throw new Error("Image bytes must be a non-empty string");
  }
  const role = message.role === Role.assistant ? "assistant" : "user";
  const imageMessage = {
    id: message.id,
    role,
    content: "",
    image: {
      format: message.format,
      bytes: message.bytes
    }
  };
  return imageMessage;
}
__name(gqlImageMessageToAGUIMessage, "gqlImageMessageToAGUIMessage");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  aguiMessageWithImageToGQLMessage,
  aguiMessageWithRenderToGQL,
  aguiTextMessageToGQLMessage,
  aguiToGQL,
  aguiToolCallToGQLActionExecution,
  aguiToolMessageToGQLResultMessage,
  gqlActionExecutionMessageToAGUIMessage,
  gqlImageMessageToAGUIMessage,
  gqlResultMessageToAGUIMessage,
  gqlTextMessageToAGUIMessage,
  gqlToAGUI
});
//# sourceMappingURL=index.js.map