import { X as KodaXToolDefinition, m as KodaXMessage, D as KodaXReasoningMode, Z as KodaXToolResultContentItem, T as KodaXThinkingBlock, G as KodaXRedactedThinkingBlock } from './types.d-B1uGoVTE.js';

/**
 * Layer A Primitive: Agent / Handoff / Guardrail / AgentReasoningProfile
 *
 * FEATURE_080 (v0.7.23): Agent-as-data types. Declarative dataclass shape.
 * The runtime counterpart is `Runner` in `./runner.ts`.
 *
 * 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 (single-consumer rule —
 * @kodax-ai/core had only @kodax-ai/coding as consumer). `@kodax-ai/coding` retains
 * a barrel re-export for batteries-included consumers.
 *
 * Status: @experimental — API shape may be refined during v0.7.x. Used by
 * the task-engine rewrite in FEATURE_084 (v0.7.26).
 *
 * Guardrail and AgentReasoningProfile are declared here but their runtime
 * behavior is deferred:
 *   - Guardrail runtime → FEATURE_085 (v0.7.26)
 *   - AgentReasoningProfile behavior → FEATURE_078 (v0.7.29)
 */

/**
 * Reasoning depth / mode selector. Alias for `KodaXReasoningMode` to keep the
 * Layer A surface independent of the `KodaX*` brand; unified during the prefix
 * cleanup in FEATURE_086 (v0.7.27).
 */
type ReasoningDepth = KodaXReasoningMode;
/**
 * Tool binding accepted by an `Agent`. Layer A treats tools as opaque
 * definitions; the executor lives in `@kodax-ai/coding` and is wired up by the
 * Runner when it dispatches through `runKodaX`.
 */
type AgentTool = KodaXToolDefinition;
/**
 * Transport-level message reused from the AI layer. Kept as an alias so
 * consumers of the Layer A primitives do not need to import from `@kodax-ai/llm`
 * directly.
 */
type AgentMessage = KodaXMessage;
/**
 * Declarative reasoning profile attached to an Agent.
 *
 * In v0.7.23 this is a placeholder shape — only the `default` depth is read
 * when the Runner dispatches to `runKodaX`. Escalation on revise/replan and
 * max clamping are implemented in FEATURE_078 (v0.7.29).
 */
interface AgentReasoningProfile {
    readonly default: ReasoningDepth;
    readonly max?: ReasoningDepth;
    readonly escalateOnRevise?: boolean;
}
/**
 * Declarative middleware reference attached to an Agent.
 *
 * FEATURE_100 (v0.7.29) introduces this field so the coding preset
 * can declare the four substrate middlewares (auto-reroute,
 * mutation-reflection, pre-answer-judge, post-tool-judge) on the
 * Agent declaration itself. Today these middlewares fire inside
 * the substrate body; the declaration field serves as the
 * machine-readable contract that the substrate honours, and lets
 * SDK consumers introspect / override middleware policy without
 * touching `runKodaX` internals.
 *
 * `enabled` is the only knob today; future versions add config
 * payload as additional fields (kept declarative — no fn callbacks).
 */
interface AgentMiddlewareDeclaration {
    readonly name: string;
    readonly enabled: boolean;
}
/**
 * Guardrail placeholder. Layer A declares the slot; the actual
 * input/output/tool-call gating runtime lives in FEATURE_085 (v0.7.26).
 *
 * A guardrail targets one of three hook points:
 *   - `input`: inspect / veto prompts before they enter the agent loop.
 *   - `output`: inspect / rewrite assistant messages before they leave.
 *   - `tool`: inspect / veto tool invocations during the loop.
 */
interface Guardrail {
    readonly kind: 'input' | 'output' | 'tool';
    readonly name: string;
}
/**
 * Handoff between Agents.
 *
 *   - `continuation`: ownership of the conversation transfers to `target` and
 *     the caller exits. Mirrors the Scout → Generator upgrade path.
 *   - `as-tool`: `target` is invoked like a tool from within the caller loop;
 *     only the generated input is passed, and control returns on completion.
 *     Mirrors FEATURE_067 `dispatch_child_task`.
 *
 * `inputFilter` is applied to the visible history before the target runs;
 * default is no filtering.
 */
interface Handoff<TTo = unknown> {
    readonly target: Agent<TTo>;
    readonly kind: 'continuation' | 'as-tool';
    readonly description?: string;
    readonly inputFilter?: (history: readonly AgentMessage[]) => readonly AgentMessage[];
}
/**
 * Agent-as-data. A declarative specification of "who is running, with which
 * instructions, tools, handoffs, and reasoning profile."
 *
 * Runtime note: in v0.7.23 the only Agent that is fully executed is the
 * built-in coding preset (`createDefaultCodingAgent()`), which dispatches
 * through `runKodaX`. Custom Agents defined by SDK consumers run through a
 * generic Runner loop with limited capabilities (LLM call + Agent-declared
 * tools only — no extensions, no managed-task harness). The full runtime
 * arrives with FEATURE_084 (v0.7.26).
 */
