import { m as KodaXMessage } from './types.d-B1uGoVTE.js';
import { a as AgentMessage, x as SpanData, w as Span, y as SpanError, A as Agent, q as RunnerLlmReturn, G as Guardrail, t as RunnerToolObserver } from './instance-discovery.d-BsKnIwpg.js';

/**
 * @kodax-ai/agent Constants
 *
 * 通用 Agent 常量配置
 */
declare const KODAX_MAX_TOKENS = 32768;
declare const KODAX_DEFAULT_TIMEOUT = 60;
declare const KODAX_HARD_TIMEOUT = 300;
declare const KODAX_MAX_RETRIES = 3;
declare const KODAX_RETRY_BASE_DELAY = 2;
declare const KODAX_MAX_INCOMPLETE_RETRIES = 2;
declare const KODAX_MAX_MAXTOKENS_RETRIES = 3;
declare const KODAX_STAGGER_DELAY = 1;
declare const KODAX_API_MIN_INTERVAL = 0.5;
declare const PROMISE_PATTERN: RegExp;

/**
 * @kodax-ai/agent Tokenizer
 *
 * Token 估算 - 使用 tiktoken 进行精确计算
 */

/**
 * 估算消息的 token 数量
 *
 * 精确计算包括：
 * - 消息结构开销（每条约 4 tokens）
 * - 角色标识
 * - 内容文本
 * - 工具调用和结果
 */
declare function estimateTokens(messages: KodaXMessage[]): number;
/**
 * 计算单个文本的 token 数量（便捷函数）
 */
declare function countTokens(text: string): number;

/**
 * Layer A Primitive: Session / SessionEntry / MessageEntry / SessionExtension
 *
 * FEATURE_081 (v0.7.23): Base Session shape. The thick
 * `KodaXSessionLineage` lives in `@kodax-ai/session-lineage` and is re-expressed
 * as a `LineageExtension` over this base.
 *
 * History: extracted to `@kodax-ai/core` in FEATURE_082 (v0.7.24); merged back
 * into `@kodax-ai/agent` in v0.7.35.1 FEATURE_142. `@kodax-ai/coding` retains a
 * barrel re-export for batteries-included consumers.
 *
 * Status: @experimental — API shape may be refined during v0.7.x.
 *
 * Design intent:
 *   - Base Session is a minimal, linearly-appendable log of typed entries.
 *   - Extensions (lineage, artifacts, labels, compaction) layer on top by
 *     claiming additional `entry.type` values and contributing operators /
 *     reducers that read the entry stream.
 *   - coding preset composes LineageExtension + CompactionExtension +
 *     ArtifactExtension to reproduce today's `KodaXSessionLineage` behavior.
 */

/**
 * A single immutable entry in a Session log. `type` is the dispatch key used
 * by extensions to claim ownership of an entry kind.
 */
interface SessionEntry {
    readonly id: string;
    readonly ts: number;
    readonly type: string;
    readonly payload: unknown;
}
/**
 * Canonical message entry type. All Layer A consumers can rely on
 * `type: 'message'` entries existing; extensions add more types.
 */
interface MessageEntry extends SessionEntry {
    readonly type: 'message';
    readonly payload: {
        readonly role: AgentMessage['role'];
        readonly content: AgentMessage['content'];
        readonly synthetic?: boolean;
    };
}
/**
 * Options for forking a session.
 *
 * v0.7.23 exposes only `name` (label for the new fork); structural options
 * (branch-at-entry, shallow copy, etc.) are reserved for later versions.
 */
interface SessionForkOptions {
    readonly name?: string;
}
/**
 * Minimal Session interface.
 *
 * Implementations must guarantee:
 *   - `append()` is atomic: either the entry is visible on next `entries()`
 *     iteration or it throws.
 *   - `entries()` yields entries in append order.
 *   - `metadata` is a readonly snapshot; mutations are made via extensions.
 *   - `fork()` returns a new Session with a snapshot of current entries; the
 *     two sessions diverge thereafter.
 */
interface Session {
    readonly id: string;
    append(entry: SessionEntry): Promise<void>;
    entries(): AsyncIterable<SessionEntry>;
    fork(opts?: SessionForkOptions): Promise<Session>;
    readonly metadata: ReadonlyMap<string, unknown>;
}
/**
 * Extension contract for teaching a Session new entry types + operators +
 * reducers.
 *
 *   - `entryTypes`: which `entry.type` values this extension owns. Two
 *     extensions composed into one Session must not claim overlapping types.
 *   - `operators`: high-level imperative verbs exposed to callers (e.g.
 *     `branch`, `rewind`, `attachArtifact`).
 *   - `reducers`: pure projections over the entry stream (e.g. "build lineage
 *     tree").
 *
 * The exact dispatch mechanics (`ExtendedSession<T>` typing, operator
 * registration) land with the coding preset integration; v0.7.23 pins the
 * shape only.
 */
interface SessionExtension {
    readonly name: string;
    readonly entryTypes: readonly string[];
    readonly operators?: Readonly<Record<string, (session: Session, ...args: readonly unknown[]) => Promise<unknown>>>;
    readonly reducers?: Readonly<Record<string, (entries: readonly SessionEntry[]) => unknown>>;
}
/**
 * Options for `createInMemorySession`.
 */
interface InMemorySessionOptions {
    readonly id?: string;
    readonly metadata?: ReadonlyMap<string, unknown>;
    readonly initialEntries?: readonly SessionEntry[];
}
/**
 * In-memory Session suitable for tests, examples, and embedded SDK use. Not
 * durable across process restarts — persistence is provided by coding-specific
 * adapters in `@kodax-ai/session-lineage` and `@kodax-ai/agent`.
 */
declare function createInMemorySession(opts?: InMemorySessionOptions): Session;

/**
 * Layer A Primitive: CompactionPolicy + DefaultSummaryCompaction
 *
 * FEATURE_081 (v0.7.23): Pluggable compaction for generic agent loops.
 *
 * Two layers:
 *   - Layer A (here): `CompactionPolicy` interface + `DefaultSummaryCompaction`
 *     — a minimal "token threshold → LLM summary of old messages" policy that
 *     any external Agent can pick up with zero KodaX runtime dependency.
 *   - Layer B (`@kodax-ai/session-lineage/src/lineage.ts`): `LineageCompaction`
 *     wraps the full FEATURE_072 lineage-native compaction for the coding
 *     preset.
 *
 * The `compaction` entry shape written by `DefaultSummaryCompaction` is the
 * same type used by `LineageExtension`, so the two layers interoperate on
 * the same Session log.
 *
 * History: extracted to `@kodax-ai/core` in FEATURE_082 (v0.7.24); merged back
 * into `@kodax-ai/agent` in v0.7.35.1 FEATURE_142.
 */

/**
 * Runtime context for a compaction pass. Abstracts the LLM/tokenizer
 * dependencies so policies stay independent of any specific provider.
 */
interface CompactionContext {
    readonly tokensUsed: number;
    readonly budget: number;
    /**
     * Summarizer implementation. Callers inject a function that maps a list of
     * messages to a short summary string. In coding-preset mode this is wired
     * to `runKodaX` internally; for external consumers it can call any LLM.
     */
    readonly summarize: (messages: readonly AgentMessage[]) => Promise<string>;
}
/**
 * Payload written to the `compaction` entry appended by `compact()`.
 */
interface CompactionEntryPayload {
    readonly summary: string;
    readonly replacedMessageEntryIds: readonly string[];
}
/**
 * Typed compaction entry. `type` is `'compaction'`; extensions (LineageExtension)
 * may claim this same type.
 */
interface CompactionEntry extends SessionEntry {
    readonly type: 'compaction';
    readonly payload: CompactionEntryPayload;
}
/**
 * Outcome of a single CompactionPolicy.compact() pass. Renamed from
 * `CompactionResult` to `PolicyCompactionResult` in v0.7.35.1 FEATURE_142
 * because the Layer A primitive collided with @kodax-ai/agent's pre-existing
 * `CompactionResult` (compaction/types.ts) used by the coding orchestration
 * post-compact pipeline. The two types model different things:
 *   - `PolicyCompactionResult` (here): "summary + replaced entry ids", the
 *     payload of one CompactionPolicy step.
 *   - `CompactionResult` (compaction/types.ts): the rich result of the
 *     coding-side multi-pass compaction (artifactLedger / memorySeed /
 *     tokensBefore / tokensAfter / etc).
 */
