import { c as LoopTraceEvent } from './types-ESeMOj94.js';
import { AgentProfileMcpServer } from '@tangle-network/agent-interface';
import { T as ToolSpec } from './router-client-r8y_VFVM.js';
import '@tangle-network/agent-eval';
import '@tangle-network/sandbox';

/**
 *
 * EffortPolicy — pure data, no execution. Resolves a named tier into a flat
 * settings object the Intelligence wrapper reads to decide WHICH intelligence
 * spawns are admitted. The composer never runs anything; it only describes the
 * shape of intelligence a tier permits.
 *
 * The billing boundary lives one layer above this (the wrapper tags trace usage
 * by class). What this module owns is the single law the OFF tier rests on:
 * `'off'` ⇒ every intelligence knob OFF (analysts:false, corpus:'off',
 * fanout:1, loops:false, intelligenceBudgetUsd:0). At OFF the wrapper runs the
 * agent as pure passthrough and only intelligence-class usage can prove to be
 * zero — there is nothing to spawn.
 *
 * @experimental
 */
/** The named effort tiers, lowest to highest. `'off'` is the honest floor
 *  below `'eco'`: intelligence fully off, telemetry still best-effort. */
type EffortTier = 'off' | 'eco' | 'standard' | 'thorough' | 'max';
/** Corpus access an intelligence tier permits. `'off'` reads and writes
 *  nothing; `'read'` consults the cross-run corpus without contributing;
 *  `'read-write'` both consults and accumulates. */
type CorpusAccess = 'off' | 'read' | 'read-write';
/**
 * The flat, resolved settings a tier compiles to. Every field is individually
 * overridable through `resolveEffort`. Pure data — read by the wrapper, never
 * self-executing.
 */
interface EffortSettings {
    /** Whether trace-derived analyst diagnosis may spawn. `false` ⇒ no analyst. */
    analysts: boolean;
    /** Cross-run corpus access this tier permits. */
    corpus: CorpusAccess;
    /** Parallel candidate width. `1` ⇒ single-shot, no breadth. */
    fanout: number;
    /** Whether multi-step improvement loops (refine / fanout-vote) may run. */
    loops: boolean;
    /**
     * Ceiling, in USD, for INTELLIGENCE-class spawns only (analysts, corpus,
     * loops) — NOT base inference. `0` refuses every intelligence spawn; `null`
     * means uncapped (the spend lands on the Pareto receipt). Base-stream
     * inference is billed on its own channel and is never constrained here.
     */
    intelligenceBudgetUsd: number | null;
}
/** Per-field overrides applied on top of a tier preset. Any subset of the
 *  resolved settings; each provided field wins over the preset. */
type EffortOverrides = Partial<EffortSettings>;
/** The default tier when a client declares no effort. `'standard'` turns
 *  intelligence on with sensible knobs; opt down to `'off'`/`'eco'` or up to
 *  `'thorough'`/`'max'`. */
declare const defaultEffortTier: EffortTier;
/**
 * Compile a named tier (plus optional per-field overrides) into the flat
 * `EffortSettings` the wrapper reads. Pure: same inputs → same object, no I/O,
 * no execution. Fails loud on an unknown tier rather than silently defaulting —
 * a typo'd tier must not quietly grant or deny intelligence.
 *
 * Invariant preserved for the billing floor: `resolveEffort('off')` always
 * yields `intelligenceBudgetUsd: 0` with every intelligence knob off UNLESS the
 * caller explicitly overrides a field — overriding off is an opt-in the caller
 * owns, not a default the composer leaks.
 */
declare function resolveEffort(tier: EffortTier, overrides?: EffortOverrides): EffortSettings;
/**
 * True when these settings admit NO intelligence spawn — the passthrough
 * predicate the wrapper branches on. Every intelligence axis must be off:
 * analysts disabled, corpus off, no breadth, no loops, and a zero intelligence
 * budget. A caller who overrides any one of these back on is no longer at the
 * OFF floor and the wrapper treats them as an intelligence-enabled run.
 */
declare function isIntelligenceOff(settings: EffortSettings): boolean;
/**
 * The run-config overrides an `EffortSettings` compiles to — the bridge between the
 * pure effort policy and the orchestration entrypoints (`runPersonified` / the
 * improvement cycle). This is ONLY data: it never constructs an analyst or runs a
 * loop. The caller reads these flags to decide WHAT to pass:
 *
 *  - `withAnalyst: false` ⇒ DO NOT construct/pass a `ScopeAnalyst` to `runPersonified`
 *    (the dormant empty-findings path runs; the base agent still works). This is the
 *    PRODUCT fail-closed at `off`/`eco` — "don't construct the analyst" — distinct from
 *    the EXPERIMENT fail-closed inside `createScopeAnalyst` ("hard abort"), which stays
 *    untouched. Degrade, never throw.
 *  - `fanout` ⇒ the `ShapeBudget.fanout` width to pass (`1` at `off`, the tier's breadth
 *    otherwise). Overrides the personify default fanout.
 *  - `withLoops: false` ⇒ the improvement cycle is a no-op for this run (no refine /
 *    fanout-vote multi-step loop spawns).
 *  - `intelligenceBudgetUsd` ⇒ the intelligence-class spend ceiling carried through for
 *    the billing clamp (passed verbatim; `0` refuses every intelligence spawn).
 */