interface Agent<TContext = unknown> {
    readonly name: string;
    readonly instructions: string | ((ctx: TContext) => string);
    readonly tools?: readonly AgentTool[];
    readonly handoffs?: readonly Handoff[];
    readonly reasoning?: AgentReasoningProfile;
    readonly guardrails?: readonly Guardrail[];
    /** Reserved for structured-output agents; not consumed in v0.7.23. */
    readonly outputSchema?: unknown;
    readonly model?: string;
    readonly provider?: string;
    /**
     * FEATURE_100 (v0.7.29) substrate executor: when set, `Runner.run`
     * delegates execution to this function instead of consulting the
     * preset-dispatcher registry or running the generic LLM loop. The
     * coding preset attaches `runKodaX`'s full execution pipeline here so
     * the SDK surface `Runner.run(createDefaultCodingAgent(), prompt, opts)`
     * directly drives substrate without a `registerPresetDispatcher`
     * indirection (the v0.7.23 "Option Y" facade).
     *
     * Type is intentionally `unknown` to avoid a `core/agent.ts` ↔
     * `core/runner.ts` module cycle. `Runner.run` casts to the
     * `PresetDispatcher` shape declared in `runner.ts` at the call site.
     */
    readonly substrateExecutor?: unknown;
    /**
     * FEATURE_100 (v0.7.29) declarative middleware list. The coding
     * preset declares the four substrate middlewares it ships with
     * (auto-reroute, mutation-reflection, pre-answer-judge,
     * post-tool-judge). Substrate consults this list on entry and
     * skips the corresponding step when `enabled === false`. SDK
     * consumers can introspect or override declared middleware
     * without touching the substrate body.
     */
    readonly middleware?: readonly AgentMiddlewareDeclaration[];
}
/**
 * Ergonomic factory. Equivalent to a plain object literal but freezes the
 * shape so tests cannot mutate a shared Agent by accident.
 */
declare function createAgent<TContext = unknown>(spec: Agent<TContext>): Agent<TContext>;
/**
 * Ergonomic factory for Handoff.
 */
declare function createHandoff<TTo = unknown>(spec: Handoff<TTo>): Handoff<TTo>;

/**
 * SpanData variants — payload shapes carried by each `Span`.
 *
 * FEATURE_083 (v0.7.24): the Agent-era tracing model uses a discriminated
 * union so consumers (OpenTelemetry adapter, Langfuse adapter, KodaX
 * built-in file processor) can render each span kind with type safety.
 *
 * Variants mirror the semantic events KodaX emits today:
 *   - AgentSpanData     : one `Runner.run(agent, ...)` round
 *   - GenerationSpanData: one provider LLM call
 *   - ToolCallSpanData  : one tool invocation (including MCP tool)
 *   - HandoffSpanData   : continuation or as-tool handoff between agents
 *   - CompactionSpanData: one compaction pass (token-threshold or lineage)
 *   - GuardrailSpanData : one guardrail check at input/output/tool
 *   - EvidenceSpanData  : repo-intelligence / evidence acquisition
 *   - FanoutSpanData    : parallel fanout bracket (winner-cancel capable)
 *
 * API surface is `@experimental` until v0.8.0 — shape may be refined as
 * FEATURE_084 (v0.7.26) starts emitting these.
 */
interface AgentSpanData {
    readonly kind: 'agent';
    readonly agentName: string;
    readonly model?: string;
    readonly provider?: string;
    readonly tools?: readonly string[];
    readonly handoffs?: readonly string[];
    readonly outputMessages?: number;
    readonly error?: string;
}
interface GenerationSpanData {
    readonly kind: 'generation';
    readonly agentName: string;
    readonly provider: string;
    readonly model: string;
    readonly inputMessages?: number;
    readonly outputTokens?: number;
    readonly inputTokens?: number;
    readonly reasoningTokens?: number;
    readonly cachedTokens?: number;
    readonly usage?: {
        readonly inputTokens?: number;
        readonly outputTokens?: number;
        readonly totalTokens?: number;
        readonly reasoningTokens?: number;
        readonly cachedTokens?: number;
        readonly costUsd?: number;
    };
    readonly finishReason?: string;
    readonly error?: string;
}
interface ToolCallSpanData {
    readonly kind: 'tool_call';
    readonly toolName: string;
    readonly providerId?: string;
    readonly capabilityId?: string;
    readonly inputPreview?: string;
    readonly outputPreview?: string;
    readonly status: 'ok' | 'error';
    readonly error?: string;
}
interface HandoffSpanData {
    readonly kind: 'handoff';
    readonly fromAgent: string;
    readonly toAgent: string;
    readonly handoffKind: 'continuation' | 'as-tool';
    readonly description?: string;
}
interface CompactionSpanData {
    readonly kind: 'compaction';
    readonly policyName: string;
    readonly tokensUsed: number;
    readonly budget: number;
    readonly replacedMessageCount: number;
    readonly summaryLength: number;
    readonly error?: string;
}
interface GuardrailSpanData {
    readonly kind: 'guardrail';
    readonly guardrailName: string;
    readonly hookPoint: 'input' | 'output' | 'tool';
    readonly decision: 'pass' | 'veto' | 'rewrite' | 'error';
    readonly reason?: string;
    readonly error?: string;
}
interface EvidenceSpanData {
    readonly kind: 'evidence';
    readonly source: string;
    readonly queryPreview?: string;
    readonly resultCount?: number;
    readonly cacheHit?: boolean;
    readonly error?: string;
}
interface FanoutSpanData {
    readonly kind: 'fanout';
    readonly agentName: string;
    readonly childCount: number;
    readonly winnerChildId?: string;
    readonly cancelledChildIds?: readonly string[];
}
/**
 * FEATURE_184 (v0.7.45) — Stop hook observability.
 *
 * Emitted when the Runner's `RunOptions.stopHook` is invoked or fails.
 * `outcome` records what the hook returned (or `'error'` for thrown
 * exceptions — fail-open path), `reanimateCount` is the running count
 * after this invocation. `reason` carries the abort/reanimate text
 * when relevant, truncated by consumers as needed.
 */
