import { R as RuntimeHooks, a as SelectionReceipt } from './types-SyuwunY_.js';
import { C as Corpus, O as Outcome } from './worktree-fanout-BDFQIO-Y.js';
import { A as Agent, B as Budget, S as Scope } from './types-eMNgWgFi.js';

/**
 * The general agentic primitive — sequential (depth) and parallel (breadth) over a shared,
 * checkable artifact, driven through the keystone Supervisor as one recursive `Agent.act`.
 *
 * The domain lives behind ONE seam — `AgenticSurface` (open an artifact, list tools, call a tool,
 * score the artifact, close it). EnterpriseOps implements it (seed a gym DB, MCP tools, SQL
 * verifier); Commit0/AppWorld/terminal-bench implement it the same way (a repo workspace, shell
 * tools, the test suite). The drivers below are domain-blind: they run over any surface.
 *
 * Two shapes, the agent's POMDP rollout as the unit:
 *  - DEPTH   one persistent artifact carried across shots. Each shot the agent works the tool loop;
 *            between shots a trace-analyst (selector≠judge: reads the trajectory, never the score)
 *            steers the resumed session toward what's unfinished. shot n stands on shot n-1's
 *            artifact state + history. This is continuation — long-horizon, same artifact.
 *  - BREADTH K independent artifacts, each a fresh rollout, the deployable verifier picks the best.
 *
 * Both are an `Agent` whose `act` spawns leaf shots through `scope.spawn` and reacts via
 * `scope.next()` — so the conserved budget pool meters them (equal-k by construction), the journal
 * records the tree, and the same primitive nests. `runAgentic` runs the chosen driver through
 * `createSupervisor().run`. The leaf (one shot over a handle) is resolved per-spawn from a
 * surface-closed registry — the open `Executor` seam, not bespoke per-benchmark glue.
 */

