import { getEffectiveResourceId, validateThreadOwnership } from './chunk-VLNRGJEM.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';

// src/server/handlers/responses.storage.ts
function isPlainObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
async function getAgentMemoryStore({
  agent,
  requestContext
}) {
  const memory = await agent.getMemory({ requestContext });
  if (!memory) {
    return null;
  }
  try {
    return await memory.storage.getStore("memory") ?? null;
  } catch {
    return null;
  }
}
function readResponseTurnRecordMetadata(message) {
  const mastraMetadata = isPlainObject(message.content?.metadata?.mastra) ? message.content.metadata.mastra : null;
  const responseMetadata = mastraMetadata && isPlainObject(mastraMetadata.response) ? mastraMetadata.response : null;
  if (!responseMetadata || typeof responseMetadata.agentId !== "string" || typeof responseMetadata.model !== "string" || typeof responseMetadata.createdAt !== "number" || responseMetadata.completedAt !== null && typeof responseMetadata.completedAt !== "number" || responseMetadata.instructions !== void 0 && typeof responseMetadata.instructions !== "string" || responseMetadata.text !== void 0 && (!isPlainObject(responseMetadata.text) || !isPlainObject(responseMetadata.text.format)) || responseMetadata.previousResponseId !== void 0 && typeof responseMetadata.previousResponseId !== "string" || !Array.isArray(responseMetadata.tools) || typeof responseMetadata.store !== "boolean" || !Array.isArray(responseMetadata.messageIds)) {
    return null;
  }
  return {
    agentId: responseMetadata.agentId,
    model: responseMetadata.model,
    createdAt: responseMetadata.createdAt,
    completedAt: responseMetadata.completedAt,
    status: responseMetadata.status === "completed" ? "completed" : "incomplete",
    usage: responseMetadata.usage,
    instructions: responseMetadata.instructions,
    text: responseMetadata.text,
    previousResponseId: responseMetadata.previousResponseId,
    providerOptions: responseMetadata.providerOptions,
    tools: responseMetadata.tools,
    store: responseMetadata.store,
    messageIds: responseMetadata.messageIds.filter((value) => typeof value === "string")
  };
}
function writeResponseTurnRecordMetadata(message, metadata) {
  const contentMetadata = isPlainObject(message.content?.metadata) ? message.content.metadata : {};
  const mastraMetadata = isPlainObject(contentMetadata.mastra) ? contentMetadata.mastra : {};
  return {
    ...message,
    content: {
      ...message.content,
      metadata: {
        ...contentMetadata,
        mastra: {
          ...mastraMetadata,
          response: metadata
        }
      }
    }
  };
}
async function findResponseTurnRecord({
  agent,
  responseId,
  requestContext
}) {
  const memoryStore = await getAgentMemoryStore({ agent, requestContext });
  if (!memoryStore) {
    return null;
  }
  const effectiveResourceId = getEffectiveResourceId(requestContext, void 0);
  const { messages: matchedMessages } = await memoryStore.listMessagesById({ messageIds: [responseId] });
  const message = matchedMessages[0];
  if (!message || message.role !== "assistant") {
    return null;
  }
  const metadata = readResponseTurnRecordMetadata(message);
  if (!metadata || metadata.agentId !== agent.id) {
    return null;
  }
  const thread = message.threadId ? await memoryStore.getThreadById({ threadId: message.threadId }) : null;
  if (!thread) {
    return null;
  }
  await validateThreadOwnership(thread, effectiveResourceId);
  const messageIds = metadata.messageIds.length > 0 ? metadata.messageIds : [message.id];
  const { messages: responseMessages } = await memoryStore.listMessagesById({ messageIds });
  const messagesById = new Map(responseMessages.map((storedMessage) => [storedMessage.id, storedMessage]));
  const orderedMessages = messageIds.map((messageId) => messagesById.get(messageId)).filter((storedMessage) => Boolean(storedMessage));
  return { metadata, message, messages: orderedMessages, thread, memoryStore };
}
async function findResponseTurnRecordAcrossAgents({
  mastra,
  responseId,
  requestContext
}) {
  if (!mastra) {
    return null;
  }
  const agents = Object.values(mastra.listAgents());
  for (const agent of agents) {
    const match = await findResponseTurnRecord({ agent, responseId, requestContext });
    if (match) {
      return match;
    }
  }
  return null;
}
async function findConversationThreadAcrossAgents({
  mastra,
  conversationId,
  requestContext
}) {
  if (!mastra) {
    return null;
  }
  const effectiveResourceId = getEffectiveResourceId(requestContext, void 0);
  const agents = Object.values(mastra.listAgents());
  for (const agent of agents) {
    const memoryStore = await getAgentMemoryStore({ agent, requestContext });
    if (!memoryStore) {
      continue;
    }
    const thread = await memoryStore.getThreadById({ threadId: conversationId });
    if (!thread) {
      continue;
    }
    await validateThreadOwnership(thread, effectiveResourceId);
    return { thread, memoryStore };
  }
  return null;
}
function createSyntheticResponseMessage({
  responseId,
  text,
  threadContext
}) {
  return {
    id: responseId,
    role: "assistant",
    type: "text",
    createdAt: /* @__PURE__ */ new Date(),
    threadId: threadContext.threadId,
    resourceId: threadContext.resourceId,
    content: {
      format: 2,
      parts: text ? [{ type: "text", text }] : []
    }
  };
}
async function resolveResponseTurnMessagesForStorage({
  result,
  responseId,
  text,
  threadContext
}) {
  const response = await result.response;
  const responseMessages = response?.dbMessages?.length ? response.dbMessages : [];
  if (!threadContext) {
    return responseMessages;
  }
  if (responseMessages.length === 0) {
    return [createSyntheticResponseMessage({ responseId, text, threadContext })];
  }
  return responseMessages;
}
async function persistResponseTurnRecord({
  memoryStore,
  responseId,
  metadata,
  threadContext,
  messages
}) {
  if (!memoryStore) {
    throw new HTTPException(500, { message: "Memory storage was not available while storing the response" });
  }
  const normalizedMessages = messages.map((message) => ({
    ...message,
    threadId: message.threadId ?? threadContext.threadId,
    resourceId: message.resourceId ?? threadContext.resourceId
  }));
  const lastAssistantIndex = [...normalizedMessages].map((message) => message.role).lastIndexOf("assistant");
  const lastAssistantMessage = lastAssistantIndex >= 0 ? {
    ...normalizedMessages[lastAssistantIndex],
    id: responseId
  } : {
    id: responseId,
    role: "assistant",
    type: "text",
    createdAt: new Date(metadata.completedAt ? metadata.completedAt * 1e3 : Date.now()),
    threadId: threadContext.threadId,
    resourceId: threadContext.resourceId,
    content: {
      format: 2,
      parts: []
    }
  };
  if (lastAssistantIndex >= 0) {
    normalizedMessages[lastAssistantIndex] = lastAssistantMessage;
  } else {
    normalizedMessages.push(lastAssistantMessage);
  }
  const staleMessageIds = lastAssistantIndex >= 0 && messages[lastAssistantIndex]?.id && messages[lastAssistantIndex]?.id !== responseId ? [messages[lastAssistantIndex].id] : [];
  const storedMessage = writeResponseTurnRecordMetadata(lastAssistantMessage, {
    ...metadata,
    messageIds: normalizedMessages.map((message) => message.id)
  });
  if (lastAssistantIndex >= 0) {
    normalizedMessages[lastAssistantIndex] = storedMessage;
  } else {
    normalizedMessages[normalizedMessages.length - 1] = storedMessage;
  }
  await memoryStore.saveMessages({ messages: normalizedMessages });
  if (staleMessageIds.length > 0) {
    await memoryStore.deleteMessages(staleMessageIds);
  }
}
async function deleteResponseTurnRecord({
  responseTurnRecord
}) {
  const messageIds = responseTurnRecord.messages.length > 0 ? responseTurnRecord.messages.map((message) => message.id) : [responseTurnRecord.message.id];
  await responseTurnRecord.memoryStore.deleteMessages(messageIds);
}

export { deleteResponseTurnRecord, findConversationThreadAcrossAgents, findResponseTurnRecord, findResponseTurnRecordAcrossAgents, getAgentMemoryStore, persistResponseTurnRecord, resolveResponseTurnMessagesForStorage };
//# sourceMappingURL=chunk-WC4RIS4D.js.map
//# sourceMappingURL=chunk-WC4RIS4D.js.map