import { S as SandboxClient, d as LoopSandboxPlacement } from '../types-ESeMOj94.js';
import { F as FleetHandle, D as DelegationExecutor, a as DelegationTaskQueue, b as FeedbackStore, c as DelegateFeedbackResult, d as DelegateFeedbackArgs, U as UiAuditorDelegate, e as DelegateUiAuditArgs, f as DelegateUiAuditResult, g as DelegationHistoryResult, h as DelegationHistoryArgs, i as DelegationStatusResult, j as DelegationStatusArgs } from '../coordination-CuDLO8wj.js';
export { A as AnalystRegistry, C as CappedDelegationTrace, k as CoderDelegate, l as CoderReview, m as CoderReviewer, n as CoordinationEvent, o as CoordinationTools, p as CoordinationToolsOptions, q as DELEGATE_DESCRIPTION, r as DELEGATE_INPUT_SCHEMA, s as DELEGATE_TOOL_NAME, t as DELEGATION_TRACE_MAX_BYTES, u as DELEGATION_TRACE_MAX_SPANS, v as DelegateArgs, w as DelegateCodeArgs, x as DelegateCodeConfig, y as DelegateCodeResult, z as DelegateHandlerOptions, B as DelegateResearchArgs, E as DelegateResearchConfig, G as DelegateResearchResult, H as DelegateResult, I as DelegateRunCtx, J as DelegateUiAuditConfig, K as DelegateUiAuditRoute, L as DelegationError, M as DelegationFeedbackSnapshot, N as DelegationHistoryEntry, O as DelegationPersistenceError, P as DelegationProfile, Q as DelegationProgress, R as DelegationRecord, S as DelegationResultPayload, T as DelegationResumeContext, V as DelegationResumeDriver, W as DelegationResumeTick, X as DelegationRunContext, Y as DelegationStateCorruptError, Z as DelegationStatus, _ as DelegationStore, $ as DelegationTaskQueueOptions, a0 as DelegationTraceCaps, a1 as DelegationTraceCollector, a2 as DelegationTraceSpan, a3 as DetachedSessionDelegateOptions, a4 as DetachedSessionRefParts, a5 as DetachedTurn, a6 as DetachedTurnResumeDriverOptions, a7 as DetachedWinnerSelection, a8 as DriveTurnCapableBox, a9 as DriveTurnTick, aa as FeedbackEvent, ab as FeedbackRating, ac as FeedbackRefersTo, ad as FileDelegationStore, ae as FileDelegationStoreOptions, af as FleetWorkspaceExecutorOptions, ag as InMemoryDelegationStore, ah as InMemoryFeedbackStore, ai as JsonRpcMessage, aj as JsonRpcResponse, ak as MakeWorkerAgent, al as McpServer, am as McpServerOptions, an as McpToolDescriptor, ao as McpTransport, ap as Question, aq as QuestionDecision, ar as QuestionPolicy, as as QuestionRecord, at as ResearchOutputShape, au as ResearchSource, av as RunDetachedTurnOptions, aw as SettleDetachedCoderTurnOptions, ax as SettledWorker, ay as SiblingSandboxExecutorOptions, az as SubmitInput, aA as SubmitOutput, aB as TraceContext, aC as UiAuditorDelegationOutput, aD as buildDelegationTraceSpans, aE as capDelegationTrace, aF as coderTaskFromArgs, aG as composeLoopTraceEmitters, aH as createCoordinationTools, aI as createDelegateHandler, aJ as createDelegationTraceCollector, aK as createDetachedTurnResumeDriver, aL as createFleetWorkspaceExecutor, aM as createInProcessTransport, aN as createMcpServer, aO as createPropagatingTraceEmitter, aP as createSiblingSandboxExecutor, aQ as detachedSessionDelegate, aR as detachedTurnEvents, aS as eventToSnapshot, aT as formatDetachedSessionRef, aU as hashIdempotencyInput, aV as parseDetachedSessionRef, aW as readTraceContextFromEnv, aX as runDetachedTurn, aY as settleDetachedCoderTurn, aZ as traceContextToEnv, a_ as validateDelegateArgs } from '../coordination-CuDLO8wj.js';
import { L as LocalHarness, r as runLocalHarness } from '../local-harness-sI0S_XNA.js';
export { a as LocalHarnessResult, R as RunLocalHarnessOptions } from '../local-harness-sI0S_XNA.js';
import { G as GitRunner } from '../worktree-harness-CX_McRLp.js';
export { C as CreateWorktreeOptions, b as DiffOptions, c as DiffResult, R as RemoveWorktreeOptions, d as WorktreeHandle, e as captureWorktreeDiff, f as createWorktree, r as removeWorktree } from '../worktree-harness-CX_McRLp.js';
export { C as CreateKbGateOptions, F as FactCandidate, a as FactJudge, b as FactJudgeVerdict, K as KbGateResult, c as createKbGate } from '../kb-gate-CwHO0vz6.js';
export { m as mcpToolsForRuntimeMcp, a as mcpToolsForRuntimeMcpSubset } from '../openai-tools-BnrOmGjN.js';
import { AnalystFinding } from '@tangle-network/agent-eval';
import { U as UiLens } from '../substrate-DO2GHNg2.js';
import '@tangle-network/sandbox';
import '../types-Driepl87.js';
import '@tangle-network/agent-interface';
import '../otel-export-BKmNwiCb.js';
import '../router-client-r8y_VFVM.js';
import '../environment-provider.js';
import '@tangle-network/agent-interface/environment-provider';
import 'node:child_process';