interface EffortOverridesCompiled {
    /** Construct + pass a `ScopeAnalyst`? `false` ⇒ omit it (degrade to the base agent). */
    withAnalyst: boolean;
    /** `ShapeBudget.fanout` width to pass to `runPersonified`. */
    fanout: number;
    /** Run the multi-step improvement cycle, or no-op it for this run? */
    withLoops: boolean;
    /** Intelligence-class spend ceiling. `0` refuses every intelligence spawn; `null` uncapped. */
    intelligenceBudgetUsd: number | null;
}
/**
 * Compile resolved `EffortSettings` into the orchestration overrides above. Pure: same
 * input → same object, no I/O, no execution, no construction. It is the single place that
 * maps the effort axes onto the run-config knobs, so no `if (effort)` leaks into the
 * supervise kernel — the kernel stays effort-blind, the caller reads these flags once.
 *
 * `off`/`eco` (`analysts: false`) compile to `withAnalyst: false` ⇒ the caller omits the
 * analyst and the run degrades to the dormant base agent rather than throwing. `fanout: 1`
 * (no breadth) at `off`; `withLoops: false` no-ops the improvement cycle. `standard`+
 * compile to `withAnalyst: true`, the tier's `fanout`, and `withLoops: true`.
 */
declare function compileEffort(settings: EffortSettings): EffortOverridesCompiled;

/**
 *
 * Redaction for Intelligence trace export. The trace carries the customer's
 * real input/output; before any of it leaves the process it passes through a
 * `Redactor`. The default scrubs the obvious leak classes (API keys, bearer
 * tokens, emails, private keys) from strings and walks nested objects/arrays,
 * but a customer with domain-specific PII supplies their own `redact` hook.
 *
 * This is intentionally narrower than `src/sanitize.ts` (which redacts the
 * runtime's *event envelope* field-by-field): here the value is opaque
 * customer payload, so the scrub is value-shaped, not schema-shaped.
 *
 * @experimental
 */
/** A redactor maps an arbitrary trace value to a safe-to-export value. Pure;
 *  must not throw on cyclic input (the default tolerates cycles). */
type Redactor = (value: unknown) => unknown;
/**
 * The built-in redactor. Walks objects and arrays; replaces values under
 * secret-bearing keys wholesale; scrubs in-value patterns from every string.
 * Cycle-safe (a seen-set short-circuits self-referential payloads to
 * `'[circular]'`), depth-bounded, and total — never throws on customer input.
 */
declare function defaultRedactor(value: unknown): unknown;
/**
 * Resolve the redactor a client uses. A caller-supplied hook replaces the
 * default entirely (the customer owns their PII rules); absent one, the
 * built-in `defaultRedactor` runs. Returning `false` is the explicit opt-out —
 * NO redaction, for a caller who has already sanitized upstream and wants raw
 * fidelity. Opt-out is loud (an explicit `false`), never a silent default.
 */
declare function resolveRedactor(redact: Redactor | false | undefined): Redactor;

/**
 *
 * Tangle Intelligence — the DELIVERY half of the loop (pull-by-default).
 *
 * The sibling Observe layer (`./index`) sends traces UP to the plane. This
 * module pulls certified artifacts DOWN: it reads the tenant's promoted,
 * gate-certified profile from the deployed Intelligence plane and folds it into
 * the running agent's prompt — so an approved improvement actually reaches the
 * agent. This is "shipping intelligence to people's agents", pull-by-default;
 * the push/Gated-PR opt-in composes on top of this.
 *
 * Pull contract (deployed plane): GET /v1/profiles/:target/composed →
 *   { target, generatedAt, promptSurface: {surface,surfaceHash,version,lift}|null,
 *     artifacts: { <artifactType>: [{path,content,contentHash,version,lift,promotedAt}] } }
 * Auth: Bearer <apiKey> (the one TANGLE_API_KEY shared by router + sandbox +
 * intelligence), resolved to a tenant by platform-api's key-verify S2S contract.
 *
 *   import { withCertifiedDelivery } from '@tangle-network/agent-runtime/intelligence'
 *
 *   export const agent = withCertifiedDelivery(
 *     async (input, applied) => myAgent(input, { systemPrompt: applied.composePrompt(BASE) }),
 *     { project: 'support-agent', target: 'support-agent' },
 *   )
 *
 * @experimental
 */

/** A promoted, certified artifact (one entry in the composed profile). */
interface CertifiedArtifact {
    path: string | null;
    content: string;
    contentHash: string;
    version: number | null;
    /** Held-out gate lift attached at certification, e.g. "+3.1pp" — never a
     *  within-run claim. `null` when the promotion carried no lift record. */
    lift: string | null;
    promotedAt: string;
}
/** The active promoted prompt surface for a target. */
interface CertifiedPromptSurface {
    surface: string;
    surfaceHash: string;
    version: number | null;
    lift: string | null;
}
/** The composed certified profile — exactly the shape the plane's
 *  `GET /v1/profiles/:target/composed` returns. */
interface CertifiedProfile {
    target: string;
    generatedAt: string;
    promptSurface: CertifiedPromptSurface | null;
    artifacts: Record<string, CertifiedArtifact[]>;
}
/** Typed outcome for the pull — inspect `succeeded` before `value`. A 404
 *  (nothing promoted yet) is a normal, non-error `succeeded: false`. */