interface StopHookSpanData {
    readonly kind: 'stop-hook';
    readonly outcome: 'accept' | 'reanimate' | 'abort' | 'budget-exhausted' | 'error';
    readonly reanimateCount: number;
    readonly reanimateBudget: number;
    readonly reason?: string;
    readonly error?: string;
}
/**
 * Discriminated union of all span payload shapes. Additional variants may
 * be added in future features — consumers should check `kind` before
 * reading specific fields.
 */
type SpanData = AgentSpanData | GenerationSpanData | ToolCallSpanData | HandoffSpanData | CompactionSpanData | GuardrailSpanData | EvidenceSpanData | FanoutSpanData | StopHookSpanData;

/**
 * Span — a single timed unit of work inside a Trace.
 *
 * FEATURE_083 (v0.7.24): minimal Span implementation modeled after the
 * openai-agents-python Trace/Span pattern.
 *
 * Design constraints:
 *   - Span creation must be cheap (no await, no serialisation). Processors
 *     do their own batching / flushing.
 *   - `addChild()` is synchronous and immediately visible in the Trace tree.
 *   - `end()` is idempotent; calling it twice is a no-op.
 *   - `error` is an optional field that sets a flag on the span without
 *     throwing. The consumer decides how to surface errors.
 */

interface SpanError {
    readonly message: string;
    readonly stack?: string;
    readonly data?: unknown;
}
/**
 * Public Span interface. Concrete implementation is `SpanImpl`.
 */
interface Span {
    readonly id: string;
    readonly traceId: string;
    readonly parentId?: string;
    readonly name: string;
    readonly data: SpanData;
    readonly startedAt: number;
    readonly endedAt?: number;
    readonly error?: SpanError;
    readonly children: readonly Span[];
    addChild(name: string, data: SpanData): Span;
    setError(err: SpanError | Error): void;
    end(): void;
}

/**
 * Runner Tool Loop — FEATURE_084 Shard 1 (v0.7.26).
 *
 * Extends the Layer A Runner generic-dispatch path with tool-call support.
 * Before Shard 1 the Runner could only do a single `system+user → assistant`
 * turn. Now the injected LLM callback may return a structured result that
 * declares tool calls; the Runner executes them, appends tool_use +
 * tool_result content blocks, and loops until the LLM stops emitting tool
 * calls (or MAX_TOOL_LOOP_ITERATIONS is reached).
 *
 * This Shard only lands the capability. No built-in Agent consumes it yet —
 * the coding preset (SA path) continues to dispatch through
 * `registerPresetDispatcher` unchanged.
 *
 * @experimental Shape may be refined during the v0.7.26 shard rollout.
 */

/**
 * Hard ceiling on tool-loop iterations. A single run may invoke at most this
 * many LLM turns (counting the initial turn); if the model keeps returning
 * tool calls past this limit we abort to prevent runaway behaviour.
 */
declare const MAX_TOOL_LOOP_ITERATIONS = 20;
/**
 * One tool invocation requested by the LLM.
 */
interface RunnerToolCall {
    readonly id: string;
    readonly name: string;
    readonly input: Record<string, unknown>;
}
/**
 * Structured LLM result. Returning this instead of a plain string lets the
 * Runner drive a tool loop. If `toolCalls` is empty or omitted the loop
 * terminates and `text` becomes the final output.
 */
interface RunnerLlmResult {
    readonly text: string;
    readonly toolCalls?: readonly RunnerToolCall[];
    readonly stopReason?: string;
    /**
     * v0.7.26 parity: extended-thinking blocks from the provider stream.
     * Must be preserved on the assistant message so (a) session resume can
     * re-render them and (b) Anthropic's extended-thinking API contract is
     * honoured — provider rejects the next turn with a 400 when a tool_use
     * turn's `thinking` block is missing from prior assistant history.
     */
    readonly thinkingBlocks?: readonly (KodaXThinkingBlock | KodaXRedactedThinkingBlock)[];
}
/**
 * LLM callback return type. `string` preserves the v0.7.23 single-turn
 * behaviour; `RunnerLlmResult` opts into the tool loop.
 */
type RunnerLlmReturn = string | RunnerLlmResult;
/**
 * Observer callbacks fired around every tool invocation. Preset
 * dispatchers (e.g. the coding Runner-driven path) pass these through
 * `RunOptions.toolObserver` so REPL / CLI consumers see live
 * `onToolCall` / `onToolResult` events, matching the legacy task-engine
 * event surface (v0.7.22 agent.ts fired `events.onToolResult` at three
 * sites per invocation).
 */
interface RunnerToolObserver {
    /**
     * Permission / policy gate fired BEFORE each tool invocation. Return
     * `true` (or `undefined`) to allow, `false` to block with a generic
     * message, or a `string` to block with that message as the tool result.
     * Used to hook plan-mode / accept-edits / extension `tool:before`
     * policies onto the Runner-driven path (v0.7.22 parity — legacy
     * `events.beforeToolExecute` surface).
     */
    readonly beforeTool?: (call: RunnerToolCall) => Promise<boolean | string | undefined>;
    readonly onToolCall?: (call: RunnerToolCall) => void;
    readonly onToolResult?: (call: RunnerToolCall, result: RunnerToolResult) => void;
}
/**
 * Context passed to a RunnableTool's `execute` function.
 */