interface AgenticTask {
    readonly id: string;
    readonly systemPrompt: string;
    readonly userPrompt: string;
    /** Opaque domain payload the surface reads (EOPS: servers/verifiers/tools). Drivers never read it. */
    readonly meta?: Record<string, unknown>;
}
interface ArtifactHandle {
    readonly id: string;
    readonly surface: string;
    /** Opaque per-artifact context the surface stashes (EOPS: the seeded gym server + db id). */
    readonly ctx?: unknown;
}
interface AgenticTool {
    readonly type: 'function';
    readonly function: {
        name: string;
        description?: string;
        parameters: Record<string, unknown>;
    };
}
interface SurfaceScore {
    passes: number;
    total: number;
    /** Checks excluded as malformed (data defect, not the agent). `total === 0` ⇒ unscoreable. */
    errored: number;
}
/** A stateful, checkable environment an agent operates over with tools. Open behind one interface. */
interface AgenticSurface {
    readonly name: string;
    open(task: AgenticTask): Promise<ArtifactHandle>;
    tools(task: AgenticTask, handle: ArtifactHandle): Promise<AgenticTool[]>;
    call(handle: ArtifactHandle, name: string, args: Record<string, unknown>): Promise<string>;
    score(task: AgenticTask, handle: ArtifactHandle): Promise<SurfaceScore>;
    close(handle: ArtifactHandle): Promise<void>;
}
interface AgenticOptions {
    routerBaseUrl: string;
    routerKey: string;
    model: string;
    /** Optional completion transport (see `RouterConfig.complete`): when set, BOTH legs of an
     *  offline run use it instead of `fetch`-ing the router — the worker's tool loop (threaded into
     *  its `routerToolLoop` cfg) AND the analyst's critic (its `ChatClient` is bound to this same
     *  transport). One injected responder serves both, as a localhost mock endpoint would. Absent ⇒
     *  the live router fetch path (the default). */
    complete?: (body: Record<string, unknown>) => Promise<unknown>;
    temperature?: number;
    /** Completion cap per worker turn — REQUIRED for thinking models (they burn unbounded
     *  budgets on reasoning and return empty content without it). Omitted ⇒ provider default. */
    maxTokens?: number;
    /** Turns the agent may take within ONE shot before the driver intervenes. */
    innerTurns?: number;
    /** The depth STEERER's analyst instruction (observe()'s system prompt). The knob a
     *  prompt optimizer (GEPA) tunes — the analyst IS the steerer. Omitted ⇒ the default. */
    analystInstruction?: string;
    /** The critic's model — lets the analyst be a stronger (or cheaper) model than the
     *  worker. Omitted ⇒ the worker's `model`. */
    analystModel?: string;
    /** Across-run learning: when set, the analyst's observe() pass appends trace-derived
     *  facts here (the flywheel write side). Read-back is opt-in via `corpusReadback`
     *  because unconditional priming can pollute context on some domains. */
    corpus?: Corpus;
    /** Tags written onto learned facts (and used by the caller's priming query). */
    corpusTags?: string[];
    /** In-context learning: when set, query `corpus` before each depth shot and inject
     *  the top trace-derived facts as guidance for the active run. No corpus means no read-back. */
    corpusReadback?: CorpusReadbackOptions;
}
interface CorpusReadbackOptions {
    /** Minimum confidence for a fact to be injected. Default 0.7. */
    minConfidence?: number;
    /** Extra tags a fact must carry, in addition to `corpusTags`. */
    tags?: ReadonlyArray<string>;
    /** Max facts injected per shot. Default 3. */
    maxFacts?: number;
    /** Default false: only facts tagged `audience:agent` are injected into the worker. */
    includeOperatorFacts?: boolean;
}
type Msg$1 = Record<string, unknown>;
interface ShotResult {
    messages: Msg$1[];
    score: number;
    passes: number;
    total: number;
    completions: number;
    toolErrors: number;
}
interface AgenticRunResult {
    /** The strategy name (built-in 'depth'/'breadth' or a custom strategy's name). */
    mode: string;
    score: number;
    resolved: boolean;
    completions: number;
    /** DEPTH: score after each shot — the progress-over-rounds curve. BREADTH: best-so-far per rollout. */
    progression: number[];
    shots: number;
    /** The cost vector, stamped by `runAgentic` from the Supervisor's conserved pool: real
     *  router tokens, priced usd (0 when the model is unpriced — never fabricated), wall ms. */
    usd: number;
    ms: number;
    tokens: {
        input: number;
        output: number;
    };
}
/** DEPTH: one persistent artifact, carried across analyst-steered shots. */
declare function depthStrategy(surface: AgenticSurface, task: AgenticTask, opts: AgenticOptions, cfg: {
    maxShots: number;
}): Agent<unknown, Outcome<unknown>>;
/** BREADTH: K independent rollouts (each own artifact), verifier picks the best. */
declare function breadthStrategy(_surface: AgenticSurface, task: AgenticTask, opts: AgenticOptions, cfg: {
    width: number;
}): Agent<unknown, Outcome<unknown>>;
/**
 * A Strategy is HOW you spend the compute budget to beat the Environment's check — it
 * builds the driver `Agent` the Supervisor runs. This is the OPEN extension point: a dev
 * authors their own by implementing `driver()` to return an Agent whose `act()` spawns
 * shots/analysts via `scope.spawn` / `scope.next` / `scope.send`. The two built-ins are
 * the reference implementations to copy:
 *   sample — K INDEPENDENT attempts, keep the best-verifying (best-of-N / resample).
 *   refine — attempt → observe() reads the trace → steer the next → repeat (iterate).
 * (A multi-agent "team" is just a Strategy whose driver spawns several different agents.)
 */
interface Strategy {
    readonly name: string;
    driver(surface: AgenticSurface, task: AgenticTask, opts: AgenticOptions, budget: number): Agent<unknown, Outcome<unknown>>;
}
/** Built-in `Strategy`: K independent attempts, keep the best-verifying (best-of-N / resample). */
declare const sample: Strategy;
/** Built-in `Strategy`: attempt → `observe()` reads the trace → steer the next attempt → repeat (deepen one lineage). */
declare const refine: Strategy;
/** A role for one shot — multi-agent loops (researcher + engineer, a panel of k
 *  researchers) give each shot its own system prompt and optionally its own model. */