type PullOutcome = {
    succeeded: true;
    value: CertifiedProfile;
} | {
    succeeded: false;
    error: string;
    status?: number;
};
interface PullCertifiedOptions {
    /** The agent target certified artifacts are promoted under. */
    target: string;
    /** Bearer key. Defaults to `process.env.TANGLE_API_KEY`. */
    apiKey?: string;
    /** Plane base URL. Defaults to `process.env.TANGLE_INTELLIGENCE_URL` then
     *  `https://intelligence.tangle.tools`. */
    baseUrl?: string;
    /** fetch impl (tests / non-global-fetch runtimes). Defaults to global fetch. */
    fetchImpl?: typeof fetch;
    /** Abort the pull after this many ms so a hung plane never blocks the caller.
     *  Default 10000. The timeout surfaces as a normal fail-closed `succeeded:
     *  false` (the agent runs on its base surface). */
    timeoutMs?: number;
}
/**
 * Pull the certified composed profile for a target. Fail-closed: a network
 * error or a non-2xx returns a typed `succeeded: false` (never throws), so a
 * caller can run on its base surface when Intelligence is unreachable. A 404 is
 * the normal "nothing promoted yet" signal, carried as `status: 404`.
 */
declare function pullCertified(opts: PullCertifiedOptions): Promise<PullOutcome>;
/**
 * Fold the certified prompt surface (and any certified prompt-folding artifacts:
 * `prompt-surface` / `skill` / `instructions`) into a base system prompt under a
 * marked section, so the deployed agent prompt == base + the gate-certified
 * additions. Order is stable (prompt surface first, then artifact buckets in
 * `promptFoldTypes` order, then by path within a bucket) so the same profile
 * renders byte-identically each call. Returns `base` unchanged when there is no
 * usable certified content.
 */
declare function composeCertifiedPrompt(base: string, certified: CertifiedProfile | null): string;
/** A cached, self-refreshing source of a target's certified prompt additions —
 *  the prompt-only delivery lane for callers that assemble their OWN system
 *  prompt (product chat routes) rather than wrapping an agent fn. Same
 *  fail-closed semantics as {@link withCertifiedDelivery}: pulls at most every
 *  `refreshMs`, coalesces concurrent pulls, keeps the last-known profile on a
 *  failed/404 pull, never throws, never blocks past the pull timeout. */
interface CertifiedPromptSource {
    /** Refresh (window-respecting) then fold the certified additions into a
     *  base system prompt. Returns `base` unchanged when nothing is promoted. */
    compose(base: string): Promise<string>;
    /** The certified profile currently in effect (`null` = none pulled yet). */
    current(): CertifiedProfile | null;
    /** Pull now if the refresh window has elapsed; coalesced and fail-closed. */
    refresh(): Promise<void>;
}
/** Options for {@link createCertifiedPromptSource} — the pull coordinates plus
 *  the refresh cadence. */
interface CertifiedPromptSourceOptions extends PullCertifiedOptions {
    /** Min interval between certified-profile pulls. Default 5m. */
    refreshMs?: number;
}
/**
 * Create the cached certified-prompt source — the ONE module-scope-cache +
 * coalesced-refresh + keep-last-known implementation. Product wiring uses this
 * rather than hand-rolling the same lines around `pullCertified`, and
 * {@link withCertifiedDelivery} is built on it.
 */
declare function createCertifiedPromptSource(opts: CertifiedPromptSourceOptions): CertifiedPromptSource;
/** What the delivery wrapper hands the agent each run. */
interface AppliedIntelligence {
    /** The certified profile in effect (null when none promoted / pull failed —
     *  fail-closed: the agent runs on its base surface). */
    certified: CertifiedProfile | null;
    /** Fold the certified prompt surface into a base system prompt. */
    composePrompt(base: string): string;
}
/** An agent wrapped by {@link withCertifiedDelivery}: receives the input plus
 *  the certified intelligence delivered for this run. */
type DeliveredAgent<I, O> = (input: I, applied: AppliedIntelligence) => Promise<O>;
/** Delivery config = the Observe config plus the pull target + refresh cadence. */
interface DeliveryConfig extends IntelligenceConfig {
    /** Pull target. Defaults to `project`. */
    target?: string;
    /** Plane base URL for the pull (NOT the OTLP `endpoint`). Defaults to
     *  `TANGLE_INTELLIGENCE_URL` then `https://intelligence.tangle.tools`. */
    baseUrl?: string;
    /** Min interval between certified-profile pulls. Default 5m. */
    refreshMs?: number;
    /** Per-pull timeout in ms (fail-closed on a hung plane). Default 10000. */
    timeoutMs?: number;
    /** fetch impl for the pull (tests). Defaults to global fetch. */
    fetchImpl?: typeof fetch;
}
/**
 * Wrap an agent so it (a) Observes each run via the shipped Observe client and
 * (b) RECEIVES the tenant's certified artifacts pulled from the deployed plane.
 * The certified profile is cached and refreshed at most every `refreshMs`; a
 * failed pull is fail-closed — the agent runs on its base surface and never
 * breaks because Intelligence is unreachable. When the plane promotes a new
 * gate-certified surface, the next refresh delivers it to the running agent.
 */
declare function withCertifiedDelivery<I, O>(agent: DeliveredAgent<I, O>, config: DeliveryConfig): ((input: I) => Promise<O>) & {
    refresh(): Promise<void>;
};