interface RunnerToolContext {
    readonly agent: Agent;
    readonly abortSignal?: AbortSignal;
    /** The agent's Span, so tool implementations can nest custom spans if needed. */
    readonly agentSpan?: Span | null;
    /**
     * Current tool_use call id. Passed through so tool wrappers can correlate
     * progress events (`onToolProgress`) and other per-call side-effects with
     * the REPL's tool-block in the transcript. Populated by `executeRunnerToolCall`.
     */
    readonly toolCallId?: string;
}
/**
 * Value returned by `RunnableTool.execute`. The `content` is what the LLM
 * sees in the next turn as `tool_result`:
 *
 *   - `string` — plain text (the default for most tools).
 *   - `readonly KodaXToolResultContentItem[]` — an array of typed items
 *     (text + image), used by multimodal tools like `read` on an image
 *     path. Provider serializers lower each item to the wire format
 *     (Anthropic accepts inline; OpenAI-compat downgrades image to text
 *     placeholder).
 */
interface RunnerToolResult {
    readonly content: string | readonly KodaXToolResultContentItem[];
    readonly isError?: boolean;
    readonly metadata?: Record<string, unknown>;
}
/**
 * A tool bundled with its executor. Extends `AgentTool` (the wire-format
 * `KodaXToolDefinition`) so it can be passed through to the provider
 * unchanged while also carrying a function the Runner can invoke.
 */
interface RunnableTool extends AgentTool {
    readonly execute: (input: Record<string, unknown>, ctx: RunnerToolContext) => Promise<RunnerToolResult>;
}
/**
 * Narrowing helper — distinguishes a `RunnableTool` from a plain
 * `AgentTool`. An agent may declare both: the Runner only executes the
 * tools that carry an `execute` function.
 */
declare function isRunnableTool(tool: AgentTool): tool is RunnableTool;
/**
 * Narrowing helper for the LLM callback return shape.
 */
declare function isRunnerLlmResult(value: unknown): value is RunnerLlmResult;
/**
 * Execute one tool call against the agent's declared tools. Emits a
 * ToolCallSpan under `ctx.agentSpan` when tracing is active. Returns a
 * `RunnerToolResult` — tool errors do not throw, they are surfaced with
 * `isError: true` so the LLM can see them in the next turn and react.
 */
declare function executeRunnerToolCall(call: RunnerToolCall, agent: Agent, ctx: RunnerToolContext): Promise<RunnerToolResult>;
/**
 * Build the assistant message that captures one LLM turn. Preserves
 * thinking blocks (extended-thinking contract), text blocks, and tool_use
 * blocks in the order Anthropic's wire format expects: thinking → text →
 * tool_use. This mirrors v0.7.22 `agent.ts:2230`
 * (`[...thinkingBlocks, ...textBlocks, ...visibleToolBlocks]`) which the
 * Runner-driven path must preserve — without it Anthropic returns 400 on
 * the next turn when extended thinking is active, and session resume
 * loses the reasoning trace.
 */
declare function buildAssistantMessageFromLlmResult(result: RunnerLlmResult): AgentMessage;
/**
 * Build the user message that carries tool_result blocks back to the LLM.
 * Provider serializers (Anthropic, OpenAI) both accept tool_result on the
 * user turn.
 */
declare function buildToolResultMessage(calls: readonly RunnerToolCall[], results: readonly RunnerToolResult[]): AgentMessage;

/**
 * Guardrail Runtime — FEATURE_085 (v0.7.26).
 *
 * Three-tier runtime for Agent guardrails:
 *
 *   - `InputGuardrail`: runs once before the first LLM turn, inspects the
 *     full input transcript, may allow / rewrite / block / escalate.
 *   - `OutputGuardrail`: runs once before returning, inspects the final
 *     assistant message, may allow / rewrite / block / escalate.
 *   - `ToolGuardrail`: runs before and/or after each tool invocation,
 *     inspects the call / result, may allow / rewrite / block / escalate.
 *
 * The four verdict actions:
 *
 *   - `allow`: continue with the current value.
 *   - `rewrite`: replace the current value with `payload`.
 *   - `block`: throw `GuardrailBlockedError` (for input/output) or surface
 *     an error tool_result (for tool-before); the LLM / caller sees a
 *     rejection and must adapt.
 *   - `escalate`: throw `GuardrailEscalateError`; the SDK consumer catches
 *     and decides whether to prompt the user, retry under different
 *     constraints, etc.
 *
 * Every guardrail invocation emits a `GuardrailSpan` under the agent's
 * span when tracing is active.
 *
 * @experimental API shape may adjust during v0.7.x rollout.
 */

/**
 * Shared execution context passed to every guardrail.
 *
 * `messages` is the live conversation transcript at the moment this
 * guardrail fires. For tool-side guardrails this is the transcript at
 * call-site time — it does NOT yet include the assistant turn that
 * emitted the current tool_use, since that turn is appended only after
 * the full tool batch settles. Optional so existing guardrails that
 * don't read context still type-check; populated by the Runner for all
 * production hook points.
 *
 * Added in FEATURE_092 (v0.7.33) so the auto-mode classifier guardrail
 * can extract intent context (user prompt + prior tool_use / tool_result
 * blocks) without reaching into Runner internals.
 */
interface GuardrailContext {
    readonly agent: Agent;
    readonly abortSignal?: AbortSignal;
    readonly messages?: readonly AgentMessage[];
}
/**
 * Outcome of a single guardrail check. `payload` shape depends on the hook
 * point — see the specific guardrail interface for the expected type.
 */
type GuardrailVerdict = {
    readonly action: 'allow';
} | {
    readonly action: 'rewrite';
    readonly payload: unknown;
    readonly reason?: string;
} | {
    readonly action: 'block';
    readonly reason: string;
} | {
    readonly action: 'escalate';
    readonly reason: string;
};
/**
 * Input-side guardrail. Expected `rewrite` payload shape:
 * `readonly AgentMessage[]` — the replacement transcript.
 */
