export { CatalogModel, ModelCatalog, RouterModel, __resetCatalogCache, buildCatalog, fetchModelCatalog, normalizeModelId } from '../catalog/index.js';
export { C as CreateTangleRouterModelConfigOptions, D as DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR, c as DEFAULT_TANGLE_ROUTER_BASE_URL, R as ResolveModelOptions, d as ResolveTangleDevOrUserKeyOptions, e as ResolveUserTangleExecutionKeyForUserOptions, f as ResolveUserTangleExecutionKeyOptions, g as ResolvedTangleExecutionKey, h as TangleBillingEnforcementOptions, a as TangleExecutionEnvironment, i as TangleExecutionKeyError, j as TangleExecutionKeyErrorCode, k as TangleExecutionKeyHttpError, b as TangleExecutionKeySource, T as TangleModelConfig, l as createTangleRouterModelConfig, m as isTangleBillingEnforcementDisabled, n as isTangleExecutionKeyError, r as resolveTangleDevOrUserKey, o as resolveTangleExecutionEnvironment, p as resolveTangleModelConfig, q as resolveUserTangleExecutionKey, s as resolveUserTangleExecutionKeyForUser, t as tangleExecutionKeyHttpError, u as trimOrNull } from '../model-CdCDfBA9.js';
import * as _tangle_network_agent_runtime from '@tangle-network/agent-runtime';
import { ToolLoopMessage } from '@tangle-network/agent-runtime';
export { RunToolLoopOptions as AppToolLoopOptions, ToolLoopAssistantToolCall as LoopAssistantToolCall, ToolLoopMessage as LoopMessage, ToolLoopCall as LoopToolCall, StreamToolLoopOptions as StreamAppToolLoopOptions, StreamToolLoopYield as StreamLoopYield, ToolLoopEvent, ToolLoopResult, ToolLoopStopReason, runToolLoop as runAppToolLoop, streamToolLoop as streamAppToolLoop } from '@tangle-network/agent-runtime';
import { CertifiedProfile } from '@tangle-network/agent-runtime/intelligence';
import { A as AppToolMcpServer } from '../mcp-D3qVzbE1.js';
import '../types-BCxK0wyS.js';
import '../auth-anc7mv2W.js';

/**
 * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.
 *
 * This is the app's own `Raw` event type for the streaming loop — the canonical
 * `streamToolLoop<Raw>` is generic over it. It widens the substrate's
 * tool-loop event with `reasoning` (DeepSeek/router `reasoning_content` /
 * `thinking` deltas, rendered as thinking sections) and `usage` (per-message
 * token accounting) — neither belongs in the substrate's loop contract, so they
 * stay here. The adapter maps each into the `streamTurn` seam; `text` and
 * `tool_call` drive the loop, `reasoning` / `usage` pass through to the UI.
 */
type LoopEvent = {
    type: 'text';
    text: string;
} | {
    type: 'reasoning';
    text: string;
} | {
    type: 'tool_call';
    call: _tangle_network_agent_runtime.ToolLoopCall;
} | {
    type: 'usage';
    usage: {
        promptTokens: number;
        completionTokens: number;
    };
} | {
    type: 'other';
    event: unknown;
};

/**
 * OpenAI-compatible stream → `LoopEvent` adapter, for NON-sandbox copilots.
 *
 * `streamAppToolLoop` takes a `streamTurn` seam that yields `LoopEvent`s. A
 * sandboxed agent produces those from its container; a browser/edge copilot
 * instead calls a model directly. The Tangle Router, the tcloud SDK, and most
 * providers all speak the OpenAI Chat Completions streaming shape — so the ONE
 * reusable piece is assembling that stream (content deltas + FRAGMENTED
 * tool-call deltas) into `LoopEvent`s. That assembly is the boilerplate every
 * copilot would re-write (and get wrong — OpenAI streams tool-call arguments in
 * pieces across chunks).
 *
 * This does NOT implement an HTTP client beyond a minimal `fetch` + SSE reader
 * (browser/edge/Node-safe, zero deps). For richer transport use the tcloud SDK
 * or the Vercel AI SDK and pipe their stream through {@link toLoopEvents}.
 */

