import {
  buildLoopOtelSpans,
  createOtelExporter,
  flatOtelSpan
} from "./chunk-UD4BHQMI.js";
import "./chunk-DGUM43GV.js";

// src/intelligence/effort.ts
var presets = {
  off: {
    analysts: false,
    corpus: "off",
    fanout: 1,
    loops: false,
    intelligenceBudgetUsd: 0
  },
  eco: {
    analysts: true,
    corpus: "read",
    fanout: 1,
    loops: false,
    intelligenceBudgetUsd: 0.25
  },
  standard: {
    analysts: true,
    corpus: "read-write",
    fanout: 3,
    loops: true,
    intelligenceBudgetUsd: 2
  },
  thorough: {
    analysts: true,
    corpus: "read-write",
    fanout: 5,
    loops: true,
    intelligenceBudgetUsd: 10
  },
  max: {
    analysts: true,
    corpus: "read-write",
    fanout: 8,
    loops: true,
    intelligenceBudgetUsd: null
  }
};
var defaultEffortTier = "standard";
function resolveEffort(tier, overrides) {
  const preset = presets[tier];
  if (!preset) {
    throw new Error(
      `resolveEffort: unknown effort tier ${JSON.stringify(tier)} (expected one of ${Object.keys(presets).map((t) => `'${t}'`).join(", ")})`
    );
  }
  return { ...preset, ...overrides ?? {} };
}
function isIntelligenceOff(settings) {
  return settings.analysts === false && settings.corpus === "off" && settings.fanout <= 1 && settings.loops === false && settings.intelligenceBudgetUsd === 0;
}
function compileEffort(settings) {
  return {
    withAnalyst: settings.analysts,
    fanout: settings.fanout,
    withLoops: settings.loops,
    intelligenceBudgetUsd: settings.intelligenceBudgetUsd
  };
}

// src/intelligence/redact.ts
var redactedMarker = "[redacted]";
var secretKeyPattern = /(api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(id|token)|cookie|bearer)/i;
var valuePatterns = [
  // Bearer tokens.
  /\bBearer\s+[A-Za-z0-9._\-+/=]{8,}/gi,
  // Provider-style API keys (sk-..., sk-tan-..., pk_live_..., ghp_...).
  /\b(?:sk|pk|rk|ak)[-_][A-Za-z0-9_-]{12,}/g,
  /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
  // AWS access key ids.
  /\bAKIA[0-9A-Z]{16}\b/g,
  // PEM private-key blocks.
  /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
  // Email addresses.
  /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g
];
function scrubString(input) {
  let out = input;
  for (const pattern of valuePatterns) {
    out = out.replace(pattern, redactedMarker);
  }
  return out;
}
function defaultRedactor(value) {
  return walk(value, /* @__PURE__ */ new WeakSet(), 0);
}
var maxDepth = 32;
function walk(value, seen, depth) {
  if (depth > maxDepth) return "[truncated]";
  if (typeof value === "string") return scrubString(value);
  if (value === null || typeof value !== "object") return value;
  if (seen.has(value)) return "[circular]";
  seen.add(value);
  if (Array.isArray(value)) {
    return value.map((item) => walk(item, seen, depth + 1));
  }
  const out = {};
  for (const [key, v] of Object.entries(value)) {
    if (secretKeyPattern.test(key)) {
      out[key] = redactedMarker;
      continue;
    }
    out[key] = walk(v, seen, depth + 1);
  }
  return out;
}
function resolveRedactor(redact) {
  if (redact === false) return (value) => value;
  return redact ?? defaultRedactor;
}