interface InputGuardrail extends Guardrail {
    readonly kind: 'input';
    check(input: readonly AgentMessage[], ctx: GuardrailContext): Promise<GuardrailVerdict>;
}
/**
 * Output-side guardrail. Expected `rewrite` payload shape:
 * `AgentMessage` — the replacement final assistant message.
 */
interface OutputGuardrail extends Guardrail {
    readonly kind: 'output';
    check(output: AgentMessage, ctx: GuardrailContext): Promise<GuardrailVerdict>;
}
/**
 * Tool-side guardrail. `beforeTool` rewrite payload shape: `RunnerToolCall`
 * (replacement call). `afterTool` rewrite payload shape: `RunnerToolResult`
 * (replacement result). Either hook is optional.
 */
interface ToolGuardrail extends Guardrail {
    readonly kind: 'tool';
    beforeTool?(call: RunnerToolCall, ctx: GuardrailContext): Promise<GuardrailVerdict>;
    afterTool?(call: RunnerToolCall, result: RunnerToolResult, ctx: GuardrailContext): Promise<GuardrailVerdict>;
}
/**
 * Thrown when any guardrail returns `{ action: 'block' }`. The Runner
 * propagates this up to the caller — the run is aborted at that point.
 */
declare class GuardrailBlockedError extends Error {
    readonly guardrailName: string;
    readonly hookPoint: 'input' | 'output' | 'tool';
    constructor(guardrailName: string, hookPoint: 'input' | 'output' | 'tool', reason: string);
}
/**
 * Thrown when any guardrail returns `{ action: 'escalate' }`. Callers can
 * catch and prompt the user or apply a stricter policy before retrying.
 */
declare class GuardrailEscalateError extends Error {
    readonly guardrailName: string;
    readonly hookPoint: 'input' | 'output' | 'tool';
    constructor(guardrailName: string, hookPoint: 'input' | 'output' | 'tool', reason: string);
}
/** Filter a guardrail list by hook-point. */
declare function collectGuardrails(guardrails: readonly Guardrail[] | undefined): {
    input: readonly InputGuardrail[];
    output: readonly OutputGuardrail[];
    tool: readonly ToolGuardrail[];
};
/**
 * Run all input guardrails in declaration order. Returns the (possibly
 * rewritten) transcript. Throws on block / escalate.
 */
declare function runInputGuardrails(transcript: readonly AgentMessage[], guardrails: readonly InputGuardrail[], ctx: GuardrailContext, agentSpan: Span | null): Promise<readonly AgentMessage[]>;
/**
 * Run all output guardrails in declaration order. Returns the (possibly
 * rewritten) final assistant message. Throws on block / escalate.
 */
declare function runOutputGuardrails(output: AgentMessage, guardrails: readonly OutputGuardrail[], ctx: GuardrailContext, agentSpan: Span | null): Promise<AgentMessage>;
/**
 * Outcome of the before-tool guardrail stage.
 *   - `{ kind: 'allow', call }`: continue to executeRunnerToolCall with `call`
 *   - `{ kind: 'block', result }`: skip execution; return `result` as the
 *     tool_result to the LLM (so it sees the rejection and can adapt)
 */
type ToolBeforeOutcome = {
    readonly kind: 'allow';
    readonly call: RunnerToolCall;
} | {
    readonly kind: 'block';
    readonly result: RunnerToolResult;
};
/**
 * Run before-tool guardrails in declaration order. Rewrite replaces the
 * tool call. Block surfaces an error tool_result to the LLM instead of
 * throwing — the LLM sees the rejection and adapts. Escalate still throws.
 */
declare function runToolBeforeGuardrails(call: RunnerToolCall, guardrails: readonly ToolGuardrail[], ctx: GuardrailContext, agentSpan: Span | null): Promise<ToolBeforeOutcome>;
/**
 * Run after-tool guardrails in declaration order. Rewrite replaces the
 * result content. Block replaces with an error result. Escalate throws.
 */
declare function runToolAfterGuardrails(call: RunnerToolCall, result: RunnerToolResult, guardrails: readonly ToolGuardrail[], ctx: GuardrailContext, agentSpan: Span | null): Promise<RunnerToolResult>;

/**
 * Child task registry primitive — generic fan-out tracking.
 *
 * FEATURE_120 v0.7.39 Step 0 (package-attribution migration, ADR-021).
 * Lifted from `@kodax-ai/coding`'s `KodaXToolExecutionContext.childTaskRegistry`
 * field + inline cleanup chain in `tools/dispatch-child-tasks.ts`. The
 * coding side now consumes this primitive specialized to its
 * `KodaXChildExecutionResult` type; any other agent-flavor downstream
 * can specialize on its own child-result type without re-implementing
 * the cleanup contract.
 *
 * The shape is intentionally minimal: a Map plus a `register` helper
 * that bundles the v0.7.38 FEATURE_155 Bug A hotfix (`c1bdaf4e`)
 * cleanup chain into a single call site. The helper exists because
 * the cleanup is **not optional** — without it, every settled promise
 * stays in the registry forever, gets re-wrapped by the next
 * idle-yield `waitForWakeEvent` call, and fires spurious
 * `child-completed` wakes (production symptom: Evaluator gets
 * bombarded by duplicate `<task-completed>` notifications, consuming
 * an LLM turn each up to `IDLE_YIELD_MAX_ITERATIONS=64`).
 */
