// src/namespaces/principal.ts
function resolvePrincipal(sessionKey, config) {
  if (!config.namespacesEnabled) return "default";
  const sk = sessionKey ?? "";
  const mode = config.principalFromSessionKeyMode;
  const rules = config.principalFromSessionKeyRules ?? [];
  if (!sk) return "default";
  if (mode === "prefix") {
    for (const r of rules) {
      if (sk.startsWith(r.match)) return r.principal;
    }
  } else if (mode === "map") {
    for (const r of rules) {
      if (sk === r.match) return r.principal;
    }
  } else if (mode === "regex") {
    for (const r of rules) {
      try {
        const re = new RegExp(r.match);
        if (re.test(sk)) return r.principal;
      } catch {
      }
    }
  }
  const parts = sk.split(":");
  if (parts.length >= 2 && parts[0] === "agent") {
    const agentId = parts[1];
    if (agentId && agentId.length > 0) return agentId;
  }
  return "default";
}
function canReadNamespace(principal, namespace, config) {
  if (!config.namespacesEnabled) return true;
  const policy = config.namespacePolicies.find((p) => p.name === namespace);
  if (!policy) return namespace === config.defaultNamespace || namespace === config.sharedNamespace;
  return policy.readPrincipals.includes(principal) || policy.readPrincipals.includes("*");
}
function canWriteNamespace(principal, namespace, config) {
  if (!config.namespacesEnabled) return true;
  const policy = config.namespacePolicies.find((p) => p.name === namespace);
  if (!policy) return namespace === config.defaultNamespace;
  return policy.writePrincipals.includes(principal) || policy.writePrincipals.includes("*");
}
function defaultNamespaceForPrincipal(principal, config) {
  if (!config.namespacesEnabled) return config.defaultNamespace;
  const exists = config.namespacePolicies.some((p) => p.name === principal);
  return exists ? principal : config.defaultNamespace;
}
function recallNamespacesForPrincipal(principal, config) {
  const out = [];
  if (!config.namespacesEnabled) return [config.defaultNamespace];
  const selfNs = defaultNamespaceForPrincipal(principal, config);
  if (config.defaultRecallNamespaces.includes("self") && canReadNamespace(principal, selfNs, config)) {
    out.push(selfNs);
  }
  if (config.defaultRecallNamespaces.includes("shared") && canReadNamespace(principal, config.sharedNamespace, config)) {
    out.push(config.sharedNamespace);
  }
  for (const p of config.namespacePolicies) {
    if (p.includeInRecallByDefault && canReadNamespace(principal, p.name, config)) {
      if (!out.includes(p.name)) out.push(p.name);
    }
  }
  return out;
}

export {
  resolvePrincipal,
  canReadNamespace,
  canWriteNamespace,
  defaultNamespaceForPrincipal,
  recallNamespacesForPrincipal
};
//# sourceMappingURL=chunk-N5AKDXAI.js.map