/**
 *
 * Helpers extracted from `bin.ts` so the env-detection + executor-selection
 * logic is unit-testable without spawning a subprocess. The bin imports from
 * here; tests import from here directly.
 *
 * @experimental
 */

/** @experimental */
interface DetectExecutorArgs {
    sandboxClient: SandboxClient;
    /** Raw env (defaults to `process.env`). Pass an explicit map for tests. */
    env?: Record<string, string | undefined>;
    /**
     * Override how a fleet handle is resolved from the client + fleet id. The
     * default reads `client.fleets.get(fleetId)` and validates the returned
     * shape against the structural `FleetHandle` contract.
     */
    resolveFleet?: (client: SandboxClient, fleetId: string) => Promise<FleetHandle>;
}
/**
 * Pick the right executor for an MCP server invocation based on env vars.
 *
 * - `TANGLE_FLEET_ID` set → fleet-workspace placement; resolves the handle
 *   via `sandboxClient.fleets.get(...)`.
 * - Otherwise → sibling-sandbox placement; each delegation creates a fresh
 *   sandbox via `sandboxClient.create(...)`.
 *
 * Fails loud (throws) when fleet mode is requested but the SDK shape is
 * incompatible — the operator chose fleet semantics, silently degrading to
 * sibling mode would lie about workspace topology.
 *
 * @experimental
 */
declare function detectExecutor(args: DetectExecutorArgs): Promise<DelegationExecutor>;

/** @experimental */
interface InProcessExecutorOptions {
    /** Absolute path to the git repo (the workspace). Worktrees go under `<repoRoot>/.agent-worktrees/`. */
    repoRoot: string;
    /** Harnesses to round-robin across `create()` calls. One entry = no fanout. Default `['claude']`. */
    harnesses?: ReadonlyArray<LocalHarness>;
    /** Optional per-delegation test command run in the worktree after the harness exits. */
    testCmd?: string;
    /** Optional per-delegation typecheck command. Same shape as `testCmd`. */
    typecheckCmd?: string;
    /** Wall-clock cap per harness subprocess (ms). Default 5min. */
    harnessTimeoutMs?: number;
    /** Wall-clock cap per test/typecheck subprocess (ms). Default 2min. */
    postCheckTimeoutMs?: number;
    /** Test seam — override the git runner used by the worktree helpers. */
    runGit?: GitRunner;
    /** Test seam — override the harness runner (defaults to the real CLI via `runLocalHarness`). */
    runHarness?: typeof runLocalHarness;
    /** Test seam — override the post-check runner (defaults to a `sh -c` spawn). A throw is folded
     *  into a non-fatal `{exitCode:-1}` so a broken check command fails the signal, not the run. */
    runPostCheck?: (cmd: string, cwd: string, signal?: AbortSignal) => Promise<{
        exitCode: number;
        stdout: string;
        stderr: string;
    }>;
}
/** @experimental */
interface InProcessExecutorDescribePlacement extends LoopSandboxPlacement {
    /** Worktree path in the parent sandbox's filesystem (set so traces correlate to on-disk artifacts). */
    worktreePath?: string;
    /** Which harness handled this delegation. */
    harness?: LocalHarness;
}
/**
 * Build an in-process executor. Returns a {@link DelegationExecutor} whose `client.create()`
 * returns a minimal virtual `SandboxInstance`; the kernel calls `streamPrompt(msg)` on it, which
 * runs the shared worktree-harness core and emits one `result` event whose `data.result` is the
 * raw `WorktreeHarnessResult` (the content-addressed patch artifact). The authored profile
 * (`backend.profile`) threads its systemPrompt + model into the harness via the core.
 *
 * @experimental
 */