// src/intelligence/capability.ts
var CapabilityNotAdmittedError = class extends Error {
  kind;
  capabilityId;
  constructor(kind, capabilityId, reason) {
    super(`capability '${capabilityId}': binding '${kind}' not admitted \u2014 ${reason}`);
    this.name = "CapabilityNotAdmittedError";
    this.kind = kind;
    this.capabilityId = capabilityId;
  }
};
var provenanceFromArtifact = (a) => ({
  contentHash: a.contentHash,
  version: a.version,
  lift: a.lift,
  promotedAt: a.promotedAt,
  sourcePath: a.path
});
var contextKindForType = (type) => type === "prompt-surface" || type === "skill" ? type : "instructions";
function inferCapability(type, a) {
  const id = `${type}:${a.path ?? a.index}`;
  const provenance = provenanceFromArtifact(a);
  const parsed = tryParseJson(a.content);
  if (parsed && typeof parsed === "object") {
    const obj = parsed;
    if (typeof obj.command === "string") {
      return {
        id,
        iface: { surface: "mcp", serverName: String(obj.name ?? type) },
        binding: {
          kind: "mcp-stdio",
          command: obj.command,
          ...Array.isArray(obj.args) ? { args: obj.args.map(String) } : {},
          ...isStringRecord(obj.env) ? { env: obj.env } : {},
          ...typeof obj.cwd === "string" ? { cwd: obj.cwd } : {}
        },
        auth: { mode: "none" },
        provenance
      };
    }
    if (typeof obj.url === "string" && (obj.transport === "http" || obj.transport === "sse")) {
      return {
        id,
        iface: { surface: "mcp", serverName: String(obj.name ?? type) },
        binding: {
          kind: "mcp-remote",
          url: obj.url,
          transport: obj.transport,
          ...isStringRecord(obj.headers) ? { headers: obj.headers } : {}
        },
        auth: { mode: "none" },
        provenance
      };
    }
    if (typeof obj.name === "string" && isJsonSchema(obj.parameters)) {
      const iface = {
        surface: "tool",
        name: obj.name,
        ...typeof obj.description === "string" ? { description: obj.description } : {},
        parameters: obj.parameters
      };
      if (typeof obj.url === "string") {
        return {
          id,
          iface,
          binding: {
            kind: "http",
            url: obj.url,
            ...typeof obj.method === "string" ? { method: obj.method } : {}
          },
          auth: { mode: "none" },
          provenance
        };
      }
      return {
        id,
        iface,
        binding: { kind: "inline", content: { kind: "inline", content: a.content } },
        auth: { mode: "none" },
        provenance
      };
    }
  }
  return {
    id,
    iface: { surface: "context", kind: "instructions", name: a.path ?? type },
    binding: { kind: "inline", content: { kind: "inline", content: a.content } },
    auth: { mode: "none" },
    provenance
  };
}
function manifestFromProfile(profile) {
  const capabilities = [];
  for (const type of Object.keys(profile.artifacts).sort()) {
    const bucket = profile.artifacts[type] ?? [];
    const sorted = [...bucket].map((a, index) => ({ ...a, index })).sort((x, y) => (x.path ?? "").localeCompare(y.path ?? ""));
    for (const a of sorted) {
      if (type === "prompt-surface" || type === "skill") {
        capabilities.push({
          id: `${type}:${a.path ?? a.index}`,
          iface: { surface: "context", kind: contextKindForType(type), name: a.path ?? type },
          binding: { kind: "inline", content: { kind: "inline", content: a.content } },
          auth: { mode: "none" },
          provenance: provenanceFromArtifact(a)
        });
      } else {
        capabilities.push(inferCapability(type, a));
      }
    }
  }
  return {
    target: profile.target,
    generatedAt: profile.generatedAt,
    promptSurface: profile.promptSurface,
    capabilities
  };
}
function tryParseJson(s) {
  try {
    return JSON.parse(s);
  } catch {
    return void 0;
  }
}
function isStringRecord(v) {
  return typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
}
function isJsonSchema(v) {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}

