// src/server/events/apply-events.ts
function markComplete(msg, reason) {
  msg.isComplete = true;
  msg.completeReason = reason;
}
function extractMessageOptionalFields(data) {
  return {
    ...data.tokenCount !== void 0 && { tokenCount: data.tokenCount },
    ...data.contextWindowId !== void 0 && { contextWindowId: data.contextWindowId },
    ...data.subAgentId !== void 0 && { subAgentId: data.subAgentId },
    ...data.subAgentType !== void 0 && { subAgentType: data.subAgentType },
    ...data.isSystemGenerated !== void 0 && { isSystemGenerated: data.isSystemGenerated },
    ...data.messageKind !== void 0 && { messageKind: data.messageKind },
    ...data.isCompactionSummary !== void 0 && { isCompactionSummary: data.isCompactionSummary },
    ...data.attachments !== void 0 && { attachments: data.attachments },
    ...data.metadata !== void 0 && { metadata: data.metadata }
  };
}
function attachToolCallToMessage(msg, toolCall) {
  const existing = msg.toolCalls ?? [];
  const newTc = { ...toolCall };
  msg.toolCalls = [...existing, newTc];
}
function attachToolResultToMessage(msg, toolCallId, result) {
  if (msg.toolCalls) {
    const toolCall = msg.toolCalls.find((tc) => tc.id === toolCallId);
    if (toolCall) {
      toolCall.result = result;
    }
  }
}
function updateMessageDelta(msg, content) {
  msg.content += content;
}
function updateMessageThinking(msg, content) {
  msg.thinkingContent = (msg.thinkingContent ?? "") + content;
}
function updateMessageDone(msg, data) {
  msg.isStreaming = false;
  if (data.stats) msg.stats = data.stats;
  if (data.segments) msg.segments = data.segments;
  if (data.partial) msg.partial = true;
  if (data.promptContext) msg.promptContext = data.promptContext;
  if (data.tokenCount !== void 0) msg.tokenCount = data.tokenCount;
  if ("preparingToolCalls" in msg) {
    msg.preparingToolCalls = [];
  }
}
function applyEvents(initialMessages, events, options) {
  const messages = new Map(initialMessages.map((message) => [message.id, deepCloneMessage(message)]));
  for (const event of events) {
    switch (event.type) {
      case "message.start": {
        const data = event.data;
        const isUserOrSystem = data.role === "user" || data.role === "system";
        const timestamp = options.timestampAsNumber ? typeof event.timestamp === "number" ? event.timestamp : Date.now() : new Date(event.timestamp).toISOString();
        messages.set(data.messageId, {
          id: data.messageId,
          role: data.role,
          content: data.content ?? "",
          timestamp,
          isStreaming: !isUserOrSystem,
          tokenCount: data.tokenCount ?? 0,
          ...extractMessageOptionalFields(data)
        });
        break;
      }
      case "message.delta": {
        const data = event.data;
        const msg = messages.get(data.messageId);
        if (msg) updateMessageDelta(msg, data.content);
        break;
      }
      case "message.thinking": {
        const data = event.data;
        const msg = messages.get(data.messageId);
        if (msg) updateMessageThinking(msg, data.content);
        break;
      }
      case "message.done": {
        const data = event.data;
        const msg = messages.get(data.messageId);
        if (msg) updateMessageDone(msg, data);
        break;
      }
      case "tool.call": {
        const data = event.data;
        const msg = messages.get(data.messageId);
        if (msg) {
          attachToolCallToMessage(msg, data.toolCall);
          removeFromPreparing(msg, data.toolCall.id);
        }
        break;
      }
      case "tool.result": {
        const data = event.data;
        const msg = messages.get(data.messageId);
        if (msg) {
          attachToolResultToMessage(msg, data.toolCallId, data.result);
          removeFromPreparing(msg, data.toolCallId);
        }
        break;
      }
      case "tool.preparing": {
        const data = event.data;
        const msg = messages.get(data.messageId);
        if (msg) {
          const preparing = msg.preparingToolCalls ?? [];
          const existingIndex = preparing.findIndex((p) => p.index === data.index);
          const entry = {
            index: data.index,
            name: data.name,
            ...data.arguments ? { arguments: data.arguments } : {}
          };
          if (existingIndex >= 0) {
            preparing[existingIndex] = entry;
          } else {
            preparing.push(entry);
          }
          ;
          msg.preparingToolCalls = preparing;
        }
        break;
      }
      case "tool.output": {
        const data = event.data;
        const msg = findMessageWithToolCall(messages, data.toolCallId);
        if (msg) {
          const tc = msg.toolCalls?.find((tc2) => tc2.id === data.toolCallId);
          if (tc) {
            const output = tc.streamingOutput ?? [];
            output.push({ stream: data.stream, content: data.content, timestamp: event.timestamp });
            tc.streamingOutput = output;
          }
        }
        break;
      }
      case "format.retry": {
        const data = event.data;
        for (const msg of messages.values()) {
          const retries = msg.formatRetries ?? [];
          retries.push({ attempt: data.attempt, maxAttempts: data.maxAttempts, timestamp: event.timestamp });
          msg.formatRetries = retries;
        }
        break;
      }
      case "chat.done": {
        const data = event.data;
        const msg = messages.get(data.messageId);
        if (msg) {
          markComplete(msg, data.reason);
        }
        break;
      }
      case "chat.error": {
        for (const msg of messages.values()) {
          if (msg.role === "assistant" && !("isComplete" in msg)) {
            markComplete(msg, "error");
          }
        }
        break;
      }
      case "session.initialized":
      case "turn.snapshot":
      case "phase.changed":
      case "mode.changed":
      case "running.changed":
      case "criteria.set":
      case "criterion.updated":
      case "context.state":
      case "context.compacted":
      case "file.read":
      case "todo.updated":
        break;
    }
  }
  return Array.from(messages.values());
}
function removeFromPreparing(msg, _toolCallId) {
  if ("preparingToolCalls" in msg && Array.isArray(msg.preparingToolCalls)) {
    ;
    msg.preparingToolCalls = [];
  }
}
function findMessageWithToolCall(messages, toolCallId) {
  for (const msg of messages.values()) {
    if ("toolCalls" in msg && Array.isArray(msg.toolCalls)) {
      if (msg.toolCalls.some((tc) => tc.id === toolCallId)) {
        return msg;
      }
    }
  }
  return void 0;
}
function deepCloneMessage(msg) {
  const cloned = { ...msg };
  const obj = cloned;
  if (obj["toolCalls"]) {
    obj["toolCalls"] = obj["toolCalls"].map((tc) => ({
      ...tc,
      ...tc.result ? { result: { ...tc.result } } : {}
    }));
  }
  if (obj["segments"]) {
    obj["segments"] = [...obj["segments"]];
  }
  if (obj["attachments"]) {
    obj["attachments"] = [...obj["attachments"]];
  }
  return cloned;
}