declare function createInProcessExecutor(options: InProcessExecutorOptions): DelegationExecutor;

/**
 *
 * The trace-analyst KIND directory — the operator's lenses, as composable DATA.
 *
 * An analyst is not one question. A kind is ONE lens (completeness, correctness, policy, efficiency,
 * tool-use, …); each emits `AnalystFinding`s tagged by its `area`. The driver `list_analysts` to see
 * the menu, `run_analyst(kind, worker)` to apply a lens, and `define_analyst` to author a new one —
 * so at test time you compose the exact lenses a domain needs (maximum specificity), not one generic
 * reviewer. The kinds are data, the runner is generic, and the finding shape + firewall are reused
 * from agent-eval / the keystone — never re-derived.
 *
 * A kind here is a lightweight lens (`Check`); it is a deliberate SUBSET of agent-eval's full
 * `TraceAnalystKindSpec`, so a kind that needs the heavy agentic actor (sub-agent recursion, tools,
 * goldens) upgrades to `createTraceAnalystKind` without changing this directory's surface.
 *
 * @experimental
 */

/** One lens — a composable analyst kind. Identity fields mirror `TraceAnalystKindSpec` so a kind is
 *  upgradeable to the full agentic factory; `lookFor` is the lens question the actor applies. */
interface Check {
    readonly id: string;
    readonly description: string;
    /** Coarse classification stamped on every finding this kind emits (the renderer groups by it). */
    readonly area: string;
    readonly version: string;
    /** The lens — what this analyst looks for in the trace. */
    readonly lookFor: string;
}
/** The built-in lens directory. Domain-blind (about any agent trace); compose at test time. */
declare const defaultChecks: Record<string, Check>;
/** Lift validated raw rows into `AnalystFinding`s (agent-eval `makeFinding` stamps `finding_id`/
 *  `produced_at`), then enforce the trace-derived firewall (selector ≠ judge). Pure — no LLM. */
declare function liftFindings(kind: Check, rows: unknown[], producedAt: string): AnalystFinding[];
/** Render a worker's trace (tool calls + results) into the text an analyst lens reads. Generic over
 *  the trace shape: a `{ messages }` conversation, a bare message array, else stringified. */
declare function renderTrace(trace: unknown): string;
interface CheckRunnerOptions {
    routerBaseUrl: string;
    routerKey: string;
    model: string;
    /** Test/override seam — replace the LLM call. Default: a router chat completion. */
    chat?: (system: string, user: string) => Promise<string>;
}
/** Run ONE lens over a trace → findings. Generic over any kind: prompt = the lens + the agent-eval
 *  finding schema; the model's JSON array is parsed (`parseRawFinding`), lifted, and firewalled. */
declare function runCheck(kind: Check, trace: unknown, opts: CheckRunnerOptions, producedAt: string): Promise<AnalystFinding[]>;
/**
 * Build a `run_analyst` runner over a kind directory.
 * Returns findings, or a typed error for an unknown kind. `producedAt` is
 * passed in because replay-safe paths must not read `Date.now`.
 */
declare function makeCheckRunner(kinds: Record<string, Check>, opts: CheckRunnerOptions): (kindId: string, trace: unknown, producedAt: string) => Promise<AnalystFinding[] | {
    error: string;
}>;

