export { C as CatalogModel, M as ModelCatalog, R as RouterModel, _ as __resetCatalogCache, b as buildCatalog, f as fetchModelCatalog, n as normalizeModelId } from '../model-catalog-BEAEVDaa.js';
export { C as CreateTangleRouterModelConfigOptions, D as DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR, a as DEFAULT_TANGLE_ROUTER_BASE_URL, R as ResolveModelOptions, b as ResolveTangleDevOrUserKeyOptions, c as ResolveUserTangleExecutionKeyForUserOptions, d as ResolveUserTangleExecutionKeyOptions, e as ResolvedTangleExecutionKey, T as TangleBillingEnforcementOptions, f as TangleExecutionEnvironment, g as TangleExecutionKeyError, h as TangleExecutionKeyErrorCode, i as TangleExecutionKeyHttpError, j as TangleExecutionKeySource, k 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-dF2h4xT9.js';
import * as _tangle_network_agent_runtime from '@tangle-network/agent-runtime';
import { ToolLoopMessage, ToolLoopResult, StreamToolLoopYield, ToolLoopCall } 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 { b as AppToolContext, e as AppToolProducedEvent, f as AppToolTaxonomy, c as AppToolHandlers, d as AppToolOutcome } from '../types-wHs0rmtu.js';
import { CertifiedProfile } from '@tangle-network/agent-runtime/intelligence';
import { A as AppToolMcpServer } from '../mcp-4I_RHhNa.js';
import '../auth-DcK5ERaL.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>;
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>;

/**
 * `createAgentRuntime` — the in-process agent core, assembled.
 *
 * The bricks to run an agent turn WITHOUT a sandbox already exist in this
 * package, but a consumer must hand-wire five of them every time: resolve the
 * model config, build the OpenAI tool schemas from the taxonomy, build a
 * `streamTurn` over the model endpoint, build an `executeToolCall` over the
 * product's handlers, and drive `runAppToolLoop` / `streamAppToolLoop` with an
 * `isExecutableTool` predicate. That boilerplate is identical across every
 * sandbox-free surface (an edge/browser copilot, an eval harness, a Node CLI),
 * and getting it subtly wrong — e.g. NOT advertising the tools, so the model
 * never emits a `tool_call` and no side effect ever fires — is exactly the
 * failure that makes a tool-driven agent score zero off-sandbox.
 *
 * This factory bundles those five into one object configured for ONE agent:
 *
 *   const runtime = createAgentRuntime({ model, taxonomy, handlers, systemPrompt })
 *   const result = await runtime.run(userMessage, { ctx })            // awaitable
 *   for await (const y of runtime.stream(userMessage, { ctx })) {…}   // streaming
 *
 * The model is advertised the app tools (so it CAN call them); each call is
 * dispatched against the product's `handlers` (so the side effect is real); the
 * `onProduced` hook fires at the real side-effect site (so an eval/UI credits a
 * persisted proposal or artifact). Substrate-free: no `@tangle-network/sandbox`,
 * no Durable Object, no `@tangle-network/agent-runtime` import. The SAME core
 * the Cloudflare Worker runs, runnable anywhere a `fetch` to an OpenAI-compatible
 * endpoint works.
 *
 * Domain stays out: the proposal taxonomy, the handlers, and the system prompt
 * are all injected — the factory knows nothing about insurance, law, tax, etc.
 */

/** OpenAI-compatible model endpoint (Tangle Router / tcloud / any compat
 *  provider). Build from {@link resolveTangleModelConfig} or pass literals. */
interface AgentRuntimeModelConfig {
    baseUrl: string;
    apiKey: string;
    model: string;
    temperature?: number;
    fetchImpl?: typeof fetch;
    /** Extra request-body fields (e.g. `max_tokens`, a `reasoning` block). */
    extraBody?: Record<string, unknown>;
}
/** 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` (the model's advertised tools is
 *  rebuilt when these change). MCP servers / memory / RAG that materialize as
 *  files or servers deliver through the sandbox-provisioning seam, not here. */
interface ResolvedAgentProfile {
    systemPrompt: string;
    extraTools: unknown[];
}
interface CreateAgentRuntimeOptions {
    /** The model endpoint the turns stream from. */
    model: AgentRuntimeModelConfig;
    /**
     * Optional transform applied to the resolved profile surfaces each turn —
     * the seam for certified-artifact delivery (`createCertifiedDelivery`). It is
     * profile-WIDE (not prompt-only): it returns the effective `systemPrompt` +
     * advertised `extraTools`. Kept generic + injected so this substrate-free core
     * never imports `@tangle-network/agent-runtime`. Fail-closed by contract: an
     * impl that can't reach the plane returns the base surfaces unchanged.
     */
    composeProfile?: (base: ResolvedAgentProfile) => ResolvedAgentProfile | Promise<ResolvedAgentProfile>;
    /** The product's proposal taxonomy — advertises `submit_proposal`'s `type`
     *  enum to the model and labels the regulated subset on the result. */
    taxonomy: AppToolTaxonomy;
    /** Domain handlers persisting each tool to the product's store/vault. */
    handlers: AppToolHandlers;
    /** Default agent identity / system prompt. A turn may override it. */
    systemPrompt: string;
    /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.
     *  For per-workflow limits use `deadlineMs` or `maxCostUsd` on the loop options. */
    maxToolTurns?: number;
    /** Extra OpenAI tool definitions advertised ALONGSIDE the four app tools
     *  (e.g. `integration_invoke`). Pair with {@link executeOtherTool}. */
    extraTools?: unknown[];
    /** Execute a tool that is NOT one of the four app tools (e.g. an integration
     *  action). Only consulted for names {@link isOtherExecutableTool} accepts. */
    executeOtherTool?: (call: ToolLoopCall, ctx: AppToolContext) => Promise<AppToolOutcome>;
    /** Which non-app tool names are executable here. Required if {@link executeOtherTool} is set. */
    isOtherExecutableTool?: (toolName: string) => boolean;
}
interface AgentTurnOptions {
    /** The trusted per-turn context (who/where the turn runs as). */
    ctx: AppToolContext;
    /** Prior conversation turns, in order. */
    priorMessages?: Array<{
        role: string;
        content: string;
    }>;
    /** Override the factory's default system prompt for this turn. */
    systemPrompt?: string;
    /** Fires at the real side-effect site for each produced proposal/artifact. */
    onProduced?: (event: AppToolProducedEvent) => void;
}
interface AgentRuntime {
    /** Run the bounded tool loop to completion; resolve with final text + every
     *  executed tool outcome. */
    run(userMessage: string, turn: AgentTurnOptions): Promise<ToolLoopResult>;
    /** Stream the bounded tool loop: yields each raw model event and each executed
     *  tool result as it happens (for SSE re-emission + telemetry). */
    stream(userMessage: string, turn: AgentTurnOptions): AsyncGenerator<StreamToolLoopYield<LoopEvent>, void, unknown>;
}
/**
 * Create an in-process agent runtime for one agent. See the module doc for the
 * full rationale; the short version: it advertises the app tools to the model,
 * dispatches each emitted call against `handlers`, and drives the bounded loop —
 * the whole agent core, sandbox-free.
 */
declare function createAgentRuntime(opts: CreateAgentRuntimeOptions): AgentRuntime;

/**
 * `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).
 */

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;
}
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>;
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 AgentRuntime, type AgentRuntimeModelConfig, type AgentTurnOptions, type AnySurfaceKind, type CertifiedDelivery, type CertifiedDeliveryConfig, type CreateAgentRuntimeOptions, type LoopEvent, type OpenAICompatStreamTurnOptions, type OpenAIStreamChunk, type ResolvedAgentProfile, type SurfaceKindDefinition, type SurfaceMcpServer, type SurfaceMergeBase, type SurfaceOverlay, type SurfacePermissionValue, type SurfaceRegistry, createAgentRuntime, createCertifiedDelivery, createOpenAICompatStreamTurn, createSurfaceRegistry, defineSurfaceKind, mergeSurfaceOverlay, toLoopEvents };