// src/intelligence/delivery.ts
var defaultPlaneBaseUrl = "https://intelligence.tangle.tools";
var defaultRefreshMs = 3e5;
var defaultPullTimeoutMs = 1e4;
function resolvePlaneBaseUrl(baseUrl) {
  if (baseUrl) return baseUrl.replace(/\/+$/, "");
  if (typeof process !== "undefined" && process.env.TANGLE_INTELLIGENCE_URL) {
    return process.env.TANGLE_INTELLIGENCE_URL.replace(/\/+$/, "");
  }
  return defaultPlaneBaseUrl;
}
function resolveApiKey(apiKey) {
  if (apiKey) return apiKey;
  if (typeof process !== "undefined" && process.env.TANGLE_API_KEY)
    return process.env.TANGLE_API_KEY;
  return "";
}
async function pullCertified(opts) {
  const doFetch = opts.fetchImpl ?? globalThis.fetch;
  if (!doFetch) return { succeeded: false, error: "no fetch implementation available" };
  const apiKey = resolveApiKey(opts.apiKey);
  if (!apiKey) return { succeeded: false, error: "no apiKey (set TANGLE_API_KEY or opts.apiKey)" };
  const baseUrl = resolvePlaneBaseUrl(opts.baseUrl);
  const url = `${baseUrl}/v1/profiles/${encodeURIComponent(opts.target)}/composed`;
  let res;
  try {
    res = await doFetch(url, {
      headers: { authorization: `Bearer ${apiKey}` },
      signal: AbortSignal.timeout(opts.timeoutMs ?? defaultPullTimeoutMs)
    });
  } catch (err) {
    return {
      succeeded: false,
      error: `pull request failed: ${err instanceof Error ? err.message : String(err)}`
    };
  }
  if (res.status === 404) {
    return {
      succeeded: false,
      error: "no certified artifacts promoted for target yet",
      status: 404
    };
  }
  if (!res.ok) {
    const body = await res.text().catch(() => "");
    return {
      succeeded: false,
      error: `pull ${res.status}: ${body.slice(0, 200)}`,
      status: res.status
    };
  }
  try {
    return { succeeded: true, value: await res.json() };
  } catch (err) {
    return {
      succeeded: false,
      error: `pull response parse failed: ${err instanceof Error ? err.message : String(err)}`
    };
  }
}
var promptFoldTypes = ["prompt-surface", "skill", "instructions"];
function composeCertifiedPrompt(base, certified) {
  if (!certified) return base;
  const parts = [];
  if (certified.promptSurface?.surface.trim()) parts.push(certified.promptSurface.surface.trim());
  for (const type of promptFoldTypes) {
    const bucket = certified.artifacts[type] ?? [];
    for (const a of [...bucket].sort((x, y) => (x.path ?? "").localeCompare(y.path ?? ""))) {
      if (a.content.trim()) parts.push(a.content.trim());
    }
  }
  if (parts.length === 0) return base;
  return `${base.trim()}

## Certified guidance (Tangle Intelligence)

${parts.join("\n\n")}`;
}
function createCertifiedPromptSource(opts) {
  const refreshMs = opts.refreshMs ?? defaultRefreshMs;
  let certified = null;
  let lastPullAt = 0;
  let inflight = null;
  async function refresh() {
    if (Date.now() - lastPullAt < refreshMs) return;
    if (inflight) return inflight;
    inflight = (async () => {
      const outcome = await pullCertified(opts);
      lastPullAt = Date.now();
      if (outcome.succeeded) certified = outcome.value;
    })();
    try {
      await inflight;
    } finally {
      inflight = null;
    }
  }
  return {
    refresh,
    current: () => certified,
    async compose(base) {
      await refresh();
      return composeCertifiedPrompt(base, certified);
    }
  };
}
function withCertifiedDelivery(agent, config) {
  const client = createIntelligenceClient(config);
  const source = createCertifiedPromptSource({
    target: config.target ?? config.project,
    ...config.apiKey !== void 0 ? { apiKey: config.apiKey } : {},
    ...config.baseUrl !== void 0 ? { baseUrl: config.baseUrl } : {},
    ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
    ...config.fetchImpl !== void 0 ? { fetchImpl: config.fetchImpl } : {},
    ...config.refreshMs !== void 0 ? { refreshMs: config.refreshMs } : {}
  });
  const wrapped = (async (input) => {
    await source.refresh();
    const certified = source.current();
    const applied = {
      certified,
      composePrompt: (base) => composeCertifiedPrompt(base, certified)
    };
    return client.traceRun(
      { input, labels: { "tangle.certified_version": certified?.promptSurface?.version ?? -1 } },
      async (trace) => {
        const out = await agent(input, applied);
        trace.recordOutput(out);
        return out;
      }
    );
  });
  wrapped.refresh = source.refresh;
  return wrapped;
}

