'use strict';

var chunkCQNREK5Y_cjs = require('./chunk-CQNREK5Y.cjs');
var chunkLFZO2LHV_cjs = require('./chunk-LFZO2LHV.cjs');
var chunkLWK57QIA_cjs = require('./chunk-LWK57QIA.cjs');
var chunk5UKYK7YK_cjs = require('./chunk-5UKYK7YK.cjs');
var chunkB34S64RC_cjs = require('./chunk-B34S64RC.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var chunkO7I5CWRX_cjs = require('./chunk-O7I5CWRX.cjs');
var utils = require('@mastra/core/utils');

// src/server/handlers/memory.ts
var memory_exports = {};
chunkO7I5CWRX_cjs.__export(memory_exports, {
  AWAIT_BUFFER_STATUS_ROUTE: () => AWAIT_BUFFER_STATUS_ROUTE,
  CLONE_THREAD_ROUTE: () => CLONE_THREAD_ROUTE,
  CREATE_THREAD_NETWORK_ROUTE: () => CREATE_THREAD_NETWORK_ROUTE,
  CREATE_THREAD_ROUTE: () => CREATE_THREAD_ROUTE,
  DELETE_MESSAGES_NETWORK_ROUTE: () => DELETE_MESSAGES_NETWORK_ROUTE,
  DELETE_MESSAGES_ROUTE: () => DELETE_MESSAGES_ROUTE,
  DELETE_THREAD_NETWORK_ROUTE: () => DELETE_THREAD_NETWORK_ROUTE,
  DELETE_THREAD_ROUTE: () => DELETE_THREAD_ROUTE,
  GET_MEMORY_CONFIG_ROUTE: () => GET_MEMORY_CONFIG_ROUTE,
  GET_MEMORY_STATUS_NETWORK_ROUTE: () => GET_MEMORY_STATUS_NETWORK_ROUTE,
  GET_MEMORY_STATUS_ROUTE: () => GET_MEMORY_STATUS_ROUTE,
  GET_OBSERVATIONAL_MEMORY_ROUTE: () => GET_OBSERVATIONAL_MEMORY_ROUTE,
  GET_THREAD_BY_ID_NETWORK_ROUTE: () => GET_THREAD_BY_ID_NETWORK_ROUTE,
  GET_THREAD_BY_ID_ROUTE: () => GET_THREAD_BY_ID_ROUTE,
  GET_WORKING_MEMORY_ROUTE: () => GET_WORKING_MEMORY_ROUTE,
  LIST_MESSAGES_NETWORK_ROUTE: () => LIST_MESSAGES_NETWORK_ROUTE,
  LIST_MESSAGES_ROUTE: () => LIST_MESSAGES_ROUTE,
  LIST_THREADS_NETWORK_ROUTE: () => LIST_THREADS_NETWORK_ROUTE,
  LIST_THREADS_ROUTE: () => LIST_THREADS_ROUTE,
  SAVE_MESSAGES_NETWORK_ROUTE: () => SAVE_MESSAGES_NETWORK_ROUTE,
  SAVE_MESSAGES_ROUTE: () => SAVE_MESSAGES_ROUTE,
  SEARCH_MEMORY_ROUTE: () => SEARCH_MEMORY_ROUTE,
  UPDATE_THREAD_NETWORK_ROUTE: () => UPDATE_THREAD_NETWORK_ROUTE,
  UPDATE_THREAD_ROUTE: () => UPDATE_THREAD_ROUTE,
  UPDATE_WORKING_MEMORY_ROUTE: () => UPDATE_WORKING_MEMORY_ROUTE,
  getTextContent: () => getTextContent
});
function getTextContent(message) {
  if (typeof message.content === "string") {
    return message.content;
  }
  if (message.content && typeof message.content === "object" && "parts" in message.content) {
    const textPart = message.content.parts.find((p) => p.type === "text");
    return textPart?.text || "";
  }
  return "";
}
async function getMemoryFromContext({
  mastra,
  agentId,
  requestContext,
  allowMissingAgent = false
}) {
  const logger = mastra.getLogger();
  let agent;
  if (agentId) {
    try {
      agent = mastra.getAgentById(agentId);
    } catch (error) {
      logger.debug("Error getting agent from mastra, searching agents for agent", error);
    }
  }
  if (agentId && !agent) {
    logger.debug("Agent not found in registered agents, trying stored agents", { agentId });
    try {
      const storedAgent = await mastra.getEditor()?.agent.getById(agentId) ?? null;
      if (storedAgent) {
        agent = storedAgent;
      }
    } catch (error) {
      logger.debug("Error getting stored agent", error);
    }
  }
  if (agentId && !agent) {
    logger.debug("Stored agent not found, searching sub-agents", { agentId });
    const agents = mastra.listAgents();
    if (Object.keys(agents || {}).length) {
      for (const [_, ag] of Object.entries(agents)) {
        try {
          const subAgents = await ag.listAgents({ requestContext });
          if (subAgents[agentId]) {
            agent = subAgents[agentId];
            break;
          }
        } catch (error) {
          logger.debug("Error getting agent from agent", error);
        }
      }
    }
    if (!agent) {
      if (allowMissingAgent) {
        logger.debug("Agent not found in any resolution tier, returning null for storage fallback", { agentId });
        return null;
      }
      throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Agent not found" });
    }
  }
  if (agent) {
    return await agent?.getMemory({
      requestContext
    });
  }
}
function getStorageFromContext({ mastra }) {
  return mastra.getStorage();
}
async function getAgentFromContext({
  mastra,
  agentId,
  requestContext
}) {
  if (!agentId) return null;
  const logger = mastra.getLogger();
  let agent = null;
  try {
    agent = mastra.getAgentById(agentId);
  } catch (error) {
    logger.debug("Error getting agent from mastra", error);
  }
  if (!agent) {
    logger.debug("Agent not found in registered agents, trying stored agents", { agentId });
    try {
      const storedAgent = await mastra.getEditor()?.agent.getById(agentId) ?? null;
      if (storedAgent) {
        agent = storedAgent;
      }
    } catch (error) {
      logger.debug("Error getting stored agent", error);
    }
  }
  if (!agent) {
    logger.debug("Stored agent not found, searching sub-agents", { agentId });
    const agents = mastra.listAgents();
    if (Object.keys(agents || {}).length) {
      for (const [_, ag] of Object.entries(agents)) {
        try {
          const nestedAgents = await ag.listAgents({ requestContext });
          if (nestedAgents[agentId]) {
            agent = nestedAgents[agentId];
            break;
          }
        } catch (error) {
          logger.debug("Error getting agent from agent", error);
        }
      }
    }
  }
  return agent;
}
async function getOMConfigFromAgent(agent, requestContext) {
  try {
    if (typeof agent.resolveProcessorById !== "function") {
      return null;
    }
    const omProcessor = await agent.resolveProcessorById("observational-memory", requestContext);
    if (!omProcessor) {
      return null;
    }
    const hasResolvedConfig = typeof omProcessor.getResolvedConfig === "function";
    if (hasResolvedConfig) {
      const resolvedConfig = await omProcessor.getResolvedConfig(requestContext);
      return {
        enabled: true,
        scope: resolvedConfig.scope || "resource",
        shareTokenBudget: resolvedConfig.shareTokenBudget,
        messageTokens: resolvedConfig.observation?.messageTokens,
        observationTokens: resolvedConfig.reflection?.observationTokens,
        observationModel: resolvedConfig.observation?.model,
        reflectionModel: resolvedConfig.reflection?.model,
        observationModelRouting: resolvedConfig.observation?.routing,
        reflectionModelRouting: resolvedConfig.reflection?.routing
      };
    }
    const processorConfig = omProcessor.config || {};
    return {
      enabled: true,
      scope: processorConfig.scope || "resource",
      shareTokenBudget: processorConfig.shareTokenBudget,
      messageTokens: processorConfig.observation?.messageTokens,
      observationTokens: processorConfig.reflection?.observationTokens,
      observationModel: void 0,
      reflectionModel: void 0,
      observationModelRouting: void 0,
      reflectionModelRouting: void 0
    };
  } catch {
    return null;
  }
}
async function getOMStatus(memoryStorage, resourceId, threadId) {
  try {
    const record = await memoryStorage.getObservationalMemory(threadId ?? null, resourceId);
    if (!record) {
      return { hasRecord: false };
    }
    return {
      hasRecord: true,
      originType: record.originType,
      lastObservedAt: record.lastObservedAt ?? null,
      tokenCount: record.totalTokensObserved,
      observationTokenCount: record.observationTokenCount,
      isObserving: record.isObserving,
      isReflecting: record.isReflecting
    };
  } catch {
    return null;
  }
}
var GET_MEMORY_STATUS_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/status",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.getMemoryStatusQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.memoryStatusResponseSchema,
  summary: "Get memory status",
  description: "Returns the current status of the memory system including configuration and health information",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, resourceId, threadId, requestContext }) => {
    try {
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      const isGateway = agent ? await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent) : false;
      if (agent && isGateway) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient) {
          let omStatus;
          if (resourceId && threadId) {
            try {
              const { record } = await gwClient.getObservationRecord(threadId, resourceId);
              if (record) {
                omStatus = {
                  enabled: true,
                  hasRecord: true,
                  originType: record.originType,
                  lastObservedAt: record.lastObservedAt ? new Date(record.lastObservedAt) : void 0,
                  tokenCount: record.totalTokensObserved,
                  observationTokenCount: record.observationTokenCount,
                  isObserving: record.isObserving,
                  isReflecting: record.isReflecting
                };
              } else {
                omStatus = { enabled: true, hasRecord: false };
              }
            } catch {
              omStatus = { enabled: true };
            }
          } else {
            omStatus = { enabled: true };
          }
          return { result: true, memoryType: "gateway", observationalMemory: omStatus };
        }
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext, allowMissingAgent: true });
      if (memory) {
        let omStatus;
        if (agent) {
          const omConfig = await getOMConfigFromAgent(agent, requestContext);
          if (omConfig?.enabled && resourceId) {
            const omThreadId = omConfig.scope === "resource" ? void 0 : threadId;
            try {
              const memoryStore = await memory.storage.getStore("memory");
              if (memoryStore) {
                const status = await getOMStatus(memoryStore, resourceId, omThreadId);
                if (status) {
                  omStatus = {
                    enabled: true,
                    ...status,
                    // Convert null to undefined for schema compatibility
                    lastObservedAt: status.lastObservedAt ?? void 0
                  };
                } else {
                  omStatus = { enabled: true, hasRecord: false };
                }
              }
            } catch {
              omStatus = { enabled: true };
            }
          } else if (omConfig?.enabled) {
            omStatus = { enabled: true };
          }
        }
        return { result: true, memoryType: "local", observationalMemory: omStatus };
      }
      const storage = getStorageFromContext({ mastra });
      if (storage) {
        return { result: true };
      }
      return { result: false };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting memory status");
    }
  }
});
var GET_MEMORY_CONFIG_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/config",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.getMemoryConfigQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.memoryConfigResponseSchema,
  summary: "Get memory configuration",
  description: "Returns the memory configuration for a specific agent or the system default",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, requestContext }) => {
    try {
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (agent && await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent) && chunkLFZO2LHV_cjs.getGatewayClient()) {
        return {
          memoryType: "gateway",
          config: {
            observationalMemory: {
              enabled: true,
              scope: "thread",
              messageTokens: 3e4,
              observationTokens: 4e4
            }
          }
        };
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext, allowMissingAgent: true });
      if (!memory) {
        return { config: null };
      }
      const config = memory.getMergedThreadConfig({});
      let omConfig;
      if (agent) {
        omConfig = await getOMConfigFromAgent(agent, requestContext) ?? { enabled: false };
      }
      return {
        config: {
          ...config,
          observationalMemory: omConfig
        }
      };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting memory configuration");
    }
  }
});
var GET_OBSERVATIONAL_MEMORY_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/observational-memory",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.getObservationalMemoryQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.getObservationalMemoryResponseSchema,
  summary: "Get observational memory data",
  description: "Returns the current observational memory record and optional history for a resource/thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, resourceId, threadId, from, to, offset, limit, requestContext }) => {
    try {
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Agent not found" });
      }
      const historyLimit = limit ?? 5;
      const historyOptions = { from, to, offset };
      if (await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent)) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient && resourceId && threadId) {
          const [recordResult, historyResult] = await Promise.all([
            gwClient.getObservationRecord(threadId, resourceId),
            gwClient.getObservationHistory(threadId, { resourceId, limit: historyLimit, from, to, offset })
          ]);
          return {
            record: recordResult.record ? chunkLFZO2LHV_cjs.toLocalOMRecord(recordResult.record) : null,
            history: historyResult.records?.length > 0 ? historyResult.records.map(chunkLFZO2LHV_cjs.toLocalOMRecord) : void 0
          };
        }
        return { record: null, history: void 0 };
      }
      const omConfig = await getOMConfigFromAgent(agent, requestContext);
      if (!omConfig?.enabled) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Observational Memory is not enabled for this agent" });
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not configured for this agent" });
      }
      let memoryStore;
      try {
        memoryStore = await memory.storage.getStore("memory");
      } catch {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory storage is not initialized" });
      }
      if (!memoryStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory storage is not initialized" });
      }
      const effectiveResourceId = resourceId;
      if (!effectiveResourceId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "resourceId is required for observational memory lookup" });
      }
      const omThreadId = omConfig.scope === "resource" ? null : threadId ?? null;
      const record = await memoryStore.getObservationalMemory(omThreadId, effectiveResourceId);
      const history = await memoryStore.getObservationalMemoryHistory(
        omThreadId,
        effectiveResourceId,
        historyLimit,
        historyOptions
      );
      return {
        record: record ?? null,
        history: history.length > 0 ? history : void 0
      };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting observational memory");
    }
  }
});
var AWAIT_BUFFER_STATUS_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/observational-memory/buffer-status",
  responseType: "json",
  bodySchema: chunkCQNREK5Y_cjs.awaitBufferStatusBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.awaitBufferStatusResponseSchema,
  summary: "Await observational memory buffering completion",
  description: "Blocks until any in-flight buffering operations complete for the given thread/resource, then returns the updated record",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, resourceId, threadId, requestContext }) => {
    try {
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (!agent) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Agent not found" });
      }
      if (await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent)) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient && resourceId && threadId) {
          const maxWaitMs = 3e4;
          const pollIntervalMs = 1e3;
          const deadline = Date.now() + maxWaitMs;
          let record2 = null;
          while (Date.now() < deadline) {
            const result = await gwClient.getObservationRecord(threadId, resourceId);
            record2 = result.record ? chunkLFZO2LHV_cjs.toLocalOMRecord(result.record) : null;
            if (!record2 || !record2.isBufferingObservation && !record2.isBufferingReflection) {
              break;
            }
            await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
          }
          return { record: record2 };
        }
        return { record: null };
      }
      const omConfig = await getOMConfigFromAgent(agent, requestContext);
      if (!omConfig?.enabled) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Observational Memory is not enabled for this agent" });
      }
      const omProcessor = await agent.resolveProcessorById("observational-memory", requestContext);
      if (!omProcessor || typeof omProcessor.waitForBuffering !== "function") {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Observational Memory processor not available" });
      }
      await omProcessor.waitForBuffering(threadId, resourceId);
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not configured for this agent" });
      }
      let memoryStore;
      try {
        memoryStore = await memory.storage.getStore("memory");
      } catch {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory storage is not initialized" });
      }
      if (!memoryStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory storage is not initialized" });
      }
      const effectiveResourceId = resourceId;
      if (!effectiveResourceId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "resourceId is required" });
      }
      const omThreadId = omConfig.scope === "resource" ? null : threadId ?? null;
      const record = await memoryStore.getObservationalMemory(omThreadId, effectiveResourceId);
      return { record: record ?? null };
    } catch (error) {
      console.error("Error awaiting buffer status", error);
      return chunkB34S64RC_cjs.handleError(error, "Error awaiting buffer status");
    }
  }
});
var LIST_THREADS_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/threads",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.listThreadsQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.listThreadsResponseSchema,
  summary: "List memory threads",
  description: "Returns a paginated list of conversation threads with optional filtering by resource ID and/or metadata",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, resourceId, metadata, requestContext, page, perPage, orderBy }) => {
    try {
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      const isGateway = agent ? await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent) : false;
      if (agent && isGateway) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient) {
          const effectivePage = page ?? 0;
          const effectivePerPage = perPage ?? 100;
          const offset = effectivePage * effectivePerPage;
          const result = await gwClient.listThreads({
            resourceId: effectiveResourceId,
            limit: effectivePerPage,
            offset
          });
          return {
            threads: result.threads.map(chunkLFZO2LHV_cjs.toLocalThread),
            page: effectivePage,
            perPage: effectivePerPage,
            total: result.total,
            hasMore: offset + result.threads.length < result.total
          };
        }
      }
      const filter = effectiveResourceId || metadata ? {} : void 0;
      if (effectiveResourceId) {
        filter.resourceId = effectiveResourceId;
      }
      if (metadata) {
        filter.metadata = metadata;
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext, allowMissingAgent: true });
      if (memory) {
        const result = await memory.listThreads({
          filter,
          page,
          perPage,
          orderBy
        });
        return result;
      }
      const storage = getStorageFromContext({ mastra });
      if (storage) {
        const memoryStore = await storage.getStore("memory");
        if (memoryStore) {
          const result = await memoryStore.listThreads({
            filter,
            page,
            perPage,
            orderBy
          });
          return result;
        }
      }
      throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error listing threads");
    }
  }
});
var GET_THREAD_BY_ID_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/threads/:threadId",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.getThreadByIdQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.getThreadByIdResponseSchema,
  summary: "Get thread by ID",
  description: "Returns details for a specific conversation thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, threadId, resourceId, requestContext }) => {
    try {
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      chunkLWK57QIA_cjs.validateBody({ threadId: effectiveThreadId });
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      const isGateway = agent ? await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent) : false;
      if (agent && isGateway) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient) {
          const result = await gwClient.getThread(effectiveThreadId);
          if (!result) {
            return {
              id: effectiveThreadId,
              resourceId: effectiveResourceId ?? "",
              title: "",
              metadata: {},
              createdAt: /* @__PURE__ */ new Date(),
              updatedAt: /* @__PURE__ */ new Date()
            };
          }
          const thread = chunkLFZO2LHV_cjs.toLocalThread(result.thread);
          await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
          return thread;
        }
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext, allowMissingAgent: true });
      if (memory) {
        const thread = await memory.getThreadById({ threadId: effectiveThreadId });
        if (!thread) {
          throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
        }
        await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
        return thread;
      }
      const storage = getStorageFromContext({ mastra });
      if (storage) {
        const memoryStore = await storage.getStore("memory");
        if (memoryStore) {
          const thread = await memoryStore.getThreadById({ threadId: effectiveThreadId });
          if (!thread) {
            throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
          }
          await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
          return thread;
        }
      }
      throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting thread");
    }
  }
});
var LIST_MESSAGES_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/threads/:threadId/messages",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.listMessagesQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.listMessagesResponseSchema,
  summary: "List thread messages",
  description: "Returns a paginated list of messages in a conversation thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: (async ({
    mastra,
    agentId,
    threadId,
    resourceId,
    perPage,
    page,
    orderBy,
    include,
    filter,
    includeSystemReminders,
    requestContext
  }) => {
    try {
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      chunkLWK57QIA_cjs.validateBody({ threadId: effectiveThreadId });
      if (!effectiveThreadId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "No threadId found" });
      }
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (agent && await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent)) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient) {
          const threadResult = await gwClient.getThread(effectiveThreadId);
          if (threadResult) {
            await chunkLWK57QIA_cjs.validateThreadOwnership(chunkLFZO2LHV_cjs.toLocalThread(threadResult.thread), effectiveResourceId);
          }
          const effectivePage = page ?? 0;
          const effectivePerPage = perPage ?? 100;
          const offset = effectivePage * effectivePerPage;
          const result = await gwClient.listMessages(effectiveThreadId, {
            limit: effectivePerPage,
            offset,
            order: orderBy?.direction?.toLowerCase()
          });
          if (!result) {
            throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
          }
          return {
            messages: result.messages.map(chunkLFZO2LHV_cjs.toLocalMessage),
            uiMessages: result.messages.map(chunkLFZO2LHV_cjs.toLocalMessage)
          };
        }
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext, allowMissingAgent: true });
      if (memory) {
        const thread = await memory.getThreadById({ threadId: effectiveThreadId });
        if (!thread) {
          throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
        }
        await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
        const result = await memory.recall({
          threadId: effectiveThreadId,
          resourceId: effectiveResourceId,
          perPage,
          page,
          orderBy,
          include,
          filter,
          includeSystemReminders
        });
        return result;
      }
      const storage = getStorageFromContext({ mastra });
      if (storage) {
        const memoryStore = await storage.getStore("memory");
        if (memoryStore) {
          const thread = await memoryStore.getThreadById({ threadId: effectiveThreadId });
          if (!thread) {
            throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
          }
          await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
          const result = await memoryStore.listMessages({
            threadId: effectiveThreadId,
            resourceId: effectiveResourceId,
            perPage,
            page,
            orderBy,
            include,
            filter
          });
          return result;
        }
      }
      return { messages: [], uiMessages: [] };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting messages");
    }
  })
});
var GET_WORKING_MEMORY_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/threads/:threadId/working-memory",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.getWorkingMemoryQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.getWorkingMemoryResponseSchema,
  summary: "Get working memory",
  description: "Returns the working memory state for a thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, threadId, resourceId, requestContext, memoryConfig }) => {
    try {
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      chunkLWK57QIA_cjs.validateBody({ threadId: effectiveThreadId });
      const gwAgent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (gwAgent && await chunkLFZO2LHV_cjs.isGatewayAgentAsync(gwAgent) && chunkLFZO2LHV_cjs.getGatewayClient()) {
        return { workingMemory: null, source: "thread", workingMemoryTemplate: null, threadExists: true };
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext, allowMissingAgent: true });
      if (!memory) {
        return { workingMemory: null, source: "thread", workingMemoryTemplate: null, threadExists: false };
      }
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (thread) {
        await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
      }
      const threadExists = !!thread;
      const template = await memory.getWorkingMemoryTemplate({ memoryConfig });
      const workingMemoryTemplate = template?.format === "json" ? { ...template, content: JSON.stringify(utils.generateEmptyFromSchema(template.content)) } : template;
      const workingMemory = await memory.getWorkingMemory({
        threadId: effectiveThreadId,
        resourceId: effectiveResourceId,
        memoryConfig
      });
      const config = memory.getMergedThreadConfig(memoryConfig || {});
      const source = config.workingMemory?.scope !== "thread" && effectiveResourceId ? "resource" : "thread";
      return { workingMemory, source, workingMemoryTemplate, threadExists };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error getting working memory");
    }
  }
});
var SAVE_MESSAGES_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/save-messages",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.agentIdQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.saveMessagesBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.saveMessagesResponseSchema,
  summary: "Save messages",
  description: "Saves new messages to memory",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, messages, requestContext }) => {
    try {
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, void 0);
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
      }
      if (!messages) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Messages are required" });
      }
      if (!Array.isArray(messages)) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Messages should be an array" });
      }
      const invalidMessages = messages.filter((message) => !message.threadId || !message.resourceId);
      if (invalidMessages.length > 0) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: `All messages must have threadId and resourceId fields. Found ${invalidMessages.length} invalid message(s).`
        });
      }
      if (effectiveResourceId) {
        const unauthorizedMessages = messages.filter((message) => message.resourceId !== effectiveResourceId);
        if (unauthorizedMessages.length > 0) {
          throw new chunk64ITUOXI_cjs.HTTPException(403, {
            message: "Access denied: cannot save messages for a different resource"
          });
        }
        const threadIds = [...new Set(messages.map((m) => m.threadId).filter(Boolean))];
        for (const threadId of threadIds) {
          const thread = await memory.getThreadById({ threadId });
          await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
        }
      }
      const processedMessages = messages.map((message) => ({
        ...message,
        id: message.id || memory.generateId(),
        createdAt: message.createdAt ? new Date(message.createdAt) : /* @__PURE__ */ new Date()
      }));
      const result = await memory.saveMessages({ messages: processedMessages, memoryConfig: {} });
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error saving messages");
    }
  }
});
var CREATE_THREAD_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/threads",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.agentIdQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.createThreadBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.getThreadByIdResponseSchema,
  summary: "Create thread",
  description: "Creates a new conversation thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, resourceId, title, metadata, threadId, requestContext }) => {
    try {
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (agent && await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent)) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient) {
          chunkLWK57QIA_cjs.validateBody({ resourceId: effectiveResourceId });
          const result2 = await gwClient.createThread({
            id: threadId,
            resourceId: effectiveResourceId,
            title,
            metadata
          });
          return chunkLFZO2LHV_cjs.toLocalThread(result2.thread);
        }
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
      }
      chunkLWK57QIA_cjs.validateBody({ resourceId: effectiveResourceId });
      const result = await memory.createThread({
        resourceId: effectiveResourceId,
        title,
        metadata,
        threadId
      });
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error saving thread to memory");
    }
  }
});
var UPDATE_THREAD_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "PATCH",
  path: "/memory/threads/:threadId",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.agentIdQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.updateThreadBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.getThreadByIdResponseSchema,
  summary: "Update thread",
  description: "Updates a conversation thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, threadId, title, metadata, resourceId, requestContext }) => {
    try {
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      chunkLWK57QIA_cjs.validateBody({ threadId: effectiveThreadId });
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (agent && await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent)) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient) {
          const existing = await gwClient.getThread(effectiveThreadId);
          if (existing) {
            await chunkLWK57QIA_cjs.validateThreadOwnership(chunkLFZO2LHV_cjs.toLocalThread(existing.thread), effectiveResourceId);
          }
          const result2 = await gwClient.updateThread(effectiveThreadId, { title, metadata });
          if (!result2) {
            throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
          }
          return chunkLFZO2LHV_cjs.toLocalThread(result2.thread);
        }
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      const updatedAt = /* @__PURE__ */ new Date();
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
      }
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (!thread) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
      }
      await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
      const updatedThread = {
        ...thread,
        title: title || thread.title,
        metadata: metadata || thread.metadata,
        // Don't allow changing resourceId if effectiveResourceId is set (prevents reassigning threads)
        resourceId: effectiveResourceId || resourceId || thread.resourceId,
        createdAt: thread.createdAt,
        updatedAt
      };
      const result = await memory.saveThread({ thread: updatedThread });
      return {
        ...result,
        resourceId: result.resourceId ?? null
      };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error updating thread");
    }
  }
});
var DELETE_THREAD_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "DELETE",
  path: "/memory/threads/:threadId",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.deleteThreadQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.deleteThreadResponseSchema,
  summary: "Delete thread",
  description: "Deletes a conversation thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, threadId, resourceId, requestContext }) => {
    try {
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      chunkLWK57QIA_cjs.validateBody({ threadId: effectiveThreadId });
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (agent && await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent)) {
        const gwClient = chunkLFZO2LHV_cjs.getGatewayClient();
        if (gwClient) {
          const existing = await gwClient.getThread(effectiveThreadId);
          if (existing) {
            await chunkLWK57QIA_cjs.validateThreadOwnership(chunkLFZO2LHV_cjs.toLocalThread(existing.thread), effectiveResourceId);
          }
          const deleteResult = await gwClient.deleteThread(effectiveThreadId);
          if (!deleteResult.ok) {
            throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found on gateway" });
          }
          return { result: "Thread deleted" };
        }
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
      }
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (!thread) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
      }
      await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
      await memory.deleteThread(effectiveThreadId);
      return { result: "Thread deleted" };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error deleting thread");
    }
  }
});
var CLONE_THREAD_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/threads/:threadId/clone",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.agentIdQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.cloneThreadBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.cloneThreadResponseSchema,
  summary: "Clone thread",
  description: "Creates a copy of a conversation thread with all its messages",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, threadId, newThreadId, resourceId, title, metadata, options, requestContext }) => {
    try {
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      chunkLWK57QIA_cjs.validateBody({ threadId: effectiveThreadId });
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
      }
      const sourceThread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (!sourceThread) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Source thread not found" });
      }
      await chunkLWK57QIA_cjs.validateThreadOwnership(sourceThread, effectiveResourceId);
      const result = await memory.cloneThread({
        sourceThreadId: effectiveThreadId,
        newThreadId,
        // Use effective resourceId for the cloned thread
        resourceId: effectiveResourceId,
        title,
        metadata,
        options
      });
      return result;
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error cloning thread");
    }
  }
});
var UPDATE_WORKING_MEMORY_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/threads/:threadId/working-memory",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.agentIdQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.updateWorkingMemoryBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.updateWorkingMemoryResponseSchema,
  summary: "Update working memory",
  description: "Updates the working memory state for a thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, threadId, resourceId, memoryConfig, workingMemory, requestContext }) => {
    try {
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      chunkLWK57QIA_cjs.validateBody({ threadId: effectiveThreadId, workingMemory });
      const gwAgent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (gwAgent && await chunkLFZO2LHV_cjs.isGatewayAgentAsync(gwAgent) && chunkLFZO2LHV_cjs.getGatewayClient()) {
        return { success: true };
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
      }
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (!thread) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: "Thread not found" });
      }
      await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
      await memory.updateWorkingMemory({
        threadId: effectiveThreadId,
        resourceId: effectiveResourceId,
        workingMemory,
        memoryConfig
      });
      return { success: true };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error updating working memory");
    }
  }
});
var DELETE_MESSAGES_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/messages/delete",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.deleteMessagesQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.deleteMessagesBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.deleteMessagesResponseSchema,
  summary: "Delete messages",
  description: "Deletes specific messages from memory",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, resourceId, messageIds, requestContext }) => {
    try {
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      if (messageIds === void 0 || messageIds === null) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "messageIds is required" });
      }
      let normalizedIds;
      if (Array.isArray(messageIds)) {
        normalizedIds = messageIds;
      } else if (typeof messageIds === "string") {
        normalizedIds = [messageIds];
      } else {
        normalizedIds = [messageIds];
      }
      const stringIds = normalizedIds.map((id) => typeof id === "string" ? id : id.id);
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext, allowMissingAgent: true });
      if (effectiveResourceId && stringIds.length > 0) {
        const storage = memory?.storage || getStorageFromContext({ mastra });
        if (!storage) {
          throw new chunk64ITUOXI_cjs.HTTPException(403, { message: "Access denied: unable to verify message ownership" });
        }
        const memoryStore = await storage.getStore("memory");
        if (!memoryStore) {
          throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
        }
        const { messages } = await memoryStore.listMessagesById({ messageIds: stringIds });
        const threadIds = [...new Set(messages.map((m) => m.threadId).filter(Boolean))];
        for (const threadId of threadIds) {
          const thread = await memoryStore.getThreadById({ threadId });
          if (thread && thread.resourceId && thread.resourceId !== effectiveResourceId) {
            throw new chunk64ITUOXI_cjs.HTTPException(403, {
              message: "Access denied: message belongs to a thread owned by a different resource"
            });
          }
        }
      }
      if (memory) {
        await memory.deleteMessages(normalizedIds);
      } else {
        const storage = getStorageFromContext({ mastra });
        if (storage) {
          const memoryStore = await storage.getStore("memory");
          if (memoryStore) {
            await memoryStore.deleteMessages(stringIds);
          } else {
            throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
          }
        } else {
          throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
        }
      }
      const count = Array.isArray(messageIds) ? messageIds.length : 1;
      return { success: true, message: `${count} message${count === 1 ? "" : "s"} deleted successfully` };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error deleting messages");
    }
  }
});
var SEARCH_MEMORY_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/search",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.searchMemoryQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.searchMemoryResponseSchema,
  summary: "Search memory",
  description: "Searches across memory using semantic or text search",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, searchQuery, resourceId, threadId, limit = 20, requestContext, memoryConfig }) => {
    try {
      const effectiveResourceId = chunkLWK57QIA_cjs.getEffectiveResourceId(requestContext, resourceId);
      const effectiveThreadId = chunkLWK57QIA_cjs.getEffectiveThreadId(requestContext, threadId);
      chunkLWK57QIA_cjs.validateBody({ searchQuery, resourceId: effectiveResourceId });
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (agent && await chunkLFZO2LHV_cjs.isGatewayAgentAsync(agent) && chunkLFZO2LHV_cjs.getGatewayClient()) {
        return {
          results: [],
          count: 0,
          query: searchQuery,
          searchScope: "resource",
          searchType: "semantic"
        };
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, { message: "Memory is not initialized" });
      }
      const config = memory.getMergedThreadConfig(memoryConfig || {});
      const hasSemanticRecall = !!config?.semanticRecall;
      const resourceScope = typeof config?.semanticRecall === "object" ? config?.semanticRecall?.scope !== "thread" : true;
      const searchResults = [];
      if (effectiveThreadId && !resourceScope) {
        const thread = await memory.getThreadById({ threadId: effectiveThreadId });
        if (!thread) {
          return {
            results: [],
            count: 0,
            query: searchQuery,
            searchScope: resourceScope ? "resource" : "thread",
            searchType: hasSemanticRecall ? "semantic" : "text"
          };
        }
        await chunkLWK57QIA_cjs.validateThreadOwnership(thread, effectiveResourceId);
      }
      let searchThreadId = effectiveThreadId;
      if (!searchThreadId) {
        const { threads } = await memory.listThreads({
          filter: { resourceId: effectiveResourceId },
          page: 0,
          perPage: 1,
          orderBy: { field: "updatedAt", direction: "DESC" }
        });
        if (threads.length === 0) {
          return {
            results: [],
            count: 0,
            query: searchQuery,
            searchScope: resourceScope ? "resource" : "thread",
            searchType: hasSemanticRecall ? "semantic" : "text"
          };
        }
        searchThreadId = threads[0].id;
      }
      const beforeRange = typeof config.semanticRecall === `boolean` ? 2 : typeof config.semanticRecall?.messageRange === `number` ? config.semanticRecall.messageRange : config.semanticRecall?.messageRange.before || 2;
      const afterRange = typeof config.semanticRecall === `boolean` ? 2 : typeof config.semanticRecall?.messageRange === `number` ? config.semanticRecall.messageRange : config.semanticRecall?.messageRange.after || 2;
      if (resourceScope && config.semanticRecall) {
        config.semanticRecall = typeof config.semanticRecall === `boolean` ? (
          // make message range 0 so we can highlight the matches in search, message range will include other messages, not the matching ones
          // and we add prev/next messages in a special section on each message anyway
          { messageRange: 0, topK: 2, scope: "resource" }
        ) : { ...config.semanticRecall, messageRange: 0 };
      }
      const threadConfig = memory.getMergedThreadConfig(config || {});
      if (!threadConfig.lastMessages && !threadConfig.semanticRecall) {
        return { results: [], count: 0, query: searchQuery };
      }
      const result = await memory.recall({
        threadId: searchThreadId,
        resourceId: effectiveResourceId,
        perPage: threadConfig.lastMessages,
        threadConfig: config,
        vectorSearchString: threadConfig.semanticRecall && searchQuery ? searchQuery : void 0
      });
      const threadIds = Array.from(
        new Set(result.messages.map((m) => m.threadId || searchThreadId).filter(Boolean))
      );
      const fetched = await Promise.all(threadIds.map((id) => memory.getThreadById({ threadId: id })));
      const threadMap = new Map(fetched.filter(Boolean).map((t) => [t.id, t]));
      for (const msg of result.messages) {
        const content = getTextContent(msg);
        const msgThreadId = msg.threadId || searchThreadId;
        const thread = threadMap.get(msgThreadId);
        const threadMessages = (await memory.recall({ threadId: msgThreadId })).messages;
        const messageIndex = threadMessages.findIndex((m) => m.id === msg.id);
        const searchResult = {
          id: msg.id,
          role: msg.role,
          content,
          createdAt: msg.createdAt,
          threadId: msgThreadId,
          threadTitle: thread?.title || msgThreadId
        };
        if (messageIndex !== -1) {
          searchResult.context = {
            before: threadMessages.slice(Math.max(0, messageIndex - beforeRange), messageIndex).map((m) => ({
              id: m.id,
              role: m.role,
              content: getTextContent(m),
              createdAt: m.createdAt || /* @__PURE__ */ new Date()
            })),
            after: threadMessages.slice(messageIndex + 1, messageIndex + afterRange + 1).map((m) => ({
              id: m.id,
              role: m.role,
              content: getTextContent(m),
              createdAt: m.createdAt || /* @__PURE__ */ new Date()
            }))
          };
        }
        searchResults.push(searchResult);
      }
      const sortedResults = searchResults.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()).slice(0, limit);
      return {
        results: sortedResults,
        count: sortedResults.length,
        query: searchQuery,
        searchScope: resourceScope ? "resource" : "thread",
        searchType: hasSemanticRecall ? "semantic" : "text"
      };
    } catch (error) {
      return chunkB34S64RC_cjs.handleError(error, "Error searching memory");
    }
  }
});
var GET_MEMORY_STATUS_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/network/status",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.getMemoryStatusNetworkQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.memoryStatusResponseSchema,
  summary: "Get memory status (network)",
  description: "Returns the current status of the memory system (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: GET_MEMORY_STATUS_ROUTE.handler
});
var LIST_THREADS_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/network/threads",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.listThreadsNetworkQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.listThreadsResponseSchema,
  summary: "List memory threads (network)",
  description: "Returns a paginated list of conversation threads (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: LIST_THREADS_ROUTE.handler
});
var GET_THREAD_BY_ID_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/network/threads/:threadId",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.getThreadByIdNetworkQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.getThreadByIdResponseSchema,
  summary: "Get thread by ID (network)",
  description: "Returns details for a specific conversation thread (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: GET_THREAD_BY_ID_ROUTE.handler
});
var LIST_MESSAGES_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "GET",
  path: "/memory/network/threads/:threadId/messages",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.listMessagesNetworkQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.listMessagesResponseSchema,
  summary: "List thread messages (network)",
  description: "Returns a paginated list of messages in a conversation thread (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: LIST_MESSAGES_ROUTE.handler
});
var SAVE_MESSAGES_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/network/save-messages",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.saveMessagesNetworkQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.saveMessagesBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.saveMessagesResponseSchema,
  summary: "Save messages (network)",
  description: "Saves new messages to memory (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: SAVE_MESSAGES_ROUTE.handler
});
var CREATE_THREAD_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/network/threads",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.createThreadNetworkQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.createThreadBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.getThreadByIdResponseSchema,
  summary: "Create thread (network)",
  description: "Creates a new conversation thread (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: CREATE_THREAD_ROUTE.handler
});
var UPDATE_THREAD_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "PATCH",
  path: "/memory/network/threads/:threadId",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.updateThreadNetworkQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.updateThreadBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.getThreadByIdResponseSchema,
  summary: "Update thread (network)",
  description: "Updates a conversation thread (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: UPDATE_THREAD_ROUTE.handler
});
var DELETE_THREAD_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "DELETE",
  path: "/memory/network/threads/:threadId",
  responseType: "json",
  pathParamSchema: chunkCQNREK5Y_cjs.threadIdPathParams,
  queryParamSchema: chunkCQNREK5Y_cjs.deleteThreadNetworkQuerySchema,
  responseSchema: chunkCQNREK5Y_cjs.deleteThreadResponseSchema,
  summary: "Delete thread (network)",
  description: "Deletes a conversation thread (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: DELETE_THREAD_ROUTE.handler
});
var DELETE_MESSAGES_NETWORK_ROUTE = chunk5UKYK7YK_cjs.createRoute({
  method: "POST",
  path: "/memory/network/messages/delete",
  responseType: "json",
  queryParamSchema: chunkCQNREK5Y_cjs.deleteMessagesNetworkQuerySchema,
  bodySchema: chunkCQNREK5Y_cjs.deleteMessagesBodySchema,
  responseSchema: chunkCQNREK5Y_cjs.deleteMessagesResponseSchema,
  summary: "Delete messages (network)",
  description: "Deletes specific messages from memory (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: DELETE_MESSAGES_ROUTE.handler
});