// src/server/events/optimize-storage.ts
function stripPromptContextMessages(messages) {
  let lastAssistantIdx = -1;
  for (let i = messages.length - 1; i >= 0; i--) {
    const msg = messages[i];
    if (!msg) continue;
    if (msg.role === "assistant" && msg.promptContext) {
      lastAssistantIdx = i;
      break;
    }
  }
  let changed = false;
  for (let i = 0; i < messages.length; i++) {
    const msg = messages[i];
    if (!msg) continue;
    const pc = msg.promptContext;
    if (pc && pc.messages && pc.messages.length > 0 && i !== lastAssistantIdx) {
      pc.messages = [];
      changed = true;
    }
  }
  return changed;
}

// src/server/events/folding.ts
import stripAnsi from "strip-ansi";
function cloneMessage(message) {
  return {
    ...message,
    ...message.attachments ? { attachments: [...message.attachments] } : {},
    ...message.toolCalls ? {
      toolCalls: message.toolCalls.map((toolCall) => ({
        ...toolCall,
        ...toolCall.streamingOutput ? { streamingOutput: [...toolCall.streamingOutput] } : {},
        ...toolCall.result ? { result: { ...toolCall.result } } : {}
      }))
    } : {},
    ...message.segments ? { segments: [...message.segments] } : {},
    ...message.preparingToolCalls && message.preparingToolCalls.length > 0 ? { preparingToolCalls: [...message.preparingToolCalls] } : {}
  };
}
function spreadOptionalMessageFields(message) {
  return {
    ...message.thinkingContent !== void 0 && { thinkingContent: message.thinkingContent },
    ...message.toolCalls !== void 0 && { toolCalls: message.toolCalls },
    ...message.segments !== void 0 && { segments: message.segments },
    ...message.stats !== void 0 && { stats: message.stats },
    ...message.tokenCount !== void 0 && { tokenCount: message.tokenCount },
    ...message.isStreaming !== void 0 && { isStreaming: message.isStreaming },
    ...message.partial !== void 0 && { partial: message.partial },
    ...message.subAgentId !== void 0 && { subAgentId: message.subAgentId },
    ...message.subAgentType !== void 0 && { subAgentType: message.subAgentType },
    ...message.isSystemGenerated !== void 0 && { isSystemGenerated: message.isSystemGenerated },
    ...message.messageKind !== void 0 && { messageKind: message.messageKind },
    ...message.contextWindowId !== void 0 && { contextWindowId: message.contextWindowId },
    ...message.isCompactionSummary !== void 0 && { isCompactionSummary: message.isCompactionSummary },
    ...message.promptContext !== void 0 && { promptContext: message.promptContext },
    ...message.attachments !== void 0 && { attachments: message.attachments },
    ...message.preparingToolCalls !== void 0 && message.preparingToolCalls.length > 0 && { preparingToolCalls: message.preparingToolCalls },
    ...message.metadata !== void 0 && { metadata: message.metadata }
  };
}
function snapshotMessageToMessage(message) {
  return cloneMessage({
    id: message.id,
    role: message.role,
    content: message.content,
    timestamp: new Date(message.timestamp).toISOString(),
    ...spreadOptionalMessageFields(message)
  });
}
function shouldIncludeContextMessage(message, windowId, options) {
  const includeVerifier = options?.includeVerifier ?? true;
  return message.role !== "system" && (windowId === void 0 || message.contextWindowId === windowId) && (includeVerifier || message.subAgentType !== "verifier") && !message.subAgentId;
}
function appendSnapshotMessageContext(result, message) {
  const contextMsg = {
    role: message.role,
    content: message.content
  };
  if (message.thinkingContent) {
    contextMsg.thinkingContent = message.thinkingContent;
  }
  if (message.toolCalls && message.toolCalls.length > 0) {
    const fulfilledToolCalls = message.toolCalls.filter((tc) => tc.result);
    if (fulfilledToolCalls.length > 0) {
      contextMsg.toolCalls = fulfilledToolCalls.map((toolCall) => ({
        id: toolCall.id,
        name: toolCall.name,
        arguments: toolCall.arguments
      }));
    }
  }
  if (message.attachments !== void 0) {
    contextMsg.attachments = message.attachments;
  }
  result.push(contextMsg);
  if (!message.toolCalls) {
    return;
  }
  for (const toolCall of message.toolCalls) {
    if (!toolCall.result) {
      continue;
    }
    result.push({
      role: "tool",
      content: stripAnsi(
        toolCall.result.success ? toolCall.result.output ?? "Success" : toolCall.result.output ? `${toolCall.result.output}

Error: ${toolCall.result.error}` : `Error: ${toolCall.result.error}`
      ),
      toolCallId: toolCall.id
    });
  }
}
function applyStoredMessageEvents(initialMessages, events) {
  return applyEvents(initialMessages, events, { timestampAsNumber: false });
}
function getTimestamp(event) {
  return event.timestamp ?? Date.now();
}
function applyTurnEventsToSnapshotMessages(initialMessages, events) {
  const messages = applyEvents(initialMessages, events, {
    timestampAsNumber: true
  });
  return messages.map((msg) => ({ ...msg, isStreaming: msg.isStreaming ?? true }));
}
function buildMessagesFromStoredEvents(events) {
  const snapshotEvent = [...events].reverse().find((event) => event.type === "turn.snapshot");
  if (snapshotEvent) {
    const snapshot = snapshotEvent.data;
    const snapshotMessages = snapshot.messages.map(snapshotMessageToMessage);
    const laterEvents = events.filter((event) => event.seq > snapshotEvent.seq);
    return applyStoredMessageEvents(snapshotMessages, laterEvents);
  }
  return applyStoredMessageEvents([], events);
}
function buildContextMessagesFromStoredEvents(events, windowId, options) {
  const includeVerifier = options?.includeVerifier ?? true;
  const messages = [];
  const messageMap = /* @__PURE__ */ new Map();
  const fulfilledToolCallIds = /* @__PURE__ */ new Set();
  for (const event of events) {
    switch (event.type) {
      case "message.start": {
        const data = event.data;
        if (data.role !== "system" && (windowId === void 0 || data.contextWindowId === windowId) && (includeVerifier || data.subAgentType !== "verifier") && !data.subAgentId) {
          const message = {
            id: data.messageId,
            role: data.role,
            content: data.content ?? "",
            ...data.attachments !== void 0 && { attachments: data.attachments }
          };
          messageMap.set(data.messageId, message);
          messages.push(message);
        }
        break;
      }
      case "message.thinking": {
        handleMessageThinking(messageMap, event.data);
        break;
      }
      case "message.delta": {
        handleMessageDelta(messageMap, event.data);
        break;
      }
      case "tool.call": {
        handleToolCall(messageMap, event.data);
        break;
      }
      case "tool.result": {
        handleToolResult(
          messages,
          messageMap,
          fulfilledToolCallIds,
          event.data
        );
        break;
      }
    }
  }
  stripOrphanedToolCalls(messages, fulfilledToolCallIds);
  return messages.map(({ id: _id, ...message }) => message);
}
function handleMessageThinking(messageMap, data) {
  const msg = messageMap.get(data.messageId);
  if (msg) {
    msg.thinkingContent = (msg.thinkingContent ?? "") + data.content;
  }
}
function handleMessageDelta(messageMap, data) {
  const msg = messageMap.get(data.messageId);
  if (msg) {
    msg.content += data.content;
  }
}
function handleToolCall(messageMap, data) {
  const msg = messageMap.get(data.messageId);
  if (msg) {
    if (!msg.toolCalls) msg.toolCalls = [];
    msg.toolCalls.push(data.toolCall);
  }
}
function handleToolResult(messages, messageMap, fulfilled, data) {
  fulfilled.add(data.toolCallId);
  if (messageMap.has(data.messageId)) {
    const imageMeta = data.result.metadata;
    const toolMsg = {
      id: `tool-${data.toolCallId}`,
      role: "tool",
      content: stripAnsi(
        data.result.success ? data.result.output ?? "Success" : data.result.output ? `${data.result.output}

Error: ${data.result.error}` : `Error: ${data.result.error}`
      ),
      toolCallId: data.toolCallId
    };
    if (imageMeta?.dataUrl && imageMeta?.mimeType?.startsWith("image/")) {
      toolMsg.attachments = [
        {
          id: crypto.randomUUID(),
          filename: imageMeta.path ?? "image",
          mimeType: imageMeta.mimeType,
          size: imageMeta.size ?? 0,
          data: imageMeta.dataUrl
        }
      ];
    }
    messages.push(toolMsg);
  }
}
function stripOrphanedToolCalls(messages, fulfilledToolCallIds) {
  for (const msg of messages) {
    if (msg.role === "assistant" && msg.toolCalls) {
      const fulfilled = msg.toolCalls.filter((tc) => fulfilledToolCallIds.has(tc.id));
      if (fulfilled.length === 0) {
        delete msg.toolCalls;
      } else {
        msg.toolCalls = fulfilled;
      }
    }
  }
}
function buildContextMessagesFromEventHistory(events, windowId, options) {
  const snapshotEvent = [...events].reverse().find((event) => event.type === "turn.snapshot");
  if (!snapshotEvent) {
    return buildContextMessagesFromStoredEvents(events, windowId, options);
  }
  const snapshot = snapshotEvent.data;
  const snapshotMessages = snapshot.messages.reduce((result, message) => {
    if (!shouldIncludeContextMessage(message, windowId, options)) {
      return result;
    }
    appendSnapshotMessageContext(result, message);
    return result;
  }, []);
  const laterEvents = events.filter((event) => event.seq > snapshotEvent.seq);
  return [...snapshotMessages, ...buildContextMessagesFromStoredEvents(laterEvents, windowId, options)];
}
function foldTurnEventsToSnapshotMessages(events) {
  return applyTurnEventsToSnapshotMessages([], events);
}
function foldTurnEventsToSnapshotMessagesFromInitial(events, initialMessages) {
  return applyTurnEventsToSnapshotMessages(initialMessages, events);
}
function foldCriteria(events) {
  let criteria = [];
  for (const event of events) {
    switch (event.type) {
      case "criteria.set": {
        const data = event.data;
        criteria = data.criteria;
        break;
      }
      case "criterion.updated": {
        const data = event.data;
        criteria = criteria.map((c) => c.id === data.criterionId ? { ...c, status: data.status } : c);
        break;
      }
    }
  }
  return criteria;
}
function foldTodos(events) {
  let todos = [];
  for (const event of events) {
    if (event.type === "todo.updated") {
      const data = event.data;
      todos = data.todos;
    }
  }
  return todos;
}
function foldContextState(events, initialWindowId) {
  let currentContextWindowId = initialWindowId;
  let compactionCount = 0;
  let latestContextState = null;
  const readFilesMap = /* @__PURE__ */ new Map();
  for (const event of events) {
    switch (event.type) {
      case "session.initialized": {
        const data = event.data;
        currentContextWindowId = data.contextWindowId;
        break;
      }
      case "turn.snapshot": {
        const data = event.data;
        currentContextWindowId = data.currentContextWindowId;
        compactionCount = data.contextState.compactionCount;
        latestContextState = data.contextState;
        readFilesMap.clear();
        if (data.readFiles) {
          for (const entry of data.readFiles) {
            readFilesMap.set(entry.path, { ...entry });
          }
        }
        break;
      }
      case "context.state": {
        const data = event.data;
        if (!data.subAgentId) {
          latestContextState = data;
        }
        break;
      }
      case "context.compacted": {
        const data = event.data;
        currentContextWindowId = data.newWindowId;
        compactionCount++;
        readFilesMap.clear();
        latestContextState = null;
        break;
      }
      case "file.read": {
        const data = event.data;
        if (data.contextWindowId === currentContextWindowId) {
          readFilesMap.set(data.path, {
            path: data.path,
            tokenCount: data.tokenCount
          });
        }
        break;
      }
    }
  }
  return {
    currentContextWindowId,
    compactionCount,
    readFiles: Array.from(readFilesMap.values()),
    latestContextState
  };
}
function foldMode(events) {
  let mode = "planner";
  for (const event of events) {
    if (event.type === "mode.changed") {
      const data = event.data;
      mode = data.mode;
    }
  }
  return mode;
}
function foldPhase(events) {
  let phase = "plan";
  for (const event of events) {
    if (event.type === "phase.changed") {
      const data = event.data;
      phase = data.phase;
    }
  }
  return phase;
}
function foldIsRunning(events) {
  let isRunning = false;
  for (const event of events) {
    if (event.type === "running.changed") {
      const data = event.data;
      isRunning = data.isRunning;
    }
  }
  return isRunning;
}
function foldPendingConfirmations(events) {
  const pending = [];
  const responded = /* @__PURE__ */ new Set();
  for (const event of events) {
    if (event.type === "path.confirmation_responded") {
      const data = event.data;
      responded.add(data.callId);
    }
  }
  for (const event of events) {
    if (event.type === "path.confirmation_pending") {
      const data = event.data;
      if (!responded.has(data.callId)) {
        pending.push({
          callId: data.callId,
          tool: data.tool,
          paths: data.paths,
          workdir: data.workdir,
          reason: data.reason
        });
      }
    }
  }
  return pending;
}
function foldSessionState(events, initialWindowId, maxTokens, initialMessages) {
  const mode = foldMode(events);
  const phase = foldPhase(events);
  const isRunning = foldIsRunning(events);
  const messages = initialMessages && initialMessages.length > 0 ? foldTurnEventsToSnapshotMessagesFromInitial(events, initialMessages) : foldTurnEventsToSnapshotMessages(events);
  const criteria = foldCriteria(events);
  const todos = foldTodos(events);
  const contextResult = foldContextState(events, initialWindowId);
  const pendingConfirmations = foldPendingConfirmations(events);
  const baseContextState = contextResult.latestContextState ?? {
    currentTokens: 0,
    maxTokens,
    compactionCount: contextResult.compactionCount,
    dangerZone: false,
    canCompact: false,
    dynamicContextChanged: false
  };
  const contextState = baseContextState.compactionCount !== contextResult.compactionCount || baseContextState.maxTokens !== maxTokens ? { ...baseContextState, compactionCount: contextResult.compactionCount, maxTokens } : { ...baseContextState, maxTokens };
  let messageReminderMode;
  let snapshotReminderMode;
  let cachedSystemPrompt;
  let dynamicContextHash;
  for (let i = events.length - 1; i >= 0; i--) {
    const event = events[i];
    if (event.type === "message.start") {
      const data = event.data;
      if (data.role === "user" && data.messageKind === "auto-prompt" && data.content?.includes("<system-reminder>")) {
        if (data.content.includes("Plan Mode")) {
          messageReminderMode = { seq: event.seq, mode: "planner" };
        } else if (data.content.includes("Build Mode")) {
          messageReminderMode = { seq: event.seq, mode: "builder" };
        }
      }
    }
    if (event.type === "turn.snapshot") {
      const snapshotData = event.data;
      if (snapshotData.lastModeWithReminder) {
        snapshotReminderMode = {
          seq: event.seq,
          mode: snapshotData.lastModeWithReminder
        };
      }
      if (snapshotData.cachedSystemPrompt && !cachedSystemPrompt) {
        cachedSystemPrompt = snapshotData.cachedSystemPrompt;
      }
      if (snapshotData.dynamicContextHash && !dynamicContextHash) {
        dynamicContextHash = snapshotData.dynamicContextHash;
      }
    }
  }
  let lastModeWithReminder;
  if (messageReminderMode && snapshotReminderMode) {
    lastModeWithReminder = messageReminderMode.seq > snapshotReminderMode.seq ? messageReminderMode.mode : snapshotReminderMode.mode;
  } else if (snapshotReminderMode) {
    lastModeWithReminder = snapshotReminderMode.mode;
  } else if (messageReminderMode) {
    lastModeWithReminder = messageReminderMode.mode;
  }
  let sessionInit;
  let sessionTitle;
  const visionFallbacks = [];
  const formatRetries = [];
  let pendingUserInput;
  let taskStats;
  const messageStats = [];
  const contextWindows = [];
  for (const event of events) {
    switch (event.type) {
      case "session.initialized": {
        const data = event.data;
        sessionInit = {
          projectId: data.projectId,
          workdir: data.workdir,
          contextWindowId: data.contextWindowId,
          ...data.maxTokens !== void 0 && { maxTokens: data.maxTokens }
        };
        break;
      }
      case "session.name_generated": {
        const data = event.data;
        sessionTitle = data.name;
        break;
      }
      case "vision_fallback.start": {
        const data = event.data;
        visionFallbacks.push({
          messageId: data.messageId,
          attachmentId: data.attachmentId,
          ...data.filename !== void 0 && { filename: data.filename },
          startedAt: getTimestamp(event)
        });
        break;
      }
      case "vision_fallback.done": {
        const data = event.data;
        const existing = visionFallbacks.find(
          (v) => v.messageId === data.messageId && v.attachmentId === data.attachmentId
        );
        if (existing) {
          existing.description = data.description;
        }
        break;
      }
      case "format.retry": {
        const data = event.data;
        formatRetries.push({
          attempt: data.attempt,
          maxAttempts: data.maxAttempts,
          timestamp: getTimestamp(event)
        });
        break;
      }
      case "chat.ask_user": {
        const data = event.data;
        pendingUserInput = { callId: data.callId, question: data.question };
        break;
      }
      case "task.completed": {
        const data = event.data;
        taskStats = data;
        break;
      }
      case "chat.done": {
        const data = event.data;
        messageStats.push({
          messageId: data.messageId,
          reason: data.reason,
          ...data.stats !== void 0 && { stats: data.stats }
        });
        break;
      }
      case "context.compacted": {
        const data = event.data;
        contextWindows.push({
          ...data,
          timestamp: getTimestamp(event)
        });
        break;
      }
    }
  }
  return {
    mode,
    phase,
    isRunning,
    messages,
    criteria,
    todos,
    contextState,
    currentContextWindowId: contextResult.currentContextWindowId,
    readFiles: contextResult.readFiles,
    ...lastModeWithReminder !== void 0 && { lastModeWithReminder },
    ...cachedSystemPrompt !== void 0 && { cachedSystemPrompt },
    ...dynamicContextHash !== void 0 && { dynamicContextHash },
    pendingConfirmations,
    ...sessionInit !== void 0 && { sessionInit },
    ...sessionTitle !== void 0 && { sessionTitle },
    ...visionFallbacks.length > 0 && { visionFallbacks },
    ...formatRetries.length > 0 && { formatRetries },
    ...pendingUserInput !== void 0 && { pendingUserInput },
    ...taskStats !== void 0 && { taskStats },
    ...messageStats.length > 0 && { messageStats },
    ...contextWindows.length > 0 && { contextWindows }
  };
}
function buildSnapshot(foldedState, latestSeq, snapshotAt = Date.now()) {
  return {
    mode: foldedState.mode,
    phase: foldedState.phase,
    isRunning: foldedState.isRunning,
    messages: foldedState.messages,
    criteria: foldedState.criteria,
    contextState: foldedState.contextState,
    currentContextWindowId: foldedState.currentContextWindowId,
    todos: foldedState.todos,
    readFiles: foldedState.readFiles,
    ...foldedState.lastModeWithReminder !== void 0 && { lastModeWithReminder: foldedState.lastModeWithReminder },
    ...foldedState.cachedSystemPrompt !== void 0 && { cachedSystemPrompt: foldedState.cachedSystemPrompt },
    ...foldedState.dynamicContextHash !== void 0 && { dynamicContextHash: foldedState.dynamicContextHash },
    snapshotSeq: latestSeq,
    snapshotAt,
    ...foldedState.sessionInit !== void 0 && { sessionInit: foldedState.sessionInit },
    ...foldedState.sessionTitle !== void 0 && { sessionTitle: foldedState.sessionTitle },
    ...foldedState.visionFallbacks !== void 0 && { visionFallbacks: foldedState.visionFallbacks },
    ...foldedState.formatRetries !== void 0 && { formatRetries: foldedState.formatRetries },
    ...foldedState.pendingUserInput !== void 0 && { pendingUserInput: foldedState.pendingUserInput },
    ...foldedState.taskStats !== void 0 && { taskStats: foldedState.taskStats },
    ...foldedState.messageStats !== void 0 && { messageStats: foldedState.messageStats },
    ...foldedState.pendingConfirmations !== void 0 && { pendingConfirmations: foldedState.pendingConfirmations },
    ...foldedState.contextWindows !== void 0 && { contextWindows: foldedState.contextWindows }
  };
}
function buildSnapshotFromSessionState(input) {
  const { session, events, latestSeq, snapshotAt = Date.now(), maxTokens = 2e5 } = input;
  let initialWindowId = "";
  for (const event of events) {
    if (event.type === "session.initialized") {
      const data = event.data;
      initialWindowId = data.contextWindowId;
      break;
    }
  }
  if (!initialWindowId) {
    initialWindowId = "legacy-window-1";
  }
  const foldedState = foldSessionState(events, initialWindowId, maxTokens);
  const latestSnapshotIndex = events.map((event) => event.type).lastIndexOf("turn.snapshot");
  const latestSnapshotEvent = latestSnapshotIndex >= 0 ? events[latestSnapshotIndex] : void 0;
  const messages = latestSnapshotEvent ? applyTurnEventsToSnapshotMessages(
    latestSnapshotEvent.data.messages,
    events.slice(latestSnapshotIndex + 1)
  ) : foldedState.messages;
  stripPromptContextMessages(messages);
  return {
    mode: session.mode,
    phase: session.phase,
    isRunning: session.isRunning,
    messages,
    criteria: session.criteria,
    contextState: {
      currentTokens: session.executionState?.currentTokenCount ?? foldedState.contextState.currentTokens,
      maxTokens: foldedState.contextState.maxTokens,
      compactionCount: session.executionState?.compactionCount ?? foldedState.contextState.compactionCount,
      dangerZone: foldedState.contextState.dangerZone,
      canCompact: foldedState.contextState.canCompact,
      dynamicContextChanged: foldedState.contextState.dynamicContextChanged
    },
    currentContextWindowId: foldedState.currentContextWindowId,
    todos: foldedState.todos,
    readFiles: foldedState.readFiles,
    snapshotSeq: latestSeq,
    snapshotAt,
    ...foldedState.sessionInit !== void 0 && { sessionInit: foldedState.sessionInit },
    ...foldedState.lastModeWithReminder !== void 0 && { lastModeWithReminder: foldedState.lastModeWithReminder },
    ...input.cachedSystemPrompt !== void 0 ? { cachedSystemPrompt: input.cachedSystemPrompt } : foldedState.cachedSystemPrompt !== void 0 ? { cachedSystemPrompt: foldedState.cachedSystemPrompt } : {},
    ...input.dynamicContextHash !== void 0 ? { dynamicContextHash: input.dynamicContextHash } : foldedState.dynamicContextHash !== void 0 ? { dynamicContextHash: foldedState.dynamicContextHash } : {}
  };
}
function getMessagesForWindow(messages, windowId) {
  return messages.filter((m) => m.contextWindowId === windowId);
}
function buildContextMessagesFromMessages(messages, windowId) {
  return getMessagesForWindow(messages, windowId).reduce((result, message) => {
    if (!shouldIncludeContextMessage(message, windowId)) {
      return result;
    }
    appendSnapshotMessageContext(result, message);
    return result;
  }, []);
}

export {
  stripPromptContextMessages,
  spreadOptionalMessageFields,
  buildMessagesFromStoredEvents,
  buildContextMessagesFromStoredEvents,
  handleMessageThinking,
  handleMessageDelta,
  handleToolCall,
  handleToolResult,
  stripOrphanedToolCalls,
  buildContextMessagesFromEventHistory,
  foldTurnEventsToSnapshotMessages,
  foldTurnEventsToSnapshotMessagesFromInitial,
  foldCriteria,
  foldTodos,
  foldContextState,
  foldMode,
  foldPhase,
  foldIsRunning,
  foldPendingConfirmations,
  foldSessionState,
  buildSnapshot,
  buildSnapshotFromSessionState,
  getMessagesForWindow,
  buildContextMessagesFromMessages
};
//# sourceMappingURL=chunk-6WZI6F6G.js.map