interface PolicyCompactionResult {
    readonly summary: string;
    readonly replacedMessageEntryIds: readonly string[];
}
/**
 * Pluggable compaction policy. Any multi-turn Agent loop can check
 * `shouldCompact()` at round boundaries and call `compact()` when it returns
 * true.
 */
interface CompactionPolicy {
    readonly name: string;
    shouldCompact(session: Session, tokensUsed: number, budget: number): boolean;
    compact(session: Session, ctx: CompactionContext): Promise<PolicyCompactionResult>;
    /** Optional: rehydrate compacted content when a restore hint is available. */
    restore?(session: Session, hint: unknown): Promise<void>;
}
/**
 * Configuration for `DefaultSummaryCompaction`.
 */
interface DefaultSummaryCompactionOptions {
    /**
     * Fraction of `budget` at which compaction triggers. Default 0.8 (i.e.
     * 80% of the token budget). Must be in (0, 1].
     */
    readonly thresholdRatio?: number;
    /**
     * Number of most-recent message entries to preserve verbatim. Default 10.
     * Must be non-negative.
     */
    readonly keepRecent?: number;
    /**
     * Optional clock override (ms epoch). Useful for deterministic tests.
     */
    readonly now?: () => number;
    /**
     * Optional random-string override. Useful for deterministic tests.
     */
    readonly randomSuffix?: () => string;
}
/**
 * Minimal "token threshold + LLM summary" compaction policy. Works on any
 * Session that stores `message` entries.
 *
 * Behavior:
 *   - `shouldCompact` returns true when `tokensUsed >= budget *
 *     thresholdRatio`.
 *   - `compact` reads all `message` entries, keeps the last `keepRecent`
 *     untouched, summarizes the rest via `ctx.summarize`, and appends a
 *     single `compaction` entry to the session.
 *
 * Caller is responsible for invoking `shouldCompact` and for interpreting the
 * appended entry when building the next turn's prompt.
 */
declare class DefaultSummaryCompaction implements CompactionPolicy {
    readonly name = "default-summary";
    private readonly thresholdRatio;
    private readonly keepRecent;
    private readonly now;
    private readonly randomSuffix;
    constructor(opts?: DefaultSummaryCompactionOptions);
    shouldCompact(_session: Session, tokensUsed: number, budget: number): boolean;
    compact(session: Session, ctx: CompactionContext): Promise<PolicyCompactionResult>;
}

/**
 * Trace — the root container for a single user-visible workflow.
 *
 * FEATURE_083 (v0.7.24): a Trace wraps a root span and all its descendants.
 * The Runner.run(agent, ...) entry creates a trace per run by default;
 * consumers can nest runs under an existing trace via `Runner.run(agent, input, { trace })`.
 */

interface Trace {
    readonly id: string;
    readonly startedAt: number;
    readonly rootSpan: Span;
    readonly metadata: ReadonlyMap<string, unknown>;
    end(): void;
    readonly endedAt?: number;
    readonly error?: SpanError;
}
interface TraceOptions {
    readonly id?: string;
    readonly name?: string;
    readonly rootSpanData?: SpanData;
    readonly metadata?: ReadonlyMap<string, unknown>;
    readonly now?: () => number;
    readonly nextSpanId?: () => string;
    readonly nextTraceId?: () => string;
    readonly onSpanStart?: (span: Span) => void;
    readonly onSpanEnd?: (span: Span) => void;
    readonly onTraceEnd?: (trace: Trace) => void;
}

/**
 * Tracer — convenience façade that creates Traces wired to the registered
 * processors and default id generators.
 *
 * FEATURE_083 (v0.7.24): callers typically use the default tracer:
 *
 *     const trace = defaultTracer.startTrace({ name: 'coding-run' });
 *     const child = trace.rootSpan.addChild('generation', { kind: 'generation', ... });
 *     // ... do work ...
 *     child.end();
 *     trace.end();
 *
 * Advanced callers can inject a custom clock / id generator for
 * deterministic tests.
 */

interface StartTraceOptions {
    readonly id?: string;
    readonly name?: string;
    readonly rootSpanData?: TraceOptions['rootSpanData'];
    readonly metadata?: ReadonlyMap<string, unknown>;
}
interface TracerOptions {
    readonly now?: () => number;
    readonly nextSpanId?: () => string;
    readonly nextTraceId?: () => string;
}
declare class Tracer {
    private readonly options;
    constructor(options?: TracerOptions);
    startTrace(opts?: StartTraceOptions): Trace;
}

/**
 * Layer A Primitive: Quality Invariant + Admission Contract types.
 *
 * FEATURE_101 (v0.7.31) — types-only module. Runner.admit() runtime lives
 * in `./runner.ts`; the seven (+1 external) invariant implementations live
 * in `@kodax-ai/coding/src/agent-runtime/invariants/`.
 *
 * Why types-only here: the admission contract is a Layer A primitive that
 * @kodax-ai/coding consumes — putting it in @kodax-ai/core keeps SDK consumers
 * from pulling in coding-specific imports just to reference admission
 * types. The actual invariant implementations need access to mutation
 * trackers, budget controllers, and ToolGuardrail capability tiers — all
 * of which live in @kodax-ai/coding — so they belong there.
 *
 * Status: @experimental. v0.7.31 ships these types alongside the FEATURE_089
 * agent-generation consumer; once dispatch eval baseline (FEATURE_101
 * Phase 3) stabilizes the schema we promote to ADR-021.
 *
 * See:
 *   - docs/features/v0.7.31.md#feature_101-constructed-agent-admission-contract
 *   - docs/features/v0.7.31.md#feature_106-ama-harness-selection-calibration
 *     (FEATURE_106 registers the 8th invariant 'harnessSelectionTiming' —
 *      external to admission v1 closed set but uses the same runtime)
 */

/**
 * Untrusted Agent declaration submitted by an LLM-driven generator
 * (FEATURE_089) or any other consumer that wants the manifest verified
 * by the admission contract before activation.
 *
 * Structurally `Agent` plus three manifest-only optional fields the LLM
 * may declare to express intent (per FEATURE_101 §Manifest schema):
 *
 *   - `requestedToolCapabilities`: "I plan to use bash:test, not bash:network"
 *      Admission intersects with the resolved capability set from `tools`.
 *   - `maxBudget`: "Cap my total turn budget at N" — admission clamps to
 *      `system_cap.maxBudget`; runtime further clamps to parent.remaining.
 *   - `declaredInvariants`: extra invariants the LLM voluntarily binds.
 *      The required set (resolved from role / toolScope / harnessTier) is
 *      ALWAYS a floor — declaredInvariants can only ADD.
 *
 * `Runner.admit(manifest)` reads as "this manifest has not been admitted
 * yet" while `Runner.run(agent, ...)` reads as "this Agent is trusted
 * to execute".
 */
type AgentManifest = Agent & {
    readonly requestedToolCapabilities?: readonly ToolPermission[];
    readonly maxBudget?: number;
    /**
     * Tool-loop iteration ceiling the manifest commits to. Admission
     * clamps to `system_cap.maxIterations` via `clampMaxIterations` patch;
     * Runner.run reads the post-clamp value through `getAdmittedAgentBindings`
     * and takes min-wins against `RunOptions.maxToolLoopIterations`. Symmetric
     * with `maxBudget` — both are activation caps, both flow through the
     * patch reducer, both consulted at runtime via the WeakMap binding.
     */
    readonly maxIterations?: number;
    readonly declaredInvariants?: readonly InvariantId[];
};
/**
 * Coarse-grained capability classes that group concrete tools by their
 * observable side effects. Replaces the v0.7.30 `ToolName[]` allow-list
 * with semantic categories so admission can reason about "this manifest
 * wants bash:network capability" without enumerating every concrete tool.
 *
 * Aligned with FEATURE_092 (Auto Mode Classifier, v0.7.33) and FEATURE_094
 * (anti-escape, v0.7.36) which both classify tools along these axes.
 */
type ToolCapability = 'read' | 'edit' | 'bash:test' | 'bash:read-only' | 'bash:mutating' | 'bash:network' | 'subagent';
/**
 * Per-tool capability declaration. Used in `AgentManifest.requestedToolCapabilities`
 * (an optional field manifests can declare to express intent — admission
 * intersects with the resolved capability set).
 */