interface ShotPersona {
    /** Replaces the task's systemPrompt for a FRESH shot; on a carried conversation it is
     *  injected as a hand-off message (the transcript's earlier roles stay intact). */
    systemPrompt?: string;
    /** Per-shot model override (e.g. a stronger model for the engineer shot). */
    model?: string;
}
interface ShotSpec {
    /** present ⇒ continue this artifact (depth); absent ⇒ the shot opens a fresh one (sample/restart). */
    handle?: ArtifactHandle;
    messages?: Msg$1[];
    steer?: string;
    persona?: ShotPersona;
    /** Restrict THIS shot to a subset of the domain's tools (by name) — focus a shot on
     *  the relevant capabilities. Restriction-only; unknown names throw. Omitted ⇒ all. */
    tools?: string[];
}
interface StrategyResult {
    score: number;
    resolved: boolean;
    completions: number;
    progression: number[];
    shots: number;
}
/** Artifact lifecycle a strategy may manage itself — open/close ONLY. Raw `call`/`score`
 *  are withheld: scores reach the body solely through `shot()`'s ShotResult (the
 *  harness-verified channel), so a body cannot peek the check or fabricate around it. */
interface StrategyArtifacts {
    readonly name: string;
    open(task: AgenticTask): Promise<ArtifactHandle>;
    close(handle: ArtifactHandle): Promise<void>;
}
/** What a strategy body composes with: the artifact lifecycle, the budget, and the two steps. */
interface StrategyCtx {
    /** Open/close artifacts the body manages itself (e.g. one persistent handle for depth). */
    readonly surface: StrategyArtifacts;
    readonly task: AgenticTask;
    readonly opts: AgenticOptions;
    readonly budget: number;
    readonly scope: Scope<Outcome<unknown>>;
    /** Run ONE worker shot; its harness-scored result, or null if it went down. */
    shot(spec?: ShotSpec): Promise<ShotResult | null>;
    /** The firewalled critic reads the trajectory → a steer string, or null on COMPLETE/down. */
    critique(messages: Msg$1[]): Promise<string | null>;
    /** The RAW analyst channel: the firewalled critic answers `instruction` over the
     *  trajectory verbatim — no findings extraction, so verdict-shaped formats
     *  (CONTINUE/STOP decisions, calibrated predictions) survive. Same firewall:
     *  trajectory in, never scores. Null when the analyst went down. */
    consult(messages: Msg$1[], instruction: string): Promise<string | null>;
    /** The tools THIS artifact's task actually offers (names + descriptions only — never
     *  the implementations). Tool sets vary per task on heterogeneous domains; a strategy
     *  that restricts shots MUST select from this list, never from hardcoded names. */
    listTools(handle: ArtifactHandle): Promise<Array<{
        name: string;
        description?: string;
    }>>;
}
/** Author a Strategy from the composable steps — the open, compact way. */
declare function defineStrategy(name: string, run: (ctx: StrategyCtx) => Promise<StrategyResult>): Strategy;
/** A NEW strategy, authored from the steps (~20 lines): refine, but when a steered shot
 *  fails to improve the score it ABANDONS that line and restarts fresh (branch-when-stuck)
 *  — the widen/MCTS idea the depth-stuck failure motivated. Scored keep-best (the best
 *  checkpoint across all lines), the deployable metric. This is the "experts build BETTER
 *  optimizations" path: a new technique, compact, with zero Supervisor ceremony. */
declare const adaptiveRefine: Strategy;
/** The explore-then-exploit MIX: spend ⌈budget/2⌉ on independent samples (kept open),
 *  then refine the best-verifying line with the remaining budget. Sample's basin escape +
 *  refine's accumulation — the third built-in, authored from the public steps. */
declare const sampleThenRefine: Strategy;
interface RunAgenticOptions extends AgenticOptions {
    surface: AgenticSurface;
    task: AgenticTask;
    /** Lifecycle observability — every spawn/settle (shots, analysts) streams here live.
     *  The seam online watchdogs/route-auditors subscribe to. */
    hooks?: RuntimeHooks;
    /** A Strategy (the open way) — author/pass your own. Overrides `mode` when present. */
    strategy?: Strategy;
    /** Built-in shorthand: 'depth'→refine, 'breadth'→sample. Default 'depth'. */
    mode?: 'depth' | 'breadth';
    /** budget: refine→max shots; sample→rollout width. */
    budget: number;
    rootBudget?: Budget;
}
/** Run a Strategy through the keystone Supervisor — `Agent.act` over a conserved-budget Scope. */
declare function runAgentic(opts: RunAgenticOptions): Promise<AgenticRunResult>;