// src/intelligence/resolver.ts
function emptyAccumulator() {
  return {
    tools: [],
    executors: /* @__PURE__ */ new Map(),
    mcpConnections: {},
    contextArtifacts: {},
    files: [],
    retrieval: [],
    hooks: [],
    subagents: [],
    teardowns: [],
    toolCapabilityId: /* @__PURE__ */ new Map(),
    mcpCapability: /* @__PURE__ */ new Map()
  };
}
async function composeCertifiedProfile(base, manifest, ctx = {}) {
  if (!manifest || manifest.capabilities.length === 0) {
    return baseSurface(base.systemPrompt, manifest?.promptSurface ?? null);
  }
  const acc = emptyAccumulator();
  for (const cap of manifest.capabilities) {
    try {
      await resolveCapability(cap, ctx, acc);
    } catch (err) {
      if (err instanceof CapabilityNotAdmittedError) throw err;
      ctx.onDrop?.(cap.id, err instanceof Error ? err : new Error(String(err)));
    }
  }
  await driftDropTools(acc, ctx);
  const promptAdditions = collectPromptAdditions(manifest.promptSurface, acc.contextArtifacts);
  const systemPrompt = composeCertifiedPrompt(base.systemPrompt, {
    target: manifest.target,
    generatedAt: manifest.generatedAt,
    promptSurface: manifest.promptSurface,
    artifacts: acc.contextArtifacts
  });
  const teardowns = acc.teardowns;
  return {
    tools: acc.tools,
    async execute(name, args, task) {
      const fn = acc.executors.get(name);
      if (!fn) throw new Error(`composeCertifiedProfile.execute: unknown tool '${name}'`);
      return fn(args, task);
    },
    mcpConnections: acc.mcpConnections,
    promptAdditions,
    files: acc.files,
    retrieval: acc.retrieval,
    hooks: acc.hooks,
    subagents: acc.subagents,
    systemPrompt,
    async dispose() {
      for (let i = teardowns.length - 1; i >= 0; i -= 1) {
        const teardown = teardowns[i];
        if (teardown) await teardown();
      }
    }
  };
}
function baseSurface(systemPrompt, promptSurface) {
  const folded = composeCertifiedPrompt(systemPrompt, {
    target: "",
    generatedAt: "",
    promptSurface,
    artifacts: {}
  });
  return {
    tools: [],
    async execute(name) {
      throw new Error(`composeCertifiedProfile.execute: unknown tool '${name}'`);
    },
    mcpConnections: {},
    promptAdditions: collectPromptAdditions(promptSurface, {}),
    files: [],
    retrieval: [],
    hooks: [],
    subagents: [],
    systemPrompt: folded,
    async dispose() {
    }
  };
}
function collectPromptAdditions(promptSurface, contextArtifacts) {
  const parts = [];
  if (promptSurface?.surface.trim()) parts.push(promptSurface.surface.trim());
  for (const type of promptFoldTypes) {
    const bucket = contextArtifacts[type] ?? [];
    for (const a of [...bucket].sort((x, y) => (x.path ?? "").localeCompare(y.path ?? ""))) {
      if (a.content.trim()) parts.push(a.content.trim());
    }
  }
  return parts;
}
async function resolveCapability(cap, ctx, acc) {
  await resolveBinding(cap, cap.binding, ctx, acc);
}
async function resolveBinding(cap, binding, ctx, acc) {
  switch (binding.kind) {
    case "inline":
      resolveInline(cap, binding, acc);
      return;
    case "file":
      resolveFile(cap, binding, acc);
      return;
    case "http":
      resolveHttp(cap, binding, ctx, acc);
      return;
    case "mcp-stdio":
    case "mcp-remote":
      resolveMcp(cap, binding, acc);
      return;
    case "sandbox-code":
      resolveSandboxCode(cap, binding, ctx, acc);
      return;
    case "process-on-infra":
      await resolveProcessOnInfra(cap, binding, ctx, acc, /* @__PURE__ */ new Set());
      return;
    case "rag-index":
      throw new CapabilityNotAdmittedError(
        binding.kind,
        cap.id,
        "rag retrieval lift must clear the E3 score-superiority admission bar before a store is trusted (memory/e3-certified-memory-verdict)"
      );
    case "memory-store":
      throw new CapabilityNotAdmittedError(
        binding.kind,
        cap.id,
        "memory-store admission is gated on the E3 score-superiority bar (memory/e3-certified-memory-verdict)"
      );
    case "wasm":
      throw new CapabilityNotAdmittedError(
        binding.kind,
        cap.id,
        "wasm is an extension-point arm, not yet admitted"
      );
    case "a2a":
      throw new CapabilityNotAdmittedError(
        binding.kind,
        cap.id,
        "a2a is an extension-point arm, not yet admitted"
      );
  }
}
function resolveInline(cap, binding, acc) {
  const content = inlineContent(cap, binding.content);
  if (cap.iface.surface === "context") {
    pushContextArtifact(acc, cap, content);
    return;
  }
  if (cap.iface.surface === "tool") {
    registerInlineTool(cap, content, acc);
    return;
  }
  pushContextArtifact(acc, cap, content);
}
function registerInlineTool(cap, content, acc) {
  if (cap.iface.surface !== "tool") return;
  const iface = cap.iface;
  acc.tools.push({
    type: "function",
    function: {
      name: iface.name,
      ...iface.description ? { description: iface.description } : {},
      parameters: iface.parameters
    }
  });
  acc.toolCapabilityId.set(iface.name, cap.id);
  acc.executors.set(iface.name, async () => content);
}
function resolveFile(cap, binding, acc) {
  const content = inlineContent(cap, binding.content);
  acc.files.push({
    path: binding.path,
    content,
    ...binding.executable ? { executable: true } : {}
  });
  if (cap.iface.surface === "context") pushContextArtifact(acc, cap, content);
}
function resolveMcp(cap, binding, acc) {
  const serverName = cap.iface.surface === "mcp" ? cap.iface.serverName : cap.id;
  acc.mcpConnections[serverName] = mcpServerFromBinding(binding, cap);
  acc.mcpCapability.set(serverName, {
    capabilityId: cap.id,
    certifiedNames: cap.iface.surface === "mcp" ? cap.iface.toolset ?? [] : []
  });
}
function mcpServerFromBinding(binding, cap) {
  const metadata = { capabilityId: cap.id };
  if (cap.iface.surface === "mcp" && cap.iface.toolset) metadata.tools = cap.iface.toolset;
  if (binding.kind === "mcp-stdio") {
    return {
      transport: "stdio",
      command: binding.command,
      ...binding.args ? { args: binding.args } : {},
      ...binding.env ? { env: binding.env } : {},
      ...binding.cwd ? { cwd: binding.cwd } : {},
      enabled: true,
      metadata
    };
  }
  return {
    transport: binding.transport,
    url: binding.url,
    ...binding.headers ? { headers: binding.headers } : {},
    enabled: true,
    metadata
  };
}
function resolveHttp(cap, binding, ctx, acc) {
  if (cap.iface.surface !== "tool") {
    throw new Error(`capability '${cap.id}': http binding requires a 'tool' interface`);
  }
  const iface = cap.iface;
  acc.tools.push({
    type: "function",
    function: {
      name: iface.name,
      ...iface.description ? { description: iface.description } : {},
      parameters: iface.parameters
    }
  });
  acc.toolCapabilityId.set(iface.name, cap.id);
  const method = binding.method ?? "POST";
  const auth = binding.auth ?? cap.auth;
  acc.executors.set(iface.name, async (args) => {
    const doFetch = ctx.fetchImpl ?? globalThis.fetch;
    if (!doFetch) throw new Error(`capability '${cap.id}': no fetch implementation for http tool`);
    const headers = { "content-type": "application/json" };
    if (auth.mode !== "none") {
      if (!ctx.resolveSecret) {
        throw new Error(
          `capability '${cap.id}': http auth '${auth.mode}' requires ResolveCtx.resolveSecret`
        );
      }
      const secret = await ctx.resolveSecret(auth, ctx.tenant);
      if (!secret.succeeded) {
        throw new Error(`capability '${cap.id}': secret resolution failed \u2014 ${secret.error}`);
      }
      headers.authorization = `Bearer ${secret.value}`;
    }
    const res = await doFetch(binding.url, {
      method,
      headers,
      ...method === "GET" ? {} : { body: JSON.stringify(args) }
    });
    if (!res.ok) {
      const body = await res.text().catch(() => "");
      throw new Error(`capability '${cap.id}': http ${res.status}: ${body.slice(0, 200)}`);
    }
    return res.text();
  });
}
function resolveSandboxCode(cap, binding, ctx, acc) {
  if (cap.iface.surface !== "tool") {
    throw new Error(`capability '${cap.id}': sandbox-code binding requires a 'tool' interface`);
  }
  const iface = cap.iface;
  acc.tools.push({
    type: "function",
    function: {
      name: iface.name,
      ...iface.description ? { description: iface.description } : {},
      parameters: iface.parameters
    }
  });
  acc.toolCapabilityId.set(iface.name, cap.id);
  acc.executors.set(iface.name, async (args, task) => {
    if (!ctx.runSandboxCode) {
      throw new Error(
        `capability '${cap.id}': sandbox-code binding requires ResolveCtx.runSandboxCode`
      );
    }
    return ctx.runSandboxCode(binding.code, binding.entry, args, task);
  });
}
async function resolveProcessOnInfra(cap, binding, ctx, acc, visited) {
  if (visited.has(binding)) {
    throw new Error(`capability '${cap.id}': process-on-infra cycle detected`);
  }
  visited.add(binding);
  if (!ctx.provisionHost) {
    throw new Error(
      `capability '${cap.id}': process-on-infra binding requires ResolveCtx.provisionHost`
    );
  }
  if (binding.inner.kind === "process-on-infra") {
    const outer = await ctx.provisionHost(
      binding.host,
      binding.inner,
      hostCostTag(cap, binding.host)
    );
    acc.teardowns.push(() => outer.teardown());
    await resolveProcessOnInfra(cap, binding.inner, ctx, acc, visited);
    return;
  }
  const provisioned = await ctx.provisionHost(
    binding.host,
    binding.inner,
    hostCostTag(cap, binding.host)
  );
  acc.teardowns.push(() => provisioned.teardown());
  if (provisioned.mcpConnection) {
    const serverName = cap.iface.surface === "mcp" ? cap.iface.serverName : cap.id;
    acc.mcpConnections[serverName] = provisioned.mcpConnection;
    acc.mcpCapability.set(serverName, {
      capabilityId: cap.id,
      certifiedNames: cap.iface.surface === "mcp" ? cap.iface.toolset ?? [] : []
    });
  }
}
function hostCostTag(cap, host) {
  return host.costTag ?? `capability/${cap.id}`;
}
async function driftDropTools(acc, ctx) {
  const specNames = new Set(acc.tools.map((t) => t.function.name));
  for (const name of acc.executors.keys()) {
    if (!specNames.has(name)) acc.executors.delete(name);
  }
  acc.tools = acc.tools.filter((t) => acc.executors.has(t.function.name));
  if (!ctx.probeLiveToolNames) return;
  const droppedTools = /* @__PURE__ */ new Set();
  for (const tool of acc.tools) {
    const capId = acc.toolCapabilityId.get(tool.function.name);
    if (!capId) continue;
    const live = await ctx.probeLiveToolNames(capId);
    if (!live.includes(tool.function.name)) droppedTools.add(tool.function.name);
  }
  for (const name of droppedTools) {
    acc.executors.delete(name);
  }
  acc.tools = acc.tools.filter((t) => !droppedTools.has(t.function.name));
  for (const [serverName, info] of acc.mcpCapability) {
    if (info.certifiedNames.length === 0) continue;
    const live = await ctx.probeLiveToolNames(info.capabilityId);
    if (!setsEqual(new Set(live), new Set(info.certifiedNames))) {
      delete acc.mcpConnections[serverName];
      acc.mcpCapability.delete(serverName);
    }
  }
}
function setsEqual(a, b) {
  if (a.size !== b.size) return false;
  for (const x of a) if (!b.has(x)) return false;
  return true;
}
function inlineContent(cap, ref) {
  if (ref.kind === "inline") return ref.content;
  throw new Error(
    `capability '${cap.id}': content ref '${ref.kind}' is not inline \u2014 wire a content fetcher to resolve it`
  );
}
function pushContextArtifact(acc, cap, content) {
  const type = contextArtifactType(cap);
  const bucket = acc.contextArtifacts[type] ?? [];
  acc.contextArtifacts[type] = bucket;
  bucket.push({
    path: contextArtifactPath(cap),
    content,
    contentHash: cap.provenance.contentHash,
    version: cap.provenance.version,
    lift: cap.provenance.lift,
    promotedAt: cap.provenance.promotedAt
  });
}
function contextArtifactType(cap) {
  if (cap.iface.surface === "context") {
    return cap.iface.kind === "instructions" ? "instructions" : cap.iface.kind;
  }
  return "instructions";
}
function contextArtifactPath(cap) {
  return cap.provenance.sourcePath;
}
async function composeCertifiedProfileFromWire(base, profile, ctx = {}) {
  if (!profile) return composeCertifiedProfile(base, null, ctx);
  return composeCertifiedProfile(base, manifestFromProfile(profile), ctx);
}