interface ToolPermission {
    readonly tool: string;
    readonly capabilities: readonly ToolCapability[];
}
/**
 * Quality invariant identifier.
 *
 * **Admission contract v1 closed set (7 ids)** — FEATURE_101 itself enforces
 * exactly these on every untrusted manifest:
 *
 *   - 'finalOwner'           Manifest must designate a final owner role
 *   - 'handoffLegality'      Handoff graph (manifest + activated agents) is acyclic
 *   - 'budgetCeiling'        manifest.maxBudget ≤ system_cap; runtime clamp to parent
 *   - 'toolPermission'       Resolved capabilities ⊆ system_cap; runtime clamp to parent
 *   - 'evidenceTrail'        Mutations must leave evidence; terminal verifies completeness
 *   - 'boundedRevise'        maxIterations ≤ system; runtime tracks revise count
 *   - 'independentReview'    Verifier role bound; verifier can't read generator reasoning
 *
 * **External consumers (open-ended) — registered to invariant runtime but
 * NOT in admission v1 closed set**:
 *
 *   - 'harnessSelectionTiming'   FEATURE_106 (v0.7.31) — multi-file mutations
 *                                 must be preceded by an emitted harness verdict
 *
 * The runtime is open: future features may register additional invariants.
 * The closed-set guarantee (7) applies to admission v1 only — see
 * docs/features/v0.7.31.md FEATURE_101 §第一版 Invariant 清单 注脚.
 */
type InvariantId = 'finalOwner' | 'handoffLegality' | 'budgetCeiling' | 'toolPermission' | 'evidenceTrail' | 'boundedRevise' | 'independentReview' | 'harnessSelectionTiming' | 'planBeforeMutate';
/**
 * Patch the admission layer applies when an invariant returns severity='clamp'.
 * Pure data — Runner applies it via a single deterministic reducer (see
 * `applyManifestPatch` in `./admission-patch.ts`).
 *
 * Empty / undefined fields mean "no change". Multiple patches compose by
 * union (removeTools concatenates, clamp* picks min, addInvariants unions).
 */
interface ManifestPatch {
    readonly removeTools?: readonly string[];
    readonly clampMaxBudget?: number;
    readonly clampMaxIterations?: number;
    readonly addInvariants?: readonly InvariantId[];
    readonly notes?: readonly string[];
}
/**
 * Three-severity result returned by every invariant hook (admit / observe /
 * assertTerminal):
 *
 *   - `ok: true`              No violation. Runner continues.
 *   - `severity: 'reject'`    Hard violation. Admission fails (admit-time)
 *                             or runtime escalates (observe/terminal-time).
 *   - `severity: 'clamp'`     Manifest is over-broad. Admission applies the
 *                             attached `patch` and admits with a warning.
 *                             clamp severity ONLY makes sense at admit-time;
 *                             observe/terminal hooks should use 'warn' or
 *                             'reject'.
 *   - `severity: 'warn'`      Log-only signal. Runner records to trace +
 *                             dispatch-eval metric, no action taken.
 *
 * The discriminated union pattern lets TypeScript narrow `patch` to only
 * be present on clamp results — callers can't forget to check.
 */
type InvariantResult = {
    readonly ok: true;
} | {
    readonly ok: false;
    readonly severity: 'reject';
    readonly reason: string;
} | {
    readonly ok: false;
    readonly severity: 'clamp';
    readonly reason: string;
    readonly patch: ManifestPatch;
} | {
    readonly ok: false;
    readonly severity: 'warn';
    readonly reason: string;
};
/**
 * System-wide caps the admission layer enforces against. The Runner
 * resolves these from configuration once at startup (or per-call when
 * the SDK consumer overrides via Runner.admit options).
 *
 * `maxBudget` / `maxIterations` are activation caps — runtime clamps to
 * parent.remaining via the budget controller (separate concern).
 * `allowedToolCapabilities` is the union of capabilities the system
 * permits ANY constructed agent to request (intersected with
 * manifest.requestedToolCapabilities at admission time).
 */
interface SystemCap {
    readonly maxBudget: number;
    readonly maxIterations: number;
    readonly allowedToolCapabilities: readonly ToolCapability[];
}
/**
 * Context passed to invariant.admit() hooks at admission time.
 *
 * `activatedAgents` is the global set of already-admitted constructed
 * agents — used by `handoffLegality` for transitive cycle detection
 * (handoffs reference these by name).
 *
 * `stagedAgents` is the set of manifests that have been staged in the
 * current generation batch but are not yet activated. FEATURE_101
 * v0.7.31.1 patch: `handoffLegality` consults both maps so a same-batch
 * cycle (A→B + B→A staged together, neither yet activated) is rejected
 * at admission time instead of slipping through. The map is
 * intentionally separate from `activatedAgents` so invariants that
 * only care about already-running agents (future work) can still
 * distinguish.
 *
 * Frozen at admission entry; invariants must not mutate.
 */
interface AdmissionCtx {
    readonly manifest: AgentManifest;
    readonly activatedAgents: ReadonlyMap<string, Agent>;
    readonly stagedAgents: ReadonlyMap<string, Agent>;
    readonly systemCap: SystemCap;
}
/**
 * Runtime event fed to invariant.observe() during agent execution.
 * Discriminated by `kind` so each invariant only narrows on what it
 * cares about (e.g. `harnessSelectionTiming` only inspects
 * `mutation_recorded` events).
 */
type RunnerEvent = {
    readonly kind: 'tool_call';
    readonly toolName: string;
    readonly capability?: ToolCapability;
} | {
    readonly kind: 'mutation_recorded';
    readonly file: string;
    readonly fileCount: number;
} | {
    readonly kind: 'handoff_taken';
    readonly target: string;
} | {
    readonly kind: 'revise_count';
    readonly harness: string;
    readonly count: number;
} | {
    readonly kind: 'evidence_added';
    readonly artifactPath: string;
};
/**
 * Read-only view of the per-run mutation tracker. Invariant observe hooks
 * may inspect but never mutate. (The full @kodax-ai/coding mutation tracker
 * has additional fields like per-file line deltas — those are the coding
 * package's concern, not the Layer A primitive.)
 */
interface ReadonlyMutationTracker {
    readonly files: ReadonlySet<string>;
    readonly totalOps: number;
}
/**
 * Recorder slice exposed to observe hooks for cross-event correlation.
 * Kept minimal — invariants that need richer state should manage their
 * own per-instance counters and use the recorder only for shared
 * "did Scout commit a harness verdict yet?" signal.
 */
interface ReadonlyRecorder {
    readonly scout?: {
        readonly payload?: {
            readonly scout?: {
                readonly confirmedHarness?: string;
            };
        };
    };
}
interface ObserveCtx {
    readonly manifest: AgentManifest;
    readonly mutationTracker: ReadonlyMutationTracker;
    readonly recorder: ReadonlyRecorder;
}
/**
 * Terminal-time deliverable inspected by invariant.assertTerminal hooks.
 *
 * `verdict` is set when an Evaluator role emitted a verdict; undefined
 * for H0 runs that bypass evaluation. `evidenceArtifacts` enumerates the
 * artifact files produced during the run (per-mutation evidence,
 * verification reports, etc.).
 */
interface Deliverable {
    readonly evidenceArtifacts: readonly string[];
    readonly verdict?: 'accept' | 'revise' | 'blocked';
    readonly mutationCount: number;
}
interface TerminalCtx {
    readonly manifest: AgentManifest;
    readonly deliverable: Deliverable;
}
/**
 * Quality Invariant declaration. An invariant declares which of the three
 * hook points it implements (admit / observe / assertTerminal) — at least
 * one of the three must be present.
 *
 * Invariants are registered to the runtime via `registerInvariant()` (in
 * `./admission.ts` once Runner.admit lands). The runtime maintains a
 * static registry indexed by `InvariantId`; `Runner.admit` resolves the
 * required set per (role, toolScope, harnessTier) tuple and applies all
 * relevant admit hooks.
 *
 * Invariants must be pure functions of their inputs. Side effects
 * (writing trace, sending events) happen in the Runner shell, not inside
 * the invariant body.
 */