/**
 * structuralRollout — the measured structural lever as a fourth member of the
 * sample/refine/sampleThenRefine strategy family: k independent samples, selection by
 * TASK-VISIBLE checks only, then a guarded self-repair loop steered by the checks'
 * failure output. Design: docs/design/structural-rollout-integration.md; measured basis
 * (bench/src/hev-structural.mts, bench/src/mbpp-structural.mts): +8.5..+21.3pp hidden-test
 * lift across Llama-3-8B/Qwen2.5-7B × HumanEval/MBPP, null only at saturation.
 *
 * Honesty invariants carried over from the proven rigs:
 *  - Visible checks are generated from task-visible information only, BEFORE any
 *    candidate exists, and FROZEN for every sample and repair round of the task.
 *  - OFFICIAL checks (shown in the task itself) rank lexicographically above
 *    model-AUTHORED guesses. This ordering is measured, not stylistic: authored guesses
 *    run 17–70% wrong depending on model × spec richness, and unweighted they flipped
 *    selection NEGATIVE on MBPP (6 noisy guesses outvoting the one reliable check).
 *  - A candidate that crashed before the checks could run ranks below one that ran and
 *    failed everything.
 *  - Repair sees ONLY the checks' failure output, and never displaces a candidate that
 *    passes more official checks with one that passes fewer (wrong visible examples
 *    poison repair at saturation — the glm /47,/116 regressions).
 *
 * Placement rule: this is an INFERENCE-TIME capability (it wraps the model call via the
 * strategy seam). It does not belong in improve()/selfImprove (training-time); improve()
 * may later tune `StructuralRolloutPolicy` as an optimizable surface.
 */

type Msg = Record<string, unknown>;
/** The rollout's compute recipe — promoted from the proven rigs' env vars (K/REPAIRS/
 *  TESTGEN/DIVERSE/TEMPERATURE). Defaults are the measured sweet spot: repair value
 *  concentrates at low k (~+12pp at k=1, +1–3pp at k=5), so `k=5, repairRounds=2` is the
 *  full recipe and `k=1, repairRounds=2` the low-compute preset. */
interface StructuralRolloutPolicy {
    /** Independent samples per task (selection breadth). */
    k: number;
    /** Repair shots after selection, each steered by the checks' failure output. */
    repairRounds: number;
    /** Model-authored visible checks requested per task; 0 disables authoring. */
    testgen: number;
    /** Per-slot strategy-lens prefixes on the k samples (attacks the all-k-fail bucket).
     *  Measured as a paired null (+0.6pp) — kept as an optional knob, off by default. */
    diverse?: boolean;
    /** Sampling temperature for every shot of this strategy; omitted ⇒ the worker default. */
    temperature?: number;
}
/** The measured default recipe: 5 samples, 2 guarded repair rounds, 6 authored checks. */
declare const defaultStructuralRolloutPolicy: StructuralRolloutPolicy;
/** One task-visible executable check (e.g. a single-line Python assert). */
interface VisibleCheck {
    code: string;
    /** 'official' = shown in the task itself (docstring example, shown assert);
     *  'authored' = the model's own guess. Official outranks authored in selection. */
    kind: 'official' | 'authored';
}
/** What a CheckSource composes with. `consult` is the strategy family's raw analyst
 *  channel (metered by the conserved pool, offline-injectable via `opts.complete`) —
 *  check authoring goes through it rather than a bespoke model client. */
interface CheckSourceCtx {
    /** Authored-check budget for this task (`policy.testgen`). */
    count: number;
    /** The symbol authored checks must reference; undefined ⇒ authoring is skipped
     *  (no guesses beats guesses pinned to nothing). */
    entrySymbol?: string;
    /** One metered LLM call: instruction in, reply text out, null when the channel went
     *  down. The task's visible prompt is included by the channel itself. */
    consult(instruction: string): Promise<string | null>;
}
/** Produces the task's visible checks. MUST derive them from agent-visible information
 *  only, before any candidate exists — the strategy freezes the returned set for every
 *  sample and repair round of the task. */
interface CheckSource {
    generate(task: AgenticTask, ctx: CheckSourceCtx): Promise<VisibleCheck[]>;
}
/** The proven authored-assert filter (lifted from the rigs' generateTests): keep only
 *  single-line, paren-balanced asserts that reference the entry symbol — malformed lines
 *  are dropped here rather than poisoning every candidate's score identically. */
