import { getEffectiveResourceId, getEffectiveThreadId, validateBody, validateThreadOwnership } from './chunk-USR6JK77.js';
import { createPagePaginationSchema, paginationInfoSchema, successResponseSchema } from './chunk-HT4LP3BO.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-OQ5GQJAS.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { generateEmptyFromSchema } from '@mastra/core/utils';
import z from 'zod';

// src/server/handlers/memory.ts
var memory_exports = {};
__export(memory_exports, {
  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_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
});
var threadIdPathParams = z.object({
  threadId: z.string().describe("Unique identifier for the conversation thread")
});
var agentIdQuerySchema = z.object({
  agentId: z.string()
});
var optionalAgentIdQuerySchema = z.object({
  agentId: z.string().optional()
});
var storageOrderBySchema = z.preprocess(
  (val) => {
    if (typeof val === "string") {
      try {
        return JSON.parse(val);
      } catch {
        return void 0;
      }
    }
    return val;
  },
  z.object({
    field: z.enum(["createdAt", "updatedAt"]).optional(),
    direction: z.enum(["ASC", "DESC"]).optional()
  }).optional()
);
var messageOrderBySchema = z.preprocess(
  (val) => {
    if (typeof val === "string") {
      try {
        return JSON.parse(val);
      } catch {
        return void 0;
      }
    }
    return val;
  },
  z.object({
    field: z.enum(["createdAt"]).optional(),
    direction: z.enum(["ASC", "DESC"]).optional()
  }).optional()
);
var includeSchema = z.preprocess(
  (val) => {
    if (typeof val === "string") {
      try {
        return JSON.parse(val);
      } catch {
        return val;
      }
    }
    return val;
  },
  z.array(
    z.object({
      id: z.string(),
      threadId: z.string().optional(),
      withPreviousMessages: z.number().optional(),
      withNextMessages: z.number().optional()
    })
  ).optional()
);
var filterSchema = z.preprocess(
  (val) => {
    if (typeof val === "string") {
      try {
        return JSON.parse(val);
      } catch {
        return val;
      }
    }
    return val;
  },
  z.object({
    dateRange: z.object({
      start: z.coerce.date().optional(),
      end: z.coerce.date().optional()
    }).optional(),
    roles: z.array(z.string()).optional()
  }).optional()
);
var memoryConfigSchema = z.preprocess((val) => {
  if (typeof val === "string") {
    try {
      return JSON.parse(val);
    } catch {
      return val;
    }
  }
  return val;
}, z.record(z.string(), z.unknown()).optional());
var threadSchema = z.object({
  id: z.string(),
  title: z.string().optional(),
  resourceId: z.string(),
  createdAt: z.date(),
  updatedAt: z.date(),
  metadata: z.record(z.string(), z.unknown()).optional()
});
var messageSchema = z.any();
var getMemoryStatusQuerySchema = agentIdQuerySchema;
var getMemoryConfigQuerySchema = agentIdQuerySchema;
var listThreadsQuerySchema = createPagePaginationSchema(100).extend({
  agentId: z.string().optional(),
  resourceId: z.string().optional(),
  metadata: z.preprocess(
    (val) => {
      if (typeof val === "string") {
        try {
          return JSON.parse(val);
        } catch {
          return val;
        }
      }
      return val;
    },
    z.optional(z.record(z.string(), z.any()))
  ),
  orderBy: storageOrderBySchema
});
var getThreadByIdQuerySchema = optionalAgentIdQuerySchema.extend({
  resourceId: z.string().optional()
});
var listMessagesQuerySchema = createPagePaginationSchema(40).extend({
  agentId: z.string().optional(),
  resourceId: z.string().optional(),
  orderBy: messageOrderBySchema,
  include: includeSchema,
  filter: filterSchema
});
var getWorkingMemoryQuerySchema = z.object({
  agentId: z.string(),
  resourceId: z.string().optional(),
  memoryConfig: memoryConfigSchema
});
var deleteThreadQuerySchema = agentIdQuerySchema.extend({
  resourceId: z.string().optional()
});
var deleteMessagesQuerySchema = agentIdQuerySchema.extend({
  resourceId: z.string().optional()
});
var getMemoryStatusNetworkQuerySchema = agentIdQuerySchema;
var listThreadsNetworkQuerySchema = createPagePaginationSchema(100).extend({
  agentId: z.string().optional(),
  resourceId: z.string().optional(),
  metadata: z.preprocess(
    (val) => {
      if (typeof val === "string") {
        try {
          return JSON.parse(val);
        } catch {
          return val;
        }
      }
      return val;
    },
    z.optional(z.record(z.string(), z.any()))
  ),
  orderBy: storageOrderBySchema
});
var getThreadByIdNetworkQuerySchema = optionalAgentIdQuerySchema.extend({
  resourceId: z.string().optional()
});
var listMessagesNetworkQuerySchema = createPagePaginationSchema(40).extend({
  agentId: z.string().optional(),
  resourceId: z.string().optional(),
  orderBy: messageOrderBySchema,
  include: includeSchema,
  filter: filterSchema
});
var saveMessagesNetworkQuerySchema = agentIdQuerySchema;
var createThreadNetworkQuerySchema = agentIdQuerySchema;
var updateThreadNetworkQuerySchema = agentIdQuerySchema;
var deleteThreadNetworkQuerySchema = agentIdQuerySchema.extend({
  resourceId: z.string().optional()
});
var deleteMessagesNetworkQuerySchema = agentIdQuerySchema.extend({
  resourceId: z.string().optional()
});
var memoryStatusResponseSchema = z.object({
  result: z.boolean()
});
var memoryConfigResponseSchema = z.object({
  config: z.object({
    lastMessages: z.union([z.number(), z.literal(false)]).optional(),
    semanticRecall: z.union([z.boolean(), z.any()]).optional(),
    workingMemory: z.any().optional()
  })
});
var listThreadsResponseSchema = paginationInfoSchema.extend({
  threads: z.array(threadSchema)
});
var getThreadByIdResponseSchema = threadSchema;
var listMessagesResponseSchema = z.object({
  messages: z.array(messageSchema),
  uiMessages: z.unknown()
  // Converted messages in UI format
});
var getWorkingMemoryResponseSchema = z.object({
  workingMemory: z.unknown(),
  // Can be string or structured object depending on template
  source: z.enum(["thread", "resource"]),
  workingMemoryTemplate: z.unknown(),
  // Template structure varies
  threadExists: z.boolean()
});
var saveMessagesBodySchema = z.object({
  messages: z.array(messageSchema)
});
var createThreadBodySchema = z.object({
  resourceId: z.string(),
  title: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional(),
  threadId: z.string().optional()
});
var updateThreadBodySchema = z.object({
  title: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional(),
  resourceId: z.string().optional()
});
var updateWorkingMemoryBodySchema = z.object({
  workingMemory: z.string(),
  resourceId: z.string().optional(),
  memoryConfig: z.record(z.string(), z.unknown()).optional()
});
var deleteMessagesBodySchema = z.object({
  messageIds: z.union([
    z.string(),
    z.array(z.string()),
    z.object({ id: z.string() }),
    z.array(z.object({ id: z.string() }))
  ])
});
var searchMemoryQuerySchema = z.object({
  agentId: z.string(),
  searchQuery: z.string(),
  resourceId: z.string(),
  threadId: z.string().optional(),
  limit: z.coerce.number().optional().default(20),
  memoryConfig: memoryConfigSchema
});
var saveMessagesResponseSchema = z.object({
  messages: z.array(messageSchema)
});
var deleteThreadResponseSchema = z.object({
  result: z.string()
});
var updateWorkingMemoryResponseSchema = successResponseSchema;
var deleteMessagesResponseSchema = successResponseSchema.extend({
  message: z.string()
});
var searchMemoryResponseSchema = z.object({
  results: z.array(z.unknown()),
  count: z.number(),
  query: z.string(),
  searchScope: z.string().optional(),
  searchType: z.string().optional()
});
var cloneThreadBodySchema = z.object({
  newThreadId: z.string().optional(),
  resourceId: z.string().optional(),
  title: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional(),
  options: z.object({
    messageLimit: z.number().optional(),
    messageFilter: z.object({
      startDate: z.coerce.date().optional(),
      endDate: z.coerce.date().optional(),
      messageIds: z.array(z.string()).optional()
    }).optional()
  }).optional()
});
var cloneThreadResponseSchema = z.object({
  thread: threadSchema,
  clonedMessages: z.array(messageSchema)
});