interface QualityInvariant {
    readonly id: InvariantId;
    readonly description: string;
    admit?(manifest: AgentManifest, ctx: AdmissionCtx): InvariantResult;
    observe?(event: RunnerEvent, ctx: ObserveCtx): InvariantResult;
    assertTerminal?(deliverable: Deliverable, ctx: TerminalCtx): InvariantResult;
}
/**
 * Opaque handle produced by `Runner.admit()` on success. Required input
 * to `ConstructionRuntime.activate()` — prevents activate from being
 * called on a manifest that hasn't gone through admission.
 *
 * `appliedPatches` records every clamp the admission applied; consumers
 * can inspect to surface "what was modified vs the manifest you submitted".
 * `invariantBindings` lists the invariants registered against this
 * admitted agent (effective set = required ∪ declared).
 */
interface AdmittedHandle {
    readonly manifest: AgentManifest;
    readonly admittedAt: string;
    readonly appliedPatches: readonly ManifestPatch[];
    readonly invariantBindings: readonly InvariantId[];
}
/**
 * Admission verdict — discriminated union so TypeScript can narrow
 * `handle` (only present on success) vs `reason` (only on failure).
 *
 * `retryable` on failure indicates whether the generator should be asked
 * to fix and retry (schema invalid / DAG cycle) vs hard reject (system
 * cap violated past clamp tolerance).
 */
type AdmissionVerdict = {
    readonly ok: true;
    readonly handle: AdmittedHandle;
    readonly clampNotes: readonly string[];
} | {
    readonly ok: false;
    readonly reason: string;
    readonly retryable: boolean;
};

/**
 * FEATURE_101 admission audit — the 5-step process `Runner.admit` runs
 * against an untrusted manifest.
 *
 * Pure orchestration of the building blocks declared elsewhere in
 * @kodax-ai/core:
 *
 *   1. **Schema validation** — manifest has well-formed name, instructions,
 *      tools, declaredInvariants, requestedToolCapabilities. Fail-fast on
 *      shape errors (no clamps).
 *   2. **Resolve effective invariants** — required (system policy) ∪
 *      declared (manifest voluntary). Required is computed from
 *      role / toolScope / harnessTier; declared can only ADD.
 *   3. **Run admit hooks** — for each effective invariant that has an
 *      admit hook registered, call it with the (manifest, ctx) tuple.
 *      Collect reject / clamp / warn results.
 *   4. **Compose patches** — clamp-severity results carry patches; we
 *      compose them with `composePatches` (min-wins for clamps, union
 *      for collections).
 *   5. **Apply patches** — `applyManifestPatch` produces the final
 *      admitted manifest. Reject results short-circuit before this step.
 *
 * Returns an `AdmissionVerdict` discriminated union — `ok: true` carries
 * the `AdmittedHandle` plus `clampNotes`; `ok: false` carries `reason`
 * and the `retryable` flag.
 *
 * Pure function (no I/O, no logging). The Runner shell is responsible
 * for tracing / observability around this call.
 */

/**
 * Default system cap — high ceilings so admission only clamps when
 * deployments have explicitly declared tighter limits. The numbers
 * mirror the legacy `runManagedTask` budget defaults so this is a
 * compatibility-preserving baseline, not a policy tightening.
 */
declare const DEFAULT_SYSTEM_CAP: SystemCap;
/**
 * Options accepted by `runAdmissionAudit` (and surfaced by `Runner.admit`).
 * All fields are optional — the audit substitutes safe defaults so the
 * SDK call surface stays a single positional argument: the manifest.
 */
interface AdmissionAuditOptions {
    readonly systemCap?: SystemCap;
    readonly activatedAgents?: ReadonlyMap<string, Agent>;
    /**
     * FEATURE_101 v0.7.31.1 — same-batch staged agents. Manifests that
     * have been staged but not yet activated still need to participate
     * in `handoffLegality` cycle detection: a generator that writes A
     * (handoff to B) and B (handoff to A) in the same batch sees neither
     * activated when admission runs on each individually. With
     * `stagedAgents` populated, the second admission detects the back
     * edge to the first and rejects.
     *
     * Sourced from `ConstructionRuntime` which builds a Map of
     * staged-status manifests at the call site.
     */
    readonly stagedAgents?: ReadonlyMap<string, Agent>;
    /**
     * Agent role identifier — opaque string from the agent layer's perspective.
     * Concrete agent presets (e.g. coding's AMA harness with 'scout' / 'planner' /
     * 'generator' / 'evaluator' / 'direct') brand this themselves; the admission
     * framework only plumbs it through to `resolveRequiredInvariants`.
     * v0.7.35.1 FEATURE_142: widened from coding-AMA literal union per ADR-021
     * (agent layer must not enumerate coding-specific role names).
     */
    readonly role?: string;
    readonly toolScope?: readonly string[];
    /**
     * Harness tier identifier — opaque string. Concrete agent presets brand it
     * (e.g. coding's 'H0_DIRECT' / 'H1_EXECUTE_EVAL' / 'H2_PLAN_EXECUTE_EVAL').
     * v0.7.35.1 FEATURE_142: widened from coding-AMA literal union per ADR-021.
     */
    readonly harnessTier?: string;
    /**
     * ISO timestamp recorded on the AdmittedHandle. Defaults to
     * `new Date().toISOString()` — overridable so tests can pin a value.
     */
    readonly nowIso?: string;
}
/**
 * Scan an instructions string for known prompt-injection patterns.
 * Returns the first matching pattern id or undefined when clean.
 */
declare function detectInstructionsInjection(text: string): string | undefined;
/**
 * Run the admission audit against an untrusted manifest. Returns an
 * `AdmissionVerdict` — never throws (errors are encoded in the verdict).
 *
 * Pure function: same inputs always return equivalent outputs (modulo
 * the `nowIso` timestamp, which can be pinned via options).
 */
declare function runAdmissionAudit(manifest: AgentManifest, options?: AdmissionAuditOptions): AdmissionVerdict;

/**
 * FEATURE_101 (v0.7.31.1) — admission session: runtime dispatch of
 * `observe` and `assertTerminal` invariant hooks.
 *
 * The v0.7.31 release shipped only the `admit` hook wired into
 * `Runner.admit`. The three-segment hook model (admit / observe /
 * assertTerminal) declared in FEATURE_101 §三段 hook 模型 had its
 * other two thirds defined as types but never invoked at runtime —
 * meaning every invariant that depended on observe / terminal
 * (`evidenceTrail`, `independentReview`, `boundedRevise`,
 * `harnessSelectionTiming`) was effectively dormant after admission.
 *
 * This module fills that gap with two pieces:
 *
 *   1. A WeakMap-backed binding registry (`setAdmittedAgentBindings` /
 *      `getAdmittedAgentBindings`) so `Runner.run` can recover the
 *      InvariantId set associated with an admitted agent without a
 *      compile-time dependency from `agent.ts` onto `admission.ts`
 *      (which would re-introduce the import cycle the original split
 *      avoided).
 *   2. `InvariantSession`: a per-run event router. The Runner creates
 *      one when an agent has bindings, and threads `record*` calls
 *      through it during the run. The session dispatches observe to
 *      bound invariants and accumulates violations; assertTerminal
 *      runs once at end.
 *
 * Pure runtime — no I/O. The session does not log or trace; the Runner
 * shell decides what to do with returned violation results
 * (typically: trace span for `warn`, throw for `reject`, accumulate
 * patches for `clamp` though clamp is admit-time only).
 */

/**
 * Associate an admitted manifest's invariant bindings with the runtime
 * Agent the consumer uses. Set by `ConstructionRuntime.activate` after
 * `Runner.admit` succeeds; SDK consumers calling `Runner.run` directly
 * on hand-authored Agents leave this unset and skip runtime invariant
 * dispatch entirely.
 */
declare function setAdmittedAgentBindings(agent: Agent, manifest: AgentManifest, bindings: readonly InvariantId[]): void;
/**
 * Look up bindings for an agent. Returns undefined when the agent was
 * never admitted (trusted SDK / preset path).
 */
declare function getAdmittedAgentBindings(agent: Agent): {
    readonly bindings: readonly InvariantId[];
    readonly manifest: AgentManifest;
} | undefined;
/**
 * Test-only — clears the registry. Production code should never call
 * this; the WeakMap entries are reclaimed naturally when agents fall
 * out of scope.
 */
declare function _resetAdmittedAgentBindings(agent: Agent): void;
/**
 * Severity surface returned by `recordX` calls. A `reject` from
 * observe means the run must abort; the Runner shell raises an error.
 * A `warn` is informational — the Runner records it but continues.
 * `ok` is the no-op success case.
 */