/**
 *
 * The Capability-Delivery Manifest — the unified, future-proof structure for
 * delivering ONE certified unit of agent power = `{ interface, binding }`.
 *
 * The law that makes it future-proof: **interfaces are closed; bindings are
 * open.** The interface is the only thing the agent and the certify lane ever
 * reason about (a tool / an MCP toolset / a prompt-context / a retrieval surface
 * / a hook / a subagent). The binding is a tagged union over runtime kinds that
 * the resolver collapses (inline / file / http / sandbox-code / mcp-stdio /
 * mcp-remote / process-on-infra / rag-index / memory-store / wasm / a2a). A new
 * runtime kind = one new binding arm + one resolver case; nothing else moves.
 *
 * This module owns the manifest TYPES and the lowering of TODAY's wire
 * (`CertifiedProfile`) into a `CapabilityManifest`. The resolver — the single
 * place that knows binding kinds and produces a uniform `ResolvedSurface` — lives
 * in `./resolver`. The shipped prompt-only path (`composeCertifiedPrompt` in
 * `./delivery`) is preserved verbatim: a prompt is a `Capability{ surface:
 * 'context', binding:{ kind:'inline' } }`, so the existing
 * `pullCertified → composeCertifiedPrompt → fail-closed` lane is a strict subset.
 *
 * Layering: this depends DOWN on `@tangle-network/sandbox` (the SDK
 * `AgentProfileMcpServer` shape the mcp binding lowers to) and on the runtime's
 * own `ToolSpec`. It never imports agent-eval and never reaches upward.
 *
 * @experimental
 */

/** A JSON Schema object describing a tool's parameters. Kept structural — the
 *  resolver forwards it verbatim into a `ToolSpec` / MCP `tools/list` check. */
type JsonSchema = Record<string, unknown>;
/**
 * What the agent consumes. CLOSED — a new runtime kind NEVER extends this. Each
 * arm maps slot-for-slot onto `AgentProfile` + the host `RouterToolsSeam`.
 */
type CapabilityInterface = {
    surface: 'tool';
    name: string;
    description?: string;
    parameters: JsonSchema;
    returns?: JsonSchema;
} | {
    surface: 'mcp';
    serverName: string;
    toolset?: string[];
} | {
    surface: 'context';
    kind: 'prompt-surface' | 'skill' | 'instructions';
    name: string;
} | {
    surface: 'retrieval';
    name: string;
    description?: string;
    topK?: number;
} | {
    surface: 'hook';
    event: string;
    matcher?: string;
} | {
    surface: 'subagent';
    name: string;
    description?: string;
};
/** Every interface surface tag — the closed set the resolver fans into slots. */
type CapabilitySurface = CapabilityInterface['surface'];
/**
 * Where a capability's bytes live. A leaked manifest carries no live secret and
 * no inlined blob: `github`/`blob` are pointers resolved at provision time.
 */
type ContentRef = {
    kind: 'inline';
    content: string;
} | {
    kind: 'github';
    repository?: string;
    path: string;
    ref?: string;
} | {
    kind: 'blob';
    uri: string;
    sha256: string;
    bytes?: number;
};
/** A named secret a binding requires — declared, never carried. */
interface CredentialRef {
    key: string;
}
/**
 * How a binding authenticates at resolve time. Declared as a REQUIREMENT in the
 * manifest; the live secret is resolved per-tenant by the resolver context,
 * never inlined here.
 */
type CapabilityAuth = {
    mode: 'none';
} | {
    mode: 'tangle-key';
} | {
    mode: 'hub-connection';
    providerId: string;
    scopes?: string[];
} | {
    mode: 'secret-ref';
    key: string;
};
/**
 * The host a `process-on-infra` binding provisions before its inner binding.
 * Reuses `createExecutor`'s backend-as-data vocabulary — no new runtime invented.
 * `image` is the sandbox image tag; `warm`/`idleTtlMs`/`costTag` meter standing
 * cost; `ports` are the inner server's listen ports the host must expose.
 */
interface HostSpec {
    backend: 'sandbox' | 'router' | 'cli';
    image?: string;
    ports?: number[];
    warm?: boolean;
    idleTtlMs?: number;
    costTag?: string;
}
/**
 * How a capability is backed. OPEN tagged union — THE extension point. All arms
 * are typed even when the resolver does not yet admit them; an un-admitted arm
 * throws {@link CapabilityNotAdmittedError} at resolve, never silently no-ops.
 */
type DeliveryBinding = {
    kind: 'inline';
    content: ContentRef;
} | {
    kind: 'file';
    path: string;
    content: ContentRef;
    executable?: boolean;
} | {
    kind: 'http';
    url: string;
    method?: string;
    auth?: CapabilityAuth;
} | {
    kind: 'sandbox-code';
    entry: string;
    code: ContentRef;
    runtime?: string;
    harness?: string;
} | {
    kind: 'mcp-stdio';
    command: string;
    args?: string[];
    env?: Record<string, string>;
    cwd?: string;
} | {
    kind: 'mcp-remote';
    url: string;
    transport: 'http' | 'sse';
    headers?: Record<string, string>;
} | {
    kind: 'process-on-infra';
    host: HostSpec;
    inner: DeliveryBinding;
} | {
    kind: 'rag-index';
    index: ContentRef;
    embedModel: string;
    topK?: number;
} | {
    kind: 'memory-store';
    provision: 'sqlite' | 'neo4j' | 'vector';
    seed?: ContentRef;
} | {
    kind: 'wasm';
    module: ContentRef;
    exports: string[];
} | {
    kind: 'a2a';
    endpoint: string;
    card: ContentRef;
    auth?: CapabilityAuth;
};
/** Every binding kind — the open set the resolver dispatches over. */
type DeliveryBindingKind = DeliveryBinding['kind'];
/**
 * The certify lane's held-out lift travelling WITH delivery. The shipped
 * `CertifiedArtifact` envelope minus its content (which moves into the binding
 * arm): `version`/`contentHash`/`lift` are stamped by the promote step, never
 * the author.
 *
 * `sourcePath` is the artifact's ORIGINAL path (including `null`). It is the
 * byte-stable fold sort key — the resolver folds context artifacts in
 * `composeCertifiedPrompt` order, which sorts by `path ?? ''`, so a `null` path
 * is load-bearing and MUST round-trip exactly. It is distinct from a context
 * `iface.name` (display only): collapsing the two flips the fold order for a
 * mix of null-path and non-null-path artifacts.
 */