/**
 *
 * `delegate_feedback` MCP tool — synchronous record of agent / user /
 * downstream-judge feedback on a delegation, artifact, or outcome.
 *
 * The store is append-only. Every rating is its own event; no dedupe.
 * When `refersTo.kind === 'delegation'`, the snapshot is also attached
 * to the matching queue record so `delegation_history` surfaces it
 * inline without a join.
 *
 * @experimental
 */

/** MCP tool name for the `delegate_feedback` feedback-recording tool. @experimental */
declare const DELEGATE_FEEDBACK_TOOL_NAME = "delegate_feedback";
/** Human-readable description of the `delegate_feedback` MCP tool, injected into the tool manifest. @experimental */
declare const DELEGATE_FEEDBACK_DESCRIPTION: string;
/** JSON Schema for `delegate_feedback` tool arguments (`refersTo`, `rating`, `by`, optional fields). @experimental */
declare const DELEGATE_FEEDBACK_INPUT_SCHEMA: {
    readonly type: "object";
    readonly properties: {
        readonly refersTo: {
            readonly type: "object";
            readonly properties: {
                readonly kind: {
                    readonly type: "string";
                    readonly enum: readonly ["delegation", "artifact", "outcome"];
                };
                readonly ref: {
                    readonly type: "string";
                };
            };
            readonly required: readonly ["kind", "ref"];
            readonly additionalProperties: false;
        };
        readonly rating: {
            readonly type: "object";
            readonly properties: {
                readonly score: {
                    readonly type: "number";
                    readonly minimum: 0;
                    readonly maximum: 1;
                };
                readonly label: {
                    readonly type: "string";
                    readonly enum: readonly ["good", "bad", "neutral", "mixed"];
                };
                readonly notes: {
                    readonly type: "string";
                };
            };
            readonly required: readonly ["score", "notes"];
            readonly additionalProperties: false;
        };
        readonly by: {
            readonly type: "string";
            readonly enum: readonly ["agent", "user", "downstream-judge"];
        };
        readonly capturedAt: {
            readonly type: "string";
        };
        readonly namespace: {
            readonly type: "string";
        };
    };
    readonly required: readonly ["refersTo", "rating", "by"];
    readonly additionalProperties: false;
};
/** Parse and validate raw MCP tool input into typed `DelegateFeedbackArgs`; throws `TypeError` on bad input. @experimental */
declare function validateDelegateFeedbackArgs(raw: unknown): DelegateFeedbackArgs;
/** @experimental */
interface DelegateFeedbackHandlerOptions {
    queue: DelegationTaskQueue;
    store: FeedbackStore;
    generateId?: () => string;
    now?: () => string;
}
/** Build the MCP tool handler that persists feedback events and attaches them to delegation records. @experimental */
declare function createDelegateFeedbackHandler(options: DelegateFeedbackHandlerOptions): (raw: unknown) => Promise<DelegateFeedbackResult>;

/**
 *
 * `delegate_ui_audit` MCP tool — async kickoff for UI audit runs. Validates
 * the input, computes an idempotency key over the canonical fields, hands
 * the task to the queue, and returns a taskId. Identical inputs return
 * the same taskId.
 *
 * The handler does not import the auditor profile directly — consumers
 * inject a `UiAuditorDelegate` via `createMcpServer({ uiAuditorDelegate })`.
 * The delegate is the seam where the consumer chooses the judge (vision
 * model) and the `SandboxClient` (in-process Playwright vs fleet vs
 * remote browser). agent-runtime ships the in-process client under
 * `./profiles` so consumers who want the canonical setup can wire it
 * with a few lines.
 *
 * @experimental
 */