interface SessionDispatchResult {
    readonly results: readonly {
        readonly id: InvariantId;
        readonly result: InvariantResult;
    }[];
}
/**
 * Per-run state machine + event router. Constructed once at the start
 * of a run (inside `Runner.run`) when the start agent has bindings.
 * The Runner threads tool / handoff / mutation events through the
 * `record*` API; the session fans them out to bound invariants.
 *
 * Threading rules (so the data stays valid):
 *   - `recordX` calls return synchronously; observe hooks are pure
 *     functions of the immutable event payload + read-only context.
 *   - `assertTerminal` must be called exactly once at run end. The
 *     Runner is responsible for honoring this.
 *   - The session is single-run; spawning a sub-run (handoff /
 *     dispatch_child_task) creates a fresh session for the target.
 *
 * The session is never exposed across module boundaries — it lives in
 * the Runner closure and dies when the run ends. WeakMap is overkill
 * for state that is by-construction scoped; plain fields suffice.
 */
declare class InvariantSession {
    private readonly bindings;
    private readonly manifest;
    private readonly mutations;
    private readonly recorder;
    private verdict;
    private readonly evidenceArtifacts;
    private readonly violations;
    private terminalRan;
    constructor(bindings: readonly InvariantId[], manifest: AgentManifest);
    recordToolCall(toolName: string, capability?: ToolCapability): SessionDispatchResult;
    recordHandoff(target: string): SessionDispatchResult;
    /**
     * Record a file mutation. `fileCount` is the cumulative distinct-file
     * total (mirrors `harnessSelectionTiming` ObserveCtx contract). The
     * session computes it from its internal MutableMutationTracker so
     * callers don't need to track it.
     */
    recordMutation(file: string): SessionDispatchResult;
    recordEvidence(artifactPath: string): SessionDispatchResult;
    recordRevise(harness: string, count: number): SessionDispatchResult;
    /**
     * Record the Scout's confirmed-harness signal — drives
     * `harnessSelectionTiming.observe`'s "did Scout commit a harness
     * verdict yet?" check. Coding-side surface invokes this after the
     * scout role emits its verdict.
     */
    setConfirmedHarness(harness: string): void;
    setVerdict(verdict: 'accept' | 'revise' | 'blocked'): void;
    /** @internal Test inspection + Runner trace surface. */
    getViolations(): readonly {
        readonly id: InvariantId;
        readonly result: InvariantResult;
    }[];
    getMutationCount(): number;
    getEvidenceArtifacts(): readonly string[];
    /**
     * Run all bound invariants' `assertTerminal` hooks. Caller must
     * invoke exactly once; subsequent calls are no-ops (returns the
     * accumulated violations from the first call). Returns the
     * union of violations gathered during observe + this terminal pass.
     */
    assertTerminal(): SessionDispatchResult;
    private dispatchObserve;
}
/**
 * Construct a session for an agent if it has admission bindings, or
 * return undefined for trusted (un-admitted) agents — the Runner
 * checks the return value and skips invariant dispatch entirely when
 * undefined, keeping the trusted-path zero-overhead.
 */
declare function createInvariantSessionForAgent(agent: Agent): InvariantSession | undefined;

/**
 * Layer A Primitive: Runner
 *
 * FEATURE_080 (v0.7.23): minimal execution entry for an `Agent`.
 *
 * Two dispatch paths:
 *   1. **Preset dispatch** (the "default coding agent" registers via
 *      `registerPresetDispatcher`): delegates to the existing `runKodaX`
 *      implementation so SA users see zero behavior change. This is the
 *      "Option Y" dog-food wiring negotiated during FEATURE_080+081 design.
 *   2. **Generic dispatch**: for user-defined agents. Performs a single
 *      system+user → assistant turn using an injected LLM callback. No tool
 *      loop, no extensions, no managed-task harness — those arrive with
 *      FEATURE_084 (v0.7.26).
 *
 * Status: @experimental. History: extracted to `@kodax-ai/core` in FEATURE_082
 * (v0.7.24); merged back into `@kodax-ai/agent` in v0.7.35.1 FEATURE_142.
 * `@kodax-ai/coding` retains a barrel re-export for batteries-included consumers.
 */

/**
 * Options accepted by `Runner.run` and `Runner.runStream`.
 */