/**
 * Map of `task_id` → in-flight child-execution promise. Generic over
 * the child-result type so the agent layer doesn't depend on any
 * specific agent flavor's result shape.
 *
 * Mutation contract:
 *   - Owned by the runner's per-turn execution context. The dispatch
 *     tool writes via `registerChildTask`; the idle-yield outer loop
 *     reads via `Map.prototype.entries()` / `.size`.
 *   - **Never delete entries manually** — call `registerChildTask`
 *     and the cleanup chain it installs will run on settle.
 */
type ChildTaskRegistry<T> = Map<string, Promise<T>>;
/**
 * Register an in-flight child-execution promise in the registry and
 * install the cleanup chain that removes the entry once the promise
 * settles (success or failure).
 *
 * The cleanup chain is two stages:
 *   1. `.finally(() => registry.delete(childId))` — runs on settle
 *      regardless of outcome, removing the entry before the next
 *      idle-yield outer-loop iteration observes the registry.
 *   2. `.catch(() => {})` — swallows the rejection on the cleanup
 *      chain so a child that crashes before any consumer awaits it
 *      doesn't surface as `unhandledRejection` on Node. Must come
 *      AFTER `.finally` because `.finally` returns a NEW promise
 *      that rejects with the same reason.
 *
 * The original `promise` argument is **not** returned — the helper's
 * value-add is the cleanup side-effect, not promise transformation.
 * Callers that need to await the result read from `registry.get(id)`
 * or hold their own reference.
 *
 * @throws Error when `childId` already exists in the registry. Caller
 *   should report this to the LLM as a tool-error (duplicate task_id);
 *   the helper does NOT swallow the conflict because that would
 *   silently overwrite an in-flight child's tracking entry.
 */
declare function registerChildTask<T>(registry: ChildTaskRegistry<T>, childId: string, promise: Promise<T>): void;

/**
 * Generic per-task abort primitive — `requestTaskStop`.
 *
 * FEATURE_120 v0.7.39 Phase 3a (ADR-021). Coordinator-style agents need
 * to request that a specific in-flight child task exit gracefully. The
 * @kodax-ai/agent layer owns the abort-controller registry shape and
 * the abort-dispatch decision; agent-flavor wrappers (e.g. the coding
 * `task_stop` tool, Phase 3b) layer in domain framing such as the
 * `<coordinator-stop-request>` message tag.
 *
 * What this primitive owns:
 *   - A `TaskAbortRegistry` type alias = `Map<string, AbortController>`.
 *     The map is owned + mutated by the caller; the primitive only
 *     reads it. Callers use `registry.set(id, controller)` /
 *     `registry.delete(id)` directly — the standard `Map` mutators
 *     are simple enough that wrapping them adds no value.
 *   - `requestTaskStop({taskId, registry, reason?})` — looks up the
 *     controller, decides whether to abort, calls `controller.abort`,
 *     returns a structured outcome.
 *
 * Abort semantics (matches the existing FEATURE_115 soft-pause
 * principle): aborting fires the signal but does NOT interrupt any
 * synchronous tool that's already executing. The child's next abort
 * check (`signal.throwIfAborted()` or an `signal.aborted` poll)
 * surfaces the abort. This matches Node's AbortController contract.
 *
 * What this primitive does NOT do (deliberate):
 *   - Enqueue a coordinator-stop-request message — that's a
 *     coding-flavor convenience and uses the existing
 *     `routeMessage` primitive at the tool layer.
 *   - Track abort lifecycle / auto-cleanup the registry — the
 *     controller's lifetime is tied to its owning task's Promise;
 *     the caller removes the registry entry when the task settles
 *     (typically in a `.finally` chain alongside the child-task
 *     registry cleanup).
 *   - Time-out enforcement / retry — orthogonal concerns owned at
 *     higher layers if needed.
 */
/**
 * Registry mapping task ids to their owning AbortController.
 * Lifetime: created per parent-run, populated at child dispatch,
 * cleared when the child Promise settles.
 */
type TaskAbortRegistry = Map<string, AbortController>;
interface RequestTaskStopOptions {
    /** Target task id. Must exist as a key in `registry`. */
    readonly taskId: string;
    /** Registry of in-flight task abort controllers. */
    readonly registry: ReadonlyMap<string, AbortController>;
    /**
     * Optional cause forwarded to `AbortController.abort(reason)`.
     *   - Error → passed through verbatim (preserves stack / custom
     *     subclasses).
     *   - string → wrapped in `new Error(reason)`.
     *   - undefined → a default Error mentioning the taskId is
     *     fabricated so the child receives a non-empty signal.reason.
     */
    readonly reason?: string | Error;
}
type RequestTaskStopResult = {
    readonly ok: true;
    readonly taskId: string;
} | {
    readonly ok: false;
    readonly reason: 'unknown-target';
    readonly taskId: string;
} | {
    readonly ok: false;
    readonly reason: 'already-aborted';
    readonly taskId: string;
};
/**
 * Look up `taskId` in `registry`. If found and not yet aborted, abort
 * the controller with the supplied reason. Returns a discriminated
 * outcome so callers can render success / error UX without string
 * matching.
 *
 * `already-aborted` is reported separately from success because the
 * first-abort `signal.reason` is preserved verbatim — debugging
 * chains depend on the original cause not being overwritten by
 * subsequent stop requests.
 *
 * Synchronous: `AbortController.abort` is synchronous; no async work
 * is performed by this primitive.
 */
declare function requestTaskStop(opts: RequestTaskStopOptions): RequestTaskStopResult;