// src/intelligence/index.ts
function resolveEffortConfig(effort) {
  if (effort === void 0) return resolveEffort(defaultEffortTier);
  if (typeof effort === "string") return resolveEffort(effort);
  return resolveEffort(effort.tier, effort.overrides);
}
function resolveEndpoint(endpoint) {
  if (endpoint) return endpoint;
  if (typeof process === "undefined") return void 0;
  return process.env.INTELLIGENCE_OTLP_ENDPOINT ?? process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
}
function freshTraceId() {
  return randomHex(32);
}
function freshRunId() {
  return `run-${randomHex(16)}`;
}
var previewMaxChars = 4096;
function previewJson(value) {
  let s;
  if (typeof value === "string") s = value;
  else {
    try {
      s = JSON.stringify(value) ?? String(value);
    } catch {
      s = String(value);
    }
  }
  return s.length > previewMaxChars ? `${s.slice(0, previewMaxChars)}\u2026[truncated]` : s;
}
function randomHex(chars) {
  const bytes = new Uint8Array(Math.ceil(chars / 2));
  if (typeof globalThis.crypto?.getRandomValues === "function") {
    globalThis.crypto.getRandomValues(bytes);
  } else {
    for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
  }
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, chars);
}
function createIntelligenceClient(config) {
  if (!config.project) {
    throw new Error("createIntelligenceClient: `project` is required");
  }
  const effort = resolveEffortConfig(config.effort);
  const intelligenceOff = isIntelligenceOff(effort);
  const redactor = resolveRedactor(config.redact);
  const apiKey = config.apiKey ?? (typeof process !== "undefined" ? process.env.TANGLE_API_KEY : void 0);
  const endpoint = resolveEndpoint(config.endpoint);
  let exporter;
  let exporterResolved = false;
  function getExporter() {
    if (exporterResolved) return exporter;
    exporterResolved = true;
    if (!endpoint) return void 0;
    exporter = createOtelExporter({
      endpoint,
      headers: apiKey ? { authorization: `Bearer ${apiKey}` } : {},
      serviceName: config.project,
      resourceAttributes: { "tangle.project": config.project }
    });
    return exporter;
  }
  function exportTrace(meta, outcome, output) {
    const ex = getExporter();
    if (!ex) return;
    const labels = {
      project: config.project,
      "tangle.effort.intelligence_off": outcome.intelligenceOff,
      "tangle.usage.inference_usd": outcome.usage.inferenceUsd,
      "tangle.usage.intelligence_usd": outcome.usage.intelligenceUsd,
      ...meta.model ? { "gen_ai.request.model": meta.model } : {},
      ...meta.provider ? { "provider.name": meta.provider } : {},
      ...typeof outcome.success === "boolean" ? { "tangle.outcome.success": outcome.success } : {},
      ...typeof outcome.score === "number" ? { "tangle.outcome.score": outcome.score } : {},
      ...meta.labels ?? {}
    };
    const redactedInput = meta.input !== void 0 ? redactor(meta.input) : void 0;
    const redactedOutput = output !== void 0 ? redactor(output) : void 0;
    if (redactedInput !== void 0) labels["tangle.input"] = previewJson(redactedInput);
    if (redactedOutput !== void 0) labels["tangle.output"] = previewJson(redactedOutput);
    try {
      ex.exportSpan(
        flatOtelSpan(
          "tangle.intelligence.run",
          { "tangle.runId": outcome.runId, ...labels },
          outcome.traceId,
          Date.now()
        )
      );
    } catch {
    }
  }
  return {
    project: config.project,
    effort,
    async traceRun(meta, fn) {
      const runId = meta.runId ?? freshRunId();
      const traceId = meta.traceId ?? freshTraceId();
      let recordedOutput;
      const usage = { inferenceUsd: 0, intelligenceUsd: 0 };
      let success;
      let score;
      const trace = {
        recordOutput(output) {
          recordedOutput = output;
        },
        recordOutcome(outcome2) {
          if (typeof outcome2.success === "boolean") success = outcome2.success;
          if (typeof outcome2.score === "number") score = outcome2.score;
          if (outcome2.usage) {
            if (typeof outcome2.usage.inferenceUsd === "number") {
              usage.inferenceUsd = outcome2.usage.inferenceUsd;
            }
            if (typeof outcome2.usage.intelligenceUsd === "number") {
              usage.intelligenceUsd = outcome2.usage.intelligenceUsd;
            }
          } else if (typeof outcome2.costUsd === "number") {
            usage.inferenceUsd = outcome2.costUsd;
          }
        }
      };
      const result = await fn(trace);
      if (intelligenceOff) usage.intelligenceUsd = 0;
      const outcome = {
        runId,
        traceId,
        project: config.project,
        effort,
        intelligenceOff,
        ...success !== void 0 ? { success } : {},
        ...score !== void 0 ? { score } : {},
        usage
      };
      exportTrace(meta, outcome, recordedOutput);
      return result;
    },
    recordTrace(events, meta) {
      const traceId = meta?.traceId ?? freshTraceId();
      const ex = getExporter();
      if (!ex || events.length === 0) return traceId;
      try {
        const spans = buildLoopOtelSpans(
          events,
          traceId,
          meta?.rootParentSpanId
        );
        for (const span of spans) ex.exportSpan(span);
      } catch {
      }
      return traceId;
    },
    doctor() {
      const hasRepo = Boolean(config.repo?.owner && config.repo?.name && config.repo?.baseBranch);
      const hasChecks = Boolean(config.checks && config.checks.length > 0);
      const hasSurfaces = Boolean(config.surfaces && config.surfaces.length > 0);
      const prMissing = [];
      if (!hasChecks) prMissing.push("checks");
      if (!hasSurfaces) prMissing.push("surfaces");
      if (!hasRepo) prMissing.push("repo");
      const recommendMissing = [];
      if (intelligenceOff) recommendMissing.push("effort above off");
      return {
        project: config.project,
        effort,
        exportConfigured: Boolean(endpoint),
        modes: {
          observe: { ready: true, missing: [] },
          recommend: {
            ready: recommendMissing.length === 0,
            missing: recommendMissing
          },
          pr: { ready: prMissing.length === 0, missing: prMissing }
        }
      };
    },
    async flush() {
      const ex = getExporter();
      if (!ex) return;
      try {
        await ex.flush();
      } catch {
      }
    }
  };
}
function isClient(value) {
  return typeof value.traceRun === "function";
}
function withTangleIntelligence(agent, clientOrConfig) {
  const client = isClient(clientOrConfig) ? clientOrConfig : createIntelligenceClient(clientOrConfig);
  return async (input) => {
    return client.traceRun({ input }, async (trace) => {
      const output = await agent(input);
      trace.recordOutput(output);
      return output;
    });
  };
}
export {
  CapabilityNotAdmittedError,
  compileEffort,
  composeCertifiedProfile,
  composeCertifiedProfileFromWire,
  composeCertifiedPrompt,
  createCertifiedPromptSource,
  createIntelligenceClient,
  defaultEffortTier,
  defaultRedactor,
  isIntelligenceOff,
  manifestFromProfile,
  pullCertified,
  resolveEffort,
  resolveRedactor,
  withCertifiedDelivery,
  withTangleIntelligence
};
//# sourceMappingURL=intelligence.js.map