declare function filterAuthoredAsserts(reply: string, entrySymbol: string, count: number): string[];
/** Default authored-check source: one metered LLM call per task, before sampling,
 *  filtered through `filterAuthoredAsserts`. Returns [] (no signal, never a fabricated
 *  check) when the budget is 0, no entry symbol resolves, or the channel went down. */
declare function modelAuthoredChecks(overrides?: {
    count?: number;
}): CheckSource;
/** Official checks the surface stashed on the task (e.g. MBPP's shown assert). Reads
 *  `task.meta[key]` as a string array; anything else means no official checks. */
declare function officialChecksFromMeta(key?: string): CheckSource;
/** Concatenate check sources (official first by convention — ordering does not affect
 *  scoring, which reads each check's `kind`). */
declare function composeCheckSources(...sources: CheckSource[]): CheckSource;
/** The symbol authored checks are pinned to: `task.meta.entryPoint` when the surface
 *  provides it, else the LAST `def name(` in the visible prompt (a code-completion stub
 *  lists helpers first, the entry stub last). Undefined ⇒ authoring is skipped. */
declare function resolveEntrySymbol(task: AgenticTask): string | undefined;
/** How one candidate fared against the frozen visible checks, split by check kind. */
interface CheckOutcome {
    passedOfficial: number;
    totalOfficial: number;
    passedAuthored: number;
    totalAuthored: number;
    /** The checks' failure report — the ONLY feedback the repair loop may see. */
    failureOutput: string;
    /** True when the candidate crashed before any check could run — ranks below a
     *  candidate that ran and failed everything. */
    crashed?: boolean;
}
/** Minimal exec channel the default runner needs. `SandboxInstance` (and therefore
 *  `ValidationCtx.box`) satisfies it structurally. */
interface CheckExecChannel {
    exec(command: string, options?: {
        timeoutMs?: number;
    }): Promise<{
        exitCode: number;
        stdout: string;
        stderr: string;
    }>;
}
interface CheckRunContext {
    task: AgenticTask;
    /** Live exec channel for this run (`ValidationCtx.box` / a sandbox instance). */
    box?: CheckExecChannel;
    signal?: AbortSignal;
}
/** Executes the frozen checks against one candidate. Implementations MUST fail loud
 *  (throw) when they cannot execute — a silent zero poisons selection. */
interface CheckRunner {
    run(candidate: string, checks: VisibleCheck[], ctx: CheckRunContext): Promise<CheckOutcome>;
}
/** Default CheckRunner backend: pipes the check program into `python3` over the sandbox
 *  exec channel (`ctx.box`, or one bound at construction). Never shells out to docker
 *  itself — the jail is the sandbox's concern. No channel ⇒ throws; it must never
 *  silently score 0. Empty check sets short-circuit to a no-signal outcome (nothing to
 *  execute, so no channel is required). */
declare function sandboxCheckRunner(options?: {
    box?: CheckExecChannel;
    python?: string;
    timeoutMs?: number;
}): CheckRunner;
/** The selection order: crash < ran; then official pass-fraction; authored guesses only
 *  break ties. Returns > 0 when `a` outranks `b`. Strictly lexicographic — on MBPP,
 *  letting 6 noisy guesses outvote the one official check flipped selection negative. */
declare function compareCheckOutcomes(a: CheckOutcome, b: CheckOutcome): number;
/** Display scalar for receipts/reports (the rigs' `visibleScore` shape): crash = -1,
 *  else official fraction + 0.001 × authored fraction. Selection itself uses the exact
 *  lexicographic comparator, never this scalar. */
declare function visibleCheckScore(o: CheckOutcome): number;
/** Argmax by `compareCheckOutcomes`, FIRST index wins ties (deterministic; with zero
 *  visible coverage every candidate ties at no-signal and index 0 is the blind pick). */
declare function selectBestIndex(outcomes: ReadonlyArray<CheckOutcome>): number;
/** The repair keep-best guard: a challenger displaces the incumbent only when it is
 *  strictly better in the selection order AND passes at least as many official checks.
 *  The raw-count clause is deliberate belt-and-braces over the comparator (a custom
 *  runner can report shifted totals): repair must NEVER replace a candidate that passes
 *  more official checks with one that passes fewer. */
