import {
  createServerMessage,
  isClientMessage
} from "./chunk-FQLK5GL5.js";

// src/server/ws/protocol.ts
function enrichMessagesWithToolResults(messages) {
  const resultMap = /* @__PURE__ */ new Map();
  for (const msg of messages) {
    if (msg.role === "tool" && msg.toolCallId && msg.toolResult) {
      resultMap.set(msg.toolCallId, msg.toolResult);
    }
  }
  if (resultMap.size === 0) return messages;
  return messages.map((msg) => {
    if (msg.role !== "assistant" || !msg.toolCalls?.length) return msg;
    const needsEnrichment = msg.toolCalls.some((tc) => !tc.result && resultMap.has(tc.id));
    if (!needsEnrichment) return msg;
    return {
      ...msg,
      toolCalls: msg.toolCalls.map((tc) => {
        if (tc.result) return tc;
        const result = resultMap.get(tc.id);
        return result ? { ...tc, result } : tc;
      })
    };
  });
}
function parseClientMessage(data) {
  try {
    const parsed = JSON.parse(data);
    if (isClientMessage(parsed)) {
      return parsed;
    }
    return null;
  } catch {
    return null;
  }
}
function serializeServerMessage(message) {
  return JSON.stringify(message);
}
function createErrorMessage(code, message, correlationId) {
  return createServerMessage("error", { code, message }, correlationId);
}
function createSessionStateMessage(session, messages, pendingConfirmations = [], gitStatus, correlationId) {
  const enrichedMessages = enrichMessagesWithToolResults(messages);
  return createServerMessage(
    "session.state",
    { session, messages: enrichedMessages, pendingConfirmations, ...gitStatus ? { gitStatus } : {} },
    correlationId
  );
}
function createSessionListMessage(sessions, correlationId) {
  return createServerMessage("session.list", { sessions }, correlationId);
}
function createSessionRunningMessage(isRunning, sessionId) {
  return createServerMessage("session.running", { isRunning }, sessionId);
}
function createProjectStateMessage(project, correlationId) {
  return createServerMessage("project.state", { project }, correlationId);
}
function createProjectListMessage(projects, correlationId) {
  return createServerMessage("project.list", { projects }, correlationId);
}
function createGitStatusMessage(branch, diffFiles, correlationId) {
  return createServerMessage("git.status", { branch, diff: { files: diffFiles } }, correlationId);
}
function createChatDeltaMessage(messageId, content, subAgentType) {
  return createServerMessage("chat.delta", {
    messageId,
    content,
    ...subAgentType ? { subAgentType } : {}
  });
}
function createChatThinkingMessage(messageId, content) {
  return createServerMessage("chat.thinking", { messageId, content });
}
function createChatToolPreparingMessage(messageId, index, name, args) {
  return createServerMessage("chat.tool_preparing", { messageId, index, name, ...args ? { arguments: args } : {} });
}
function createChatToolCallMessage(messageId, callId, tool, args) {
  return createServerMessage("chat.tool_call", { messageId, callId, tool, args });
}
function createChatToolResultMessage(messageId, callId, tool, result) {
  return createServerMessage("chat.tool_result", { messageId, callId, tool, result });
}
function createChatToolOutputMessage(messageId, callId, output, stream) {
  return createServerMessage("chat.tool_output", { messageId, callId, output, stream });
}
function createChatTodoMessage(todos) {
  return createServerMessage("chat.todo", { todos });
}
function createChatProgressMessage(message, phase) {
  return createServerMessage("chat.progress", { message, ...phase ? { phase } : {} });
}
function createChatFormatRetryMessage(attempt, maxAttempts) {
  return createServerMessage("chat.format_retry", { attempt, maxAttempts });
}
function createChatMessageMessage(message) {
  return createServerMessage("chat.message", { message });
}
function createChatMessageUpdatedMessage(messageId, updates) {
  return createServerMessage("chat.message_updated", { messageId, updates });
}
function createChatDoneMessage(messageId, reason, stats, agentType) {
  return createServerMessage("chat.done", {
    messageId,
    reason,
    ...stats ? { stats } : {},
    ...agentType ? { agentType } : {}
  });
}
function createChatErrorMessage(error, recoverable) {
  return createServerMessage("chat.error", { error, recoverable });
}
function createChatPathConfirmationMessage(callId, tool, paths, workdir, reason) {
  return createServerMessage("chat.path_confirmation", { callId, tool, paths, workdir, reason });
}
function createChatAskUserMessage(callId, question) {
  return createServerMessage("chat.ask_user", { callId, question });
}
function createChatVisionFallbackMessage(payload) {
  return createServerMessage("chat.vision_fallback", payload);
}
function createModeChangedMessage(mode, auto, reason) {
  return createServerMessage("mode.changed", { mode, auto, ...reason ? { reason } : {} });
}
function createPhaseChangedMessage(phase) {
  return createServerMessage("phase.changed", { phase });
}
function createCriteriaUpdatedMessage(criteria, changedId) {
  return createServerMessage("criteria.updated", { criteria, ...changedId ? { changedId } : {} });
}
function createMetadataUpdatedMessage(key, entries) {
  return createServerMessage("metadata.updated", { key, entries });
}
function createContextStateMessage(context, subAgentId) {
  return createServerMessage("context.state", { context, ...subAgentId && { subAgentId } });
}
function createSessionNameGeneratedMessage(name, sessionId) {
  const msg = {
    type: "session.name_generated",
    payload: { name }
  };
  if (sessionId) {
    msg.sessionId = sessionId;
  }
  return msg;
}
function isSessionLoadPayload(payload) {
  return typeof payload === "object" && payload !== null && "sessionId" in payload;
}
function isPathConfirmPayload(payload) {
  return typeof payload === "object" && payload !== null && "callId" in payload && "approved" in payload;
}
function isAskAnswerPayload(payload) {
  return typeof payload === "object" && payload !== null && "callId" in payload && "answer" in payload;
}
function isUIFeedbackPayload(payload) {
  if (typeof payload !== "object" || payload === null) return false;
  const obj = payload;
  return "sessionId" in payload && typeof obj.sessionId === "string" && "element" in payload && "annotation" in payload && typeof obj.annotation === "string" && "pageUrl" in payload && typeof obj.pageUrl === "string";
}
function createQueueStateMessage(messages) {
  return createServerMessage("queue.state", { messages });
}
function storedEventToServerMessage(event) {
  switch (event.type) {
    case "message.start": {
      const data = event.data;
      const isUserOrSystem = data.role === "user" || data.role === "system";
      const { messageId, ...rest } = data;
      const message = {
        ...rest,
        id: messageId,
        content: data.content ?? "",
        timestamp: new Date(event.timestamp).toISOString(),
        tokenCount: data.tokenCount ?? 0,
        isStreaming: !isUserOrSystem
      };
      return createChatMessageMessage(message);
    }
    case "message.delta": {
      const data = event.data;
      return createChatDeltaMessage(data.messageId, data.content, data.subAgentType);
    }
    case "message.thinking": {
      const data = event.data;
      return createChatThinkingMessage(data.messageId, data.content);
    }
    case "message.done": {
      const data = event.data;
      const updates = { isStreaming: false };
      if (data.partial) {
        updates.partial = true;
      }
      if (data.stats) {
        updates.stats = data.stats;
      }
      if (data.promptContext) {
        updates.promptContext = data.promptContext;
      }
      return createChatMessageUpdatedMessage(data.messageId, updates);
    }
    case "tool.preparing": {
      const data = event.data;
      return createChatToolPreparingMessage(data.messageId, data.index, data.name, data.arguments);
    }
    case "tool.call": {
      const data = event.data;
      return createChatToolCallMessage(data.messageId, data.toolCall.id, data.toolCall.name, data.toolCall.arguments);
    }
    case "tool.output": {
      const data = event.data;
      return createChatToolOutputMessage(data.messageId, data.toolCallId, data.content, data.stream);
    }
    case "tool.result": {
      const data = event.data;
      return createChatToolResultMessage(
        data.messageId,
        data.toolCallId,
        "",
        // Tool name not available in event, but not used by frontend for matching
        data.result
      );
    }
    case "phase.changed": {
      const data = event.data;
      return createPhaseChangedMessage(data.phase);
    }
    case "task.completed": {
      const data = event.data;
      return createServerMessage("task.completed", data);
    }
    case "session.initialized": {
      return null;
    }
    case "mode.changed": {
      const data = event.data;
      return createModeChangedMessage(data.mode, data.auto, data.reason);
    }
    case "running.changed": {
      const data = event.data;
      return createSessionRunningMessage(data.isRunning);
    }
    case "criteria.set": {
      const data = event.data;
      return createCriteriaUpdatedMessage(data.criteria);
    }
    case "metadata.set": {
      const data = event.data;
      return createMetadataUpdatedMessage(data.key, data.entries);
    }
    case "criterion.updated": {
      return null;
    }
    case "context.state": {
      const data = event.data;
      return createContextStateMessage(data);
    }
    case "session.name_generated": {
      const data = event.data;
      return {
        type: "session.name_generated",
        payload: { name: data.name },
        sessionId: event.sessionId
      };
    }
    case "todo.updated": {
      const data = event.data;
      return createChatTodoMessage(data.todos);
    }
    case "chat.done": {
      const data = event.data;
      return createChatDoneMessage(data.messageId, data.reason, data.stats, data.agentType);
    }
    case "chat.error": {
      const data = event.data;
      return createChatErrorMessage(data.error, data.recoverable);
    }
    case "chat.ask_user": {
      const data = event.data;
      return createChatAskUserMessage(data.callId, data.question);
    }
    case "format.retry": {
      const data = event.data;
      return createChatFormatRetryMessage(data.attempt, data.maxAttempts);
    }
    case "turn.snapshot":
    case "context.compacted":
      return null;
    default:
      return null;
  }
}