interface CertProvenance {
    contentHash: string;
    version: number | null;
    lift: string | null;
    promotedAt: string;
    sourcePath: string | null;
}
/** One certified unit of agent power. */
interface CertifiedCapability {
    id: string;
    iface: CapabilityInterface;
    binding: DeliveryBinding;
    auth: CapabilityAuth;
    provenance: CertProvenance;
}
/**
 * The strict generalization of `CertifiedProfile`. `promptSurface` is kept
 * during the migration window (the shipped pull lane still emits it); new
 * capabilities live in `capabilities`.
 */
interface CapabilityManifest {
    target: string;
    generatedAt: string;
    promptSurface: CertifiedPromptSurface | null;
    capabilities: CertifiedCapability[];
}
/** One retrieval handle. The agent never learns vector vs graph vs index. */
interface ResolvedRetrieval {
    name: string;
    retrieve(query: string, k?: number): Promise<Array<{
        text: string;
        score?: number;
    }>>;
}
/** One resolved hook — event + the command/matcher the seam folds into
 *  `AgentProfile.hooks`. */
interface ResolvedHook {
    event: string;
    command: string;
    matcher?: string;
}
/** One resolved subagent — folded into `AgentProfile.subagents`. */
interface ResolvedSubagent {
    name: string;
    description?: string;
    prompt?: string;
}
/**
 * What `composeCertifiedProfile` produces. Every binding fans into the same
 * slots, consumed identically by the in-process seam (`RouterToolsSeam.{tools,
 * executeToolCall}` + folded prompt) and the sandbox seam (`AgentProfile`).
 * `dispose()` tears provisioned hosts down in REVERSE dependency order.
 */
interface ResolvedSurface {
    /** Host-side tool defs → `RouterToolsSeam.tools` / agent-app `extraTools`. */
    tools: ToolSpec[];
    /** Host-side dispatch for a resolved tool. Throws when `name` is unknown so a
     *  mis-dispatch is loud, never a silent empty string. */
    execute(name: string, args: Record<string, unknown>, task: unknown): Promise<string>;
    /** Sandbox-side tool delivery → `AgentProfile.mcp` / in-proc `createMcpEnvironment`. */
    mcpConnections: Record<string, AgentProfileMcpServer>;
    /** Prompt-context additions, byte-stable-ordered → folded system prompt. */
    promptAdditions: string[];
    /** Workspace files → `AgentProfile.resources.files`. */
    files: Array<{
        path: string;
        content: string;
        executable?: boolean;
    }>;
    /** Uniform retrieval handles. */
    retrieval: ResolvedRetrieval[];
    /** Hooks → `AgentProfile.hooks`. */
    hooks: ResolvedHook[];
    /** Subagents → `AgentProfile.subagents`. */
    subagents: ResolvedSubagent[];
    /** The folded system prompt — base + the byte-stable prompt additions, exactly
     *  as `composeCertifiedPrompt` renders the inline/context capabilities. */
    systemPrompt: string;
    /** Tear down provisioned hosts (reverse dependency order). */
    dispose(): Promise<void>;
}
/**
 * A binding kind whose resolver case is typed but not yet admitted (rag-index,
 * memory-store, wasm, a2a). Thrown by the resolver — NEVER faked into a working
 * surface. The TYPE arms exist so the union is closed against the spec; the
 * resolver grows them later behind their lifecycle + admission gate.
 */
declare class CapabilityNotAdmittedError extends Error {
    readonly kind: DeliveryBindingKind;
    readonly capabilityId: string;
    constructor(kind: DeliveryBindingKind, capabilityId: string, reason: string);
}
/**
 * Lower the EXISTING plane wire (`CertifiedProfile`) into a `CapabilityManifest`.
 * `prompt-surface`/`skill` artifacts → `context`/inline capabilities (the
 * shipped fold, generalized); any other artifact type → best-effort binding
 * inference (see {@link inferCapability}). `promptSurface` is carried through so
 * the resolver folds it first, exactly as `composeCertifiedPrompt` does today.
 * This delivers the spine against today's wire before the plane changes.
 */
declare function manifestFromProfile(profile: CertifiedProfile): CapabilityManifest;