interface RunOptions {
    /**
     * Opaque payload forwarded to the preset dispatcher when one matches.
     * For the built-in coding preset this carries `KodaXOptions`.
     */
    readonly presetOptions?: unknown;
    /**
     * LLM callback used by the generic dispatch path. Receives the assembled
     * message transcript and the current Agent.
     *
     * Return a plain `string` to preserve the v0.7.23 single-turn behaviour
     * (no tool loop). Return a `RunnerLlmResult` with `toolCalls` to opt into
     * the FEATURE_084 tool loop — the Runner will execute each call against
     * the agent's `RunnableTool`s, append tool_use + tool_result blocks to
     * the transcript, and invoke this callback again until no tool calls are
     * returned (or `MAX_TOOL_LOOP_ITERATIONS` is reached).
     */
    readonly llm?: (messages: readonly AgentMessage[], agent: Agent) => Promise<RunnerLlmReturn>;
    /**
     * Optional Session to persist the generic-path transcript into. When
     * supplied, each generated message is appended as a `message` entry.
     */
    readonly session?: Session;
    /**
     * Abort signal forwarded to preset dispatchers that honor it.
     */
    readonly abortSignal?: AbortSignal;
    /**
     * FEATURE_083 (v0.7.24): tracer used to record AgentSpan / GenerationSpan /
     * ToolCallSpan / HandoffSpan for this run. Defaults to `defaultTracer` when
     * omitted. Pass `null` to disable tracing for this call.
     */
    readonly tracer?: Tracer | null;
    /**
     * When supplied, the run attaches its AgentSpan as a child of this trace's
     * root span instead of starting a new trace. Useful when an outer Agent
     * is orchestrating sub-runs and wants one trace per user request.
     */
    readonly trace?: Trace;
    /**
     * FEATURE_085 (v0.7.26): run-scoped guardrails. Merged with
     * `agent.guardrails` — declaration order is agent-first, then opts.
     * Input / output / tool-before / tool-after hooks all dispatch from
     * this union. See `@kodax-ai/agent/primitives/guardrail.ts` for shape.
     */
    readonly guardrails?: readonly Guardrail[];
    /**
     * Per-run override for the tool-loop iteration cap. When omitted, the
     * loop uses `MAX_TOOL_LOOP_ITERATIONS` (20) — a safe ceiling for
     * stand-alone agent runs. Managed-task orchestration (multi-role
     * handoff chain: Scout → Planner → Generator → Evaluator) needs a much
     * higher cap because the iteration counter is shared across every
     * role in the chain. Legacy `runManagedTask` gave each role its own
     * `DEFAULT_MANAGED_WORK_BUDGET` (200) — the Runner-driven path passes
     * that value here so long investigations don't trip the safety valve
     * after ~20 tool calls.
     */
    readonly maxToolLoopIterations?: number;
    /**
     * v0.7.26 parity: observer callbacks fired around every tool
     * invocation. Legacy `runManagedTask` emitted `events.onToolResult`
     * at three sites per invocation so the REPL worker ledger could
     * render live tool-call progress — without this plumbing, the
     * Runner-driven path's UI shows only the final output. Preset
     * dispatchers can attach this observer to surface `onToolCall` /
     * `onToolResult` through the usual `KodaXEvents` bus.
     */
    readonly toolObserver?: RunnerToolObserver;
    /**
     * Compaction hook. Fires at the TOP of every tool-loop iteration,
     * BEFORE the LLM call. Return the replacement transcript to trigger
     * compaction; return the same array (or undefined) to skip. The Runner
     * owns the transcript mutably, so this is the only point consumers can
     * insert a compacted view before the next provider.stream invocation.
     *
     * **Trigger frequency**: every iteration of every Runner.run() call.
     * - Iteration 0 fires BEFORE the first LLM call (covers idle-yield
     *   resume / new user activation where the transcript already exceeds
     *   threshold from accumulated prior turns).
     * - Iteration N (N≥1) fires after the previous iteration's tool_result
     *   was appended, same "before next LLM call" timing as the legacy
     *   post-tool-result firing point.
     * - Text-only iterations are covered: the next Runner.run() invocation
     *   (when the user/parent re-engages) runs iter 0 → hook fires before
     *   the new LLM call.
     *
     * **Why not after tool_result append (legacy v0.7.26 location)**: that
     * boundary skipped text-only termination — Runner exits at line ~611
     * without firing the hook, so idle-yield + text-only end-of-turn
     * sessions grew unbounded between checks. claudecode (`query.ts:307-454`),
     * pi-mono (`agent-session.ts:949`), opencode (`processor.ts:609-613`),
     * and KodaX SA (`run-substrate.ts:621-627`) all check at the per-LLM-
     * call boundary. FEATURE_179 (v0.7.42) brought the AMA Runner path
     * into line — the failure scenario was a Worker session that grew
     * 165K → 180K through text-only end-of-turn + idle-yield, then
     * triggered at 181K (61K over the 120K threshold) only after the next
     * tool call landed.
     */
    readonly compactionHook?: (transcript: readonly AgentMessage[]) => Promise<readonly AgentMessage[] | undefined>;
    /**
     * FEATURE_101 (v0.7.31.1): callback fired once when the Runner has
     * resolved invariant bindings on the start agent and created an
     * `InvariantSession` for the run. Coding-side consumers (mutation
     * tracker, verdict recorder, evidence trail) bind to the session
     * here so per-tool event recording and verdict propagation flow
     * into observe / assertTerminal hooks.
     *
     * Trusted (un-admitted) agents skip session creation entirely —
     * this callback is never fired for them. The "auto-created
     * session" path keeps SDK consumers from having to instantiate
     * sessions themselves while still letting them observe.
     */
    readonly onInvariantSessionStarted?: (session: InvariantSession) => void;
    /**
     * FEATURE_101 (v0.7.31.1): pluggable tool capability classifier.
     * Runner calls this on every tool invocation (after Guardrail
     * before-hooks but before the actual execution); when present, the
     * returned `ToolCapability` is attached to the `tool_call` event
     * dispatched to `invariant.observe` hooks. Without a classifier
     * the event omits the capability field — invariants that key on
     * capability gracefully fall back to "unknown capability" semantics.
     *
     * The coding package wires `resolveToolCapability` from
     * `agent-runtime/invariants/tool-permission.ts` here.
     */
    readonly capabilityClassifier?: (toolName: string) => ToolCapability | undefined;
    /**
     * FEATURE_101 (v0.7.31.1): runtime tool capability re-clamp.
     *
     * Admission's `toolPermission` invariant clamps an admitted manifest's
     * tools to `system_cap.allowedToolCapabilities` at activation time.
     * That covers "agent declared a tool the system never allows", but
     * NOT the runtime case where a parent run is itself capped lower
     * than system_cap and dispatches a sub-agent. The design's two-stage
     * clamp model wants the parent's narrower set to apply to every
     * tool call inside the sub-run.
     *
     * When this option is set AND the start agent has admission bindings,
     * Runner.run filters every tool invocation through `capabilityClassifier`
     * and rejects calls whose capability tier is not in the parent set.
     * Rejection materializes as an error tool_result so the LLM can
     * observe the clamp and recover. Trusted (un-admitted) agents are
     * NOT clamped — the parent passes them as-is by design (admission
     * trust = runtime trust).
     */
    readonly parentToolCapabilities?: readonly ToolCapability[];
    /**
     * FEATURE_164 (v0.7.41) — mid-turn message injection hook.
     *
     * Called AFTER tool execution + compaction + handoff handling have
     * completed for the current iteration, but BEFORE the next iteration's
     * `runGenerationTurn` starts. The hook returns an array of additional
     * messages (typically user-role prompts the caller wants to splice in)
     * which the Runner pushes to the transcript and Session before the
     * next LLM call.
     *
     * Designed to support claudecode-style "chat-while-waiting": when the
     * user types a new query while the agent is mid-task, the caller's
     * hook can drain the input queue and inject it as a user message at
     * the tool-result boundary — Worker continues its loop, the LLM
     * sees the new user message in its next call, and no empty turn is
     * emitted. Replaces the legacy "return `{text: '', toolCalls: []}`"
     * pattern that polluted the transcript with an empty assistant turn.
     *
     * The hook fires only when the current iteration ran tool calls (the
     * terminal-no-tool branch returns before reaching here). Empty return
     * value is the no-op fast path. Returning a transcript-replacement
     * is intentionally NOT supported — callers wanting that semantic
     * should use `compactionHook` instead.
     */
    readonly beforeNextTurn?: (ctx: {
        readonly agent: Agent;
        readonly transcript: readonly AgentMessage[];
        readonly iteration: number;
    }) => Promise<readonly AgentMessage[]>;
    /**
     * FEATURE_166 (v0.7.41 follow-up) — agent-switch hook.
     *
     * Fires AFTER `currentAgent` has been swapped to the handoff target
     * (`handoffSignal.to`) AND after the transcript inputFilter +
     * system-message replacement have run, but BEFORE the next
     * iteration's `runGenerationTurn`. Lets callers react to a role
     * transition between
     * turns — most notably the coding observer, which uses this signal to
     * flip the REPL's `activeWorkerTitle` ahead of the new agent's first
     * streaming output (without this hook, the label only flips when the
     * new agent's first slot-tool succeeds, so the label LAGS through
     * Evaluator's thinking / pre-verdict text and any verification
     * tool calls; production session 20260515_185354 trace confirms).
     *
     * Awaitable so callers can perform async side effects (e.g. flushing
     * a status emit through an event bus). Errors propagate verbatim —
     * the hook is caller-controlled, matching `beforeNextTurn` semantics.
     *
     * Fires at most once per iteration (only the first matching handoff
     * in a tool-result batch transitions ownership; see line ~782).
     */
    readonly onAgentSwitched?: (ctx: {
        readonly from: Agent;
        readonly to: Agent;
        readonly iteration: number;
    }) => void | Promise<void>;
    /**
     * FEATURE_184 (v0.7.45) — Stop Hook primitive.
     *
     * Fires when the model terminates a turn with no `tool_use` blocks
     * (text-only response). The hook receives the post-output-guardrail
     * transcript and the final assistant text, and returns one of:
     *
     * - `undefined` → accept the termination, fall through to the normal
     *   terminal path (assertTerminal + return). This is the no-op default.
     * - `string` → "blockingErrors" / reanimate. Runner synthesizes a
     *   `{role: 'user', content: <string>}` message, appends it to the
     *   transcript + session, and continues the loop. Bounded by
     *   `stopHookReanimateBudget` (default 2); exceeded budget converts
     *   the string return to a forced abort.
     * - `{abort: true, reason}` → preventContinuation / halt-and-surface.
     *   Run returns immediately with `output = reason` and
     *   `stoppedByHook = true`. assertTerminal still fires before the
     *   return so invariant violations on the halted state surface
     *   normally.
     *
     * Errors thrown by the hook are caught and treated as `undefined`
     * (fail-open). A span is emitted for observability. Matches the
     * `compactionHook` failure semantics — a buggy hook must never
     * abort the run.
     *
     * Design reference: claudecode `query.ts:1282-1305` blockingErrors +
     * `query.ts:1278` preventContinuation. Generalizes the deterministic
     * shell-script Stop hook surface to an LLM-driven Sidecar Verifier
     * (the v0.7.45 first consumer; see FEATURE_184 Phase D).
     */
    readonly stopHook?: StopHookFn;
    /**
     * FEATURE_184 (v0.7.45) — Reanimate budget for `stopHook`. Default 2.
     *
     * When `stopHook` returns a string AND `reanimateCount` has already
     * reached this budget, the string return is forcibly converted to an
     * abort with reason `"reanimate budget exhausted: <string>"`. Prevents
     * unbounded reanimate loops when the hook + model disagree on
     * completion forever.
     */
    readonly stopHookReanimateBudget?: number;
}
/**
 * FEATURE_184 (v0.7.45) — Stop hook context handed to the caller's
 * `stopHook` when the model terminates a turn text-only.
 */
