import {
  collapseWhitespace,
  truncateCodePointSafe
} from "./chunk-6MKAMLQL.js";
import {
  canReadNamespace,
  defaultNamespaceForPrincipal,
  resolvePrincipal
} from "./chunk-N5AKDXAI.js";

// src/active-memory-bridge.ts
function isArtifactPath(value) {
  return typeof value === "string" && /(?:^|[\\/])artifacts(?:[\\/]|$)/i.test(value);
}
function clampLimit(value) {
  if (typeof value !== "number" || !Number.isFinite(value)) return 8;
  return Math.max(1, Math.min(50, Math.floor(value)));
}
function truncateSnippet(value, maxChars) {
  const compact = collapseWhitespace(value);
  return truncateCodePointSafe(compact, maxChars);
}
function pickMetadata(value) {
  if (!value) return void 0;
  const metadata = {};
  if (typeof value.type === "string") metadata.type = value.type;
  if (typeof value.topic === "string") metadata.topic = value.topic;
  if (typeof value.updatedAt === "string") metadata.updatedAt = value.updatedAt;
  if (typeof value.sourceUri === "string") metadata.sourceUri = value.sourceUri;
  return Object.keys(metadata).length > 0 ? metadata : void 0;
}
function resolveActiveMemoryNamespace(orchestrator, sessionKey, requestedNamespace) {
  const explicitNamespace = typeof requestedNamespace === "string" && requestedNamespace.trim().length > 0 ? requestedNamespace.trim() : void 0;
  const config = orchestrator.config;
  if (config?.namespacesEnabled === false) {
    if (typeof orchestrator.resolveSelfNamespace === "function") {
      return orchestrator.resolveSelfNamespace(sessionKey);
    }
    return "default";
  }
  if (!config) {
    if (explicitNamespace) return explicitNamespace;
    if (typeof orchestrator.resolveSelfNamespace === "function") {
      return orchestrator.resolveSelfNamespace(sessionKey);
    }
    return "default";
  }
  const principal = typeof orchestrator.resolvePrincipal === "function" ? orchestrator.resolvePrincipal(sessionKey) : resolvePrincipal(sessionKey, config);
  if (explicitNamespace) {
    if (!canReadNamespace(principal, explicitNamespace, config)) {
      throw new Error(`namespace ${explicitNamespace} is not readable for principal ${principal}`);
    }
    return explicitNamespace;
  }
  if (typeof orchestrator.resolveSelfNamespace === "function") {
    return orchestrator.resolveSelfNamespace(sessionKey);
  }
  return defaultNamespaceForPrincipal(principal, config);
}
async function recallForActiveMemory(orchestrator, params) {
  const limit = clampLimit(params.limit);
  const requestedResults = Math.min(200, limit + 20);
  const snippetMaxChars = typeof params.snippetMaxChars === "number" && Number.isFinite(params.snippetMaxChars) ? Math.max(1, Math.min(4e3, Math.floor(params.snippetMaxChars))) : 600;
  const namespace = resolveActiveMemoryNamespace(
    orchestrator,
    params.sessionKey,
    typeof params.filters?.namespace === "string" ? params.filters.namespace : void 0
  );
  const raw = await orchestrator.searchAcrossNamespaces({
    query: params.query,
    maxResults: requestedResults,
    namespaces: [namespace],
    mode: "search"
  });
  const visible = raw.filter((candidate) => !isArtifactPath(candidate.path));
  return {
    results: visible.slice(0, limit).map((candidate, index) => ({
      id: candidate.id ?? candidate.path ?? `memory-${index + 1}`,
      score: typeof candidate.score === "number" ? candidate.score : 0,
      text: truncateSnippet(candidate.snippet ?? candidate.text ?? "", snippetMaxChars),
      metadata: pickMetadata(candidate.metadata)
    })),
    truncated: visible.length > limit
  };
}
function buildActiveMemoryMetadataFromMemory(memory) {
  const metadata = {};
  if (typeof memory.frontmatter.category === "string") {
    const category = memory.frontmatter.category;
    if (category === "fact" || category === "preference") {
      metadata.type = category;
    }
  }
  if (Array.isArray(memory.frontmatter.tags) && memory.frontmatter.tags.length > 0) {
    metadata.topic = memory.frontmatter.tags[0];
  }
  if (typeof memory.frontmatter.updated === "string") metadata.updatedAt = memory.frontmatter.updated;
  if (typeof memory.frontmatter.source === "string") metadata.sourceUri = memory.frontmatter.source;
  return Object.keys(metadata).length > 0 ? metadata : void 0;
}
async function getMemoryForActiveMemory(orchestrator, id, options = {}) {
  const namespace = resolveActiveMemoryNamespace(
    orchestrator,
    options.sessionKey,
    options.namespace
  );
  const storage = typeof orchestrator.getStorageForNamespace === "function" ? await orchestrator.getStorageForNamespace(namespace) : orchestrator.storage;
  const memory = await storage?.getMemoryById?.(id);
  if (!memory) return { error: "not_found" };
  return {
    id,
    text: collapseWhitespace(memory.content),
    metadata: buildActiveMemoryMetadataFromMemory(memory)
  };
}

export {
  recallForActiveMemory,
  getMemoryForActiveMemory
};
//# sourceMappingURL=chunk-G4SK7DSQ.js.map