/**
 * FEATURE_125 (v0.7.41) — Team Mode Layer 1: per-instance state broadcast.
 *
 * Each running KodaX session registers a directory under
 * `<agentConfigHome>/instances/<pid>/` containing three files:
 *
 *   meta.json   — written once at registration; cwd / startedAt /
 *                  optional git branch + remote. Static for the session.
 *   state.json  — re-written whenever the session's `currentIntent`,
 *                  `agentPhase`, or active/recently-modified file set
 *                  changes. Read by sibling sessions for context.
 *   heartbeat   — empty file whose mtime is touched on every refresh.
 *                  Sibling sessions use the mtime to declare an instance
 *                  stale (default 30s of no heartbeat → cleanup).
 *
 * Atomic write strategy:
 *   - state.json is written via `<path>.tmp` + `rename()`. On POSIX the
 *     rename is atomic; on Windows it is atomic when source + target sit
 *     on the same filesystem (always true for `<agentConfigHome>/...`).
 *   - heartbeat is touched via `utimesSync()`. Cheap, no rename needed.
 *
 * Lifecycle:
 *   - `createStateWriter` writes meta.json + state.json + heartbeat once,
 *     then starts an interval timer (default 1000ms) that refreshes
 *     state.json and touches heartbeat.
 *   - `update(patch)` shallow-merges the patch into the in-memory state
 *     and flushes immediately so peer sessions see the change at the
 *     next tool boundary, not at the next heartbeat tick.
 *   - `shutdown()` clears the timer, removes the instance directory,
 *     and resolves. Idempotent — safe to call multiple times.
 *
 * Crash recovery:
 *   - If a process is killed mid-run, the directory is left on disk.
 *     The next session's discovery scan (S2, `instance-discovery.ts`)
 *     detects the stale heartbeat and removes the directory.
 *
 * DI-clean: every fs / clock dependency is injectable for hermetic tests.
 */
/**
 * Live session state surfaced to sibling KodaX sessions. Mirrors the
 * shape documented in `docs/features/v0.7.41.md#feature_125-step-1`.
 */
interface SessionStateSnapshot {
    readonly agentPhase: 'idle' | 'awaiting_llm' | 'running_tool';
    /** Single-line description of what the agent is currently doing. */
    readonly currentIntent?: string;
    /** Files the session is actively editing right now. */
    readonly activeFiles?: readonly string[];
    /** Files modified in the recent past (sibling sessions read this to detect "their content may be stale"). */
    readonly recentlyModifiedFiles?: readonly RecentlyModifiedFile[];
    /**
     * FEATURE_170 (v0.7.41) — optional one-line summary of the active
     * todo list. Lets sibling sessions display "they're currently
     * working on: <X>" without owning the todo store.
     */
    readonly currentTodoSummary?: CurrentTodoSummary;
}
interface RecentlyModifiedFile {
    readonly path: string;
    readonly modifiedAt: number;
}
interface CurrentTodoSummary {
    readonly inProgress?: string;
    readonly pendingCount: number;
    readonly completedCount: number;
}
interface SessionMeta {
    readonly cwd: string;
    readonly startedAt: number;
    readonly gitBranch?: string;
    readonly gitRemote?: string;
}
/**
 * Stored shape of `state.json` on disk — additive over SessionStateSnapshot.
 *
 * Reader contract (S2 `instance-discovery.ts`): parse the JSON, verify
 * `version === '1'` before reading any other field. On an unknown
 * version, log + skip the instance — this lets a newer writer coexist
 * with an older reader during an in-place upgrade.
 *
 * Fields are camelCase + a nested `meta` object (cwd / startedAt /
 * gitBranch / gitRemote). Do NOT assume the snake_case / flat shape
 * shown in early design-doc drafts — the typed interface here is the
 * ground truth; the doc has been updated to match.
 */
interface PersistedSessionState extends SessionStateSnapshot {
    readonly version: '1';
    readonly pid: number;
    readonly updatedAt: number;
    readonly meta: SessionMeta;
}
/** Minimal injectable fs surface — lets tests drive the writer without disk I/O. */
interface StateWriterFs {
    mkdirSync(dirPath: string, options: {
        recursive: true;
    }): void;
    writeFileSync(filePath: string, data: string): void;
    /** Atomic write helper: writes to `${filePath}.tmp` then renames. */
    atomicWriteSync(filePath: string, data: string): void;
    utimesSync(filePath: string, atime: number, mtime: number): void;
    rmSync(dirPath: string, options: {
        recursive: true;
        force: true;
    }): void;
    existsSync(targetPath: string): boolean;
}
interface StateWriterOptions {
    /** Defaults to `process.pid`. Tests / multi-instance fixtures override. */
    readonly pid?: number;
    readonly meta: SessionMeta;
    readonly initialState: SessionStateSnapshot;
    /** Defaults to 1000ms. Tests pass a faster tick. */
    readonly heartbeatIntervalMs?: number;
    /** Defaults to `Date.now`. Tests inject a controllable clock. */
    readonly clock?: () => number;
    /** Defaults to {@link REAL_FS}. Tests inject an in-memory fs. */
    readonly fs?: StateWriterFs;
    /**
     * Root directory under which `<pid>/` is created. Defaults to
     * `getAgentConfigPath('instances')`. Tests can point at a temp dir.
     */
    readonly instancesRoot?: string;
}
interface StateWriter {
    readonly pid: number;
    readonly instanceDir: string;
    /** Apply a partial update to the in-memory state and flush to disk. */
    update(patch: Partial<SessionStateSnapshot>): void;
    /** Touch the heartbeat and re-write state.json without changing state. */
    refresh(): void;
    /** Stop the interval, remove the instance directory, resolve when done. */
    shutdown(): Promise<void>;
    /** Read-only snapshot of the current state. Useful for tests. */
    getState(): SessionStateSnapshot;
}
/**
 * Construct a writer, register the instance directory, and start the
 * heartbeat interval. Returns synchronously so the caller can rely on
 * `instanceDir` being live the moment the function returns.
 */