/**
 *
 * The capability resolver — the ONLY place that knows binding kinds. It lowers a
 * `CapabilityManifest` into a uniform `ResolvedSurface` consumed identically by
 * the in-process seam (`RouterToolsSeam.{tools, executeToolCall}` + a folded
 * prompt) and the sandbox seam (`AgentProfile`).
 *
 * The spine (zero new infra) resolves inline/file, mcp-stdio/mcp-remote, and
 * http tools for BOTH seams, reusing shipped primitives:
 *   - inline/context → `composeCertifiedPrompt` (delivery.ts) — byte-stable order;
 *   - http           → a `ToolSpec` + a host-side fetch `execute`;
 *   - mcp-stdio/remote → an `AgentProfileMcpServer` (the strict union widens to
 *     the SDK's flat shape — an always-valid lowering).
 *
 * The ladder rungs that need infra are INJECTED capabilities of the resolve
 * context (`runSandboxCode`, `provisionHost`), so the substrate-free caller wires
 * only what it can host — a binding that needs an absent provider throws loudly,
 * it is NEVER faked into a working surface. The not-yet-admitted arms (rag-index,
 * memory-store, wasm, a2a) throw {@link CapabilityNotAdmittedError}.
 *
 * Fail-closed by construction (mirroring `pullCertified`): a `null` manifest
 * returns the base surface only; a per-capability resolve failure DROPS that
 * capability (never a half-wired tool); a post-resolve drift check drops any tool
 * whose live names diverge from the certified interface.
 *
 * @experimental
 */

/** A live, provisioned host the resolver tore up for a `process-on-infra` arm.
 *  `teardown()` runs at `dispose()` in reverse provisioning order. */
interface ProvisionedHost {
    /** Lower the inner binding's mcp connection now that the host is up; the URL/
     *  command points at the host. Absent when the host serves a non-mcp inner. */
    mcpConnection?: AgentProfileMcpServer;
    teardown(): Promise<void>;
}
/**
 * Per-call, per-tenant context the resolver reads. Everything that touches the
 * network, a secret, or an infra provisioner is INJECTED so the manifest carries
 * no live secret and the substrate-free caller wires only what it can host.
 */
interface ResolveCtx {
    /** Stable tenant id — namespaces billing + teardown (`tenant#target`). */
    tenant?: string;
    /** fetch impl for http tools. Defaults to global fetch; absent ⇒ http tools fail loud. */
    fetchImpl?: typeof fetch;
    /**
     * Resolve a declared credential to a live secret for THIS tenant. Returns a
     * typed outcome — inspect `succeeded` before `value`. Absent ⇒ a binding that
     * declares non-`none` auth fails loud (never a request with no credential).
     */
    resolveSecret?: (auth: CapabilityAuth, tenant: string | undefined) => Promise<{
        succeeded: true;
        value: string;
    } | {
        succeeded: false;
        error: string;
    }>;
    /**
     * Run a `sandbox-code` body per call. Injected by the host that owns a sandbox
     * client (the spine does not import the sandbox executor). Absent ⇒
     * `sandbox-code` bindings fail loud.
     */
    runSandboxCode?: (code: ContentRef, entry: string, args: Record<string, unknown>, task: unknown) => Promise<string>;
    /**
     * Provision a host for a `process-on-infra` binding, then serve the inner
     * binding inside it. Injected by the host that owns `createExecutor`. Absent ⇒
     * `process-on-infra` bindings fail loud. The provider resolves the inner
     * binding INSIDE the host and returns the connection + a teardown.
     */
    provisionHost?: (host: HostSpec, inner: DeliveryBinding, costTag: string) => Promise<ProvisionedHost>;
    /**
     * Drift probe: return the LIVE tool names a resolved surface exposes for a
     * given capability id (a `tools/list` over an mcp connection, the agent's
     * actual registered tool names for a host tool). When present, the post-resolve
     * drift check drops any tool/mcp whose live names diverge from the certified
     * interface — the only callable surfaces are gate-blessed ones. Absent ⇒ the
     * check enforces only the host-side executor↔spec parity (no live probe).
     */
    probeLiveToolNames?: (capabilityId: string) => Promise<string[]>;
    /**
     * Observe a DROPPED capability — a per-capability resolve failure that is
     * fail-closed (the capability is omitted, never half-wired). The drop is the
     * contract; this surfaces the diagnostic so it is never silently erased. NOT
     * called for {@link CapabilityNotAdmittedError} (that rethrows — a manifest
     * carrying an un-admitted binding kind is a hard error, not a soft drop).
     */
    onDrop?: (capabilityId: string, error: Error) => void;
}
/**
 * Compose a certified profile into a uniform `ResolvedSurface`. Additive over
 * `composeCertifiedPrompt`: the inline/context fold is delegated to
 * `composeCertifiedPrompt` so the byte-stable ordering (prompt surface first,
 * then type alphabetic, then path locale-compare) is reused EXACTLY — the
 * prompt-only path is a strict subset of this.
 *
 * Fail-closed: a `null` manifest returns the base surface only.
 */
declare function composeCertifiedProfile(base: {
    systemPrompt: string;
}, manifest: CapabilityManifest | null, ctx?: ResolveCtx): Promise<ResolvedSurface>;
/** Lower a plane `CertifiedProfile` straight into a `ResolvedSurface` via
 *  `manifestFromProfile` — the convenience the shipped pull lane calls when it
 *  already holds a `CertifiedProfile` (today's wire) rather than a manifest. */
declare function composeCertifiedProfileFromWire(base: {
    systemPrompt: string;
}, profile: CertifiedProfile | null, ctx?: ResolveCtx): Promise<ResolvedSurface>;

