import {
  assertSkillDeliveryDisjoint,
  composeShellResources,
  composeSkills,
  corpusSkills,
  loadMarkdownCorpus,
  mergeComposedSkills,
  parseCorpusSkills,
  parseSkillFrontmatter,
  registrySkills,
  renderInlineSkills,
  renderSkillIndex,
  skillEntryFromMarkdown,
  skillMountPath,
  skillRefs
} from "../chunk-NBSBRZ6F.js";

// src/profile/index.ts
import { mergeAgentProfiles } from "@tangle-network/sandbox";
import { profile } from "@tangle-network/agent-eval";
var DEFAULT_MAX_SYSTEM_PROMPT_BYTES = 4e4;
function largestPromptSections(prompt, top = 3) {
  const encoder = new TextEncoder();
  const sections = [];
  let title = "(preamble)";
  let start = 0;
  const flush = (end) => {
    const body = prompt.slice(start, end);
    if (body.trim()) sections.push({ title, bytes: encoder.encode(body).byteLength });
  };
  const headingRe = /^#{1,6}\s+(.+)$/gm;
  for (const match of prompt.matchAll(headingRe)) {
    flush(match.index);
    title = (match[1] ?? "").trim() || "(untitled section)";
    start = match.index;
  }
  flush(prompt.length);
  return sections.sort((a, b) => b.bytes - a.bytes).slice(0, top);
}
function assertSystemPromptWithinBudget(systemPrompt, budget = {}) {
  const max = budget.maxSystemPromptBytes ?? DEFAULT_MAX_SYSTEM_PROMPT_BYTES;
  const bytes = new TextEncoder().encode(systemPrompt).byteLength;
  if (bytes <= max) return;
  const sections = largestPromptSections(systemPrompt).map((s) => `"${s.title}" (${s.bytes}B)`).join(", ");
  const message = `composed systemPrompt is ${bytes} bytes \u2014 over the ${max}-byte budget (oversized prompts degrade to empty answers). ` + (sections ? `Largest sections: ${sections}. ` : "") + `Trim the prompt, move content to skills/knowledge mounts, or raise maxSystemPromptBytes deliberately.`;
  if (budget.warnOnly) {
    console.warn(`[profile] ${message}`);
    return;
  }
  throw new Error(message);
}
function userSkillMounts(userSkills) {
  return userSkills.map(
    (s) => ({
      path: skillMountPath(s.id),
      resource: { kind: "inline", name: s.id, content: s.skillMd }
    })
  ).sort((a, b) => a.path.localeCompare(b.path));
}
function composeAgentProfile(base, channels = {}, overlay = {}, budget = {}) {
  const shellInput = {
    skills: channels.skills,
    knowledge: channels.knowledge,
    evolvable: channels.evolvable,
    registry: channels.registry ? registrySkills(channels.registry, channels.registryTier ?? "free") : void 0,
    predicate: channels.filesPredicate
  };
  const channelFiles = composeShellResources(shellInput);
  const userFiles = channels.userSkills ? userSkillMounts(channels.userSkills) : [];
  const overlayFiles = channels.filesPredicate ? userFiles.filter(channels.filesPredicate) : userFiles;
  const files = [...channelFiles, ...overlayFiles];
  const promptOverlay = {};
  if (overlay.systemPrompt) promptOverlay.systemPrompt = overlay.systemPrompt;
  if (overlay.instructions && overlay.instructions.length > 0) promptOverlay.instructions = overlay.instructions;
  const overlayProfile = {
    ...overlay.name ? { name: overlay.name } : {},
    ...Object.keys(promptOverlay).length > 0 ? { prompt: promptOverlay } : {},
    ...overlay.mcp ? { mcp: overlay.mcp } : {},
    resources: {
      files,
      ...channels.skillRefs && channels.skillRefs.length > 0 ? { skills: channels.skillRefs } : {}
    }
  };
  const merged = mergeAgentProfiles(base, overlayProfile);
  if (!merged)
    throw new Error("composeAgentProfile: mergeAgentProfiles returned undefined for a defined base");
  const systemPrompt = merged.prompt?.systemPrompt;
  if (typeof systemPrompt === "string") assertSystemPromptWithinBudget(systemPrompt, budget);
  return pruneEmptyResourceChannels(merged);
}
function pruneEmptyResourceChannels(profile2) {
  if (!profile2.resources) return profile2;
  const kept = Object.fromEntries(
    Object.entries(profile2.resources).filter(([, value]) => !(Array.isArray(value) && value.length === 0))
  );
  const out = { ...profile2, resources: kept };
  if (kept && Object.keys(kept).length === 0) delete out.resources;
  return out;
}
function stripComments(raw) {
  return raw.replace(/<!--[\s\S]*?-->/g, "").trim();
}
function makeEvolvableSection(input) {
  const loaded = input.load();
  const body = stripComments(loaded) ? loaded.trim() : input.baseline;
  return { id: input.id, title: input.title, body, evolvable: true };
}
export {
  DEFAULT_MAX_SYSTEM_PROMPT_BYTES,
  assertSkillDeliveryDisjoint,
  assertSystemPromptWithinBudget,
  composeAgentProfile,
  composeShellResources,
  composeSkills,
  corpusSkills,
  largestPromptSections,
  loadMarkdownCorpus,
  makeEvolvableSection,
  mergeComposedSkills,
  parseCorpusSkills,
  parseSkillFrontmatter,
  profile,
  registrySkills,
  renderInlineSkills,
  renderSkillIndex,
  skillEntryFromMarkdown,
  skillMountPath,
  skillRefs,
  stripComments,
  userSkillMounts
};
//# sourceMappingURL=index.js.map