export {
  parseClientMessage,
  serializeServerMessage,
  createErrorMessage,
  createSessionStateMessage,
  createSessionListMessage,
  createSessionRunningMessage,
  createProjectStateMessage,
  createProjectListMessage,
  createGitStatusMessage,
  createChatDeltaMessage,
  createChatThinkingMessage,
  createChatToolPreparingMessage,
  createChatToolCallMessage,
  createChatToolResultMessage,
  createChatToolOutputMessage,
  createChatTodoMessage,
  createChatProgressMessage,
  createChatFormatRetryMessage,
  createChatMessageMessage,
  createChatMessageUpdatedMessage,
  createChatDoneMessage,
  createChatErrorMessage,
  createChatPathConfirmationMessage,
  createChatAskUserMessage,
  createChatVisionFallbackMessage,
  createModeChangedMessage,
  createPhaseChangedMessage,
  createCriteriaUpdatedMessage,
  createMetadataUpdatedMessage,
  createContextStateMessage,
  createSessionNameGeneratedMessage,
  isSessionLoadPayload,
  isPathConfirmPayload,
  isAskAnswerPayload,
  isUIFeedbackPayload,
  createQueueStateMessage,
  storedEventToServerMessage
};
//# sourceMappingURL=chunk-CEZNMLOO.js.map