interface StopHookContext {
    /** Transcript snapshot at the moment the hook fires. Includes the
     *  just-pushed final assistant message. Readonly — the hook must not
     *  mutate; to influence the run return a `string` (reanimate) or
     *  `{abort, reason}` instead. */
    readonly transcript: readonly AgentMessage[];
    /** Convenience field: the final assistant message's text content. */
    readonly lastAssistantText: string;
    /** Why the turn ended. For Phase A this is always `'natural-end'`
     *  (model emitted no `tool_use`). Future signal sources (explicit
     *  COMPLETE protocol emission, harness-injected stop) can extend
     *  the union without breaking existing hooks. */
    readonly signal: 'natural-end';
    /** How many times the hook has already reanimated this run. Starts
     *  at 0; incremented after each `string` return. Hooks can use this
     *  for telemetry but enforcement is Runner-side. */
    readonly reanimateCount: number;
    /** Total reanimate budget for this run (`stopHookReanimateBudget`
     *  or default 2). Exposed for transparency. */
    readonly reanimateBudget: number;
}
/**
 * FEATURE_184 (v0.7.45) — Stop hook return surface.
 */
type StopHookResult = undefined | string | {
    readonly abort: true;
    readonly reason: string;
};
/**
 * FEATURE_184 (v0.7.45) — Stop hook signature.
 */
type StopHookFn = (ctx: StopHookContext) => StopHookResult | Promise<StopHookResult>;
/**
 * Result returned by `Runner.run`.
 */
interface RunResult<TData = unknown> {
    readonly output: string;
    readonly messages: readonly AgentMessage[];
    readonly sessionId?: string;
    readonly data?: TData;
    /** FEATURE_184 (v0.7.45): `true` when the run terminated because
     *  the caller's `stopHook` returned `{abort: true}` OR because the
     *  hook's `string` return exceeded `stopHookReanimateBudget`. The
     *  abort reason is in `output`. Sidecar Verifier sets this when it
     *  outputs a `blocked` verdict (halt + surface to user). */
    readonly stoppedByHook?: boolean;
}
/**
 * Stream events emitted by `Runner.runStream`. The event surface is
 * intentionally small in v0.7.23; FEATURE_084 expands it to mirror the
 * task-engine's event set.
 */
type RunEvent<TData = unknown> = {
    readonly kind: 'message';
    readonly message: AgentMessage;
} | {
    readonly kind: 'complete';
    readonly result: RunResult<TData>;
} | {
    readonly kind: 'error';
    readonly error: Error;
};
/**
 * Tracing context handed to preset dispatchers so they can attach richer
 * spans (e.g. GenerationSpan, ToolCallSpan) under the Runner's AgentSpan.
 *
 * FEATURE_083 (v0.7.24): added in Slice 8 to let the coding preset emit
 * the AgentSpan lifecycle under the same trace as the Runner entry point.
 */
interface PresetTracingContext {
    readonly tracer: Tracer;
    readonly trace: Trace;
    readonly agentSpan: Span;
}
/**
 * Preset dispatcher signature. Registered via `registerPresetDispatcher` and
 * keyed on `Agent.name`. The optional fourth argument carries tracing
 * context created by the Runner; dispatchers may emit child spans under
 * `tracingContext.agentSpan`.
 */
type PresetDispatcher = (agent: Agent, input: string | readonly AgentMessage[], opts: RunOptions | undefined, tracingContext?: PresetTracingContext) => Promise<RunResult>;
/**
 * Register a preset dispatcher for a given Agent name. The coding package
 * registers the `runKodaX` dispatcher for the default coding agent on
 * import of `createDefaultCodingAgent`.
 *
 * Returns an unregister function.
 */
declare function registerPresetDispatcher(agentName: string, dispatcher: PresetDispatcher): () => void;
/** @internal Testing helper. Do not rely on this from application code. */
declare function _resetPresetDispatchers(): void;
/**
 * Wrap a role-spec string in the trusted/untrusted boundary admission
 * applies to admitted (constructed) agents. Exported so the FEATURE_104
 * benchmark dataset (`benchmark/datasets/admission-wrap-baseline/`) can
 * use the production wrap text verbatim — preventing drift between the
 * Q6 non-degradation eval and the actual Runner behavior.
 *
 * `agent` selects the path: agents with admission bindings get the
 * full wrap; trusted agents pass through unchanged. Callers wanting the
 * wrap unconditionally (e.g. for test harnessing) should pass an agent
 * whose bindings are populated via `setAdmittedAgentBindings`.
 */
declare function buildSystemPrompt(agent: Agent, instructions: string): string;
/**
 * Minimal execution entry for an `Agent`.
 */
declare class Runner {
    /**
     * Run an agent to completion. Resolves with the final output plus the
     * full transcript.
     *
     * FEATURE_083 (v0.7.24): emits an AgentSpan around every run and a
     * GenerationSpan around the underlying LLM call in the generic path.
     * Preset dispatchers receive a `PresetTracingContext` so they can attach
     * richer spans under the AgentSpan. Pass `opts.tracer = null` to skip
     * tracing entirely for performance-sensitive calls.
     */
    static run<TData = unknown>(agent: Agent, input: string | readonly AgentMessage[], opts?: RunOptions): Promise<RunResult<TData>>;
    /**
     * FEATURE_101 (v0.7.31): admit an untrusted `AgentManifest` against the
     * admission contract. Returns an `AdmissionVerdict` — `{ ok: true,
     * handle, clampNotes }` on admission, `{ ok: false, reason, retryable }`
     * on schema/invariant rejection.
     *
     * `Runner.admit` is the single gate between an LLM-emitted manifest and
     * an executable Agent. The caller MUST receive an admitted handle
     * before invoking `Runner.run` on any LLM-constructed agent (FEATURE_089
     * agent-generation enforces this via the activate handle plumbing in
     * v0.7.31; SDK consumers calling `Runner.run` on hand-authored Agents
     * are trusted by definition and skip admission).
     *
     * Pure delegation to `runAdmissionAudit` — invariants are resolved from
     * the shared module-scope registry (registered via
     * `registerCoreInvariants()` and the @kodax-ai/coding capability-coupled
     * invariants). The runtime stays sync (no I/O); `async` is reserved
     * for future versions that may need to consult external policy stores.
     *
     * @experimental
     */
    static admit(manifest: AgentManifest, options?: AdmissionAuditOptions): Promise<AdmissionVerdict>;
    /**
     * Streaming variant. v0.7.23 emits a single `complete` event after
     * delegating to `run`; richer intermediate events land with FEATURE_084.
     */
    static runStream<TData = unknown>(agent: Agent, input: string | readonly AgentMessage[], opts?: RunOptions): AsyncIterable<RunEvent<TData>>;
}
/** @internal Exposed so preset dispatchers can extract the assistant text from a KodaXResult. */
declare function extractAssistantTextFromMessage(message: AgentMessage): string;

/**
 * v0.7.35.1 FEATURE_145 — Agent config home, 3-tier resolution.
 *
 * Centralizes the user-config directory used to be hardcoded across
 * ~30 sites in 6 packages as `path.join(os.homedir(), '.kodax', ...)`.
 * That pattern had two problems:
 *
 *   1. **Drift**: each new caller in a future feature was a fresh
 *      hardcode site; nothing stopped a caller from using the wrong
 *      string (`'kodax'` instead of `'.kodax'`, etc.).
 *   2. **Substrate consumer coupling**: when `@kodax-ai/agent` is reused
 *      by a downstream agent (e.g. `@kodax-ai/ops-agent`,
 *      `@kodax-ai/data-analysis-agent`), there was no way to redirect the
 *      runtime config dir — every derivative agent was forced to
 *      share the `~/.kodax/` namespace.
 *
 * The helper exposes a 3-tier priority chain:
 *
 *   1. **Programmatic override** via {@link setAgentConfigHome} —
 *      highest priority. Substrate consumers call this once at boot,
 *      before any subsystem reads the path.
 *   2. **`KODAX_HOME` env var** — middle priority. Used by shell / CI /
 *      test isolation / multi-tenant shared machines. (Already honored
 *      historically by `@kodax-ai/llm/src/reasoning-overrides.ts`; this
 *      helper makes it the canonical path for all packages.)
 *   3. **`~/.kodax/`** — lowest priority. Default for the standalone
 *      kodax CLI. With DI not set + env not set, the resolver returns
 *      the same byte sequence as the prior hardcoded
 *      `path.join(os.homedir(), '.kodax')` calls — so the migration
 *      from hardcoded sites to this helper is byte-equivalent for the
 *      existing user base.
 *
 * Why a process-level singleton (and not per-call DI):
 * the ~30 fs callsites are buried in library helpers (construction /
 * mcp catalog / oauth tokens / paste-cache etc.). Threading a
 * `configHome` parameter through every helper would change ~50
 * function signatures, and every caller would have to remember to
 * thread it — a single forgotten thread silently falls back to
 * default. Singleton matches the `process.env.NODE_ENV` pattern: a
 * process really has a single config home (no legitimate use case
 * for a process to interleave reads/writes against `~/.kodax/` AND
 * `~/.opsagent/` simultaneously).
 *
 * NOT migrated:
 *   - `@kodax-ai/llm/src/reasoning-overrides.ts:49` keeps its inline
 *     `process.env.KODAX_HOME ?? path.join(os.homedir(), '.kodax')`
 *     fallback because moving it to this helper would create an
 *     `@kodax-ai/llm → @kodax-ai/agent` dependency cycle (agent already
 *     imports ai). The two implementations have identical observable
 *     behavior at the env / default tiers; the programmatic override
 *     tier doesn't apply to ai-layer code.
 *   - **Project-relative** `.kodax/` paths (e.g. `path.join(projectRoot,
 *     '.kodax', 'AGENTS.md')`) are NOT migrated — those name a
 *     different concept (per-project config) and use a different root.
 *   - **CWD-relative** subpath constants like `path.join('.kodax',
 *     'constructed', '_audit.jsonl')` (joined with a project root by
 *     the caller) are likewise project-scoped and stay as-is.
 */