/** MCP tool name for the `delegate_ui_audit` async kickoff tool. @experimental */
declare const DELEGATE_UI_AUDIT_TOOL_NAME = "delegate_ui_audit";
/** Human-readable description of the `delegate_ui_audit` MCP tool, injected into the tool manifest. @experimental */
declare const DELEGATE_UI_AUDIT_DESCRIPTION: string;
/** JSON Schema for `delegate_ui_audit` tool arguments (`workspaceDir`, `routes`, optional config). @experimental */
declare const DELEGATE_UI_AUDIT_INPUT_SCHEMA: {
    readonly type: "object";
    readonly properties: {
        readonly workspaceDir: {
            readonly type: "string";
            readonly description: "Absolute path for the audit workspace.";
        };
        readonly routes: {
            readonly type: "array";
            readonly items: {
                readonly type: "object";
                readonly properties: {
                    readonly name: {
                        readonly type: "string";
                        readonly description: "Stable route name (used in screenshot filenames).";
                    };
                    readonly url: {
                        readonly type: "string";
                        readonly description: "Fully-qualified URL.";
                    };
                    readonly viewports: {
                        readonly type: "array";
                        readonly items: {
                            readonly type: "object";
                            readonly properties: {
                                readonly width: {
                                    readonly type: "integer";
                                    readonly minimum: 1;
                                };
                                readonly height: {
                                    readonly type: "integer";
                                    readonly minimum: 1;
                                };
                            };
                            readonly required: readonly ["width", "height"];
                            readonly additionalProperties: false;
                        };
                        readonly description: "Viewports to capture at. Default [{1280, 800}].";
                    };
                    readonly fullPage: {
                        readonly type: "boolean";
                    };
                    readonly waitFor: {
                        readonly type: "string";
                        readonly description: "CSS selector to wait for before capturing.";
                    };
                };
                readonly required: readonly ["name", "url"];
                readonly additionalProperties: false;
            };
            readonly minItems: 1;
        };
        readonly namespace: {
            readonly type: "string";
            readonly description: "Multi-tenant scope.";
        };
        readonly config: {
            readonly type: "object";
            readonly properties: {
                readonly lenses: {
                    readonly type: "array";
                    readonly items: {
                        readonly type: "string";
                        readonly enum: readonly UiLens[];
                    };
                    readonly description: "Lenses to iterate. Default: every lens except \"other\".";
                };
                readonly maxIterations: {
                    readonly type: "integer";
                    readonly minimum: 1;
                };
                readonly maxConcurrency: {
                    readonly type: "integer";
                    readonly minimum: 1;
                };
                readonly productContext: {
                    readonly type: "string";
                };
            };
            readonly additionalProperties: false;
        };
    };
    readonly required: readonly ["workspaceDir", "routes"];
    readonly additionalProperties: false;
};
/** Parse and validate raw MCP tool input into typed `DelegateUiAuditArgs`; throws `TypeError` on bad input. @experimental */
declare function validateDelegateUiAuditArgs(raw: unknown): DelegateUiAuditArgs;
/** @experimental */
interface DelegateUiAuditHandlerOptions {
    queue: DelegationTaskQueue;
    delegate: UiAuditorDelegate;
    estimateDurationMs?: (args: DelegateUiAuditArgs) => number;
}
/** Build the MCP tool handler that validates input, deduplicates via idempotency key, and enqueues a UI audit. @experimental */
declare function createDelegateUiAuditHandler(options: DelegateUiAuditHandlerOptions): (raw: unknown) => Promise<DelegateUiAuditResult>;

/**
 *
 * `delegation_history` MCP tool — synchronous read of past delegations.
 * The agent uses this for self-introspection — "have I delegated this
 * kind of task before? did it work?" — and calibration.
 *
 * @experimental
 */

/** MCP tool name for the `delegation_history` read-past-delegations tool. @experimental */
declare const DELEGATION_HISTORY_TOOL_NAME = "delegation_history";
/** Human-readable description of the `delegation_history` MCP tool, injected into the tool manifest. @experimental */
declare const DELEGATION_HISTORY_DESCRIPTION: string;
/** JSON Schema for `delegation_history` tool arguments (optional `namespace`, `profile`, `since`, `limit`). @experimental */
declare const DELEGATION_HISTORY_INPUT_SCHEMA: {
    readonly type: "object";
    readonly properties: {
        readonly namespace: {
            readonly type: "string";
        };
        readonly profile: {
            readonly type: "string";
            readonly enum: readonly ["coder", "researcher"];
        };
        readonly since: {
            readonly type: "string";
            readonly description: "ISO datetime — earliest startedAt to include.";
        };
        readonly limit: {
            readonly type: "integer";
            readonly minimum: 1;
            readonly maximum: 500;
        };
    };
    readonly additionalProperties: false;
};
/** Parse and validate raw MCP tool input into typed `DelegationHistoryArgs`; throws `TypeError` on bad input. @experimental */
declare function validateDelegationHistoryArgs(raw: unknown): DelegationHistoryArgs;
/** @experimental */
interface DelegationHistoryHandlerOptions {
    queue: DelegationTaskQueue;
}
/** Build the MCP tool handler that reads filtered past delegations from a `DelegationTaskQueue`. @experimental */
declare function createDelegationHistoryHandler(options: DelegationHistoryHandlerOptions): (raw: unknown) => Promise<DelegationHistoryResult>;

