import { E as ExecutorFactory, b as ExecutorRegistry, h as Spend, c as Agent, i as Scope, d as ResultBlobStore, B as Budget } from './types-Driepl87.js';
import { AgentProfile } from '@tangle-network/agent-interface';
import { U as UiLens, a as UiFinding, C as CoderTask } from './substrate-DO2GHNg2.js';
import { e as LoopTraceEmitter, c as LoopTraceEvent, S as SandboxClient, A as AgentRunSpec, E as ExecCtx } from './types-ESeMOj94.js';
import { SandboxEvent, SandboxInstance, BackendType } from '@tangle-network/sandbox';
import { AgentEvalError } from '@tangle-network/agent-eval';
import { O as OtelExporter } from './otel-export-BKmNwiCb.js';
import { T as ToolSpec, R as RouterConfig } from './router-client-r8y_VFVM.js';
import { G as GitRunner, a as WorktreeCheckRunner, D as DeliverableSpec } from './worktree-harness-CX_McRLp.js';
import { L as LocalHarness } from './local-harness-sI0S_XNA.js';
import { ProviderExecutorOptions, AgentEnvironmentProviderRegistry } from './environment-provider.js';
import { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider';

/**
 *
 * The child→parent message bus: the ONE pipe carrying every message a worker, sub-driver, or
 * analyst sends up to the driver — settled outputs, questions, and trace-analyst findings. It
 * unifies channels that were ad-hoc before (the settled-worker cursor, the ask-parent question
 * channel, and analyst results) into a single typed primitive with two lanes:
 *
 *   - PASS-THROUGH (`subscribe`): every published event reaches subscribers immediately — the
 *     express lane for online steering and live observation (a UI, a hook, the parent's box).
 *   - STANDBY (`pull`): events also queue so the driver consumes them on its own cadence. The queue
 *     is PRIORITY-ordered: a higher-`priority` event (a blocking question) is bumped ahead of
 *     queued settles/findings so the driver sees it first; ties resolve FIFO by publish order.
 *
 * Observability is first-class (A++): every event is stamped with a monotonic `seq` and wall-clock
 * `at`, the full ordered `history()` is retained as an audit/replay trail, and `stats()` exposes
 * published/pulled counts by kind. Subscribers receive the stamped record, not a bare event.
 *
 * The interface is transport-agnostic on purpose. Same box → this in-process queue. Cross box →
 * the SAME publish/pull/subscribe surface backed by a durable mailbox on the parent's box (children
 * POST events with at-least-once retry; payloads are blob refs so the event stays small). Consumers
 * depend only on this interface, so distribution is a transport swap, never an architecture change.
 *
 * @experimental
 */
/** Every bus event is a discriminated union member keyed by `type`. */
interface BusEvent {
    readonly type: string;
}
/** A published event stamped for ordering and observability. `seq` is the monotonic publish index;
 *  `priority` drives pull order (higher = bumped ahead); `at` is the wall-clock publish time (ms). */
interface BusRecord<E extends BusEvent> {
    readonly seq: number;
    readonly at: number;
    readonly priority: number;
    readonly event: E;
}
interface PublishOptions {
    /** Higher = pulled ahead of lower-priority queued events (default 0). A blocking question sets
     *  this so it bumps to the front of the driver's inbox. */
    readonly priority?: number;
    /** Whether the event enters the pull queue (default true). Set `false` for record-only events —
     *  the parent→child down-leg (steer / answer / resume): they belong in `history()` and reach
     *  `subscribe` observers, but the parent must never `pull` its own outbound message back. */
    readonly queue?: boolean;
}
interface BusStats {
    readonly published: number;
    readonly pulled: number;
    /** Count published per event `type`. */
    readonly byKind: Readonly<Record<string, number>>;
}
interface EventBus<E extends BusEvent> {
    /** Stamp + queue the event, then deliver the stamped record to every subscriber in order.
     *  Returns the stamped record. */
    publish(event: E, opts?: PublishOptions): Promise<BusRecord<E>>;
    /** Remove and return the highest-priority QUEUED event whose type is in `kinds` (any if omitted),
     *  ties broken FIFO by `seq`; `undefined` when nothing matches. */
    pull(kinds?: ReadonlyArray<E['type']>): E | undefined;
    /** Register a pass-through handler; it receives the stamped record of every event published after
     *  registration. Returns an unsubscribe fn. */
    subscribe(handler: (record: BusRecord<E>) => void | Promise<void>): () => void;
    /** Count of queued, not-yet-pulled events (filtered by `kinds` when given). */
    pending(kinds?: ReadonlyArray<E['type']>): number;
    /** The full ordered log of every event ever published (the audit/replay trail). */
    history(): ReadonlyArray<BusRecord<E>>;
    /** Throughput counters for observability dashboards. */
    stats(): BusStats;
}
/** Create the child→parent coordination bus: one typed pipe for settled outputs, questions, and analyst findings, with a priority-ordered pull queue and a pass-through subscribe lane. */
declare function createEventBus<E extends BusEvent>(now?: () => number): EventBus<E>;

/**
 *
 * Sandbox-session coder decode layer. The sandbox-session delegate (`./delegates`) and the
 * cross-restart resume driver run the in-box harness over a `SandboxClient` and need to
 * (a) build an `AgentRunSpec` from the caller-authored (or minimal model-only default) worker
 * profile, (b) decode the harness event stream into a structured `CoderOutput`, and (c) gate it with
 * the shared mechanical checks. This sandbox-session path is kept separate from the generic recursive
 * path: `worktreeFanout` instead settles the raw `WorktreePatchArtifact` and gates via
 * `patchDelivered`. Prefer `worktreeFanout` / `worktreeLoopRunner` for NEW local-repo coding.
 *
 * The decode tolerates two `result`-event shapes:
 *   1. the in-process executor's raw worktree-harness result (`{ branch, patch, stats, checks }`),
 *      projected onto `CoderOutput`; and
 *   2. an LLM-emitted JSON block (`{ branch, patch, testResult, typecheckResult, diffStats }`),
 *      lifted onto `data.result` or scanned out of the assistant transcript (any harness shape).
 *
 * @experimental
 */

/** @experimental The structured coder result the sandbox-session path decodes + gates. */
interface CoderOutput {
    /** Branch the agent wrote the patch on. */
    branch: string;
    /** Unified diff (`git diff <base>..HEAD`). */
    patch: string;
    testResult: {
        passed: boolean;
        output: string;
    };
    typecheckResult: {
        passed: boolean;
        output: string;
    };
    diffStats: {
        filesChanged: number;
        insertions: number;
        deletions: number;
    };
    /** Optional reviewer commentary surfaced by the agent. */
    reviewerNotes?: string;
}

/**
 *
 * Persistence port for the MCP delegation queue.
 *
 * `DelegationTaskQueue` keeps its working set in memory (status/history
 * reads stay synchronous) and journals every record mutation through a
 * `DelegationStore`. `DelegationTaskQueue.restore({ store })` is the load
 * path: it reads the full record set once at construction and rehydrates
 * the queue from it. After that the store only sees writes.
 *
 * Records MUST be JSON-safe — `FileDelegationStore` round-trips them
 * through `JSON.stringify`/`JSON.parse`, so a `Date`, `Map`, or function
 * smuggled into `args`/`result` would corrupt the journal.
 *
 * @experimental
 */

/** @experimental */
interface DelegationStore {
    /**
     * Read every persisted record. Called once, by
     * `DelegationTaskQueue.restore`, before any write. A missing backing
     * file is an empty store; an unparseable one throws
     * `DelegationStateCorruptError`.
     */
    loadAll(): Promise<DelegationRecord[]>;
    /** Insert or replace the record keyed by `record.taskId`. */
    upsert(record: DelegationRecord): Promise<void>;
    /**
     * Resolve an idempotency key to the taskId that claimed it, if any.
     * The queue serves submit-time dedupe from its rehydrated in-memory
     * index; this read exists for consumers that share a store across
     * processes without holding the full record set.
     */
    lookupIdempotencyKey(key: string): Promise<string | undefined>;
    /** Delete the named records — the retention-cap eviction path. */
    remove(taskIds: readonly string[]): Promise<void>;
}
/**
 * The persisted delegation state exists but cannot be parsed into
 * records. Fail loud: silently starting empty over a corrupt journal
 * would erase delegation history and re-run idempotent work. Opt into
 * recovery explicitly via `FileDelegationStoreOptions.recoverCorrupt`
 * (the bin maps `AGENT_RUNTIME_DELEGATION_STATE_RECOVER=1` onto it),
 * which archives the corrupt file and starts fresh.
 *
 * @experimental
 */
declare class DelegationStateCorruptError extends AgentEvalError {
    constructor(message: string, options?: {
        cause?: unknown;
    });
}
/**
 * A delegation-store read or write failed (filesystem error, store
 * called before `loadAll`, ...). Once the queue observes one, it stops
 * accepting new submissions — accepting work it cannot journal would
 * silently demote durable mode to in-memory mode.
 *
 * @experimental
 */
declare class DelegationPersistenceError extends AgentEvalError {
    constructor(message: string, options?: {
        cause?: unknown;
    });
}
/** In-memory `DelegationStore` — suitable for single-process use and tests. @experimental */
declare class InMemoryDelegationStore implements DelegationStore {
    private readonly records;
    loadAll(): Promise<DelegationRecord[]>;
    upsert(record: DelegationRecord): Promise<void>;
    lookupIdempotencyKey(key: string): Promise<string | undefined>;
    remove(taskIds: readonly string[]): Promise<void>;
}
/** @experimental */
interface FileDelegationStoreOptions {
    /** Absolute path of the JSON state file. Parent directories are created on first write. */
    filePath: string;
    /**
     * When the state file exists but cannot be parsed, archive it to
     * `<filePath>.corrupt-<timestamp>` and start empty instead of
     * throwing `DelegationStateCorruptError`. Default false.
     */
    recoverCorrupt?: boolean;
}
/**
 * JSON-file persistence for the delegation queue. Each write serializes
 * the full record set and lands it atomically (write to a sibling tmp
 * file, then `rename`), so readers never observe a torn file — a crash
 * mid-write leaves the previous snapshot intact. Writes are serialized
 * internally; concurrent `upsert`/`remove` calls cannot interleave.
 *
 * Built for the MCP server's scale (one stdio process, hundreds of
 * records): full-snapshot writes keep the format trivially inspectable
 * and corruption-detectable without a database dependency.
 *
 * @experimental
 */
declare class FileDelegationStore implements DelegationStore {
    private readonly filePath;
    private readonly recoverCorrupt;
    private readonly records;
    private loaded;
    private writeTail;
    private tmpSeq;
    constructor(options: FileDelegationStoreOptions);
    loadAll(): Promise<DelegationRecord[]>;
    upsert(record: DelegationRecord): Promise<void>;
    lookupIdempotencyKey(key: string): Promise<string | undefined>;
    remove(taskIds: readonly string[]): Promise<void>;
    private assertLoaded;
    private enqueueWrite;
    private writeSnapshot;
}

/**
 *
 * Compact loop-trace tee for the delegation journal.
 *
 * The OTEL exporter ({@link createPropagatingTraceEmitter}) is a no-op
 * without `OTEL_EXPORTER_OTLP_ENDPOINT`, which leaves delegated work streams
 * dark in practice. This module derives the same loop → round → branch span
 * tree (via the shared {@link buildLoopSpanNodes} builder) into a small,
 * JSON-safe shape persisted directly on the `DelegationRecord` — observable
 * through `delegation_status` with no collector infrastructure. Both sinks
 * coexist: the OTEL export path is unchanged.
 *
 * Payload discipline: a record's trace is hard-capped (spans + serialized
 * bytes). Past the cap the OLDEST spans are dropped and the record carries a
 * `traceTruncated: true` marker — truncation is never silent.
 *
 * @experimental
 */

/**
 * One span of a delegation's compact trace. Flat (parent linkage by id), all
 * values JSON-safe scalars — `FileDelegationStore` round-trips records
 * through `JSON.stringify`. `meta` carries the span's attributes (GenAI
 * semconv keys + `tangle.loop.*` extensions) exactly as the OTEL sink emits
 * them, so a consumer can re-export journal traces losslessly.
 *
 * @experimental
 */
interface DelegationTraceSpan {
    spanId: string;
    /** Absent on the tree root. */
    parentSpanId?: string;
    /** `'loop'` | `'loop.round'` | `'loop.iteration'` (or a sink-specific name). */
    name: string;
    /** Topology level: loop root, plan round, or iteration branch. */
    kind: 'loop' | 'round' | 'branch';
    startMs: number;
    endMs: number;
    meta?: Record<string, string | number | boolean>;
}
/** Default cap on spans retained per delegation record. @experimental */
declare const DELEGATION_TRACE_MAX_SPANS = 512;
/** Default cap on the serialized trace payload per record, in bytes. @experimental */
declare const DELEGATION_TRACE_MAX_BYTES: number;
/** @experimental */
interface DelegationTraceCaps {
    /** Default {@link DELEGATION_TRACE_MAX_SPANS}. */
    maxSpans?: number;
    /** Default {@link DELEGATION_TRACE_MAX_BYTES}. Approximate — measured as the
     *  sum of per-span `JSON.stringify` lengths. */
    maxBytes?: number;
}
/** @experimental */
interface CappedDelegationTrace {
    trace: DelegationTraceSpan[];
    /** True when oldest spans were dropped to honor the caps. */
    truncated: boolean;
}
/**
 * Derive the compact span tree for ONE loop run from its buffered
 * `LoopTraceEvent` stream. Same reconstruction as the OTEL exporter
 * ({@link buildLoopSpanNodes}); tolerates partial streams.
 *
 * @experimental
 */
declare function buildDelegationTraceSpans(events: ReadonlyArray<LoopTraceEvent>): DelegationTraceSpan[];
/**
 * Enforce the trace caps over an ordered (oldest-first) span list. Drops the
 * OLDEST spans first and reports `truncated: true` when anything was dropped;
 * the newest span always survives, so a non-empty input never caps to empty.
 * Dropping a parent may orphan surviving children's `parentSpanId` references
 * — acceptable for the flat journal shape; consumers treat unresolved parents
 * as roots.
 *
 * @experimental
 */
declare function capDelegationTrace(spans: ReadonlyArray<DelegationTraceSpan>, caps?: DelegationTraceCaps): CappedDelegationTrace;
/**
 * Per-delegation trace collector. Buffers `LoopTraceEvent`s per runId
 * (mirroring the OTEL emitter's buffering) and hands the derived compact
 * spans to `onSpans` when a run reaches `loop.ended`. `settle()` drains runs
 * that never ended — a hard-aborted loop still leaves its partial tree in the
 * journal, unlike the OTEL path which drops it.
 *
 * @experimental
 */
interface DelegationTraceCollector {
    emitter: LoopTraceEmitter;
    /** Flush buffered events of runs that never reached `loop.ended`. */
    settle(): void;
}
/** Build a `DelegationTraceCollector` that buffers loop-trace events and converts them to spans on settle. @experimental */
declare function createDelegationTraceCollector(onSpans: (spans: DelegationTraceSpan[]) => void): DelegationTraceCollector;
/**
 * Fan one `LoopTraceEvent` stream into several emitters — e.g. the
 * process-wide OTEL exporter AND the per-delegation journal collector.
 * `undefined` entries are skipped; returns `undefined` when nothing is left
 * so callers keep the kernel's "no emitter, no events" fast path.
 *
 * @experimental
 */
declare function composeLoopTraceEmitters(...emitters: ReadonlyArray<LoopTraceEmitter | undefined>): LoopTraceEmitter | undefined;

/**
 *
 * Trace context propagation for MCP subprocess.
 *
 * When the MCP server is launched as a child process by a sandbox harness,
 * the parent passes trace context via environment variables:
 *
 *   TRACE_ID=<current-run-trace-id>
 *   PARENT_SPAN_ID=<span-that-dispatched-the-delegation>
 *
 * The MCP server reads these at startup and uses them as the root of its
 * internal trace tree. All spans emitted by `runLoop` invocations inside
 * the MCP are children of the parent's delegation span.
 *
 * When these env vars are absent, the MCP generates a fresh trace root —
 * the server operates standalone without trace joining.
 *
 * @experimental
 */

interface TraceContext {
    /** Trace id inherited from the parent process, or a fresh one. */
    traceId: string;
    /** Parent span id from the delegation that launched this MCP server. */
    parentSpanId?: string;
}
/**
 * Read trace context from the process environment.
 * Returns a context with inherited ids or a freshly generated root.
 */
declare function readTraceContextFromEnv(): TraceContext;
/**
 * Create a LoopTraceEmitter that:
 *   1. Parents all spans under the inherited PARENT_SPAN_ID.
 *   2. Exports spans to OTEL when OTEL_EXPORTER_OTLP_ENDPOINT is set.
 *
 * Returns both the emitter and the optional exporter handle for shutdown.
 */
declare function createPropagatingTraceEmitter(ctx: TraceContext): {
    emitter: LoopTraceEmitter;
    exporter: OtelExporter | undefined;
    context: TraceContext;
};
/**
 * Build env vars to pass to a child MCP subprocess so it inherits the
 * current trace context.
 */
declare function traceContextToEnv(ctx: TraceContext): Record<string, string>;

/**
 *
 * MCP delegation tool surface — the typed inputs/outputs the product agent
 * sees over the wire. These types are the contract; the JSON schemas under
 * `tools/*` mirror them for the MCP `tools/list` advertisement.
 *
 * Async semantics: `delegate_ui_audit` returns a `taskId` immediately. The
 * product agent polls `delegation_status` until the task transitions to
 * `completed` | `failed` | `cancelled`. `delegate_feedback` +
 * `delegation_history` are synchronous reads / writes against the local
 * task queue + feedback store.
 *
 * @experimental
 */

/** @experimental */
type DelegationProfile = 'coder' | 'researcher' | 'ui-auditor';
/** @experimental */
type DelegationStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
/**
 * Minimal `CoderTask` overrides exposed over the MCP wire. The full
 * `CoderTask` carries fields the kernel synthesizes from `goal` +
 * `repoRoot` — the agent only edits the few that materially gate
 * validator behavior.
 *
 * @experimental
 */
interface DelegateCodeConfig {
    testCmd?: string;
    typecheckCmd?: string;
    forbiddenPaths?: string[];
    maxDiffLines?: number;
}
/** @experimental */
interface DelegateCodeArgs {
    /** Natural-language description of what the coder must accomplish. */
    goal: string;
    /** Absolute path inside the sandbox where the repo lives. */
    repoRoot: string;
    /** Optional free-form context the agent surfaces in the prompt prelude. */
    contextHint?: string;
    /**
     * When > 1, dispatches `multiHarnessCoderFanout` across N harnesses
     * (claude-code, codex, opencode-glm) and picks the highest-scoring
     * passing patch. Default 1.
     */
    variants?: number;
    /** Validator + prompt overrides the agent knows for this repo. */
    config?: DelegateCodeConfig;
    /** Multi-tenant scope (customer-id, workspace-id). */
    namespace?: string;
}
/** @experimental */
interface DelegateCodeResult {
    taskId: string;
    /** Best-effort hint — coder loops can take minutes-to-hours. */
    estimatedDurationMs?: number;
}
/** @experimental */
type ResearchSource = 'web' | 'corpus' | 'twitter' | 'github' | 'docs';
/** @experimental */
interface DelegateResearchConfig {
    recencyWindow?: {
        since?: string;
        until?: string;
    };
    maxItems?: number;
    minConfidence?: number;
}
/** @experimental */
interface DelegateResearchArgs {
    question: string;
    namespace: string;
    scope?: string;
    sources?: ResearchSource[];
    variants?: number;
    config?: DelegateResearchConfig;
}
/** @experimental */
interface DelegateResearchResult {
    taskId: string;
    estimatedDurationMs?: number;
}
/** @experimental */
interface FeedbackRefersTo {
    kind: 'delegation' | 'artifact' | 'outcome';
    /** For `'delegation'`, this is the taskId. */
    ref: string;
}
/** @experimental */
interface FeedbackRating {
    /** [0, 1]. */
    score: number;
    label?: 'good' | 'bad' | 'neutral' | 'mixed';
    notes: string;
}
/** @experimental */
interface DelegateFeedbackArgs {
    refersTo: FeedbackRefersTo;
    rating: FeedbackRating;
    by: 'agent' | 'user' | 'downstream-judge';
    /** ISO timestamp; defaults to server clock when omitted. */
    capturedAt?: string;
    namespace?: string;
}
/** @experimental */
interface DelegateFeedbackResult {
    recorded: true;
    id: string;
}
/** @experimental */
interface DelegationStatusArgs {
    taskId: string;
    /**
     * Return the delegation's compact loop-trace span tree alongside the
     * status. Default false — status polls stay light; opt in when you need
     * the topology (which iterations ran, where they were placed, what each
     * cost) rather than just the state machine.
     */
    includeTrace?: boolean;
}
/** @experimental */
interface DelegationProgress {
    iteration: number;
    phase: string;
}
/** @experimental */
interface DelegationError {
    message: string;
    kind: string;
}
/**
 * Polymorphic `result` field: `CoderOutput` when the underlying profile
 * is `'coder'`, a structurally-typed research output when `'researcher'`.
 * The MCP wire carries it as JSON either way.
 *
 * @experimental
 */
type DelegationResultPayload = {
    profile: 'coder';
    output: CoderOutput;
} | {
    profile: 'researcher';
    output: ResearchOutputShape;
} | {
    profile: 'ui-auditor';
    output: UiAuditorDelegationOutput;
};
/**
 * Wire-shape of a completed UI-audit delegation. The `findings` array
 * contains every finding persisted to the workspace during the run,
 * already enriched with `id` and `createdAt` by the writer. `workspaceDir`
 * is the absolute path to the workspace; `indexFile` is the workspace-
 * relative path to the regenerated index.md.
 *
 * @experimental
 */
interface UiAuditorDelegationOutput {
    workspaceDir: string;
    indexFile: string;
    findings: UiFinding[];
    /** Total iterations the loop ran for this delegation. */
    iterations: number;
}
/** @experimental */
type UiAuditLensFilter = readonly UiLens[];
/** Optional per-route capture spec the agent surfaces over the wire. */
interface DelegateUiAuditRoute {
    /** Stable route name (used in screenshot filenames + finding metadata). */
    name: string;
    /** Fully-qualified URL. */
    url: string;
    /** Viewports to capture at. Defaults to `[{ width: 1280, height: 800 }]`. */
    viewports?: readonly {
        width: number;
        height: number;
    }[];
    /** Default false. Full-page captures for the broad lenses. */
    fullPage?: boolean;
    /** Selector to wait for before capture. */
    waitFor?: string;
}
/** @experimental */
interface DelegateUiAuditConfig {
    /**
     * Lenses to iterate. Default: every lens except `'other'`. Order is
     * preserved — the driver iterates lens-by-lens.
     */
    lenses?: UiAuditLensFilter;
    /** Maximum total iterations across all (lens × route) pairs. Default 33 (11 lenses × 3 routes). */
    maxIterations?: number;
    /** Maximum concurrent iterations within a single plan() round. Default 2. */
    maxConcurrency?: number;
    /** Free-form product context surfaced to the judge. */
    productContext?: string;
}
/** @experimental */
interface DelegateUiAuditArgs {
    /** Workspace root for the audit (absolute path). */
    workspaceDir: string;
    /** Routes to audit. Must be non-empty. */
    routes: readonly DelegateUiAuditRoute[];
    /** Multi-tenant scope. */
    namespace?: string;
    config?: DelegateUiAuditConfig;
}
/** @experimental */
interface DelegateUiAuditResult {
    taskId: string;
    estimatedDurationMs?: number;
}
/**
 * Loose shape of a research output over the wire — the substrate cannot
 * import the `ResearchOutput` type from agent-knowledge without inducing
 * a dependency cycle, so the MCP layer treats it structurally.
 *
 * @experimental
 */
interface ResearchOutputShape {
    items: unknown[];
    citations: unknown[];
    proposedWrites: unknown[];
    gaps?: string[];
    notes?: string;
    [key: string]: unknown;
}
/** @experimental */
interface DelegationStatusResult {
    taskId: string;
    profile: DelegationProfile;
    status: DelegationStatus;
    progress?: DelegationProgress;
    result?: DelegationResultPayload;
    error?: DelegationError;
    costUsd?: number;
    startedAt: string;
    completedAt?: string;
    /** Compact loop-trace span tree; present only when `includeTrace: true` was passed and spans were recorded. */
    trace?: DelegationTraceSpan[];
    /** Present when oldest trace spans were dropped to honor the trace caps. */
    traceTruncated?: true;
    /** Inherited trace identity recorded at submit — join key into the caller's trace. */
    traceId?: string;
    /** Caller span that dispatched the delegation, when one was inherited. */
    parentSpanId?: string;
}
/** @experimental */
interface DelegationHistoryArgs {
    namespace?: string;
    profile?: DelegationProfile;
    /** ISO date — only delegations started at-or-after `since` are returned. */
    since?: string;
    /** Default 50. Hard cap 500. */
    limit?: number;
}
/** @experimental */
interface DelegationFeedbackSnapshot {
    id: string;
    score: number;
    label?: FeedbackRating['label'];
    by: DelegateFeedbackArgs['by'];
    notes: string;
    capturedAt: string;
}
/** @experimental */
interface DelegationHistoryEntry {
    taskId: string;
    profile: DelegationProfile;
    namespace?: string;
    args: DelegateCodeArgs | DelegateResearchArgs | DelegateUiAuditArgs;
    status: DelegationStatus;
    feedback?: DelegationFeedbackSnapshot[];
    costUsd?: number;
    startedAt: string;
    completedAt?: string;
    /**
     * True when the record carries a journaled loop trace. History stays
     * light by design — fetch the spans via
     * `delegation_status { taskId, includeTrace: true }`.
     */
    hasTrace: boolean;
    /** Inherited trace identity recorded at submit — join key into the caller's trace. */
    traceId?: string;
}
/** @experimental */
interface DelegationHistoryResult {
    delegations: DelegationHistoryEntry[];
}

/**
 *
 * State machine for async MCP delegations:
 *
 *   pending → running → completed | failed
 *           ↘ cancelled (from any non-terminal state via cancel())
 *
 * Each `submit` returns a `taskId` immediately and kicks the work off in the
 * background. The work function receives an `AbortSignal` the queue fires
 * when `cancel(taskId)` is called. The queue does NOT supervise runtime
 * timeouts — the underlying `runLoop` driver / sandbox imposes those.
 *
 * Idempotency: callers may supply an `idempotencyKey` (hash of the input).
 * A duplicate `submit` with a known key returns the existing task instead of
 * starting a new one. Mutated input → different key → different task.
 *
 * Durability: the working set lives in memory (reads stay synchronous) and
 * every record mutation is journaled through a `DelegationStore`. The default
 * `InMemoryDelegationStore` keeps today's semantics — a process restart drops
 * all state. Construct via `DelegationTaskQueue.restore({ store })` with a
 * `FileDelegationStore` to reload prior records on startup: terminal records
 * stay queryable, in-flight records either re-attach through the
 * `resumeDelegate` seam (when they carry a `detachedSessionRef`) or fail
 * loud with a driver-restart error so `delegation_status` tells the truth.
 *
 * @experimental
 */

type AnyDelegateArgs = DelegateCodeArgs | DelegateResearchArgs | DelegateUiAuditArgs;
/**
 * Must be JSON-safe end to end (`args`, `result`, `error`, `feedback`) —
 * persistent stores round-trip records through `JSON.stringify`.
 *
 * @experimental
 */
interface DelegationRecord {
    taskId: string;
    profile: DelegationProfile;
    namespace?: string;
    args: AnyDelegateArgs;
    status: DelegationStatus;
    progress?: DelegationProgress;
    result?: DelegationResultPayload;
    error?: DelegationError;
    costUsd?: number;
    startedAt: string;
    completedAt?: string;
    /** Sha-prefix hash of the canonical input — used for idempotency lookup. */
    idempotencyKey?: string;
    /**
     * Caller-generated deterministic id of a detached run (e.g. the sandbox
     * session id a single-tick driver resumes by). Presence is what makes a
     * restored in-flight record resumable via `resumeDelegate`; without it a
     * restart settles the record as failed.
     */
    detachedSessionRef?: string;
    /** Feedback events keyed by this delegation's taskId. */
    feedback: DelegationFeedbackSnapshot[];
    /**
     * Compact loop-trace span tree teed from the delegation's run, oldest
     * spans first. Appended when a delegated loop reaches `loop.ended` and
     * settled (partial buffers included) at the terminal transition. Capped
     * via `capDelegationTrace` — see `traceTruncated`.
     */
    trace?: DelegationTraceSpan[];
    /** Present when oldest trace spans were dropped to honor the trace caps. */
    traceTruncated?: true;
    /**
     * Inherited trace identity (the queue's `traceContext` at submit time —
     * typically `readTraceContextFromEnv()`), distinct from the span payload:
     * a journal consumer joins records into the parent trace by these ids
     * without parsing spans. Restored records keep their persisted identity.
     */
    traceId?: string;
    /** Caller span that dispatched the delegation, when one was inherited. */
    parentSpanId?: string;
}
/** @experimental */
interface SubmitInput<Args extends AnyDelegateArgs> {
    profile: DelegationProfile;
    args: Args;
    namespace?: string;
    idempotencyKey?: string;
    /**
     * Records the detached-run resume key on the new record. The submitted
     * `run` function still executes in-process exactly as without it — the
     * ref only matters after a restart, when `DelegationTaskQueue.restore`
     * hands it to the `resumeDelegate` seam instead of failing the record.
     */
    detachedSessionRef?: string;
    /**
     * Runs the underlying delegation. The queue passes a fresh `AbortSignal`
     * and a `report` channel for incremental progress updates. The function
     * MUST resolve with the typed `DelegationResultPayload['output']`; the
     * queue wraps it with the profile tag.
     */
    run: (ctx: DelegationRunContext) => Promise<DelegationResultPayload['output']>;
}
/** @experimental Context handed to a `SubmitInput.run` function. */
interface DelegationRunContext {
    signal: AbortSignal;
    report(progress: DelegationProgress): void;
    /** The `detachedSessionRef` recorded at submit, when one was supplied. */
    detachedSessionRef?: string;
    /**
     * Replace the record's detached-run resume key — the detached dispatch path
     * calls this once the sandbox id is known so the persisted ref names a
     * resolvable box. Ignored after the record settles (a cancel racing the
     * rebind is legitimate; the ref no longer matters then). Throws on an empty
     * ref — erasing the resume key would silently make the record unresumable.
     */
    updateDetachedSessionRef(ref: string): void;
    /**
     * Per-delegation loop-trace sink, always provided by the queue. Events
     * emitted here are journaled onto the record as a compact span tree
     * (`record.trace`) when each loop run ends and at the delegation's
     * terminal transition. Delegates forward it into their `runLoop` ctx,
     * composed with any process-wide OTEL emitter
     * (`composeLoopTraceEmitters`). Optional in the type so consumer-built
     * contexts stay source-compatible.
     */
    traceEmitter?: LoopTraceEmitter;
}
/** @experimental */
interface SubmitOutput {
    taskId: string;
    /** True when a prior matching `idempotencyKey` returned an existing record. */
    reused: boolean;
}
/**
 * One observation of a detached run, mapped 1:1 from a single-tick driver
 * (e.g. the sandbox SDK's `driveTurn`, which reports
 * completed | running | failed per pass). `running` schedules another tick
 * after `intervalMs`; `completed` / `failed` settle the record.
 *
 * @experimental
 */
type DelegationResumeTick = {
    state: 'running';
} | {
    state: 'completed';
    output: DelegationResultPayload['output'];
    costUsd?: number;
} | {
    state: 'failed';
    error: DelegationError;
};
/** @experimental */
interface DelegationResumeContext {
    /** Fired by `cancel(taskId)`; the driver should stop the remote run when it can. */
    signal: AbortSignal;
    report(progress: DelegationProgress): void;
}
/**
 * Re-attaches restored in-flight records to their detached runs. The queue
 * calls `tick` repeatedly — it never awaits a whole run — so the driver can
 * be a thin wrapper over a one-pass primitive: resolve the run named by
 * `detachedSessionRef`, advance/poll it once, report where it stands. A
 * thrown error settles the record as failed; `failed` ticks are treated as
 * terminal and are not retried.
 *
 * @experimental
 */
interface DelegationResumeDriver {
    tick(task: {
        record: DelegationRecord;
        detachedSessionRef: string;
    }, ctx: DelegationResumeContext): Promise<DelegationResumeTick>;
    /** Delay between `running` ticks, in milliseconds. Default 5000. */
    intervalMs?: number;
}
/** @experimental */
interface DelegationTaskQueueOptions {
    /** ID generator override; default `randomTaskId`. */
    generateId?: () => string;
    /** Clock override; default `() => new Date().toISOString()`. */
    now?: () => string;
    /**
     * Journal for record mutations and the `restore()` load source. Default
     * `InMemoryDelegationStore` — observably identical to an unjournaled
     * queue. Pass a `FileDelegationStore` through
     * `DelegationTaskQueue.restore` for state that survives a restart;
     * constructing with `new` never loads prior state.
     */
    store?: DelegationStore;
    /** Resume seam for restored in-flight records that carry a `detachedSessionRef`. */
    resumeDelegate?: DelegationResumeDriver;
    /**
     * Maximum number of terminal (completed | failed | cancelled) records
     * retained; the oldest (by `completedAt`) are evicted from memory and
     * store once the cap is exceeded. Default unbounded.
     */
    maxTerminalRecords?: number;
    /**
     * Observes the first store failure. After it fires, the queue refuses
     * new submissions and `flush()` rejects with the same error. Default:
     * rethrow on a microtask — an unhandled crash — because silently
     * degrading durable mode to memory-only would lie to the caller.
     */
    onPersistError?: (error: DelegationPersistenceError) => void;
    /**
     * Inherited trace identity stamped on every submitted record
     * (`traceId` / `parentSpanId`). The bin passes
     * `readTraceContextFromEnv()` so journal consumers can join delegation
     * records into the caller's trace. Restored records keep the identity
     * they were persisted with.
     */
    traceContext?: TraceContext;
}
/** In-process queue for async delegation tasks — submit, cancel, poll status, and read history. @experimental */
declare class DelegationTaskQueue {
    private readonly records;
    private readonly controllers;
    private readonly byIdempotencyKey;
    private readonly generateId;
    private readonly now;
    private readonly store;
    private readonly resumeDelegate?;
    private readonly maxTerminalRecords;
    private readonly onPersistError;
    private readonly traceContext;
    private persistTail;
    private persistFailure;
    constructor(options?: DelegationTaskQueueOptions);
    /**
     * Construct a queue from previously-persisted state. Loads every record
     * from `options.store`, rebuilds the idempotency index (so a re-submitted
     * identical task returns the prior taskId and its terminal state), then:
     *
     *   - terminal records stay queryable via `status()` / `history()`
     *   - in-flight records with a `detachedSessionRef` re-attach through
     *     `options.resumeDelegate` and report `running`
     *   - other in-flight records settle as failed — their driver died with
     *     the previous process and the result is unrecoverable
     *
     * The retention cap applies to the loaded set as well.
     */
    static restore(options?: DelegationTaskQueueOptions): Promise<DelegationTaskQueue>;
    /**
     * Kick off a delegation in the background. Returns immediately. The
     * `taskId` is queryable via `status` once this method returns. Throws
     * the recorded `DelegationPersistenceError` once the store has failed —
     * the queue does not accept work it cannot journal.
     */
    submit<Args extends AnyDelegateArgs>(input: SubmitInput<Args>): SubmitOutput;
    /**
     * Snapshot the current state of a delegation. Returns `undefined` for
     * unknown ids so callers can distinguish missing from terminal.
     * `includeTrace` attaches the journaled loop-trace span tree — off by
     * default so status polls stay light.
     */
    status(taskId: string, opts?: {
        includeTrace?: boolean;
    }): DelegationStatusResult | undefined;
    /**
     * Abort an in-flight delegation. Returns `false` if the task is unknown
     * or already terminal. The underlying `run` function MUST honor the
     * abort signal for the cancel to take effect; the queue marks the
     * record `cancelled` regardless so a misbehaving runner cannot pin the
     * UI on `running` forever.
     */
    cancel(taskId: string): boolean;
    /**
     * Append a feedback event to the matching delegation. Returns `false`
     * when `ref` does not name a known taskId — the caller should still
     * record the feedback through a different surface (artifact/outcome
     * kinds are not queue-bound).
     */
    attachFeedback(taskId: string, snapshot: DelegationFeedbackSnapshot): boolean;
    /**
     * Query the recorded delegations. Returns entries newest-first (by
     * `startedAt`), truncated to `limit`.
     */
    history(args?: DelegationHistoryArgs): DelegationHistoryEntry[];
    /**
     * Await every journal write issued so far. Rejects with the recorded
     * `DelegationPersistenceError` when any of them failed. Call before
     * handing the store's backing file to another process.
     */
    flush(): Promise<void>;
    /** Test-only — number of in-flight (non-terminal) records. */
    inflightCount(): number;
    private execute;
    private appendTrace;
    private rehydrate;
    private startResume;
    private driveResume;
    /**
     * Journal the resumed segment of a detached run as one compact span. The
     * resume driver re-attaches after a process restart, so the original
     * process's loop events are gone — this span records the post-restart
     * observation window (re-attach → terminal tick) under the
     * `'detached-resume'` driver tag, keeping restored delegations observable
     * in the journal alongside trace-carrying live runs.
     */
    private appendResumeSpan;
    private persist;
    private persistRemoval;
    private failPersistence;
    private enforceRetention;
}
/**
 * Best-effort stable hash for use as `idempotencyKey`. Not cryptographic;
 * collisions only affect dedupe, never correctness.
 *
 * @experimental
 */
declare function hashIdempotencyInput(value: unknown): string;

/**
 *
 * Detached delegation turns over the sandbox SDK's `driveTurn` primitive.
 *
 * Two halves of one story:
 *
 *   - {@link runDetachedTurn} — the dispatch side. A single-session delegate
 *     (single-variant coder / researcher) acquires a box, binds the sandbox id
 *     into the record's `detachedSessionRef`, then advances the turn with
 *     repeated `driveTurn` ticks instead of holding a live SSE stream. The
 *     session id is deterministic and supplied at submit time, so a process
 *     crash between ticks loses nothing — the turn keeps running in the box.
 *
 *   - {@link createDetachedTurnResumeDriver} — the resume side. A
 *     `DelegationResumeDriver` that re-attaches restored in-flight records to
 *     their detached runs: parse the record's ref, resolve the box, advance the
 *     turn one `driveTurn` pass per `tick()`, and map the SDK's three states
 *     (`completed | running | failed`) onto `DelegationResumeTick`.
 *
 * Both sides type the box structurally ({@link DriveTurnCapableBox}) so tests
 * inject fakes and the module never requires the sandbox SDK at runtime — the
 * SDK stays an optional peer, exactly like the executors' `SandboxClient` seam.
 *
 * Tradeoffs of detached mode (why it is opt-in, not the default): a detached
 * turn yields one terminal payload instead of a live event stream, so kernel
 * token/cost aggregation is not produced for that turn. The trace sinks still
 * observe detached work — `runDetachedTurn` synthesizes a single-iteration
 * loop event stream (see `RunDetachedTurnOptions.traceEmitter`) so the span
 * topology joins the inherited trace context, with cost/tokens reported as 0
 * under the `'detached-turn'` driver tag. Multi-variant fanout stays on the
 * streaming `runLoop` path — N concurrent sessions cannot be expressed as one
 * resume key, and winner selection needs every candidate.
 *
 * @experimental
 */

/**
 * Structural mirror of the sandbox SDK's `TurnDriveResult` (>= 0.6).
 * Discriminated on `state`; `failed` is terminal and deterministic per the
 * SDK contract — re-invoking with the same ids returns the same outcome.
 *
 * @experimental
 */
type DriveTurnTick = {
    state: 'completed';
    text: string;
    result: Record<string, unknown>;
} | {
    state: 'running';
    startedAt?: Date;
    elapsedMs?: number;
} | {
    state: 'failed';
    error: string;
};
/**
 * The box surface detached turns need. `SandboxInstance`
 * (`@tangle-network/sandbox` >= 0.6) satisfies it structurally; tests pass
 * in-memory fakes. `_sessionCancel` is the SDK's remote-cancellation surface —
 * optional here because older SDKs / fakes may not expose it; when present it
 * is invoked on abort so the remote run actually stops.
 *
 * @experimental
 */
interface DriveTurnCapableBox {
    driveTurn(message: string, opts: {
        sessionId: string;
        turnId?: string;
        wallCapMs?: number;
    }): Promise<DriveTurnTick>;
    _sessionCancel?(id: string): Promise<void>;
}
/**
 * Decoded `DelegationRecord.detachedSessionRef`. `sandboxId` is absent between
 * submit and box acquisition — a record restored in that window is not
 * resumable (there is no box to resume on) and the resume driver fails it
 * loud rather than dispatching onto a guessed box.
 *
 * @experimental
 */
interface DetachedSessionRefParts {
    sessionId: string;
    sandboxId?: string;
}
/**
 * Encode ref parts into the JSON-safe string stored on the record:
 * `session=<id>` before the box exists, `sandbox=<id>;session=<id>` once
 * bound. Ids must not contain the `;`/`=` delimiters.
 *
 * @experimental
 */
declare function formatDetachedSessionRef(parts: DetachedSessionRefParts): string;
/** Parse a `detachedSessionRef` string back to parts; throws `ValidationError` on malformed input. @experimental */
declare function parseDetachedSessionRef(raw: string): DetachedSessionRefParts;
/** @experimental The terminal payload of a finished detached turn. */
interface DetachedTurn {
    /** Final assistant text. */
    text: string;
    /** The SDK's cached AgentExecutionResult-shape record for the turn. */
    result: Record<string, unknown>;
}
/**
 * Synthesize the terminal event array a detached turn settles through. Shaped
 * so the existing event-stream output adapters (coder, researcher) parse it:
 * `data.result` for adapters that read a structured terminal record, `data.text`
 * for adapters that scan assistant text for the fenced result block.
 *
 * @experimental
 */
declare function detachedTurnEvents(sessionId: string, turn: DetachedTurn): SandboxEvent[];
/** @experimental */
interface RunDetachedTurnOptions {
    /** Sandbox client used to acquire the box (the delegate's executor client). */
    client: SandboxClient;
    /** Profile + overrides for box acquisition — same spec the streaming path uses. */
    spec: AgentRunSpec<unknown>;
    /** The full turn prompt; consumed by `driveTurn`'s dispatch leg. */
    prompt: string;
    /** Deterministic resume key, minted at submit time (`parseDetachedSessionRef(ref).sessionId`). */
    sessionId: string;
    /**
     * Called once the box exists, with its sandbox id. Callers persist
     * `formatDetachedSessionRef({ sandboxId, sessionId })` onto the record here so
     * a restart can resolve the box again.
     */
    bindSandbox(sandboxId: string): void;
    signal: AbortSignal;
    report(progress: DelegationProgress): void;
    /** Delay between `running` ticks (ms). Default 5000. */
    tickIntervalMs?: number;
    /** Wall-clock cap forwarded to `driveTurn` — the SDK cancels and fails a session past it. */
    wallCapMs?: number;
    /**
     * Loop-trace sink. When set, the detached turn synthesizes a
     * single-iteration loop span tree (`runId` = `sessionId`, driver
     * `'detached-turn'`) so trace-context inheritance survives the detached
     * path — the same events the streaming `runLoop` path would emit, minus
     * per-token telemetry: `driveTurn` yields one terminal payload, so token
     * and cost figures are structurally unavailable and reported as 0 under
     * this driver tag.
     */
    traceEmitter?: LoopTraceEmitter;
    /** Physical placement stamped on the synthesized dispatch event. Default `'sibling'`. */
    placement?: 'sibling' | 'fleet';
}
/**
 * Dispatch one detached turn and advance it to a terminal state with
 * `driveTurn` ticks. The first tick dispatches (idempotent on `sessionId`);
 * subsequent ticks poll. On abort the remote session is cancelled via
 * `_sessionCancel` when the box exposes it. The box is torn down on every
 * in-process exit path (success, failure, abort) — only a process death skips
 * teardown, which is exactly the case the resume driver re-attaches to.
 *
 * @experimental
 */
declare function runDetachedTurn(options: RunDetachedTurnOptions): Promise<DetachedTurn>;
/** @experimental */
interface DetachedTurnResumeDriverOptions {
    /**
     * Resolve the live box owning a detached session. The bin wires this to the
     * sandbox client's `get(sandboxId)`; throw when the box no longer exists —
     * a thrown tick settles the record as failed, which is the truth.
     */
    resolveSandbox(sandboxId: string): Promise<DriveTurnCapableBox>;
    /**
     * Rebuild the turn prompt from the persisted record. Only consumed by
     * `driveTurn`'s dispatch leg — i.e. when the previous process died after
     * binding the box but before the session was dispatched. Must reproduce the
     * prompt the delegate would have sent.
     */
    buildMessage(record: DelegationRecord): string;
    /**
     * Map a completed turn onto the delegation's typed output payload (parse +
     * validate per profile). Throw when the resumed result does not pass the
     * profile's gate — the queue settles the record as failed with that error.
     */
    settleOutput(turn: DetachedTurn, record: DelegationRecord, ctx: {
        signal: AbortSignal;
    }): Promise<DelegationResultPayload['output']> | DelegationResultPayload['output'];
    /** Delay between `running` ticks (ms). Default 5000. */
    intervalMs?: number;
    /** Wall-clock cap forwarded to `driveTurn` on every tick. */
    wallCapMs?: number;
}
/**
 * Build the `driveTurn`-backed {@link DelegationResumeDriver}. Each `tick()`
 * is one settle/poll/dispatch pass:
 *
 *   - ref without a sandbox binding → `failed` (`DetachedSessionUnboundError`):
 *     the previous process died before a box existed; there is nothing to resume.
 *   - `driveTurn` `completed` → `settleOutput` → `completed` tick.
 *   - `running` → progress via `ctx.report`, `running` tick (queue re-ticks
 *     after `intervalMs`).
 *   - `failed` → `failed` tick (`DetachedTurnFailedError`) — terminal per the
 *     SDK's deterministic-failure contract.
 *
 * Abort: the queue stops ticking once `cancel()` flips the record, so remote
 * cancellation is hooked onto `ctx.signal` (once per task) and fires
 * `_sessionCancel` when the SDK surface exposes it. The driver never deletes
 * boxes — it cannot know whether `sandboxId` is a disposable sibling or a
 * fleet machine, and destroying a fleet machine would be unrecoverable.
 *
 * @experimental
 */
declare function createDetachedTurnResumeDriver(options: DetachedTurnResumeDriverOptions): DelegationResumeDriver;

/**
 *
 * Delegation executors — the layer between MCP delegates and the sandbox
 * substrate. Each executor exposes a {@link SandboxClient} the kernel
 * consumes plus a placement tag so the trace pipeline can correlate workers
 * with their physical placement.
 *
 * Two implementations ship in-box:
 *
 * - {@link createSiblingSandboxExecutor} — every delegation spawns a fresh
 *   sandbox sibling to the caller. Default when the MCP server runs as a
 *   standalone CLI mounted outside a fleet.
 *
 * - {@link createFleetWorkspaceExecutor} — delegations dispatch onto machines
 *   in the caller's existing fleet so worker diffs land directly on the
 *   caller's filesystem (the fleet's shared workspace). Selected when the
 *   parent sandbox passes `TANGLE_FLEET_ID` into the MCP server's env.
 *
 * @experimental
 */

/** @experimental */
interface DelegationExecutor {
    /** Sandbox client the kernel calls. Returned with `describePlacement` set. */
    readonly client: SandboxClient;
    /** Best-effort one-liner used in stderr boot logs and diagnostics. */
    describe(): string;
    /**
     * Where delegated work physically runs. `sibling` and `fleet` placements are
     * session-backed (boxes expose `driveTurn`, so detached dispatch + resume
     * apply); `in-process` spawns local harness CLIs with no sandbox session to
     * detach. Optional so consumer-implemented executors stay source-compatible;
     * absent means "unknown" and detached dispatch is not enabled for it.
     */
    readonly placement?: 'sibling' | 'fleet' | 'in-process';
}
/** @experimental */
interface SiblingSandboxExecutorOptions {
    client: SandboxClient;
}
/**
 * Wrap a raw sandbox SDK client so the kernel emits
 * `loop.iteration.dispatch` events with `{ placement: 'sibling', sandboxId }`.
 *
 * The returned client `.create()` delegates to the underlying client; the
 * only added behavior is a `describePlacement` tag the kernel reads.
 *
 * @experimental
 */
declare function createSiblingSandboxExecutor(options: SiblingSandboxExecutorOptions): DelegationExecutor;
/**
 * Minimal `SandboxFleet` surface the fleet executor calls. Declared
 * structurally so tests can pass an in-memory stub without instantiating the
 * sandbox SDK.
 *
 * @experimental
 */
interface FleetHandle {
    readonly fleetId: string;
    /** Machine ids in dispatch-eligible order. The executor round-robins. */
    readonly ids: ReadonlyArray<string>;
    /** Resolve a machine id to its `SandboxInstance` — that machine is mounted
     * on the fleet's shared workspace, so any diff the worker writes lands on
     * every other fleet machine's filesystem too. */
    sandbox(machineId: string): Promise<SandboxInstance>;
}
/** @experimental */
interface FleetWorkspaceExecutorOptions {
    fleet: FleetHandle;
    /**
     * Override the machine-selection policy. Default = round-robin across
     * `fleet.ids`, skipping the optional `excludeMachineIds` set (typically the
     * coordinator machine the MCP server is running on).
     */
    selectMachine?: (call: {
        callIndex: number;
        ids: ReadonlyArray<string>;
    }) => string;
    /**
     * Machine ids to skip during default round-robin. Set to the caller's own
     * machineId so workers don't compete with the orchestrator on the same VM.
     */
    excludeMachineIds?: ReadonlyArray<string>;
}
/**
 * Build an executor that resolves each delegated iteration to an existing
 * machine in `fleet`. The fleet's shared-workspace policy means the worker
 * machine sees the caller's filesystem — diffs land in-place with no
 * cross-sandbox copy step.
 *
 * @experimental
 */
declare function createFleetWorkspaceExecutor(options: FleetWorkspaceExecutorOptions): DelegationExecutor;

/**
 *
 * `detachedSessionDelegate` — the sandbox-session coder delegate: a closure that drives `runLoop`
 * against a `SandboxClient` + a caller-supplied (or minimal model-only default) worker profile, to a
 * mechanically-validated `CoderOutput`. The caller invokes the returned delegate directly with its
 * coder args; when wired into a durable queue it also settles cross-restart-resumed records.
 *
 * Delegation vs COORDINATION (`../runtime/supervise/coordination-mcp.ts`): this delegate runs a
 * coding task INSIDE the agent's OWN sandbox environment — a sibling box on its own `SandboxClient`,
 * fresh branch on its repo. It is NOT backend-pluggable. To instead SPAWN + live-drive workers in a
 * CHOSEN backend (sandbox OR cli-bridge, via `createExecutor({ backend })`) with observe/steer/resume
 * + recursion, use `delegate()` / the coordination MCP.
 *
 * The worker profile is a parameter the caller supplies (§1.5: the system authors profiles). When
 * none is passed, a minimal model-only default profile is materialized in `./detached-coder` — no
 * hardcoded skills or tools. For NEW local-repo coding use `worktreeFanout` / `worktreeLoopRunner`
 * (author one `AgentProfile` per harness → `createWorktreeCliExecutor` leaves → `gateOnDeliverable`).
 *
 * @experimental
 */

/** @experimental */
interface DelegateRunCtx {
    signal: AbortSignal;
    report(progress: DelegationProgress): void;
    /**
     * Detached-run resume key recorded on the queue record at submit time
     * (`formatDetachedSessionRef`). Present only when the submit path requested
     * detached dispatch — its presence is what routes a session-backed delegate
     * onto the `driveTurn` tick path instead of holding a stream.
     */
    detachedSessionRef?: string;
    /** Rebind the record's resume key (e.g. once the sandbox id is known). */
    updateDetachedSessionRef?(ref: string): void;
    /**
     * Per-delegation trace sink supplied by the queue — loop events emitted
     * here land on the delegation record as a compact span tree. Delegates
     * compose it with their configured OTEL emitter so both sinks observe
     * the same stream.
     */
    traceEmitter?: LoopTraceEmitter;
}
/** @experimental The coder delegate closure — given the coder args + run context, drives the
 *  sandbox-session coder path to a validated `CoderOutput`. `detachedSessionDelegate` is the
 *  built-in implementation; the queue invokes one of these per coder delegation. */
type CoderDelegate = (args: DelegateCodeArgs, ctx: DelegateRunCtx) => Promise<CoderOutput>;
/**
 * UI-auditor delegate — fully consumer-injected. agent-runtime ships no
 * default factory because the inputs are workspace path + judge function
 * + (optionally) a `SandboxClient`, and the judge is the consumer's
 * model seam. See `createInProcessUiAuditClient` + `uiAuditorProfile` in
 * `@tangle-network/agent-runtime/profiles` for the canonical wiring.
 *
 * @experimental
 */
type UiAuditorDelegate = (args: DelegateUiAuditArgs, ctx: DelegateRunCtx) => Promise<UiAuditorDelegationOutput>;
/** @experimental Structured review verdict over a coder candidate. */
interface CoderReview {
    /** Gate: only approved candidates are eligible to win. */
    approved: boolean;
    /** Reviewer's recommendation — surfaced in traces. */
    recommendation: 'ship' | 'approve-with-nits' | 'changes-requested' | 'reject';
    /** Readiness 0..1, used by the `highest-readiness` winner-selection strategy. */
    readiness: number;
    notes?: string;
}
/**
 *
 * Optional adversarial reviewer over a coder candidate that already passed
 * mechanical validation (tests/typecheck/forbidden/diff/no-op/secrets). Folded
 * from the ai-trading-blueprint delegation MCP: a candidate is only eligible to
 * win if the reviewer approves it. The reviewer is the consumer's seam — an LLM
 * judge, a `pnpm review` command, anything returning a `CoderReview`.
 *
 * @experimental
 */
type CoderReviewer = (output: CoderOutput, task: CoderTask, ctx: {
    signal: AbortSignal;
}) => Promise<CoderReview> | CoderReview;
/**
 * @experimental Winner-selection strategy among validated (+ reviewed) candidates on the
 * sandbox-session path. The base strategies (`highest-score` / `smallest-diff` /
 * `first-approved`) delegate to the shared `selectValidWinner`; `highest-readiness` is the
 * reviewer-only strategy this path keeps that the generic selector does not express. Default
 * `highest-score`.
 */
type DetachedWinnerSelection = 'highest-score' | 'smallest-diff' | 'highest-readiness' | 'first-approved';
/** @experimental */
interface DetachedSessionDelegateOptions {
    /**
     * Execution placement. Pass a {@link DelegationExecutor} (sibling or fleet)
     * to control where worker iterations land. `sandboxClient` is a
     * convenience shorthand that wraps the client in a sibling executor — pass
     * one or the other, not both.
     */
    executor?: DelegationExecutor;
    /**
     * Convenience shorthand for sibling placement. Equivalent to
     * `executor: createSiblingSandboxExecutor({ client: sandboxClient })`.
     */
    sandboxClient?: SandboxClient;
    /**
     * The worker's authored `AgentProfile` (§1.5: the system authors profiles). Spread onto the
     * sandbox-session run spec → `runLoop` → the executor's `harnessInvocation`, so the harness runs
     * under the caller's stance. Omit to use a minimal model-only default (no hardcoded skills/tools);
     * `harness` / `model` / `systemPrompt` below are convenience overrides layered onto whichever
     * profile is used.
     */
    workerProfile?: AgentProfile;
    /** Backend harness for the single-coder path (sets `metadata.backendType`). Default `claude-code`. */
    harness?: string;
    /** Model override for the single-coder path. */
    model?: string;
    /**
     * The worker's authored system prompt (§1.5). Flows onto the run spec's
     * `profile.prompt.systemPrompt` → through `runLoop` → the executor's `harnessInvocation`, so the
     * harness runs under this stance. Omit to keep the profile's own prompt.
     */
    systemPrompt?: string;
    /** Default `['claude-code', 'codex', 'opencode/zai-coding-plan/glm-5.1']` when variants > 1. */
    fanoutHarnesses?: string[];
    /** Optional per-harness model override for `variants > 1`. */
    fanoutModels?: (string | undefined)[];
    /** Hard cap on the kernel's per-batch concurrency. Default 4. */
    maxConcurrency?: number;
    /**
     * Optional adversarial reviewer. When set, a candidate must pass mechanical
     * validation AND `reviewer.approved` to be eligible to win — empty/secret/
     * test-failing patches are already gone; this catches the "compiles + passes
     * but wrong/unsafe" class the deterministic validator can't see.
     */
    reviewer?: CoderReviewer;
    /** Winner-selection strategy among eligible candidates. Default `highest-score`. */
    winnerSelection?: DetachedWinnerSelection;
    /**
     * Loop trace emitter forwarded into every delegated `runLoop`. Wire
     * `createPropagatingTraceEmitter(readTraceContextFromEnv())` here (the bin
     * does) so delegated build-loops export their topology spans to the OTLP /
     * Tangle Intelligence sink when `OTEL_EXPORTER_OTLP_ENDPOINT` is set — and
     * are a cheap no-op when it isn't. Configurable by construction.
     *
     * Detached single-variant turns (taken when `ctx.detachedSessionRef` is set)
     * bypass `runLoop`; `runDetachedTurn` synthesizes a single-iteration loop
     * event stream for them so this emitter observes detached work too.
     */
    traceEmitter?: LoopTraceEmitter;
    /** Tick cadence (ms) for the detached single-variant path. Default 5000. */
    detachedTickIntervalMs?: number;
    /** Wall-clock cap (ms) forwarded to `driveTurn` for detached turns. */
    detachedWallCapMs?: number;
}
/**
 * Build the sandbox-session coder delegate. It drives `runLoop` against the project's
 * sandbox client + coder profile; when `args.variants > 1` it switches to the multi-harness fanout
 * topology.
 *
 * This is the SANDBOX-SESSION coder path: workers run the in-box harness via the
 * `SandboxClient`'s `streamPrompt`, and single-variant turns can dispatch DETACHED
 * (driveTurn ticks) so a durable queue resumes them across an MCP restart — a substrate
 * the recursive worktree-CLI leaf does not yet have a journal-replay equivalent for.
 *
 * For NEW local-repo coding use `worktreeFanout` / `worktreeLoopRunner` (author an `AgentProfile`
 * per harness → `createWorktreeCliExecutor` leaves → `gateOnDeliverable`). This delegate runs
 * held-stream by default and only its OPTIONAL cross-restart resume (the `driveTurn` tick) is opt-in
 * behind `MCP_ENABLE_DETACHED_RESUME`.
 *
 * @experimental
 */
declare function detachedSessionDelegate(options: DetachedSessionDelegateOptions): CoderDelegate;
/**
 * Canonical `DelegateCodeArgs` → `CoderTask` mapping — the single source for
 * the delegate's live dispatch AND the resume driver's settle/message
 * rebuilding, so a resumed record reproduces exactly the task the original
 * process dispatched.
 *
 * @experimental
 */
declare function coderTaskFromArgs(args: DelegateCodeArgs): CoderTask;
/** @experimental */
interface SettleDetachedCoderTurnOptions {
    task: CoderTask;
    /** Session id of the detached turn — used as the synthesized event id. */
    sessionId: string;
    signal: AbortSignal;
    harness?: string;
    model?: string;
    /** Same gate as the streaming path: an unapproved candidate cannot win. */
    reviewer?: CoderReviewer;
}
/**
 * Settle a completed detached coder turn through the same gate the streaming
 * path applies: parse the terminal payload with the coder output adapter,
 * run the mechanical validator (tests/typecheck/forbidden/diff/no-op/secrets),
 * then the optional reviewer. Throws when nothing survives — a resumed or
 * detached run must not return an unvalidated patch.
 *
 * SCOPE NOTE (detached/resume): the detached `driveTurn`-tick + cross-restart resume path is
 * bound to the `runLoop` + sandbox-session substrate. The recursive `Scope`/worktree-CLI leaf has
 * journal→replay but no driveTurn-over-a-detached-sandbox-session equivalent yet, so resume is NOT
 * advertised on the generic `worktreeFanout` path. This helper (with `coderTaskFromArgs` and
 * `createDetachedTurnResumeDriver`) stays as the resume seam `bin.ts` wires for in-flight records.
 *
 * @experimental
 */
declare function settleDetachedCoderTurn(turn: DetachedTurn, options: SettleDetachedCoderTurnOptions): Promise<CoderOutput>;

/**
 *
 * Feedback persistence surface for the MCP layer.
 *
 * The substrate cannot import `@tangle-network/agent-knowledge` (it would
 * induce a dependency cycle), so the store is an abstract interface. The
 * default implementation is in-memory; consumers wire their own adapter
 * (a real KbStore-backed sink, an HTTP relay to gtm-agent's knowledge
 * service, etc.) via `createMcpServer({ feedbackStore })`.
 *
 * Feedback events are append-only: every rating is a new event with a
 * fresh id, even when the same delegation is rated multiple times. The
 * caller decides how to roll up scores downstream.
 *
 * @experimental
 */

/** @experimental */
interface FeedbackEvent {
    id: string;
    refersTo: DelegateFeedbackArgs['refersTo'];
    rating: DelegateFeedbackArgs['rating'];
    by: DelegateFeedbackArgs['by'];
    capturedAt: string;
    namespace?: string;
}
/** @experimental */
interface FeedbackStore {
    /** Append a new event. Never dedupes — every rating is its own event. */
    put(event: FeedbackEvent): Promise<void>;
    /**
     * List events filtered by `namespace`. When `namespace` is omitted, list
     * across all namespaces. Returns events in insertion order.
     */
    list(filter?: {
        namespace?: string;
        refersToRef?: string;
    }): Promise<FeedbackEvent[]>;
}
/** In-memory `FeedbackStore` — suitable for single-process use and tests. @experimental */
declare class InMemoryFeedbackStore implements FeedbackStore {
    private readonly events;
    put(event: FeedbackEvent): Promise<void>;
    list(filter?: {
        namespace?: string;
        refersToRef?: string;
    }): Promise<FeedbackEvent[]>;
}
/**
 * Project a `FeedbackEvent` down to the snapshot shape carried on
 * `delegation_history` entries.
 *
 * @experimental
 */
declare function eventToSnapshot(event: FeedbackEvent): DelegationFeedbackSnapshot;

/**
 *
 * The leaf runtime — the built-in `Executor` IMPLEMENTATIONS behind the ONE
 * open interface frozen in `./types`, plus the open resolver/registry that maps
 * an `AgentSpec` to one of them OR accepts a bring-your-own executor verbatim.
 *
 * The interface is the extension point, not a closed `inline|sandbox|cli` union:
 *   - router/inline : a direct OpenAI-compatible Router call, no box (one-shot).
 *   - sandbox       : COMPOSES the existing `runLoop` kernel as a single-task
 *                     leaf and surfaces its token/cost usage as `UsageEvent`s;
 *                     forwards PR #150's optional `lineage` passthrough WITHOUT
 *                     reinventing checkpoint/fork (streaming).
 *   - cli           : a Halo/RLM subprocess; `budgetExempt` (no token accounting),
 *                     excluded from the equal-k arms by construction (streaming).
 * Every metered runtime reports through the SAME normalized `UsageEvent` channel
 * so the conserved budget pool meters them identically. A user's own agent is
 * first-class the moment it implements `Executor` — register it by name or
 * pass it as `AgentSpec.executor`.
 *
 * Layering: `estimateCost`/`isModelPriced` are substrate primitives from
 * `@tangle-network/agent-eval`; `runLoop`/`acquireSandbox` are runtime kernels
 * from this package. No per-vendor adapters live here.
 *
 * @experimental
 */

/**
 * Router/inline connection seam. A direct OpenAI-compatible Router endpoint —
 * the cheapest leaf, no box, no tools. `model` overrides the profile's model
 * hint when present; otherwise the profile's `model.default` is required.
 */
interface RouterSeam {
    routerBaseUrl: string;
    routerKey: string;
    model?: string;
}
/**
 * Sandbox executor seam. The `sandboxClient` the composed `runLoop` creates
 * boxes through, plus the optional trace/run/lineage wiring forwarded into the
 * loop. `lineage` is opaque here (PR #150's `RunLoopOptions.lineage`): forwarded
 * forward-compatibly, never inspected — this executor does NOT reinvent
 * checkpoint/fork.
 */
interface SandboxSeam {
    sandboxClient: SandboxClient;
    /** Forwarded into the composed `runLoop`'s `ctx` (trace emitter, run handle, etc.). */
    loopCtx?: Partial<Omit<ExecCtx, 'sandboxClient' | 'signal'>>;
    /** PR #150 `RunLoopOptions.lineage` passthrough — opaque; forwarded, not parsed. */
    lineage?: unknown;
    /** Hard cap on the composed loop's iterations. The budget pool reserves against
     *  the spawn `Budget.maxIterations`; this is the leaf's own ceiling. Default 1. */
    maxIterations?: number;
}
/** CLI subprocess seam. `bin` + `args` describe the Halo/RLM process to spawn. */
interface CliSeam {
    bin: string;
    args?: string[];
    /** Extra environment for the subprocess (merged over `process.env`). */
    env?: Record<string, string>;
    /** Working directory for the subprocess. */
    cwd?: string;
}
/**
 * cli-worktree seam. A supervisor-authored `AgentProfile` driving a local coding-harness CLI
 * (claude / codex / opencode) on its own git worktree — the leaf `createWorktreeCliExecutor`
 * named as data. `harness` + `repoRoot` + `taskPrompt` are required; the authored
 * `profile.prompt.systemPrompt` + `profile.model.default` reach the harness via the §1.5
 * `harnessInvocation` mapper. Everything else mirrors `WorktreeCliExecutorOptions`.
 */
interface CliWorktreeSeam {
    repoRoot: string;
    /** Local CLI harness transport. Omit when `bridge` is set. */
    harness?: LocalHarness;
    taskPrompt: string;
    runId?: string;
    baseRef?: string;
    harnessTimeoutMs?: number;
    testCmd?: string;
    typecheckCmd?: string;
    checkTimeoutMs?: number;
    checkOutputCap?: number;
    budgetExempt?: boolean;
    /** Live cli-bridge transport inside the worktree. When set, the worktree leaf accepts
     *  `deliver()` messages and resumes the same bridge session in this worktree cwd. */
    bridge?: CliWorktreeBridgeSeam;
    /** Test seam — forwarded to worktree helpers. */
    runGit?: GitRunner;
    /** Test seam — forwarded to verification checks. */
    runCommand?: WorktreeCheckRunner;
}
interface CliWorktreeBridgeSeam {
    bridgeUrl: string;
    bridgeBearer: string;
    /** Bridge model/harness id. Defaults to the profile's model hint when omitted. */
    model?: string;
    agentProfile?: Record<string, unknown>;
    timeoutMs?: number;
    /** Stable cli-bridge session id. Defaults to `bridge-worktree-${runId}`. */
    sessionId?: string;
    maxTurns?: number;
}
/**
 * cli-bridge seam. A local OpenAI-compatible bridge that fronts harness CLIs
 * (claude-code / opencode / kimi / pi) behind one HTTP surface; `model` doubles
 * as the harness selector (e.g. `claude-code/sonnet`, `opencode/<provider>/<model>`).
 * `agentProfile` is the bridge-dialect profile (metadata.disallowedTools, mcp)
 * forwarded verbatim per request — how an arm disables native tools or injects
 * a provider search MCP.
 *
 * The executor opens a RESUMABLE cli-bridge session — structurally identical to the
 * sandbox executor's persistent box, just local. `sessionId` is the stable
 * caller-owned id cli-bridge maps to the harness's internal conversation id; a
 * follow-up steer/resume on the SAME id continues the SAME harness session (opencode
 * `-s`, claude `--resume`, …). Omit it and the executor mints a stable one per spawn.
 */
interface BridgeSeam {
    bridgeUrl: string;
    bridgeBearer: string;
    model: string;
    /** Optional working directory forwarded to cli-bridge and persisted with the session. */
    cwd?: string;
    agentProfile?: Record<string, unknown>;
    timeoutMs?: number;
    /** Stable, caller-owned cli-bridge session id for harness-side resume. Defaults
     *  to a freshly minted per-spawn id so each worker is its own resumable session. */
    sessionId?: string;
    /** Per-resume-turn inference cap before the worker settles on its last output.
     *  Mirrors `routerToolsInlineExecutor.maxTurns`; default 200 (runaway backstop). */
    maxTurns?: number;
}
/** Generic environment provider executor config. External packages implement
 *  `AgentEnvironmentProvider`; this built-in wrapper lets `createExecutor`
 *  consume them as backend data while preserving the existing usage channel. */
interface ProviderSeam extends ProviderExecutorOptions {
    provider: AgentEnvironmentProvider | string;
    registry?: AgentEnvironmentProviderRegistry;
}
/**
 * Router seam WITH tool use — the tool-using router backend. Same direct
 * OpenAI-compatible endpoint as `RouterSeam`, but each turn passes `tools`; when
 * the model emits tool_calls they run via `executeToolCall` ON THIS HOST and the
 * results fold back as `tool` messages, repeating until the model answers without
 * a tool or `maxTurns` is hit. A real agentic loop, OFF-BOX — no sandbox, so it
 * is unaffected by a box's egress allowlist. One turn = one completion = the
 * equal-compute unit. `executeToolCall` receives the task so per-task tool
 * surfaces (e.g. a gym keyed by task) can dispatch correctly.
 */
interface RouterToolsSeam {
    routerBaseUrl: string;
    routerKey: string;
    model?: string;
    tools: ReadonlyArray<ToolSpec>;
    executeToolCall: (name: string, args: Record<string, unknown>, task: unknown) => Promise<string>;
    /** Online observer of each tool step — the seam a `DetectorMonitor` taps to watch the live pipe
     *  (raise a `finding` when the worker loops/errors). Called after every tool call resolves, with
     *  real per-call wall-clock (`startedAt`/`endedAt`/`durationMs`) so a push `TraceSource` can carry
     *  non-zero span durations onto the unified timeline. */
    onToolStep?: (step: {
        toolName: string;
        args: Record<string, unknown>;
        status: 'ok' | 'error';
        startedAt?: number;
        endedAt?: number;
        durationMs?: number;
    }) => void;
    /** Max inference turns. Default 200 (runaway backstop — set far above any
     *  legitimate workflow). For tighter per-workflow limits use a cost budget
     *  or wall-clock deadline at the call site. */
    maxTurns?: number;
}
/**
 * The leaf `createWorktreeCliExecutor` as a backend-as-data factory: a supervisor-authored
 * `AgentProfile` driving claude / codex / opencode on its own worktree. `budgetExempt` like
 * the other CLI leaves; the authored systemPrompt + model reach the harness via §1.5.
 */
declare const cliWorktreeExecutor: ExecutorFactory<unknown>;
/**
 * Config for {@link createExecutor}: the backend is DATA — the cost dial a profile,
 * an experiment config, or a replay journal can name — not an import choice. Each
 * variant carries its backend's seam (router/router-tools/bridge/cli/cli-worktree/sandbox).
 */
type ExecutorConfig = ({
    backend: 'router';
} & RouterSeam) | ({
    backend: 'router-tools';
} & RouterToolsSeam) | ({
    backend: 'bridge';
} & BridgeSeam) | ({
    backend: 'cli';
} & CliSeam) | ({
    backend: 'cli-worktree';
} & CliWorktreeSeam) | ({
    backend: 'provider';
} & ProviderSeam) | ({
    backend: 'sandbox';
    harness?: BackendType;
} & SandboxSeam);
/**
 * The single built-in executor factory. Picks a leaf backend by data (`config.backend`),
 * injects the matching seam, and delegates to that backend's built-in implementation.
 * The `Executor` port stays OPEN: bring-your-own agents implement `Executor` directly
 * and never pass through here. Use this (or `createExecutorRegistry`) instead of a
 * per-vendor adapter or a closed `inline|sandbox|cli` switch — those bypass the
 * `UsageEvent` reporting channel.
 */
declare function createExecutor(config: ExecutorConfig): ExecutorFactory<unknown>;
/**
 * The open resolver/registry. Pre-registers the three built-ins under their
 * runtime tags (`'router'`, `'sandbox'`, `'cli'`) and accepts `register(name,
 * factory)` for any additional runtime — and a BYO `AgentSpec.executor` resolves
 * without touching the registry at all. NOT a closed switch; registration + BYO
 * ARE the extension points.
 *
 * `resolve` precedence (frozen in `ExecutorRegistry`): a BYO `spec.executor` →
 * `harness === null` → the `'router'` factory; else a registered factory for the
 * harness-derived runtime (`'sandbox'` for any `BackendType`); else fail loud.
 */
declare function createExecutorRegistry(): ExecutorRegistry;

/**
 *
 * `delegate` MCP tool — the ONE generic delegation verb, the agent-facing front door to
 * `delegate()` / `supervise()`. The agent hands it an INTENT (what it wants done); a default
 * authoring supervisor decomposes the intent and AUTHORS the worker profile it needs — there is no
 * hardcoded coder/researcher profile, so one verb covers code, research, and anything else.
 *
 * `delegate` is SYNCHRONOUS: it awaits the full supervised run and returns the delivered output
 * TOGETHER WITH `spentTotal` — the conserved cost of the whole delegation (`iterations` / `tokens` /
 * `usd` / `ms`), so the caller always learns what the delegation actually spent.
 *
 * The supervisor's substrate (its brain `router`, the worker `backend`, the completion `deliverable`)
 * is INJECTED at server construction — never an agent-supplied arg. The agent supplies only the
 * intent (+ an optional per-call `model` / `runId`).
 *
 * @experimental
 */

/** MCP tool name for the `delegate` generic-delegation tool. @experimental */
declare const DELEGATE_TOOL_NAME = "delegate";
/** Human-readable description of the `delegate` MCP tool, injected into the tool manifest. @experimental */
declare const DELEGATE_DESCRIPTION: string;
/** JSON Schema for `delegate` tool arguments (`intent` + optional `model` and `runId`). @experimental */
declare const DELEGATE_INPUT_SCHEMA: {
    readonly type: "object";
    readonly properties: {
        readonly intent: {
            readonly type: "string";
            readonly description: "What you want accomplished, as an outcome. The supervisor authors the worker.";
        };
        readonly model: {
            readonly type: "string";
            readonly description: "Optional per-call override for the supervisor brain model.";
        };
        readonly runId: {
            readonly type: "string";
            readonly description: "Optional trace-correlation id for this delegation.";
        };
    };
    readonly required: readonly ["intent"];
    readonly additionalProperties: false;
};
/** Parsed `delegate` tool arguments. */
interface DelegateArgs {
    intent: string;
    model?: string;
    runId?: string;
}
/** Parse and validate raw MCP tool input into typed `DelegateArgs`; throws `TypeError` on bad input. @experimental */
declare function validateDelegateArgs(raw: unknown): DelegateArgs;
/** The synchronous result the `delegate` tool returns to the calling agent: the delivered output (or
 *  the no-winner reason) PLUS the conserved spend of the whole delegation. */
type DelegateResult = {
    status: 'winner';
    out: unknown;
    outRef: string;
    spentTotal: Spend;
} | {
    status: 'no-winner';
    reason: string;
    spentTotal: Spend;
};
/** @experimental */
interface DelegateHandlerOptions {
    /** The supervisor brain's router substrate (REQUIRED — the default supervisor is router-brained). */
    router: RouterConfig;
    /** WHERE the authored workers run. Required for `supervise()` to spawn anything. */
    backend: ExecutorConfig;
    /** The completion oracle the authored workers settle against (settled ⟺ delivered). */
    deliverable?: DeliverableSpec;
    /** Default supervisor brain model when a call omits `model`. */
    model?: string;
    /** Restrict the run to this subset of models. */
    allowedModels?: readonly string[];
}
/**
 * Build the `delegate` tool handler. Closes over the injected supervisor substrate (`router` /
 * `backend` / `deliverable`); each call routes the agent's intent to `delegate()` and returns the
 * delivered output with its conserved cost.
 */
declare function createDelegateHandler(options: DelegateHandlerOptions): (raw: unknown) => Promise<DelegateResult>;

/**
 *
 * Stdio JSON-RPC MCP server exposing the delegation tools to sandbox
 * coding-harness agents (claude-code, codex, opencode, ...): the generic
 * `delegate` verb plus the queue-bound `delegate_feedback`,
 * `delegation_status`, and `delegation_history`. `delegate_ui_audit` is served
 * when a `uiAuditorDelegate` is wired.
 *
 * The server is transport-bound but topology-free: tool execution is
 * delegated to handler functions composed from a queue, a feedback
 * store, and the wired run delegates. Consumers wire those at
 * construction time. The `agent-runtime-mcp` bin serves the generic
 * `delegate` verb over a real sandbox client when `MCP_ENABLE_DELEGATE=1`.
 *
 * Wire protocol: line-delimited JSON-RPC 2.0 over stdio. Each line is
 * one request; each response is one line. `tools/list` and `tools/call`
 * mirror the MCP 2024-11-05 spec; we do not pull in
 * `@modelcontextprotocol/sdk` to keep the dependency footprint zero.
 *
 * @experimental
 */

/** @experimental */
interface McpServerOptions {
    /**
     * Required to enable `delegate` — the ONE generic delegation verb. Inject the supervisor
     * substrate: its brain `router`, the worker `backend`, and the completion `deliverable`. The
     * supervisor AUTHORS its own worker from the agent's intent, so there is no worker profile to
     * wire here.
     */
    delegateSupervisor?: DelegateHandlerOptions;
    /**
     * Required to enable delegate_ui_audit. Wire one that closes over your
     * `runLoop` + `uiAuditorProfile` + a `SandboxClient` (the
     * canonical in-process choice is `createInProcessUiAuditClient` from
     * `@tangle-network/agent-runtime/profiles`) + your vision judge.
     */
    uiAuditorDelegate?: UiAuditorDelegate;
    /** Override the default in-memory feedback store. */
    feedbackStore?: FeedbackStore;
    /** Override the default in-memory task queue. */
    queue?: DelegationTaskQueue;
    /**
     * Extra tools to serve alongside the delegation tools, for example
     * `createCoordinationTools(...).tools`. Registered after the built-ins; a
     * duplicate name throws so delegation tools cannot be shadowed silently.
     */
    extraTools?: McpToolDescriptor[];
    /**
     * Inherited trace identity (`readTraceContextFromEnv()`) stamped on every
     * record the DEFAULT queue creates. Ignored when `queue` is supplied —
     * pass `traceContext` to that queue's constructor instead.
     */
    traceContext?: TraceContext;
    /** Server display name surfaced via `initialize`. Default `'agent-runtime-mcp'`. */
    serverName?: string;
    /** Server version surfaced via `initialize`. Default = the package version baked at build time. */
    serverVersion?: string;
}
/** @experimental */
interface McpToolDescriptor {
    name: string;
    description: string;
    inputSchema: Record<string, unknown>;
    handler: (raw: unknown) => Promise<unknown>;
}
/** @experimental */
interface McpServer {
    /** Tools currently registered (depend on which delegates were wired). */
    readonly tools: ReadonlyMap<string, McpToolDescriptor>;
    /** The underlying queue — exposed so tests can introspect it. */
    readonly queue: DelegationTaskQueue;
    /** The feedback store — exposed for the same reason. */
    readonly feedbackStore: FeedbackStore;
    /** Handle a single parsed JSON-RPC message. Returns the response object (or `null` for notifications). */
    handle(message: JsonRpcMessage): Promise<JsonRpcResponse | null>;
    /** Drive the server on a stdio-shaped transport until `stop()` is called. */
    serve(transport?: McpTransport): Promise<void>;
    /** Stop a `serve` call. Subsequent requests are rejected. */
    stop(): void;
}
/** @experimental */
interface McpTransport {
    input: NodeJS.ReadableStream;
    output: NodeJS.WritableStream;
}
/** @experimental */
interface JsonRpcMessage {
    jsonrpc: '2.0';
    id?: number | string | null;
    method: string;
    params?: unknown;
}
/** @experimental */
interface JsonRpcResponse {
    jsonrpc: '2.0';
    id: number | string | null;
    result?: unknown;
    error?: {
        code: number;
        message: string;
        data?: unknown;
    };
}
/**
 * Stdio JSON-RPC MCP server exposing the delegation tools (`delegate`, `delegate_feedback`, `delegation_status`, `delegation_history`, optional `delegate_ui_audit`) to sandbox coding-harness agents.
 *
 * @experimental
 */
declare function createMcpServer(options?: McpServerOptions): McpServer;
/**
 * In-process pair of `Readable` + `Writable` streams suitable for driving
 * `server.serve(...)` from a test. Returns the agent-side stream (the
 * client writes to it) and the server-side stream (the test reads from it).
 *
 * @experimental
 */
declare function createInProcessTransport(): {
    transport: McpTransport;
    clientWrite(line: string): void;
    clientClose(): void;
    readServer(): Promise<JsonRpcResponse[]>;
};

/**
 *
 * MCP binding for a live `Scope`. A sandbox driver gets the same small verbs
 * the in-process driver has: spawn, observe, await, steer, ask/answer, analyze,
 * and stop. Settled outputs remain Scope artifacts; product code can project
 * them into any UI/report envelope it needs.
 *
 * @experimental
 */

/** A worker the driver has drained via `await_event`. */
interface SettledWorker {
    readonly id: string;
    readonly status: 'done' | 'down';
    readonly score?: number;
    readonly valid?: boolean;
    readonly outRef?: string;
    readonly reason?: string;
}
type QuestionLevel = 'worker' | 'driver' | 'loop';
type QuestionUrgency = 'continue-without' | 'blocks-step' | 'blocks-run';
interface QuestionOption {
    readonly label: string;
    readonly tradeoff: string;
}
interface Question {
    readonly id: string;
    readonly from: string;
    readonly level: QuestionLevel;
    readonly question: string;
    readonly reason: string;
    readonly urgency: QuestionUrgency;
    readonly options?: ReadonlyArray<QuestionOption>;
}
type QuestionDecision = {
    readonly kind: 'answer';
    readonly answer: string;
    readonly by: string;
} | {
    readonly kind: 'defer';
    readonly reason: string;
} | {
    readonly kind: 'escalate';
    readonly to: 'parent' | 'user' | string;
    readonly reason: string;
};
interface QuestionRecord extends Question {
    readonly status: 'open' | 'answered' | 'deferred' | 'escalated';
    readonly decision?: QuestionDecision;
    readonly openedAt: number;
}
type QuestionPolicy = 'auto' | 'mustDecide' | 'bubble' | 'failClosed';
interface AnalystRegistry {
    readonly kinds: ReadonlyArray<{
        id: string;
        description: string;
        area: string;
    }>;
    readonly run: (kindId: string, trace: unknown) => Promise<unknown>;
}
/** A trace-analyst result re-entered as a message on the bus (the `finding` event kind). */
interface AnalystFindingEvent {
    readonly fromWorker: string;
    readonly analyst: string;
    readonly findings: unknown;
}
/** A parent→child message (the down-leg): recorded for observability, delivered via the child inbox,
 *  never pulled back by the parent. `delivered` mirrors whether the live child accepted it. */
interface DownMessageEvent {
    readonly toWorker: string;
    readonly instruction: string;
    readonly delivered: boolean;
}
/** Every message on the one typed pipe. UP (child→parent): question / settled / finding — queued for
 *  the driver to `pull`. DOWN (parent→child): steer / answer — record-only (history + subscribers),
 *  routed to the child inbox. New kinds are additive. */
type CoordinationEvent = {
    readonly type: 'question';
    readonly question: QuestionRecord;
} | {
    readonly type: 'settled';
    readonly worker: SettledWorker;
} | {
    readonly type: 'finding';
    readonly finding: AnalystFindingEvent;
} | {
    readonly type: 'steer';
    readonly down: DownMessageEvent;
} | {
    readonly type: 'answer';
    readonly down: DownMessageEvent;
    readonly questionId: string;
};
type MakeWorkerAgent = (profile: unknown) => Agent<unknown, unknown>;
interface CoordinationToolsOptions {
    readonly scope: Scope<unknown>;
    readonly blobs: ResultBlobStore;
    readonly makeWorkerAgent: MakeWorkerAgent;
    readonly perWorker: Budget;
    readonly analysts?: AnalystRegistry;
    readonly onEvent?: (event: CoordinationEvent) => void | Promise<void>;
    readonly questionPolicy?: QuestionPolicy;
    /** Analyst kind ids to run AUTOMATICALLY when a worker settles `done` (the analyst-on-settle
     *  hook). Each result is published as a `finding` event on the bus — pass-through to subscribers
     *  and queued for the driver to pull via `await_event`. Omit/empty = no auto-analysis (default;
     *  the driver can still run lenses on demand via `run_analyst`). Requires `analysts`. */
    readonly analyzeOnSettle?: ReadonlyArray<string>;
    /** Hard cap on how many workers may be LIVE (spawned but not yet settled) at once. `spawn_agent`
     *  counts the scope's non-terminal nodes and fails closed (`error: 'max-live-workers'`) BEFORE
     *  reserving from the pool when the cap is already met — a concurrency fence on top of the
     *  conserved-budget fence (the pool bounds total work; this bounds simultaneous work, e.g. live
     *  sandboxes/boxes). Omit or `<= 0` = no cap (the prior behavior; the pool stays the only fence). */
    readonly maxLiveWorkers?: number;
}
/**
 * The supervisor-side toolbox returned by {@link createCoordinationTools}: the MCP tool
 * descriptors a driver `AgentProfile` calls to spawn, steer, observe, and settle workers
 * over a live `Scope`, plus the typed accessors (`settled`/`questions`/`history`/`stats`/
 * `raiseFinding`) for the bidirectional coordination bus. This is the live, backend-of-your-
 * choice, steerable counterpart to the one-shot own-sandbox delegation MCP.
 */
interface CoordinationTools {
    readonly tools: McpToolDescriptor[];
    isStopped(): boolean;
    stopReason(): string | undefined;
    settled(): ReadonlyArray<SettledWorker>;
    questions(): ReadonlyArray<QuestionRecord>;
    /** The full ordered log of every bus event — UP (settled / question / finding) and DOWN
     *  (steer / answer) — the observability audit + replay trail. Each record carries seq,
     *  timestamp, and priority. */
    history(): ReadonlyArray<BusRecord<CoordinationEvent>>;
    /** Bus throughput counters (published / pulled / by-kind) for live dashboards. */
    stats(): BusStats;
    /** Raise a `finding` on the bus from outside the settle hook — the seam an ONLINE detector
     *  (mid-run, on the worker pipe) uses to tell the driver "this worker is looping/erroring" the
     *  moment it happens, instead of only at settle. Queued for `await_event` + pass-through. */
    raiseFinding(finding: AnalystFindingEvent): Promise<void>;
    /**
     * Post-loop drain: pull every ALREADY-settled, unpulled child into the ledger (publishing each
     * as a `settled` bus event for the audit trail) WITHOUT awaiting live children. The driver
     * calls this once its brain loop ends, so a delivered child the brain never awaited still
     * reaches `finalizeBestDelivered` — a gate-verified delivery must never be lost to the
     * driver's pull discipline. Analyst-on-settle hooks do NOT fire here (the driver has stopped;
     * nobody is left to read a finding, and analysts spend real compute). Returns the count.
     */
    drainResolved(): Promise<number>;
}
/** Build the driver's MCP tools over a live scope. */
declare function createCoordinationTools(opts: CoordinationToolsOptions): CoordinationTools;

export { type DelegationTaskQueueOptions as $, type AnalystRegistry as A, type DelegateResearchArgs as B, type CappedDelegationTrace as C, type DelegationExecutor as D, type DelegateResearchConfig as E, type FleetHandle as F, type DelegateResearchResult as G, type DelegateResult as H, type DelegateRunCtx as I, type DelegateUiAuditConfig as J, type DelegateUiAuditRoute as K, type DelegationError as L, type DelegationFeedbackSnapshot as M, type DelegationHistoryEntry as N, DelegationPersistenceError as O, type DelegationProfile as P, type DelegationProgress as Q, type DelegationRecord as R, type DelegationResultPayload as S, type DelegationResumeContext as T, type UiAuditorDelegate as U, type DelegationResumeDriver as V, type DelegationResumeTick as W, type DelegationRunContext as X, DelegationStateCorruptError as Y, type DelegationStatus as Z, type DelegationStore as _, DelegationTaskQueue as a, type ExecutorConfig as a$, type DelegationTraceCaps as a0, type DelegationTraceCollector as a1, type DelegationTraceSpan as a2, type DetachedSessionDelegateOptions as a3, type DetachedSessionRefParts as a4, type DetachedTurn as a5, type DetachedTurnResumeDriverOptions as a6, type DetachedWinnerSelection as a7, type DriveTurnCapableBox as a8, type DriveTurnTick as a9, type SubmitOutput as aA, type TraceContext as aB, type UiAuditorDelegationOutput as aC, buildDelegationTraceSpans as aD, capDelegationTrace as aE, coderTaskFromArgs as aF, composeLoopTraceEmitters as aG, createCoordinationTools as aH, createDelegateHandler as aI, createDelegationTraceCollector as aJ, createDetachedTurnResumeDriver as aK, createFleetWorkspaceExecutor as aL, createInProcessTransport as aM, createMcpServer as aN, createPropagatingTraceEmitter as aO, createSiblingSandboxExecutor as aP, detachedSessionDelegate as aQ, detachedTurnEvents as aR, eventToSnapshot as aS, formatDetachedSessionRef as aT, hashIdempotencyInput as aU, parseDetachedSessionRef as aV, readTraceContextFromEnv as aW, runDetachedTurn as aX, settleDetachedCoderTurn as aY, traceContextToEnv as aZ, validateDelegateArgs as a_, type FeedbackEvent as aa, type FeedbackRating as ab, type FeedbackRefersTo as ac, FileDelegationStore as ad, type FileDelegationStoreOptions as ae, type FleetWorkspaceExecutorOptions as af, InMemoryDelegationStore as ag, InMemoryFeedbackStore as ah, type JsonRpcMessage as ai, type JsonRpcResponse as aj, type MakeWorkerAgent as ak, type McpServer as al, type McpServerOptions as am, type McpToolDescriptor as an, type McpTransport as ao, type Question as ap, type QuestionDecision as aq, type QuestionPolicy as ar, type QuestionRecord as as, type ResearchOutputShape as at, type ResearchSource as au, type RunDetachedTurnOptions as av, type SettleDetachedCoderTurnOptions as aw, type SettledWorker as ax, type SiblingSandboxExecutorOptions as ay, type SubmitInput as az, type FeedbackStore as b, type BusEvent as b0, type BusRecord as b1, type BusStats as b2, type EventBus as b3, type ProviderSeam as b4, type PublishOptions as b5, cliWorktreeExecutor as b6, createEventBus as b7, createExecutor as b8, createExecutorRegistry as b9, type DelegateFeedbackResult as c, type DelegateFeedbackArgs as d, type DelegateUiAuditArgs as e, type DelegateUiAuditResult as f, type DelegationHistoryResult as g, type DelegationHistoryArgs as h, type DelegationStatusResult as i, type DelegationStatusArgs as j, type CoderDelegate as k, type CoderReview as l, type CoderReviewer as m, type CoordinationEvent as n, type CoordinationTools as o, type CoordinationToolsOptions as p, DELEGATE_DESCRIPTION as q, DELEGATE_INPUT_SCHEMA as r, DELEGATE_TOOL_NAME as s, DELEGATION_TRACE_MAX_BYTES as t, DELEGATION_TRACE_MAX_SPANS as u, type DelegateArgs as v, type DelegateCodeArgs as w, type DelegateCodeConfig as x, type DelegateCodeResult as y, type DelegateHandlerOptions as z };