exports.AWAIT_BUFFER_STATUS_ROUTE = AWAIT_BUFFER_STATUS_ROUTE;
exports.CLONE_THREAD_ROUTE = CLONE_THREAD_ROUTE;
exports.CREATE_THREAD_NETWORK_ROUTE = CREATE_THREAD_NETWORK_ROUTE;
exports.CREATE_THREAD_ROUTE = CREATE_THREAD_ROUTE;
exports.DELETE_MESSAGES_NETWORK_ROUTE = DELETE_MESSAGES_NETWORK_ROUTE;
exports.DELETE_MESSAGES_ROUTE = DELETE_MESSAGES_ROUTE;
exports.DELETE_THREAD_NETWORK_ROUTE = DELETE_THREAD_NETWORK_ROUTE;
exports.DELETE_THREAD_ROUTE = DELETE_THREAD_ROUTE;
exports.GET_MEMORY_CONFIG_ROUTE = GET_MEMORY_CONFIG_ROUTE;
exports.GET_MEMORY_STATUS_NETWORK_ROUTE = GET_MEMORY_STATUS_NETWORK_ROUTE;
exports.GET_MEMORY_STATUS_ROUTE = GET_MEMORY_STATUS_ROUTE;
exports.GET_OBSERVATIONAL_MEMORY_ROUTE = GET_OBSERVATIONAL_MEMORY_ROUTE;
exports.GET_THREAD_BY_ID_NETWORK_ROUTE = GET_THREAD_BY_ID_NETWORK_ROUTE;
exports.GET_THREAD_BY_ID_ROUTE = GET_THREAD_BY_ID_ROUTE;
exports.GET_WORKING_MEMORY_ROUTE = GET_WORKING_MEMORY_ROUTE;
exports.LIST_MESSAGES_NETWORK_ROUTE = LIST_MESSAGES_NETWORK_ROUTE;
exports.LIST_MESSAGES_ROUTE = LIST_MESSAGES_ROUTE;
exports.LIST_THREADS_NETWORK_ROUTE = LIST_THREADS_NETWORK_ROUTE;
exports.LIST_THREADS_ROUTE = LIST_THREADS_ROUTE;
exports.SAVE_MESSAGES_NETWORK_ROUTE = SAVE_MESSAGES_NETWORK_ROUTE;
exports.SAVE_MESSAGES_ROUTE = SAVE_MESSAGES_ROUTE;
exports.SEARCH_MEMORY_ROUTE = SEARCH_MEMORY_ROUTE;
exports.UPDATE_THREAD_NETWORK_ROUTE = UPDATE_THREAD_NETWORK_ROUTE;
exports.UPDATE_THREAD_ROUTE = UPDATE_THREAD_ROUTE;
exports.UPDATE_WORKING_MEMORY_ROUTE = UPDATE_WORKING_MEMORY_ROUTE;
exports.getTextContent = getTextContent;
exports.memory_exports = memory_exports;
//# sourceMappingURL=chunk-JOC7WKJ2.cjs.map
//# sourceMappingURL=chunk-JOC7WKJ2.cjs.map