declare function createStateWriter(options: StateWriterOptions): StateWriter;

/**
 * FEATURE_125 (v0.7.41) — Team Mode Layer 2a: sibling instance discovery.
 *
 * Scans `<agentConfigHome>/instances/`, filters out the caller's own
 * pid, drops any directory whose `heartbeat` file is stale (>30s of no
 * touch), parses `state.json`, validates `version === '1'`, and returns
 * a typed list of live sibling instances. Stale directories are
 * optionally reaped (`reapStale: true`) — the next session entering
 * Team Mode does the cleanup so crashed processes don't accumulate
 * forever.
 *
 * Per-instance failures (corrupt JSON, vanished file mid-read, permission
 * error) are isolated: the bad directory is logged + skipped, the rest
 * of the scan completes. Discovery NEVER throws to its caller — a
 * Team-Mode-disabled return is `[]`, not an exception. This keeps the
 * worker LLM call path resilient to one peer session's bad state.
 *
 * DI-clean: every fs / clock / logger dependency is injectable so
 * hermetic tests can simulate stale / corrupt / mid-scan-deletion
 * scenarios without real disk.
 */

/** A sibling KodaX session that passed stale + version-guard checks. */
interface DiscoveredInstance {
    readonly pid: number;
    readonly state: PersistedSessionState;
    /** Heartbeat mtime in ms (epoch). Useful for ordering "freshest first". */
    readonly heartbeatMtimeMs: number;
}
/** Minimal injectable fs surface used by `discoverInstances`. */
interface InstanceDiscoveryFs {
    existsSync(targetPath: string): boolean;
    readdirSync(dirPath: string): string[];
    /** Returns the mtime of the path in ms, or `null` if missing / unreadable. */
    statMtimeMs(filePath: string): number | null;
    readFileSync(filePath: string, encoding: 'utf8'): string;
    rmSync(dirPath: string, options: {
        recursive: true;
        force: true;
    }): void;
}
interface DiscoveryOptions {
    /**
     * pid to exclude from the result. Defaults to `process.pid` — the
     * caller's own state.json should not appear in its own sibling list.
     */
    readonly excludePid?: number;
    /**
     * Heartbeat mtime older than `now - staleThresholdMs` → directory is
     * stale. Default 30_000 (matches v0.7.41 spec).
     */
    readonly staleThresholdMs?: number;
    /**
     * When true, stale directories are removed during the scan (best-
     * effort `rmSync(force:true)`; failure is swallowed). When false,
     * stale directories are skipped but left on disk. Defaults to false
     * — wire from the session-startup path with `true` so crashed-process
     * dirs don't accumulate.
     */
    readonly reapStale?: boolean;
    readonly clock?: () => number;
    readonly fs?: InstanceDiscoveryFs;
    readonly instancesRoot?: string;
    /** Per-instance failure log; defaults to a no-op. Pass `console.warn` in dev. */
    readonly logger?: (message: string) => void;
}
/**
 * Synchronous discovery scan. Returns a freshness-sorted array
 * (newest heartbeat first) so callers that want only the N most-recent
 * siblings can slice without re-sorting.
 *
 * Never throws. A missing `<instancesRoot>` directory means the user
 * is the first session ever on this machine → `[]`. A scan failure on
 * one entry is logged + skipped, not propagated.
 */
declare function discoverInstances(options?: DiscoveryOptions): DiscoveredInstance[];

export { requestTaskStop as $, buildAssistantMessageFromLlmResult as K, buildToolResultMessage as L, MAX_TOOL_LOOP_ITERATIONS as M, collectGuardrails as N, createAgent as Q, createHandoff as U, createStateWriter as V, discoverInstances as W, executeRunnerToolCall as X, isRunnableTool as Y, isRunnerLlmResult as Z, registerChildTask as _, runInputGuardrails as a0, runOutputGuardrails as a1, runToolAfterGuardrails as a2, runToolBeforeGuardrails as a3, GuardrailBlockedError as g, GuardrailEscalateError as i };
export type { Agent as A, StateWriterFs as B, ChildTaskRegistry as C, DiscoveredInstance as D, StateWriterOptions as E, ToolBeforeOutcome as F, Guardrail as G, Handoff as H, InputGuardrail as I, ToolGuardrail as J, OutputGuardrail as O, PersistedSessionState as P, ReasoningDepth as R, SessionMeta as S, TaskAbortRegistry as T, AgentMessage as a, AgentMiddlewareDeclaration as b, AgentReasoningProfile as c, AgentTool as d, CurrentTodoSummary as e, DiscoveryOptions as f, GuardrailContext as h, GuardrailVerdict as j, InstanceDiscoveryFs as k, RecentlyModifiedFile as l, RequestTaskStopOptions as m, RequestTaskStopResult as n, RunnableTool as o, RunnerLlmResult as p, RunnerLlmReturn as q, RunnerToolCall as r, RunnerToolContext as s, RunnerToolObserver as t, RunnerToolResult as u, SessionStateSnapshot as v, Span as w, SpanData as x, SpanError as y, StateWriter as z };