/** Minimal OpenAI Chat Completions streaming chunk (structural — no `openai` dep). */
interface OpenAIStreamChunk {
    choices?: Array<{
        delta?: {
            content?: string | null;
            /** Reasoning deltas — DeepSeek/router use `reasoning_content`; some proxies use `thinking`. */
            reasoning_content?: string | null;
            thinking?: string | null;
            tool_calls?: Array<{
                index: number;
                id?: string;
                function?: {
                    name?: string;
                    arguments?: string;
                };
            }>;
        };
        finish_reason?: string | null;
    }>;
    /** Final-chunk token accounting (requires `stream_options.include_usage`). */
    usage?: {
        prompt_tokens?: number;
        completion_tokens?: number;
    } | null;
}
/**
 * Map an OpenAI-compat streaming chunk iterator to `LoopEvent`s: each content
 * delta → a `text` event; tool-call deltas are accumulated by index across
 * chunks and emitted as one complete `tool_call` event when the stream finishes
 * (arguments JSON-parsed; an empty/garbled args string yields `{}` rather than
 * throwing). Works for the Tangle Router, tcloud, or any OpenAI-compat source.
 */
declare function toLoopEvents(chunks: AsyncIterable<OpenAIStreamChunk>): AsyncIterable<LoopEvent>;
/** Define options for configuring an OpenAI-compatible streaming chat turn including API details and tools */
interface OpenAICompatStreamTurnOptions {
    /** OpenAI-compat base URL (e.g. the Tangle Router `https://router.tangle.tools/v1`). */
    baseUrl: string;
    apiKey: string;
    model: string;
    /** OpenAI tool definitions — pass `buildAppToolOpenAITools(taxonomy)` so the
     *  model can call the app tools. Omit for a tool-free copilot. */
    tools?: unknown[];
    temperature?: number;
    fetchImpl?: typeof fetch;
    /** Extra body fields (e.g. `max_tokens`). */
    extraBody?: Record<string, unknown>;
}
/**
 * Build a `streamTurn` that calls an OpenAI-compatible `/chat/completions`
 * endpoint (Tangle Router / tcloud / any compat provider) with `stream: true`
 * and yields `LoopEvent`s via {@link toLoopEvents}. Browser/edge/Node-safe —
 * just `fetch` + an SSE reader. Drop straight into `streamAppToolLoop`:
 *
 *   const cfg = resolveTangleModelConfig()                 // or { baseUrl, apiKey, model }
 *   streamAppToolLoop({ streamTurn: createOpenAICompatStreamTurn({ ...cfg, tools }), executeToolCall, ... })
 */
declare function createOpenAICompatStreamTurn(opts: OpenAICompatStreamTurnOptions): (messages: ToolLoopMessage[]) => AsyncIterable<LoopEvent>;

/**
 * The resolved per-turn profile surfaces a delivered / certified `AgentProfile`
 * can change.
 *
 * This file used to also carry `createAgentRuntime` — a factory that hand-wired
 * `resolveTangleModelConfig` + `buildAppToolOpenAITools` + `createOpenAICompatStreamTurn`
 * + `createAppToolRuntimeExecutor` + `runAppToolLoop` into one object. It shipped
 * for the whole life of the package and never acquired a consumer (0 references
 * across all nine repos on the fleet's default branches), while every product
 * that drives an in-process model turn composes those five directly or uses
 * `handleChatTurn`. It was removed in 0.44.0; compose the pieces, or see
 * `examples/browser-copilot.md` for the sandbox-free assembly.
 */
/** The agent's resolved profile surfaces for one turn — the things a delivered
 *  / certified `AgentProfile` can change. Profile-WIDE on purpose: certified
 *  delivery folds prompt-surface + skills into `systemPrompt` AND can add
 *  certified `tool` artifacts to `extraTools`. MCP servers / memory / RAG that
 *  materialize as files or servers deliver through the sandbox-provisioning
 *  seam, not here. */
interface ResolvedAgentProfile {
    systemPrompt: string;
    extraTools: unknown[];
}