/**
 *
 * Tangle Intelligence SDK — the Observe + Mode-0 product layer.
 *
 * A thin, best-effort wrapper over the shipped trace-export substrate
 * (`createOtelExporter` in `../otel-export`). It does exactly two things in
 * this slice:
 *
 *   1. OBSERVE — wrap a generic agent and export one trace span per call to
 *      Tangle Intelligence, swallowing every export failure so a live agent
 *      never fails because Intelligence is down.
 *   2. MODE 0 / OFF — at `effort: 'off'`, run the agent as PURE PASSTHROUGH
 *      (zero intelligence spawns) with best-effort telemetry still on. The
 *      exported trace tags usage by class `{ inferenceUsd, intelligenceUsd }`,
 *      and at OFF `intelligenceUsd` is provably `0` — the mechanism that proves
 *      an OFF customer paid inference-only.
 *
 * Behavior-changing intelligence (analyst steer, candidate promotion, loops)
 * is a LATER phase and is NOT built here. This wrapper only Observes and passes
 * through; there is no abort path, so the only fail-soft surface is the
 * telemetry export.
 *
 * @experimental
 */

/** Usage class for billing. Base-stream tokens bill `'inference'`; every
 *  intelligence spawn (analyst, corpus, loop) bills `'intelligence'`. The
 *  billing line falls on the spawn line. */
type UsageClass = 'inference' | 'intelligence';
/**
 * The per-class cost split carried by every trace and outcome. `off` ⇒
 * `intelligenceUsd: 0` by construction — there is no intelligence spawn to
 * bill. This is a classification on the trace, NOT a budget-pool split.
 */
interface UsageSplit {
    /** Base-stream (model) spend in USD. */
    inferenceUsd: number;
    /** Intelligence-spawn spend in USD. Provably `0` at the OFF tier. */
    intelligenceUsd: number;
}
/** Repo coordinates a product may declare for the (later) Gated-PR mode. The
 *  Observe slice only records their PRESENCE for `doctor()`; it never touches
 *  the repo. */
interface RepoConfig {
    owner: string;
    name: string;
    baseBranch: string;
}
/** Client configuration. `project` + `apiKey` are the Observe minimum; the
 *  rest tune effort, endpoint, redaction, and (for `doctor()` readiness)
 *  declare the surfaces/checks/repo a later PR mode would need. */
interface IntelligenceConfig {
    /** Stable project id — the tenant dimension every trace is tagged with. */
    project: string;
    /** Bearer key for the Intelligence ingest. Reads `TANGLE_API_KEY` when omitted. */
    apiKey?: string;
    /** Effort tier (default `'standard'`) plus optional per-field overrides. */
    effort?: EffortTier | {
        tier: EffortTier;
        overrides?: EffortOverrides;
    };
    /**
     * OTLP ingest base. The underlying exporter appends `/v1/traces`, so point
     * this at the OTLP route (e.g. `https://intelligence.tangle.tools/v1/otlp`).
     * Reads `INTELLIGENCE_OTLP_ENDPOINT` then `OTEL_EXPORTER_OTLP_ENDPOINT` when
     * omitted; absent all three, export is a no-op (best-effort by construction).
     */
    endpoint?: string;
    /**
     * Redaction hook run over every exported input/output. A function replaces
     * the default scrubber; `false` opts out entirely (raw fidelity, caller has
     * sanitized upstream); omitted ⇒ the built-in `defaultRedactor`.
     */
    redact?: Redactor | false;
    /** Mutable surfaces a later PR mode would edit. Recorded for `doctor()` only. */
    surfaces?: string[];
    /** Verification checks a later PR mode would gate on. Recorded for `doctor()` only. */
    checks?: string[];
    /** Repo access a later PR mode would need. Recorded for `doctor()` only. */
    repo?: RepoConfig;
}
/** Metadata describing one traced run. `runId`/`traceId` default to fresh ids. */
interface TraceMeta {
    /** The run's input — exported through the redactor. */
    input?: unknown;
    /** Stable run id. Defaults to a fresh id. */
    runId?: string;
    /** 32-hex trace id. Defaults to a fresh id. */
    traceId?: string;
    /** Model id, when known — stamped on the span. */
    model?: string;
    /** Provider name, when known — stamped on the span. */
    provider?: string;
    /** Arbitrary extra labels (string/number/boolean) stamped on the span. */
    labels?: Record<string, string | number | boolean>;
}
/**
 * The trace handle a `traceRun` body records into. `recordOutput` captures the
 * agent's result (redacted on export); `recordOutcome` captures the scored
 * outcome + the `{ inferenceUsd, intelligenceUsd }` split. Both are optional —
 * an un-recorded run still exports a span with whatever was set.
 */
interface TraceHandle {
    /** Capture the run's output. Exported through the redactor. */
    recordOutput(output: unknown): void;
    /**
     * Capture the run's outcome. `usage` defaults to inference-only
     * (`intelligenceUsd: 0`) — the OFF baseline; an intelligence-enabled run
     * fills `intelligenceUsd` itself. `costUsd`, when given without a split, is
     * treated as pure inference.
     */
    recordOutcome(outcome: {
        success?: boolean;
        score?: number;
        costUsd?: number;
        usage?: Partial<UsageSplit>;
    }): void;
}
/** Metadata for {@link IntelligenceClient.recordTrace}. */
interface RecordTraceMeta {
    /** 32-hex trace id to anchor every span to. Defaults to a fresh id. */
    traceId?: string;
    /** Span id of an enclosing span the loop root should parent under (e.g. a
     *  `traceRun` span). Omitted ⇒ the loop root is the trace root. */
    rootParentSpanId?: string;
}
/** The resolved outcome of one traced run, surfaced on the export span and
 *  available to the caller for downstream billing assertions. */
