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-D5VCL56B.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, {
  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
});
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.extend({
  resourceId: z.string().optional(),
  threadId: z.string().optional()
});
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(),
  observationalMemory: z.object({
    enabled: z.boolean(),
    hasRecord: z.boolean().optional(),
    originType: z.string().optional(),
    lastObservedAt: z.date().optional(),
    tokenCount: z.number().optional(),
    observationTokenCount: z.number().optional(),
    isObserving: z.boolean().optional(),
    isReflecting: z.boolean().optional()
  }).optional()
});
var observationalMemoryConfigSchema = z.object({
  enabled: z.boolean(),
  scope: z.enum(["thread", "resource"]).optional(),
  shareTokenBudget: z.boolean().optional(),
  messageTokens: z.union([z.number(), z.object({ min: z.number(), max: z.number() })]).optional(),
  observationTokens: z.union([z.number(), z.object({ min: z.number(), max: z.number() })]).optional(),
  observationModel: z.string().optional(),
  reflectionModel: z.string().optional()
});
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(),
    observationalMemory: observationalMemoryConfigSchema.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)
});
var getObservationalMemoryQuerySchema = z.object({
  agentId: z.string(),
  resourceId: z.string().optional(),
  threadId: z.string().optional()
});
var observationalMemoryRecordSchema = z.object({
  id: z.string(),
  scope: z.enum(["thread", "resource"]),
  resourceId: z.string(),
  threadId: z.string().nullable(),
  activeObservations: z.string(),
  bufferedObservations: z.string().optional(),
  bufferedReflection: z.string().optional(),
  originType: z.enum(["initial", "observation", "reflection"]),
  generationCount: z.number(),
  lastObservedAt: z.date().optional(),
  totalTokensObserved: z.number(),
  observationTokenCount: z.number(),
  pendingMessageTokens: z.number(),
  isObserving: z.boolean(),
  isReflecting: z.boolean(),
  config: z.record(z.string(), z.unknown()),
  metadata: z.record(z.string(), z.unknown()).optional(),
  createdAt: z.date(),
  updatedAt: z.date()
});
var getObservationalMemoryResponseSchema = z.object({
  record: observationalMemoryRecordSchema.nullable(),
  history: z.array(observationalMemoryRecordSchema).optional()
});
var awaitBufferStatusBodySchema = z.object({
  agentId: z.string(),
  resourceId: z.string().optional(),
  threadId: z.string().optional()
});
var awaitBufferStatusResponseSchema = z.object({
  record: observationalMemoryRecordSchema.nullable()
});

// 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.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) {
      throw new 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
      };
    }
    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
    };
  } 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 = 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, resourceId, threadId, requestContext }) => {
    try {
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (memory) {
        const agent = await getAgentFromContext({ mastra, agentId, requestContext });
        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, observationalMemory: omStatus };
      }
      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({});
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      let omConfig;
      if (agent) {
        omConfig = await getOMConfigFromAgent(agent, requestContext) ?? { enabled: false };
      }
      return {
        config: {
          ...config,
          observationalMemory: omConfig
        }
      };
    } catch (error) {
      return handleError(error, "Error getting memory configuration");
    }
  }
});
var GET_OBSERVATIONAL_MEMORY_ROUTE = createRoute({
  method: "GET",
  path: "/memory/observational-memory",
  responseType: "json",
  queryParamSchema: getObservationalMemoryQuerySchema,
  responseSchema: 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, requestContext }) => {
    try {
      const agent = await getAgentFromContext({ mastra, agentId, requestContext });
      if (!agent) {
        throw new HTTPException(404, { message: "Agent not found" });
      }
      const omConfig = await getOMConfigFromAgent(agent, requestContext);
      if (!omConfig?.enabled) {
        throw new HTTPException(400, { message: "Observational Memory is not enabled for this agent" });
      }
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not configured for this agent" });
      }
      let memoryStore;
      try {
        memoryStore = await memory.storage.getStore("memory");
      } catch {
        throw new HTTPException(400, { message: "Memory storage is not initialized" });
      }
      if (!memoryStore) {
        throw new HTTPException(400, { message: "Memory storage is not initialized" });
      }
      const effectiveResourceId = resourceId;
      if (!effectiveResourceId) {
        throw new 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, 5);
      return {
        record: record ?? null,
        history: history.length > 0 ? history : void 0
      };
    } catch (error) {
      return handleError(error, "Error getting observational memory");
    }
  }
});
var AWAIT_BUFFER_STATUS_ROUTE = createRoute({
  method: "POST",
  path: "/memory/observational-memory/buffer-status",
  responseType: "json",
  bodySchema: awaitBufferStatusBodySchema,
  responseSchema: 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 HTTPException(404, { message: "Agent not found" });
      }
      const omConfig = await getOMConfigFromAgent(agent, requestContext);
      if (!omConfig?.enabled) {
        throw new 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 HTTPException(400, { message: "Observational Memory processor not available" });
      }
      await omProcessor.waitForBuffering(threadId, resourceId);
      const memory = await getMemoryFromContext({ mastra, agentId, requestContext });
      if (!memory) {
        throw new HTTPException(400, { message: "Memory is not configured for this agent" });
      }
      let memoryStore;
      try {
        memoryStore = await memory.storage.getStore("memory");
      } catch {
        throw new HTTPException(400, { message: "Memory storage is not initialized" });
      }
      if (!memoryStore) {
        throw new HTTPException(400, { message: "Memory storage is not initialized" });
      }
      const effectiveResourceId = resourceId;
      if (!effectiveResourceId) {
        throw new 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 handleError(error, "Error awaiting buffer status");
    }
  }
});
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 { AWAIT_BUFFER_STATUS_ROUTE, 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_OBSERVATIONAL_MEMORY_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-LHKI5QFK.js.map
//# sourceMappingURL=chunk-LHKI5QFK.js.map