/**
 * `createCertifiedDelivery` — the delivery truck for Tangle Intelligence.
 *
 * Pulls a tenant's CERTIFIED `AgentProfile` from the deployed plane
 * (`GET /v1/profiles/:target/composed`) and applies it to the agent's resolved
 * surfaces each turn, so an approved improvement reaches the running agent with
 * NO redeploy. This is the `composeProfile` transform `createAgentRuntime`
 * accepts — opt-in per product, fail-closed, cached + refreshed.
 *
 * Profile-WIDE by design (not prompt-only): the composed profile carries every
 * promoted artifact type keyed by kind. What's folded where:
 *   - `prompt-surface` + `skill` → the system prompt (via `composeCertifiedPrompt`).
 *   - `tool` artifacts that carry an OpenAI tool definition → `extraTools`
 *     (advertised to the model; the matching executor is supplied by the product
 *     via `executeOtherTool`). Until a `tool` artifact carries a runnable def,
 *     it is surfaced (see `current()`) but not advertised — advertising a tool
 *     with no executor would make the model call into a dead end.
 *   - `mcp` / `memory` / `rag` artifacts materialize as servers/files and deliver
 *     through the SANDBOX-provisioning seam, not this in-process one. The full
 *     certified profile is exposed via `current()` so that seam can consume it.
 *
 * Substrate boundary: THIS module imports `@tangle-network/agent-runtime`; the
 * `createAgentRuntime` core does not (it only consumes the generic transform).
 */

/** Define configuration options for delivering certified artifacts to a specified tenant target */
interface CertifiedDeliveryConfig {
    /** The tenant target whose certified artifacts to deliver (the agent id). */
    target: string;
    /** Bearer for the plane. Reads `TANGLE_API_KEY` when omitted. */
    apiKey?: string;
    /** Plane base URL. Reads `TANGLE_INTELLIGENCE_URL` then the public plane. */
    baseUrl?: string;
    /** Min interval between certified-profile pulls. Default 5m. */
    refreshMs?: number;
    /** fetch impl (tests / non-global-fetch runtimes). */
    fetchImpl?: typeof fetch;
}
/** Resolve and manage certified profiles with refresh and composition capabilities */
interface CertifiedDelivery {
    /** The `composeProfile` transform to pass to `createAgentRuntime`. Applies the
     *  cached certified profile to the base surfaces; refreshes on the cadence. */
    composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>;
    /** Force a pull now (ignores the refresh window). Best-effort. */
    refresh(): Promise<void>;
    /** The certified profile currently in effect (null = none promoted / pull
     *  failed). Lets the sandbox-provisioning seam deliver the file/server
     *  artifact types this in-process seam doesn't. */
    current(): CertifiedProfile | null;
}
/**
 * Build a certified-delivery transform for one agent target. Fail-closed: a pull
 * error or 404 keeps the last-known certified profile (or null), and the agent
 * runs on its base surfaces — it never breaks because Intelligence is down.
 */
declare function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery;

/**
 * Surface-scoped profile overlay — the seam letting any product page (a
 * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt
 * addendum, and permission tightening to the workspace agent profile for turns
 * initiated FROM that surface, without the chat orchestrator knowing any
 * surface's specifics. The orchestrator resolves `(kind, ctx)` through a
 * registry the REQUEST HANDLER constructs per request (construction is a Map
 * build — cheap) and merges the result into the base profile it was about to
 * send to the sandbox. Per-request construction is the trust mechanism, not an
 * optimization target: each `build()` closes over server-trusted request state
 * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers
 * exists only per request — a startup-built registry would force identity
 * through the untrusted client `ctx`.
 *
 * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on
 * the client request and are pure ROUTING data — never trusted content, never
 * identity. Identity comes from the closure (see above). The registered
 * `build()` runs server-side only: it validates the routing ids against the
 * product's access control, then mints its own URLs and capability tokens from
 * server configuration (`buildHttpMcpServer` + `createCapabilityToken` in
 * ../tools). A client can therefore never inject an arbitrary MCP url, header,
 * or token into the agent profile: the overlay's `mcp` values are typed as
 * {@link SurfaceMcpServer} (= the server-built `AppToolMcpServer` entry shape),
 * and only build() constructs them.
 */