/**
 * Set the agent config home programmatically. Highest priority in
 * {@link getAgentConfigHome}'s 3-tier chain.
 *
 * Substrate consumers (e.g. an agent built on top of `@kodax-ai/agent`)
 * should call this once at process boot, before any subsystem reads
 * the path. Pass `undefined` to reset (used in tests).
 */
declare function setAgentConfigHome(path: string | undefined): void;
/**
 * Resolve the agent runtime config home directory.
 *
 * Priority (high → low):
 *   1. Programmatic override via {@link setAgentConfigHome}
 *   2. `KODAX_HOME` env var
 *   3. `~/.kodax` (hardcoded default)
 */
declare function getAgentConfigHome(): string;
/**
 * Resolve a sub-path under the agent config home.
 *
 * Equivalent to `path.join(getAgentConfigHome(), ...segments)` but
 * shorter at every callsite (which is the entire point of the helper —
 * 30 callsites of `path.join(os.homedir(), '.kodax', x, y)` collapse to
 * 30 callsites of `getAgentConfigPath(x, y)`).
 */
declare function getAgentConfigPath(...segments: string[]): string;
/**
 * v0.7.42 — Namespaced data directory for third-party apps embedding the
 * KodaX SDK (e.g. `KodaX Space` desktop client, IDE extensions).
 *
 * Returns `${getAgentConfigHome()}/apps/<appId>/` and creates the directory
 * if missing. Provides a coordination point so multiple SDK consumers can
 * share `~/.kodax/` without colliding on path conventions.
 *
 * Constraints:
 *   - `appId` must match `^[a-z][a-z0-9-]{1,31}$` (lowercase kebab, 2–32 chars,
 *     no dots, no slashes, no underscores) — keeps the directory name safe
 *     across all filesystems and prevents `../` traversal.
 *   - Reserved prefixes (`kodax`, `kodax-*`) are rejected to leave room
 *     for first-party feature directories that may collide later.
 *
 * The convention is intentionally light — no central registry, no manifest.
 * Apps owning their data dir means SDK upgrades cannot trample on third-party
 * state. Apps are responsible for migration/cleanup within their own subtree.
 */
declare function getAppDataDir(appId: string): string;

/**
 * History cleanup middleware — CAP-002
 *
 * Capability inventory: docs/features/v0.7.29-capability-inventory.md#cap-002
 *
 * Two pure functions that maintain the assistant↔user `tool_use`/`tool_result`
 * pairing invariant the provider expects. Both functions take a message array
 * and return a new array (immutable — never mutate the input).
 *
 *   - `cleanupIncompleteToolCalls`: when a stream is interrupted mid-flight,
 *     the last assistant message may carry orphan `tool_use` blocks with no
 *     matching `tool_result`. The next provider call would 400 with
 *     "tool_call_id not found". This function strips those orphans before
 *     the next request.
 *
 *   - `validateAndFixToolHistory`: deeper pass that walks the full message
 *     history and fixes mis-pairings on both sides — orphan `tool_use` in
 *     assistant messages, orphan `tool_result` in user messages, and ensures
 *     no message becomes empty after stripping (Kimi specifically rejects
 *     empty assistant messages with 400, so we inject a `'...'` placeholder
 *     when stripping would empty an assistant message).
 *
 * Migration history: extracted from `agent.ts` (originally lines 517–758)
 * during FEATURE_100 P2. Both `agent.ts` and `task-engine/runner-driven.ts`
 * already consume these via the package re-export (`@kodax-ai/coding`).
 *
 * Type guards are inlined here rather than imported from agent.ts because
 * the migration's whole point is to remove dependencies on agent.ts. If
 * additional agent-runtime modules need the same guards in the future,
 * extract them to `agent-runtime/content-blocks.ts`.
 */

/**
 * Walk the message history and remove mis-paired `tool_use` / `tool_result`
 * blocks. Preserves message order and structure; never mutates input.
 *
 * Rules enforced:
 *   - assistant `tool_use` with no matching `tool_result` in the next user
 *     message → removed
 *   - assistant `tool_use` with empty / missing id → removed
 *   - user `tool_result` with no matching assistant `tool_use` in the previous
 *     message → removed
 *   - user `tool_result` with empty / missing tool_use_id → removed
 *   - assistant message that becomes content-empty after stripping → inject
 *     a `'...'` placeholder text block (preserves message-alternation invariant
 *     downstream providers like Kimi require)
 */
declare function validateAndFixToolHistory(messages: KodaXMessage[]): KodaXMessage[];
/**
 * Strip orphan `tool_use` blocks from the LAST assistant message only.
 *
 * Used as a quick pre-stream guard when a previous turn was interrupted
 * (Issue 072): the last assistant message has unanswered tool_use blocks,
 * and the next provider request would 400 with "tool_call_id not found".
 *
 * Cheaper than `validateAndFixToolHistory` because it only touches the tail.
 */
declare function cleanupIncompleteToolCalls(messages: KodaXMessage[]): KodaXMessage[];

export { _resetAdmittedAgentBindings as $, DEFAULT_SYSTEM_CAP as D, Runner as G, KODAX_API_MIN_INTERVAL as K, PROMISE_PATTERN as P, _resetPresetDispatchers as a0, buildSystemPrompt as a1, cleanupIncompleteToolCalls as a2, countTokens as a3, createInMemorySession as a4, createInvariantSessionForAgent as a5, detectInstructionsInjection as a6, estimateTokens as a7, extractAssistantTextFromMessage as a8, getAdmittedAgentBindings as a9, getAgentConfigHome as aa, getAgentConfigPath as ab, getAppDataDir as ac, registerPresetDispatcher as ad, runAdmissionAudit as ae, setAdmittedAgentBindings as af, setAgentConfigHome as ag, validateAndFixToolHistory as ah, DefaultSummaryCompaction as h, InvariantSession as m, KODAX_DEFAULT_TIMEOUT as n, KODAX_HARD_TIMEOUT as o, KODAX_MAX_INCOMPLETE_RETRIES as p, KODAX_MAX_MAXTOKENS_RETRIES as q, KODAX_MAX_RETRIES as r, KODAX_MAX_TOKENS as s, KODAX_RETRY_BASE_DELAY as t, KODAX_STAGGER_DELAY as u };
export type { AdmissionAuditOptions as A, RunEvent as B, CompactionContext as C, RunOptions as E, RunResult as F, RunnerEvent as H, InMemorySessionOptions as I, SessionDispatchResult as J, SessionEntry as L, ManifestPatch as M, SessionExtension as N, ObserveCtx as O, QualityInvariant as Q, ReadonlyMutationTracker as R, Session as S, SessionForkOptions as T, StopHookContext as U, StopHookFn as V, StopHookResult as W, SystemCap as X, TerminalCtx as Y, ToolCapability as Z, ToolPermission as _, AdmissionCtx as a, AdmissionVerdict as b, AdmittedHandle as c, AgentManifest as d, CompactionEntry as e, CompactionEntryPayload as f, CompactionPolicy as g, DefaultSummaryCompactionOptions as i, Deliverable as j, InvariantId as k, InvariantResult as l, MessageEntry as v, PolicyCompactionResult as w, PresetDispatcher as x, PresetTracingContext as y, ReadonlyRecorder as z };