declare function canDisplace(challenger: CheckOutcome, incumbent: CheckOutcome): boolean;
/** The candidate a shot produced, read from its conversation: the LAST `submit_answer`
 *  tool-call argument (verifier environments submit the artifact explicitly), else the
 *  latest assistant reply's fenced code block — preferring a block containing a `def`,
 *  because repair replies echo the failure report in a bare fence BEFORE the fixed code
 *  (the rigs' extractRepairCode lesson) — else the latest non-empty assistant text. */
declare function defaultExtractCandidate(messages: ReadonlyArray<Msg>): string;
type RepairStop = 'already-passing' | 'no-signal' | 'repaired-pass' | 'rounds-exhausted' | 'no-candidates';
/** The body's deliverable — a `StrategyResult` plus selection provenance. The extra
 *  fields ride through `defineStrategy`'s deliverable spread onto `AgenticRunResult`
 *  (score/resolved stay harness-verified, exactly as for every authored strategy). */
interface StructuralRolloutResult extends StrategyResult {
    /** One receipt per scored candidate (k samples, then repairs), `SelectionReceipt`
     *  shaped like the kernel's (`types.ts`), selector 'driver'. */
    selection: SelectionReceipt[];
    repairStop: RepairStop;
    officialChecks: number;
    authoredChecks: number;
}
interface StructuralRolloutConfig {
    /** Knobs; missing fields take the measured defaults (k=5, repairRounds=2, testgen=6). */
    policy?: Partial<StructuralRolloutPolicy>;
    /** Where the visible checks come from. Default: official checks from
     *  `task.meta.visibleChecks` composed with `modelAuthoredChecks()`. */
    checkSource?: CheckSource;
    /** How candidates are measured. Default `sandboxCheckRunner()` — it needs an exec
     *  channel (bind one to the runner, or pass `box` here) and fails loud without one. */
    checkRunner?: CheckRunner;
    /** Exec channel threaded into every check run of this strategy (a sandbox instance /
     *  `ValidationCtx.box`). The strategy seam itself carries no sandbox, so the caller
     *  who owns one supplies it here or binds it into the runner. */
    box?: CheckExecChannel;
    /** Candidate extraction from a shot's conversation. Default `defaultExtractCandidate`. */
    extractCandidate?: (messages: ReadonlyArray<Msg>) => string;
}
/**
 * Build the structuralRollout `Strategy`: k shots → score each by the frozen visible
 * checks (official above authored, crash lowest) → argmax with first-index tie-break →
 * up to `repairRounds` repair shots steered by the failure output, keep-best under the
 * official-check guard. Authored via `defineStrategy`, so the deliverable score stays
 * harness-verified and every shot is metered by the conserved pool.
 *
 * Budget note: `runAgentic`'s `budget` sizes the pool — pass at least
 * `k + repairRounds + 1` so the samples, repairs, and the check-author consult all admit.
 */
declare function structuralRollout(config?: StructuralRolloutConfig): Strategy;

export { type AgenticSurface as A, defaultStructuralRolloutPolicy as B, type CheckExecChannel as C, defineStrategy as D, depthStrategy as E, filterAuthoredAsserts as F, modelAuthoredChecks as G, officialChecksFromMeta as H, refine as I, resolveEntrySymbol as J, runAgentic as K, sample as L, sampleThenRefine as M, sandboxCheckRunner as N, selectBestIndex as O, structuralRollout as P, visibleCheckScore as Q, type RepairStop as R, type StructuralRolloutPolicy as S, type VisibleCheck as V, type AgenticTask as a, type AgenticOptions as b, type Strategy as c, type ArtifactHandle as d, type SurfaceScore as e, type AgenticTool as f, type AgenticRunResult as g, type CheckOutcome as h, type CheckRunContext as i, type CheckRunner as j, type CheckSource as k, type CheckSourceCtx as l, type CorpusReadbackOptions as m, type RunAgenticOptions as n, type ShotPersona as o, type ShotSpec as p, type StrategyCtx as q, type StrategyResult as r, type StructuralRolloutConfig as s, type StructuralRolloutResult as t, adaptiveRefine as u, breadthStrategy as v, canDisplace as w, compareCheckOutcomes as x, composeCheckSources as y, defaultExtractCandidate as z };