/**
 *
 * `delegation_status` MCP tool — synchronous poll. Returns the current
 * state machine + optional progress + final result (when terminal).
 *
 * @experimental
 */

/** MCP tool name for the `delegation_status` synchronous-poll tool. @experimental */
declare const DELEGATION_STATUS_TOOL_NAME = "delegation_status";
/** Human-readable description of the `delegation_status` MCP tool, injected into the tool manifest. @experimental */
declare const DELEGATION_STATUS_DESCRIPTION: string;
/** JSON Schema for `delegation_status` tool arguments (`taskId` + optional `includeTrace`). @experimental */
declare const DELEGATION_STATUS_INPUT_SCHEMA: {
    readonly type: "object";
    readonly properties: {
        readonly taskId: {
            readonly type: "string";
            readonly description: "Returned by delegate_ui_audit.";
        };
        readonly includeTrace: {
            readonly type: "boolean";
            readonly description: "Also return the journaled loop-trace span tree for this delegation. Default false.";
        };
    };
    readonly required: readonly ["taskId"];
    readonly additionalProperties: false;
};
/** Parse and validate raw MCP tool input into typed `DelegationStatusArgs`; throws `TypeError` on bad input. @experimental */
declare function validateDelegationStatusArgs(raw: unknown): DelegationStatusArgs;
/** @experimental */
interface DelegationStatusHandlerOptions {
    queue: DelegationTaskQueue;
}
/** Build the MCP tool handler that polls a `DelegationTaskQueue` for task status. @experimental */
declare function createDelegationStatusHandler(options: DelegationStatusHandlerOptions): (raw: unknown) => Promise<DelegationStatusResult>;

export { type Check, type CheckRunnerOptions, DELEGATE_FEEDBACK_DESCRIPTION, DELEGATE_FEEDBACK_INPUT_SCHEMA, DELEGATE_FEEDBACK_TOOL_NAME, DELEGATE_UI_AUDIT_DESCRIPTION, DELEGATE_UI_AUDIT_INPUT_SCHEMA, DELEGATE_UI_AUDIT_TOOL_NAME, DELEGATION_HISTORY_DESCRIPTION, DELEGATION_HISTORY_INPUT_SCHEMA, DELEGATION_HISTORY_TOOL_NAME, DELEGATION_STATUS_DESCRIPTION, DELEGATION_STATUS_INPUT_SCHEMA, DELEGATION_STATUS_TOOL_NAME, DelegateFeedbackArgs, DelegateFeedbackResult, DelegateUiAuditArgs, DelegateUiAuditResult, DelegationExecutor, DelegationHistoryArgs, DelegationHistoryResult, DelegationStatusArgs, DelegationStatusResult, DelegationTaskQueue, type DetectExecutorArgs, FeedbackStore, FleetHandle, GitRunner, type InProcessExecutorDescribePlacement, type InProcessExecutorOptions, LocalHarness, UiAuditorDelegate, createDelegateFeedbackHandler, createDelegateUiAuditHandler, createDelegationHistoryHandler, createDelegationStatusHandler, createInProcessExecutor, defaultChecks, detectExecutor, liftFindings, makeCheckRunner, renderTrace, runCheck, runLocalHarness, validateDelegateFeedbackArgs, validateDelegateUiAuditArgs, validateDelegationHistoryArgs, validateDelegationStatusArgs };