// src/server/handlers/memory.ts
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
}) {
  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.getStoredAgentById(agentId);
      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) {
      throw new HTTPException(404, { message: "Agent not found" });
    }
  }
  if (agent) {
    return await agent?.getMemory({
      requestContext
    });
  }
}
function getStorageFromContext({ mastra }) {
  return mastra.getStorage();
}
var GET_MEMORY_STATUS_ROUTE = createRoute({
  method: "GET",
  path: "/memory/status",
  responseType: "json",
  queryParamSchema: getMemoryStatusQuerySchema,
  responseSchema: 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, requestContext }) => {
    try {
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (memory) {
        return { result: true };
      }
      if (!agentId) {
        const storage = getStorageFromContext({ mastra });
        if (storage) {
          return { result: true };
        }
      }
      return { result: false };
    } catch (error) {
      return handleError(error, "Error getting memory status");
    }
  }
});
var GET_MEMORY_CONFIG_ROUTE = createRoute({
  method: "GET",
  path: "/memory/config",
  responseType: "json",
  queryParamSchema: getMemoryConfigQuerySchema,
  responseSchema: 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 memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not initialized" });
      }
      const config = memory.getMergedThreadConfig({});
      return { config };
    } catch (error) {
      return handleError(error, "Error getting memory configuration");
    }
  }
});
var LIST_THREADS_ROUTE = createRoute({
  method: "GET",
  path: "/memory/threads",
  responseType: "json",
  queryParamSchema: listThreadsQuerySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, resourceId);
      const filter = effectiveResourceId || metadata ? {} : void 0;
      if (effectiveResourceId) {
        filter.resourceId = effectiveResourceId;
      }
      if (metadata) {
        filter.metadata = metadata;
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (memory) {
        const result = await memory.listThreads({
          filter,
          page,
          perPage,
          orderBy
        });
        return result;
      }
      if (!agentId) {
        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 HTTPException(400, { message: "Memory is not initialized" });
    } catch (error) {
      return handleError(error, "Error listing threads");
    }
  }
});
var GET_THREAD_BY_ID_ROUTE = createRoute({
  method: "GET",
  path: "/memory/threads/:threadId",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: getThreadByIdQuerySchema,
  responseSchema: 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 = getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
      validateBody({ threadId: effectiveThreadId });
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (memory) {
        const thread = await memory.getThreadById({ threadId: effectiveThreadId });
        if (!thread) {
          throw new HTTPException(404, { message: "Thread not found" });
        }
        await validateThreadOwnership(thread, effectiveResourceId);
        return thread;
      }
      if (!agentId) {
        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 HTTPException(404, { message: "Thread not found" });
            }
            await validateThreadOwnership(thread, effectiveResourceId);
            return thread;
          }
        }
      }
      throw new HTTPException(400, { message: "Memory is not initialized" });
    } catch (error) {
      return handleError(error, "Error getting thread");
    }
  }
});
var LIST_MESSAGES_ROUTE = createRoute({
  method: "GET",
  path: "/memory/threads/:threadId/messages",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: listMessagesQuerySchema,
  responseSchema: 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,
    requestContext
  }) => {
    try {
      const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
      validateBody({ threadId: effectiveThreadId });
      if (!effectiveThreadId) {
        throw new HTTPException(400, { message: "No threadId found" });
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (memory) {
        const thread = await memory.getThreadById({ threadId: effectiveThreadId });
        if (!thread) {
          throw new HTTPException(404, { message: "Thread not found" });
        }
        await validateThreadOwnership(thread, effectiveResourceId);
        const result = await memory.recall({
          threadId: effectiveThreadId,
          resourceId: effectiveResourceId,
          perPage,
          page,
          orderBy,
          include,
          filter
        });
        return result;
      }
      if (!agentId) {
        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 HTTPException(404, { message: "Thread not found" });
            }
            await 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 handleError(error, "Error getting messages");
    }
  }
});
var GET_WORKING_MEMORY_ROUTE = createRoute({
  method: "GET",
  path: "/memory/threads/:threadId/working-memory",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: getWorkingMemoryQuerySchema,
  responseSchema: 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 = getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      validateBody({ threadId: effectiveThreadId });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not initialized" });
      }
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (thread) {
        await validateThreadOwnership(thread, effectiveResourceId);
      }
      const threadExists = !!thread;
      const template = await memory.getWorkingMemoryTemplate({ memoryConfig });
      const workingMemoryTemplate = template?.format === "json" ? { ...template, content: JSON.stringify(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 handleError(error, "Error getting working memory");
    }
  }
});
var SAVE_MESSAGES_ROUTE = createRoute({
  method: "POST",
  path: "/memory/save-messages",
  responseType: "json",
  queryParamSchema: agentIdQuerySchema,
  bodySchema: saveMessagesBodySchema,
  responseSchema: saveMessagesResponseSchema,
  summary: "Save messages",
  description: "Saves new messages to memory",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, messages, requestContext }) => {
    try {
      const effectiveResourceId = getEffectiveResourceId(requestContext, void 0);
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not initialized" });
      }
      if (!messages) {
        throw new HTTPException(400, { message: "Messages are required" });
      }
      if (!Array.isArray(messages)) {
        throw new HTTPException(400, { message: "Messages should be an array" });
      }
      const invalidMessages = messages.filter((message) => !message.threadId || !message.resourceId);
      if (invalidMessages.length > 0) {
        throw new 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 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 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 handleError(error, "Error saving messages");
    }
  }
});
var CREATE_THREAD_ROUTE = createRoute({
  method: "POST",
  path: "/memory/threads",
  responseType: "json",
  queryParamSchema: agentIdQuerySchema,
  bodySchema: createThreadBodySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, resourceId);
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not initialized" });
      }
      validateBody({ resourceId: effectiveResourceId });
      const result = await memory.createThread({
        resourceId: effectiveResourceId,
        title,
        metadata,
        threadId
      });
      return result;
    } catch (error) {
      return handleError(error, "Error saving thread to memory");
    }
  }
});
var UPDATE_THREAD_ROUTE = createRoute({
  method: "PATCH",
  path: "/memory/threads/:threadId",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: agentIdQuerySchema,
  bodySchema: updateThreadBodySchema,
  responseSchema: 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 = getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      const updatedAt = /* @__PURE__ */ new Date();
      validateBody({ threadId: effectiveThreadId });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not initialized" });
      }
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (!thread) {
        throw new HTTPException(404, { message: "Thread not found" });
      }
      await 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 handleError(error, "Error updating thread");
    }
  }
});
var DELETE_THREAD_ROUTE = createRoute({
  method: "DELETE",
  path: "/memory/threads/:threadId",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: deleteThreadQuerySchema,
  responseSchema: deleteThreadResponseSchema,
  summary: "Delete thread",
  description: "Deletes a conversation thread",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, threadId, resourceId, requestContext }) => {
    try {
      const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
      validateBody({ threadId: effectiveThreadId });
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not initialized" });
      }
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (!thread) {
        throw new HTTPException(404, { message: "Thread not found" });
      }
      await validateThreadOwnership(thread, effectiveResourceId);
      await memory.deleteThread(effectiveThreadId);
      return { result: "Thread deleted" };
    } catch (error) {
      return handleError(error, "Error deleting thread");
    }
  }
});
var CLONE_THREAD_ROUTE = createRoute({
  method: "POST",
  path: "/memory/threads/:threadId/clone",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: agentIdQuerySchema,
  bodySchema: cloneThreadBodySchema,
  responseSchema: 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 = getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
      validateBody({ threadId: effectiveThreadId });
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not initialized" });
      }
      const sourceThread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (!sourceThread) {
        throw new HTTPException(404, { message: "Source thread not found" });
      }
      await 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 handleError(error, "Error cloning thread");
    }
  }
});
var UPDATE_WORKING_MEMORY_ROUTE = createRoute({
  method: "POST",
  path: "/memory/threads/:threadId/working-memory",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: agentIdQuerySchema,
  bodySchema: updateWorkingMemoryBodySchema,
  responseSchema: 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 = getEffectiveThreadId(requestContext, threadId);
      const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
      validateBody({ threadId: effectiveThreadId, workingMemory });
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not initialized" });
      }
      const thread = await memory.getThreadById({ threadId: effectiveThreadId });
      if (!thread) {
        throw new HTTPException(404, { message: "Thread not found" });
      }
      await validateThreadOwnership(thread, effectiveResourceId);
      await memory.updateWorkingMemory({
        threadId: effectiveThreadId,
        resourceId: effectiveResourceId,
        workingMemory,
        memoryConfig
      });
      return { success: true };
    } catch (error) {
      return handleError(error, "Error updating working memory");
    }
  }
});
var DELETE_MESSAGES_ROUTE = createRoute({
  method: "POST",
  path: "/memory/messages/delete",
  responseType: "json",
  queryParamSchema: deleteMessagesQuerySchema,
  bodySchema: deleteMessagesBodySchema,
  responseSchema: deleteMessagesResponseSchema,
  summary: "Delete messages",
  description: "Deletes specific messages from memory",
  tags: ["Memory"],
  requiresAuth: true,
  handler: async ({ mastra, agentId, resourceId, messageIds, requestContext }) => {
    try {
      const effectiveResourceId = getEffectiveResourceId(requestContext, resourceId);
      if (messageIds === void 0 || messageIds === null) {
        throw new 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 });
      if (effectiveResourceId && stringIds.length > 0) {
        const storage = memory?.storage || getStorageFromContext({ mastra });
        if (!storage) {
          throw new HTTPException(403, { message: "Access denied: unable to verify message ownership" });
        }
        const memoryStore = await storage.getStore("memory");
        if (!memoryStore) {
          throw new 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 HTTPException(403, {
              message: "Access denied: message belongs to a thread owned by a different resource"
            });
          }
        }
      }
      if (memory) {
        await memory.deleteMessages(normalizedIds);
      } else if (!agentId) {
        const storage = getStorageFromContext({ mastra });
        if (storage) {
          const memoryStore = await storage.getStore("memory");
          if (memoryStore) {
            await memoryStore.deleteMessages(stringIds);
          } else {
            throw new HTTPException(400, { message: "Memory is not initialized" });
          }
        } else {
          throw new HTTPException(400, { message: "Memory is not initialized" });
        }
      } else {
        throw new 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 handleError(error, "Error deleting messages");
    }
  }
});
var SEARCH_MEMORY_ROUTE = createRoute({
  method: "GET",
  path: "/memory/search",
  responseType: "json",
  queryParamSchema: searchMemoryQuerySchema,
  responseSchema: 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 = getEffectiveResourceId(requestContext, resourceId);
      const effectiveThreadId = getEffectiveThreadId(requestContext, threadId);
      validateBody({ searchQuery, resourceId: effectiveResourceId });
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new 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 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 handleError(error, "Error searching memory");
    }
  }
});
var GET_MEMORY_STATUS_NETWORK_ROUTE = createRoute({
  method: "GET",
  path: "/memory/network/status",
  responseType: "json",
  queryParamSchema: getMemoryStatusNetworkQuerySchema,
  responseSchema: 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 = createRoute({
  method: "GET",
  path: "/memory/network/threads",
  responseType: "json",
  queryParamSchema: listThreadsNetworkQuerySchema,
  responseSchema: 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 = createRoute({
  method: "GET",
  path: "/memory/network/threads/:threadId",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: getThreadByIdNetworkQuerySchema,
  responseSchema: 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 = createRoute({
  method: "GET",
  path: "/memory/network/threads/:threadId/messages",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: listMessagesNetworkQuerySchema,
  responseSchema: 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 = createRoute({
  method: "POST",
  path: "/memory/network/save-messages",
  responseType: "json",
  queryParamSchema: saveMessagesNetworkQuerySchema,
  bodySchema: saveMessagesBodySchema,
  responseSchema: 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 = createRoute({
  method: "POST",
  path: "/memory/network/threads",
  responseType: "json",
  queryParamSchema: createThreadNetworkQuerySchema,
  bodySchema: createThreadBodySchema,
  responseSchema: 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 = createRoute({
  method: "PATCH",
  path: "/memory/network/threads/:threadId",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: updateThreadNetworkQuerySchema,
  bodySchema: updateThreadBodySchema,
  responseSchema: 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 = createRoute({
  method: "DELETE",
  path: "/memory/network/threads/:threadId",
  responseType: "json",
  pathParamSchema: threadIdPathParams,
  queryParamSchema: deleteThreadNetworkQuerySchema,
  responseSchema: 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 = createRoute({
  method: "POST",
  path: "/memory/network/messages/delete",
  responseType: "json",
  queryParamSchema: deleteMessagesNetworkQuerySchema,
  bodySchema: deleteMessagesBodySchema,
  responseSchema: deleteMessagesResponseSchema,
  summary: "Delete messages (network)",
  description: "Deletes specific messages from memory (network route)",
  tags: ["Memory - Network"],
  requiresAuth: true,
  handler: DELETE_MESSAGES_ROUTE.handler
});

export { CLONE_THREAD_ROUTE, CREATE_THREAD_NETWORK_ROUTE, CREATE_THREAD_ROUTE, DELETE_MESSAGES_NETWORK_ROUTE, DELETE_MESSAGES_ROUTE, DELETE_THREAD_NETWORK_ROUTE, DELETE_THREAD_ROUTE, GET_MEMORY_CONFIG_ROUTE, GET_MEMORY_STATUS_NETWORK_ROUTE, GET_MEMORY_STATUS_ROUTE, GET_THREAD_BY_ID_NETWORK_ROUTE, GET_THREAD_BY_ID_ROUTE, GET_WORKING_MEMORY_ROUTE, LIST_MESSAGES_NETWORK_ROUTE, LIST_MESSAGES_ROUTE, LIST_THREADS_NETWORK_ROUTE, LIST_THREADS_ROUTE, SAVE_MESSAGES_NETWORK_ROUTE, SAVE_MESSAGES_ROUTE, SEARCH_MEMORY_ROUTE, UPDATE_THREAD_NETWORK_ROUTE, UPDATE_THREAD_ROUTE, UPDATE_WORKING_MEMORY_ROUTE, getTextContent, memory_exports };
//# sourceMappingURL=chunk-LU2HDW7X.js.map
//# sourceMappingURL=chunk-LU2HDW7X.js.map