interface TraceOutcome {
    runId: string;
    traceId: string;
    project: string;
    /** The resolved effort settings this run executed under. */
    effort: EffortSettings;
    /** True when this run ran as pure passthrough (the OFF floor). */
    intelligenceOff: boolean;
    success?: boolean;
    score?: number;
    /** Per-class billing split. `intelligenceUsd` is `0` at the OFF tier. */
    usage: UsageSplit;
}
/** The Observe-mode Intelligence client. */
interface IntelligenceClient {
    /** The resolved project id. */
    readonly project: string;
    /** The resolved effort settings. */
    readonly effort: EffortSettings;
    /**
     * Run `fn` under a trace, export one span best-effort, and return whatever
     * `fn` returns. Telemetry-export failures are swallowed; an error THROWN by
     * `fn` propagates to the caller (the agent's own failures are not masked).
     */
    traceRun<T>(meta: TraceMeta, fn: (trace: TraceHandle) => Promise<T>): Promise<T>;
    /**
     * Export a run's full loop topology — the ordered `LoopTraceEvent` stream a
     * `runLoop`/`Supervisor` run emits — as a nested OTLP span tree (loop → round →
     * iteration) into ONE trace. Reuses the shipped `buildLoopOtelSpans` builder
     * (NO second span builder), so the topology a viewer renders matches the
     * kernel's. `traceId` defaults to a fresh id; `rootParentSpanId` parents the
     * loop root under an enclosing span (e.g. a `traceRun` span) when given.
     * Best-effort: export failures are swallowed. Returns the resolved `traceId`.
     */
    recordTrace(events: ReadonlyArray<LoopTraceEvent>, meta?: RecordTraceMeta): string;
    /**
     * Network-free readiness report: which adoption modes are reachable given
     * this config. Observe is always reachable; Recommend needs outcomes; PR
     * needs checks + surfaces + repo.
     */
    doctor(): DoctorReport;
    /** Flush any pending export spans. Best-effort; resolves even if export fails. */
    flush(): Promise<void>;
}
/** One mode's readiness verdict. */
interface ModeReadiness {
    ready: boolean;
    /** Inputs this mode still needs, when not ready. Empty when ready. */
    missing: string[];
}
/** The `doctor()` readiness report — Mode-readiness without any network call. */
interface DoctorReport {
    project: string;
    effort: EffortSettings;
    /** True when an OTLP endpoint is configured (export will actually ship). */
    exportConfigured: boolean;
    modes: {
        observe: ModeReadiness;
        recommend: ModeReadiness;
        pr: ModeReadiness;
    };
}
/**
 * Create an Observe-mode Intelligence client. Resolves effort, endpoint, and
 * redactor up front; the exporter is built lazily and is `undefined` when no
 * endpoint is configured (export becomes a no-op — best-effort by
 * construction).
 */
declare function createIntelligenceClient(config: IntelligenceConfig): IntelligenceClient;
/** A generic agent: one async input → output. The shape `withTangleIntelligence`
 *  preserves exactly. */
type Agent<TInput, TOutput> = (input: TInput) => Promise<TOutput>;
/** Either a built client or the config to build one. */
type ClientOrConfig = IntelligenceClient | IntelligenceConfig;
/**
 * Wrap a generic `agent` with best-effort Observe-mode tracing, returning the
 * SAME shape. Each call runs the agent under a trace and exports one span; an
 * export failure is swallowed (the live agent never fails because Intelligence
 * is down) but an error from the agent itself propagates unchanged.
 *
 * At `effort: 'off'` this is pure passthrough plus best-effort telemetry —
 * zero intelligence spawns, `intelligenceUsd: 0` on the trace.
 */
declare function withTangleIntelligence<TInput, TOutput>(agent: Agent<TInput, TOutput>, clientOrConfig: ClientOrConfig): Agent<TInput, TOutput>;

export { type Agent, type AppliedIntelligence, type CapabilityAuth, type CapabilityInterface, type CapabilityManifest, CapabilityNotAdmittedError, type CapabilitySurface, type CertProvenance, type CertifiedArtifact, type CertifiedCapability, type CertifiedProfile, type CertifiedPromptSource, type CertifiedPromptSourceOptions, type CertifiedPromptSurface, type ClientOrConfig, type ContentRef, type CorpusAccess, type CredentialRef, type DeliveredAgent, type DeliveryBinding, type DeliveryBindingKind, type DeliveryConfig, type DoctorReport, type EffortOverrides, type EffortOverridesCompiled, type EffortSettings, type EffortTier, type HostSpec, type IntelligenceClient, type IntelligenceConfig, type JsonSchema, type ModeReadiness, type ProvisionedHost, type PullCertifiedOptions, type PullOutcome, type RecordTraceMeta, type Redactor, type RepoConfig, type ResolveCtx, type ResolvedHook, type ResolvedRetrieval, type ResolvedSubagent, type ResolvedSurface, type TraceHandle, type TraceMeta, type TraceOutcome, type UsageClass, type UsageSplit, compileEffort, composeCertifiedProfile, composeCertifiedProfileFromWire, composeCertifiedPrompt, createCertifiedPromptSource, createIntelligenceClient, defaultEffortTier, defaultRedactor, isIntelligenceOff, manifestFromProfile, pullCertified, resolveEffort, resolveRedactor, withCertifiedDelivery, withTangleIntelligence };