/** Sandbox permission posture values, ranked deny > ask > allow for merging. */
type SurfacePermissionValue = 'allow' | 'ask' | 'deny';
/** The only MCP entry shape an overlay may carry: the server-built bridge
 *  entry from ../tools/mcp (transport, url, headers, and capability token all
 *  assembled server-side). The alias exists so overlay authors reach for the
 *  builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes
 *  that would let request data become a dialable endpoint. */
type SurfaceMcpServer = AppToolMcpServer;
/** What one surface contributes to the agent profile for a single turn. */
interface SurfaceOverlay {
    /** MCP servers to mount for this turn, keyed by tool-routing name. Names
     *  must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */
    mcp?: Record<string, SurfaceMcpServer>;
    /** Appended to the base system-prompt addendum with a blank-line separator. */
    promptAddendum?: string;
    /** Per-key posture the surface wants for its turns. Merging is monotone
     *  fail-closed: the stricter of base/overlay wins, so a surface can tighten
     *  the workspace posture but never relax it. */
    permissions?: Record<string, SurfacePermissionValue>;
}
/**
 * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM
 * about the client payload, not a guarantee: the registry hands build() the
 * request's `ctx` unvalidated, so build() must treat every field as an
 * untrusted id (resolve it through access control that throws on a bad or
 * foreign id) before minting anything from it.
 */
interface SurfaceKindDefinition<TCtx> {
    kind: string;
    build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>;
}
/** The variance-erased form a registry accepts (`build` is contravariant in
 *  `TCtx`, so every concrete definition is assignable to this). */
type AnySurfaceKind = SurfaceKindDefinition<never>;
/**
 * Declare one surface kind. The `kind` string is the client-visible routing
 * key (e.g. `'sequences'`); `build` is the server-side factory that turns a
 * validated ctx into the overlay for one turn.
 */
declare function defineSurfaceKind<TCtx>(opts: {
    kind: string;
    build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>;
}): SurfaceKindDefinition<TCtx>;
/** Resolve and build the overlay for a given surface kind within a turn context */
interface SurfaceRegistry {
    /** Build the overlay for one turn. Throws on an unknown kind — an unknown
     *  surface is a routing bug (client and server registries drifted), and
     *  silently returning an empty overlay would strip the surface's tools from
     *  the turn with no signal anywhere. Build errors propagate unwrapped. */
    resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>;
}
/**
 * Assemble the product's surface registry from its registered kinds. Duplicate
 * kinds throw at construction: two builders behind one routing key would make
 * the mounted toolset depend on registration order.
 */
declare function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry;
/** Base-profile slice the merge reads/writes. Real callers pass their full
 *  profile object; every field outside this slice passes through untouched. */
interface SurfaceMergeBase {
    mcp?: Record<string, unknown>;
    systemPromptAddendum?: string;
    permissions?: Record<string, SurfacePermissionValue>;
}
/**
 * Merge one surface overlay into a base profile, returning a new object
 * (the base is never mutated; untouched nested records are shared by
 * reference).
 *
 * - `mcp`: overlay servers are added under their own names. A name already
 *   present on the base THROWS — a collision is two servers claiming one
 *   routing name, and renaming either silently would corrupt tool routing for
 *   whichever caller expected the original binding.
 * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a
 *   blank-line separator (no separator when the base has no addendum).
 * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A
 *   surface can tighten the base posture for its turns; a base 'deny' survives
 *   any overlay.
 */
declare function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(base: TBase, overlay: SurfaceOverlay): TBase & SurfaceMergeBase;

export { type AnySurfaceKind, type CertifiedDelivery, type CertifiedDeliveryConfig, type LoopEvent, type OpenAICompatStreamTurnOptions, type OpenAIStreamChunk, type ResolvedAgentProfile, type SurfaceKindDefinition, type SurfaceMcpServer, type SurfaceMergeBase, type SurfaceOverlay, type SurfacePermissionValue, type SurfaceRegistry, createCertifiedDelivery, createOpenAICompatStreamTurn, createSurfaceRegistry, defineSurfaceKind, mergeSurfaceOverlay, toLoopEvents };
