import {
  createPropagatingTraceEmitter,
  readTraceContextFromEnv,
  traceContextToEnv
} from "../chunk-4WXGK6GV.js";
import {
  mcpToolsForRuntimeMcp,
  mcpToolsForRuntimeMcpSubset
} from "../chunk-J3N6GODQ.js";
import {
  createKbGate
} from "../chunk-SGKPNBXE.js";
import {
  assertTraceDerivedFindings,
  runCoderChecks,
  selectValidWinner
} from "../chunk-QDVLTRCP.js";
import {
  DELEGATE_DESCRIPTION,
  DELEGATE_FEEDBACK_DESCRIPTION,
  DELEGATE_FEEDBACK_INPUT_SCHEMA,
  DELEGATE_FEEDBACK_TOOL_NAME,
  DELEGATE_INPUT_SCHEMA,
  DELEGATE_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,
  DELEGATION_TRACE_MAX_BYTES,
  DELEGATION_TRACE_MAX_SPANS,
  DelegationPersistenceError,
  DelegationStateCorruptError,
  DelegationTaskQueue,
  FileDelegationStore,
  InMemoryDelegationStore,
  InMemoryFeedbackStore,
  buildDelegationTraceSpans,
  capDelegationTrace,
  captureWorktreeDiff,
  composeLoopTraceEmitters,
  createCoordinationTools,
  createDelegateFeedbackHandler,
  createDelegateHandler,
  createDelegateUiAuditHandler,
  createDelegationHistoryHandler,
  createDelegationStatusHandler,
  createDelegationTraceCollector,
  createInProcessTransport,
  createMcpServer,
  createSandboxForSpec,
  createWorktree,
  eventToSnapshot,
  hashIdempotencyInput,
  removeWorktree,
  runLoop,
  runWorktreeHarness,
  validateDelegateArgs,
  validateDelegateFeedbackArgs,
  validateDelegateUiAuditArgs,
  validateDelegationHistoryArgs,
  validateDelegationStatusArgs
} from "../chunk-SSA6OERV.js";
import "../chunk-UD4BHQMI.js";
import {
  deleteBoxSafe,
  sleep,
  throwAbort,
  throwIfAborted
} from "../chunk-BZF3KQ6G.js";
import "../chunk-4J6RBI3K.js";
import {
  runLocalHarness
} from "../chunk-7LO5GMAO.js";
import {
  ValidationError
} from "../chunk-YEJR7IXO.js";
import {
  coderTaskToPrompt
} from "../chunk-5IBQAPVB.js";
import "../chunk-DPEUKJRO.js";
import "../chunk-DGUM43GV.js";

// src/mcp/executor.ts
function createSiblingSandboxExecutor(options) {
  const underlying = options.client;
  const client = {
    create(opts) {
      return underlying.create(opts);
    },
    describePlacement(box) {
      return { kind: "sibling", sandboxId: readId(box) };
    }
  };
  return {
    client,
    placement: "sibling",
    describe() {
      return "sibling-sandbox (each delegation = fresh sandbox via client.create)";
    }
  };
}
function createFleetWorkspaceExecutor(options) {
  const fleet = options.fleet;
  const exclude = new Set(options.excludeMachineIds ?? []);
  let callIndex = 0;
  const placementBySandboxId = /* @__PURE__ */ new Map();
  const client = {
    async create() {
      const ids = fleet.ids.filter((id) => !exclude.has(id));
      if (ids.length === 0) {
        throw new Error(
          `agent-runtime: fleet ${fleet.fleetId} has no eligible worker machines (ids=[${fleet.ids.join(",")}], excluded=[${[...exclude].join(",")}])`
        );
      }
      const selector = options.selectMachine;
      const machineId = selector ? selector({ callIndex, ids }) : ids[callIndex % ids.length];
      callIndex += 1;
      if (typeof machineId !== "string" || machineId.length === 0) {
        throw new Error("agent-runtime: fleet executor selectMachine returned an empty machine id");
      }
      const box = await fleet.sandbox(machineId);
      const sandboxId = readId(box);
      if (sandboxId) placementBySandboxId.set(sandboxId, { machineId });
      return box;
    },
    describePlacement(box) {
      const sandboxId = readId(box);
      const recorded = sandboxId ? placementBySandboxId.get(sandboxId) : void 0;
      return {
        kind: "fleet",
        sandboxId,
        fleetId: fleet.fleetId,
        machineId: recorded?.machineId
      };
    }
  };
  return {
    client,
    placement: "fleet",
    describe() {
      const excluded = exclude.size > 0 ? ` (excluded=[${[...exclude].join(",")}])` : "";
      return `fleet-workspace (fleetId=${fleet.fleetId}, machines=[${fleet.ids.join(",")}]${excluded})`;
    }
  };
}
function readId(box) {
  const raw = box.id;
  return typeof raw === "string" && raw.length > 0 ? raw : void 0;
}

// src/mcp/in-process-executor.ts
import { randomUUID } from "crypto";
var DEFAULT_HARNESS_TIMEOUT_MS = 5 * 60 * 1e3;
var DEFAULT_POSTCHECK_TIMEOUT_MS = 2 * 60 * 1e3;
function createInProcessExecutor(options) {
  const harnesses = options.harnesses && options.harnesses.length > 0 ? [...options.harnesses] : ["claude"];
  const runPostCheck = options.runPostCheck ?? defaultRunPostCheck;
  const runCommand = async ({
    command,
    cwd,
    signal
  }) => {
    try {
      const r = await runPostCheck(command, cwd, signal);
      return { exitCode: r.exitCode, output: r.stderr || r.stdout };
    } catch (err) {
      return { exitCode: -1, output: err instanceof Error ? err.message : String(err) };
    }
  };
  let callIndex = 0;
  const client = {
    async create(opts) {
      const runId = randomUUID();
      const harness = harnesses[callIndex % harnesses.length];
      callIndex += 1;
      const profile = opts?.backend?.profile ?? { name: `in-process-${harness}` };
      const virtual = {
        id: `in-process-${runId}`,
        __inProcess: { runId, harness },
        async *streamPrompt(message, promptOpts) {
          const taskPrompt = typeof message === "string" ? message : message.map(
            (p) => typeof p === "object" && p && "text" in p ? String(p.text) : ""
          ).join("\n");
          const run = await runWorktreeHarness({
            repoRoot: options.repoRoot,
            profile,
            harness,
            taskPrompt,
            runId,
            harnessTimeoutMs: options.harnessTimeoutMs ?? DEFAULT_HARNESS_TIMEOUT_MS,
            checkTimeoutMs: options.postCheckTimeoutMs ?? DEFAULT_POSTCHECK_TIMEOUT_MS,
            ...options.testCmd !== void 0 ? { testCmd: options.testCmd } : {},
            ...options.typecheckCmd !== void 0 ? { typecheckCmd: options.typecheckCmd } : {},
            ...options.runGit ? { runGit: options.runGit } : {},
            ...options.runHarness ? { runHarness: options.runHarness } : {},
            runCommand,
            ...promptOpts?.signal ? { signal: promptOpts.signal } : {}
          });
          this.__inProcess.worktree = run.worktree;
          try {
            yield {
              type: "in_process.harness.started",
              data: { runId, harness, worktreePath: run.worktree.path, command: harness }
            };
            const h = run.result.harness;
            yield {
              type: "in_process.harness.ended",
              data: {
                runId,
                exitCode: h.exitCode,
                durationMs: h.durationMs,
                killedBySignal: h.killedBySignal,
                timedOut: h.timedOut,
                stdoutBytes: h.stdout.length,
                stderrBytes: h.stderr.length
              }
            };
            yield {
              type: "result",
              data: {
                result: run.result,
                source: "in-process-executor",
                harness,
                runId
              }
            };
          } finally {
            await run.cleanup();
          }
        }
      };
      return virtual;
    },
    describePlacement(box) {
      const sandboxId = box.id;
      const meta = box.__inProcess;
      return {
        kind: "sibling",
        sandboxId,
        worktreePath: meta?.worktree?.path,
        harness: meta?.harness
      };
    }
  };
  return {
    client,
    placement: "in-process",
    describe() {
      return `in-process (repoRoot=${options.repoRoot}, harnesses=[${harnesses.join(",")}]${options.testCmd ? `, testCmd="${options.testCmd}"` : ""}${options.typecheckCmd ? `, typecheckCmd="${options.typecheckCmd}"` : ""})`;
    }
  };
}
async function defaultRunPostCheck(cmd, cwd, signal) {
  const { spawn } = await import("child_process");
  return new Promise((resolve, reject) => {
    const child = spawn("sh", ["-c", cmd], { cwd, stdio: "pipe" });
    let stdout = "";
    let stderr = "";
    child.stdout?.on("data", (c) => {
      stdout += String(c);
    });
    child.stderr?.on("data", (c) => {
      stderr += String(c);
    });
    if (signal) {
      const onAbort = () => {
        if (!child.killed) child.kill("SIGTERM");
      };
      if (signal.aborted) onAbort();
      else signal.addEventListener("abort", onAbort, { once: true });
    }
    const killTimer = setTimeout(() => {
      if (!child.killed) child.kill("SIGTERM");
    }, DEFAULT_POSTCHECK_TIMEOUT_MS);
    if (typeof killTimer.unref === "function") {
      ;
      killTimer.unref();
    }
    child.on("error", (err) => {
      clearTimeout(killTimer);
      reject(err);
    });
    child.on("close", (code) => {
      clearTimeout(killTimer);
      resolve({ exitCode: code ?? -1, stdout, stderr });
    });
  });
}

// src/mcp/bin-helpers.ts
async function detectExecutor(args) {
  const env = args.env ?? process.env;
  if (env.AGENT_RUNTIME_IN_SANDBOX === "1") {
    const repoRoot = env.AGENT_RUNTIME_REPO_ROOT?.trim();
    if (!repoRoot) {
      throw new Error(
        "agent-runtime-mcp: AGENT_RUNTIME_IN_SANDBOX=1 requires AGENT_RUNTIME_REPO_ROOT to point at the workspace root"
      );
    }
    return createInProcessExecutor({
      repoRoot,
      harnesses: parseHarnesses(env.AGENT_RUNTIME_LOCAL_HARNESSES),
      testCmd: env.AGENT_RUNTIME_TEST_CMD?.trim() || void 0,
      typecheckCmd: env.AGENT_RUNTIME_TYPECHECK_CMD?.trim() || void 0
    });
  }
  const fleetId = parseFleetId(env.TANGLE_FLEET_ID);
  if (!fleetId) {
    return createSiblingSandboxExecutor({ client: args.sandboxClient });
  }
  const resolveFleet = args.resolveFleet ?? defaultResolveFleet;
  const fleet = await resolveFleet(args.sandboxClient, fleetId);
  const excludeMachineIds = parseList(env.TANGLE_FLEET_EXCLUDE_MACHINES);
  return createFleetWorkspaceExecutor({
    fleet,
    excludeMachineIds
  });
}
var KNOWN_HARNESSES = ["claude", "codex", "opencode"];
function parseHarnesses(raw) {
  if (!raw) return void 0;
  const parts = raw.split(",").map((s) => s.trim()).filter(Boolean);
  if (parts.length === 0) return void 0;
  for (const part of parts) {
    if (!KNOWN_HARNESSES.includes(part)) {
      throw new Error(
        `agent-runtime-mcp: AGENT_RUNTIME_LOCAL_HARNESSES contains unknown harness "${part}". Expected: ${KNOWN_HARNESSES.join(", ")}.`
      );
    }
  }
  return parts;
}
async function defaultResolveFleet(sandboxClient, fleetId) {
  const fleets = sandboxClient.fleets;
  if (!fleets || typeof fleets.get !== "function") {
    throw new Error(
      "agent-runtime-mcp: the configured sandbox client does not expose `.fleets.get`; upgrade @tangle-network/sandbox to >= 0.2.1 or unset TANGLE_FLEET_ID."
    );
  }
  const raw = await fleets.get(fleetId);
  if (!raw || typeof raw !== "object") {
    throw new Error(`agent-runtime-mcp: fleets.get(${fleetId}) returned no handle`);
  }
  const handle = raw;
  if (typeof handle.fleetId !== "string" || !Array.isArray(handle.ids)) {
    throw new Error(
      `agent-runtime-mcp: fleet handle for ${fleetId} is missing fleetId/ids \u2014 incompatible sandbox SDK shape`
    );
  }
  if (typeof handle.sandbox !== "function") {
    throw new Error(
      `agent-runtime-mcp: fleet handle for ${fleetId} is missing sandbox(machineId) \u2014 incompatible sandbox SDK shape`
    );
  }
  return handle;
}
function parseFleetId(raw) {
  if (typeof raw !== "string") return void 0;
  const trimmed = raw.trim();
  return trimmed.length > 0 ? trimmed : void 0;
}
function parseList(raw) {
  if (!raw) return void 0;
  const list = raw.split(",").map((entry) => entry.trim()).filter(Boolean);
  return list.length > 0 ? list : void 0;
}

// src/mcp/detached-coder.ts
var DEFAULT_MAX_DIFF_LINES = 400;
function minimalCoderProfile() {
  return { name: "coder" };
}
function coderRunProfile(options) {
  const harness = options.harness ?? "claude-code";
  const name = options.name ?? `coder-${harness}`;
  const base = options.profile ?? minimalCoderProfile();
  return {
    ...base,
    name,
    ...options.systemPrompt ? { prompt: { systemPrompt: options.systemPrompt } } : {},
    model: options.model ? { default: options.model } : base.model,
    metadata: { ...base.metadata, backendType: harness }
  };
}
function coderRunSpec(options = {}) {
  return {
    name: options.name ?? `coder-${options.harness ?? "claude-code"}`,
    profile: coderRunProfile(options),
    taskToPrompt: coderTaskToPrompt
  };
}
var coderOutputAdapter = { parse: parseCoderEvents };
function multiHarnessCoderFanout(options = {}) {
  const harnesses = options.harnesses && options.harnesses.length > 0 ? options.harnesses : ["claude-code", "codex", "opencode/zai-coding-plan/glm-5.1"];
  const models = options.models ?? [];
  const agentRuns = harnesses.map(
    (harness, i) => coderRunSpec({
      ...options.profile ? { profile: options.profile } : {},
      harness,
      model: models[i]
    })
  );
  const driver = {
    name: "fanout",
    plan: async (task, history) => history.length === 0 ? agentRuns.map(() => task) : [],
    decide: (history) => history.some((i) => i.verdict?.valid === true) ? "pick-winner" : "fail"
  };
  return { agentRuns, output: coderOutputAdapter, validator: defaultCoderValidator(), driver };
}
function createCoderValidator(task) {
  const constraints = {
    maxDiffLines: task.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES,
    forbiddenPaths: task.forbiddenPaths ?? []
  };
  return {
    async validate(output) {
      return runCoderChecks(
        {
          patch: output.patch,
          testsPassed: output.testResult.passed,
          typecheckPassed: output.typecheckResult.passed
        },
        constraints
      );
    }
  };
}
function defaultCoderValidator() {
  return createCoderValidator({
    goal: "",
    repoRoot: "",
    forbiddenPaths: [],
    maxDiffLines: DEFAULT_MAX_DIFF_LINES
  });
}
function parseCoderEvents(events) {
  for (let i = events.length - 1; i >= 0; i -= 1) {
    const event = events[i];
    if (!event) continue;
    const type = String(event.type ?? "");
    const data = isRecord(event.data) ? event.data : {};
    if (type === "result" || type === "final" || type === "coder.result") {
      const payload = data.result ?? data.output ?? data;
      const projected = projectWorktreeArtifact(payload);
      if (projected) return projected;
      const direct = coerceCoderOutput(payload);
      if (direct) return direct;
    }
  }
  const transcript = collectAssistantText(events);
  for (const candidate of fencedJsonBlocks(transcript)) {
    const coerced = coerceCoderOutput(candidate);
    if (coerced) return coerced;
  }
  return {
    branch: "",
    patch: "",
    testResult: { passed: false, output: "" },
    typecheckResult: { passed: false, output: "" },
    diffStats: { filesChanged: 0, insertions: 0, deletions: 0 }
  };
}
function projectWorktreeArtifact(value) {
  if (!isRecord(value)) return void 0;
  const stats = value.stats;
  if (!isRecord(stats)) return void 0;
  const branch = pickString(value.branch) ?? "";
  const patch = pickString(value.patch) ?? "";
  const checks = isRecord(value.checks) ? value.checks : {};
  const tests = isRecord(checks.tests) ? checks.tests : void 0;
  const typecheck = isRecord(checks.typecheck) ? checks.typecheck : void 0;
  const harness = isRecord(value.harness) ? value.harness : void 0;
  const exitCode = harness ? toFiniteInt(harness.exitCode) : 0;
  const timedOut = harness?.timedOut === true;
  const harnessName = harness ? pickString(harness.name) ?? "harness" : "harness";
  return {
    branch,
    patch,
    testResult: {
      passed: tests ? tests.passed === true : true,
      output: tail(pickString(tests?.output) ?? "", 4e3)
    },
    typecheckResult: {
      passed: typecheck ? typecheck.passed === true : true,
      output: tail(pickString(typecheck?.output) ?? "", 4e3)
    },
    diffStats: {
      filesChanged: toFiniteInt(stats.filesChanged),
      insertions: toFiniteInt(stats.insertions),
      deletions: toFiniteInt(stats.deletions)
    },
    ...exitCode !== 0 ? {
      reviewerNotes: `harness ${harnessName} exited ${exitCode}${timedOut ? " (timed out)" : ""}`
    } : {}
  };
}
function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function tail(text, max) {
  return text.length <= max ? text : text.slice(text.length - max);
}
function pickString(value) {
  return typeof value === "string" && value.length > 0 ? value : void 0;
}
function collectAssistantText(events) {
  const chunks = [];
  for (const event of events) {
    if (!event) continue;
    const data = isRecord(event.data) ? event.data : {};
    if (String(event.type ?? "") === "message.part.updated") {
      const part = isRecord(data.part) ? data.part : {};
      const partType = String(part.type ?? "");
      if (partType !== "text" && partType !== "") continue;
      const text2 = pickString(data.delta) ?? pickString(part.text);
      if (text2) chunks.push(text2);
      continue;
    }
    const text = pickString(data.text) ?? pickString(data.delta);
    if (text) chunks.push(text);
  }
  return chunks.join("");
}
function fencedJsonBlocks(text) {
  const out = [];
  const matches = [...text.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
  for (let i = matches.length - 1; i >= 0; i -= 1) {
    const body = (matches[i]?.[1] ?? "").trim();
    if (!body) continue;
    try {
      out.push(JSON.parse(body));
    } catch {
    }
  }
  return out;
}
function coerceCoderOutput(value) {
  if (!isRecord(value)) return void 0;
  const branch = pickString(value.branch);
  const patch = pickString(value.patch) ?? "";
  if (branch === void 0) return void 0;
  return {
    branch,
    patch,
    testResult: coerceCmdResult(value.testResult),
    typecheckResult: coerceCmdResult(value.typecheckResult),
    diffStats: coerceDiffStats(value.diffStats),
    reviewerNotes: pickString(value.reviewerNotes)
  };
}
function coerceCmdResult(value) {
  if (!isRecord(value)) return { passed: false, output: "" };
  return { passed: value.passed === true, output: pickString(value.output) ?? "" };
}
function coerceDiffStats(value) {
  if (!isRecord(value)) return { filesChanged: 0, insertions: 0, deletions: 0 };
  return {
    filesChanged: toFiniteInt(value.filesChanged),
    insertions: toFiniteInt(value.insertions),
    deletions: toFiniteInt(value.deletions)
  };
}
function toFiniteInt(value) {
  if (typeof value !== "number") return 0;
  if (!Number.isFinite(value)) return 0;
  return Math.max(0, Math.trunc(value));
}

// src/mcp/detached-turn.ts
var DEFAULT_TICK_INTERVAL_MS = 5e3;
function formatDetachedSessionRef(parts) {
  assertRefComponent("sessionId", parts.sessionId);
  if (parts.sandboxId === void 0) return `session=${parts.sessionId}`;
  assertRefComponent("sandboxId", parts.sandboxId);
  return `sandbox=${parts.sandboxId};session=${parts.sessionId}`;
}
function parseDetachedSessionRef(raw) {
  const fields = /* @__PURE__ */ new Map();
  for (const pair of raw.split(";")) {
    const eq = pair.indexOf("=");
    const key = eq === -1 ? "" : pair.slice(0, eq);
    const value = eq === -1 ? "" : pair.slice(eq + 1);
    if (key !== "session" && key !== "sandbox" || value.length === 0 || fields.has(key)) {
      throw new ValidationError(
        `parseDetachedSessionRef: malformed detachedSessionRef ${JSON.stringify(raw)} \u2014 expected "session=<id>" or "sandbox=<id>;session=<id>"`
      );
    }
    fields.set(key, value);
  }
  const sessionId = fields.get("session");
  if (!sessionId) {
    throw new ValidationError(
      `parseDetachedSessionRef: detachedSessionRef ${JSON.stringify(raw)} carries no session id`
    );
  }
  const sandboxId = fields.get("sandbox");
  return { sessionId, ...sandboxId !== void 0 ? { sandboxId } : {} };
}
function assertRefComponent(name, value) {
  if (value.length === 0 || value.includes(";") || value.includes("=")) {
    throw new ValidationError(
      `formatDetachedSessionRef: ${name} ${JSON.stringify(value)} must be non-empty and free of ";" / "="`
    );
  }
}
function detachedTurnEvents(sessionId, turn) {
  return [
    {
      type: "result",
      id: sessionId,
      data: {
        text: turn.text,
        finalText: turn.text,
        success: true,
        result: turn.result
      }
    }
  ];
}
async function runDetachedTurn(options) {
  const intervalMs = options.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS;
  const trace = createDetachedTurnTrace(options);
  trace.started();
  const box = await createSandboxForSpec(options.client, options.spec, options.signal).catch(
    (err) => {
      trace.ended(err instanceof Error ? err.message : String(err));
      throw err;
    }
  );
  const drive = box;
  const onAbort = () => {
    void drive._sessionCancel?.(options.sessionId).catch(() => {
    });
  };
  try {
    if (typeof drive.driveTurn !== "function") {
      throw new ValidationError(
        "runDetachedTurn: the acquired sandbox exposes no driveTurn(message, { sessionId }) \u2014 detached dispatch requires @tangle-network/sandbox >= 0.6 and a session-backed placement (sibling/fleet); disable detached dispatch for this executor."
      );
    }
    const sandboxId = box.id;
    if (typeof sandboxId !== "string" || sandboxId.length === 0) {
      throw new ValidationError(
        "runDetachedTurn: the acquired sandbox carries no id \u2014 without it the detached run cannot be resumed after a restart, so refusing to dispatch detached."
      );
    }
    options.bindSandbox(sandboxId);
    trace.dispatched(sandboxId);
    options.signal.addEventListener("abort", onAbort, { once: true });
    for (; ; ) {
      throwIfAborted(options.signal);
      const tick = await drive.driveTurn(options.prompt, {
        sessionId: options.sessionId,
        turnId: options.sessionId,
        ...options.wallCapMs !== void 0 ? { wallCapMs: options.wallCapMs } : {}
      });
      throwIfAborted(options.signal);
      if (tick.state === "completed") {
        trace.ended();
        return { text: tick.text, result: tick.result };
      }
      if (tick.state === "failed") {
        throw new Error(`detached turn ${options.sessionId} failed: ${tick.error}`);
      }
      options.report({ iteration: 0, phase: detachedRunningPhase(tick.elapsedMs) });
      await sleep(intervalMs, options.signal);
    }
  } catch (err) {
    trace.ended(err instanceof Error ? err.message : String(err));
    throw err;
  } finally {
    options.signal.removeEventListener("abort", onAbort);
    if (options.signal.aborted) onAbort();
    await deleteBoxSafe(box);
  }
}
function createDetachedTurnTrace(options) {
  const emitter = options.traceEmitter;
  if (!emitter) {
    return { started() {
    }, dispatched() {
    }, ended() {
    } };
  }
  const runId = options.sessionId;
  const agentRunName = options.spec.name ?? options.spec.profile.name ?? "detached-turn";
  const startMs = Date.now();
  let done = false;
  const emit = (event) => {
    void emitter.emit(event);
  };
  return {
    started() {
      emit({
        kind: "loop.started",
        runId,
        timestamp: startMs,
        payload: {
          driver: "detached-turn",
          agentRunNames: [agentRunName],
          maxIterations: 1,
          maxConcurrency: 1
        }
      });
      emit({
        kind: "loop.iteration.started",
        runId,
        timestamp: startMs,
        payload: { iterationIndex: 0, agentRunName, taskHash: options.sessionId }
      });
    },
    dispatched(sandboxId) {
      emit({
        kind: "loop.iteration.dispatch",
        runId,
        timestamp: Date.now(),
        payload: {
          iterationIndex: 0,
          agentRunName,
          placement: options.placement ?? "sibling",
          sandboxId
        }
      });
    },
    ended(error) {
      if (done) return;
      done = true;
      const endMs = Date.now();
      emit({
        kind: "loop.iteration.ended",
        runId,
        timestamp: endMs,
        payload: {
          iterationIndex: 0,
          agentRunName,
          costUsd: 0,
          durationMs: endMs - startMs,
          ...error !== void 0 ? { error } : {}
        }
      });
      emit({
        kind: "loop.ended",
        runId,
        timestamp: endMs,
        payload: {
          ...error === void 0 ? { winnerIterationIndex: 0 } : {},
          totalCostUsd: 0,
          durationMs: endMs - startMs,
          iterations: 1
        }
      });
    }
  };
}
function detachedRunningPhase(elapsedMs) {
  return elapsedMs === void 0 ? "detached-running" : `detached-running ${Math.round(elapsedMs / 1e3)}s`;
}
function createDetachedTurnResumeDriver(options) {
  const cancelHooked = /* @__PURE__ */ new Set();
  return {
    intervalMs: options.intervalMs ?? DEFAULT_TICK_INTERVAL_MS,
    async tick({ record, detachedSessionRef }, ctx) {
      const ref = parseDetachedSessionRef(detachedSessionRef);
      if (ref.sandboxId === void 0) {
        return {
          state: "failed",
          error: {
            message: `detached session "${ref.sessionId}" was never bound to a sandbox \u2014 the previous process died before the box was acquired, so the turn was never dispatched and cannot be resumed`,
            kind: "DetachedSessionUnboundError"
          }
        };
      }
      const box = await options.resolveSandbox(ref.sandboxId);
      if (!cancelHooked.has(record.taskId)) {
        cancelHooked.add(record.taskId);
        ctx.signal.addEventListener(
          "abort",
          () => {
            void box._sessionCancel?.(ref.sessionId).catch(() => {
            });
          },
          { once: true }
        );
      }
      if (ctx.signal.aborted) throwAbort();
      const tick = await box.driveTurn(options.buildMessage(record), {
        sessionId: ref.sessionId,
        turnId: ref.sessionId,
        ...options.wallCapMs !== void 0 ? { wallCapMs: options.wallCapMs } : {}
      });
      if (tick.state === "completed") {
        const output = await options.settleOutput(
          { text: tick.text, result: tick.result },
          record,
          {
            signal: ctx.signal
          }
        );
        return { state: "completed", output };
      }
      if (tick.state === "failed") {
        return {
          state: "failed",
          error: {
            message: `detached turn ${ref.sessionId} failed: ${tick.error}`,
            kind: "DetachedTurnFailedError"
          }
        };
      }
      ctx.report({ iteration: 0, phase: detachedRunningPhase(tick.elapsedMs) });
      return { state: "running" };
    }
  };
}

// src/mcp/delegates.ts
function detachedSessionDelegate(options) {
  const executor = resolveExecutor(options);
  const sandboxClient = executor.client;
  const fanoutHarnesses = options.fanoutHarnesses;
  const maxConcurrency = options.maxConcurrency ?? 4;
  const traceEmitter = options.traceEmitter;
  return async (args, ctx) => {
    const task = coderTaskFromArgs(args);
    const variants = Math.max(1, Math.trunc(args.variants ?? 1));
    const loopEmitter = composeLoopTraceEmitters(traceEmitter, ctx.traceEmitter);
    ctx.report({ iteration: 0, phase: "starting" });
    if (variants <= 1) {
      const agentRunSpec = coderRunSpec({
        ...options.workerProfile ? { profile: options.workerProfile } : {},
        ...options.harness ? { harness: options.harness } : {},
        ...options.model ? { model: options.model } : {},
        ...options.systemPrompt ? { systemPrompt: options.systemPrompt } : {}
      });
      const output = coderOutputAdapter;
      const validator = createCoderValidator(task);
      if (ctx.detachedSessionRef !== void 0 && ctx.updateDetachedSessionRef) {
        const { sessionId } = parseDetachedSessionRef(ctx.detachedSessionRef);
        const rebind = ctx.updateDetachedSessionRef;
        const turn = await runDetachedTurn({
          client: sandboxClient,
          spec: agentRunSpec,
          prompt: agentRunSpec.taskToPrompt(task),
          sessionId,
          bindSandbox: (sandboxId) => rebind(formatDetachedSessionRef({ sandboxId, sessionId })),
          signal: ctx.signal,
          report: ctx.report,
          ...loopEmitter ? { traceEmitter: loopEmitter } : {},
          ...executor.placement === "fleet" ? { placement: "fleet" } : {},
          ...options.detachedTickIntervalMs !== void 0 ? { tickIntervalMs: options.detachedTickIntervalMs } : {},
          ...options.detachedWallCapMs !== void 0 ? { wallCapMs: options.detachedWallCapMs } : {}
        });
        const chosen3 = await settleDetachedCoderTurn(turn, {
          task,
          sessionId,
          signal: ctx.signal,
          ...options.harness ? { harness: options.harness } : {},
          ...options.model ? { model: options.model } : {},
          ...options.reviewer ? { reviewer: options.reviewer } : {}
        });
        ctx.report({ iteration: 1, phase: "completed" });
        return chosen3;
      }
      const result2 = await runLoop({
        driver: singleShotDriver,
        agentRun: agentRunSpec,
        output,
        validator,
        task,
        ctx: {
          sandboxClient,
          signal: ctx.signal,
          ...loopEmitter ? { traceEmitter: loopEmitter } : {}
        },
        maxIterations: 1,
        maxConcurrency
      });
      const chosen2 = await pickCoderWinner({
        iterations: result2.iterations,
        reviewer: options.reviewer,
        selection: options.winnerSelection ?? "highest-score",
        task,
        signal: ctx.signal
      });
      if (!chosen2) throw new Error(noWinnerMessage(options.reviewer));
      ctx.report({ iteration: 1, phase: "completed" });
      return chosen2;
    }
    const fanout = multiHarnessCoderFanout({
      ...options.workerProfile ? { profile: options.workerProfile } : {},
      ...fanoutHarnesses && fanoutHarnesses.length > 0 ? { harnesses: fanoutHarnesses.slice(0, variants) } : {},
      ...options.fanoutModels ? { models: options.fanoutModels.slice(0, variants) } : {}
    });
    const agentRuns = fanout.agentRuns.slice(0, variants);
    const result = await runLoop({
      driver: fanout.driver,
      agentRuns,
      output: fanout.output,
      validator: fanout.validator,
      task,
      ctx: {
        sandboxClient,
        signal: ctx.signal,
        ...loopEmitter ? { traceEmitter: loopEmitter } : {}
      },
      maxIterations: variants,
      maxConcurrency: Math.min(maxConcurrency, variants)
    });
    const chosen = await pickCoderWinner({
      iterations: result.iterations,
      reviewer: options.reviewer,
      selection: options.winnerSelection ?? "highest-score",
      task,
      signal: ctx.signal
    });
    if (!chosen) throw new Error(noWinnerMessage(options.reviewer));
    ctx.report({ iteration: agentRuns.length, phase: "completed" });
    return chosen;
  };
}
async function pickCoderWinner(args) {
  const eligible = [];
  for (const iter of args.iterations) {
    if (iter.output === void 0 || iter.error || iter.verdict?.valid !== true) continue;
    const readiness = iter.verdict.score ?? 0;
    if (args.reviewer) {
      const review = await args.reviewer(iter.output, args.task, { signal: args.signal });
      if (!review.approved) continue;
      eligible.push({ iter, readiness: review.readiness });
    } else {
      eligible.push({ iter, readiness });
    }
  }
  if (eligible.length === 0) return void 0;
  if (args.selection === "highest-readiness") {
    const sorted = [...eligible].sort(
      (a, b) => b.readiness - a.readiness || a.iter.index - b.iter.index
    );
    return sorted[0].iter.output;
  }
  const wrapped = eligible.map(({ iter }) => ({
    ...iter,
    output: { kind: "done", deliverable: iter.output }
  }));
  const winner = selectValidWinner({
    strategy: baseStrategy(args.selection),
    sizeOf: (o) => o.diffStats.insertions + o.diffStats.deletions
  })(wrapped);
  const out = winner?.output;
  if (!out || out.kind !== "done") return void 0;
  return out.deliverable;
}
function baseStrategy(selection) {
  switch (selection) {
    case "smallest-diff":
      return "smallest-artifact";
    case "first-approved":
      return "first-valid";
    default:
      return "highest-score";
  }
}
function noWinnerMessage(reviewer) {
  return reviewer ? "coder delegate: no candidate passed validation + review" : "coder delegate: no candidate passed validation";
}
function coderTaskFromArgs(args) {
  return {
    goal: buildCoderGoal(args),
    repoRoot: args.repoRoot,
    testCmd: args.config?.testCmd,
    typecheckCmd: args.config?.typecheckCmd,
    forbiddenPaths: args.config?.forbiddenPaths,
    maxDiffLines: args.config?.maxDiffLines
  };
}
async function settleDetachedCoderTurn(turn, options) {
  const parsed = coderOutputAdapter.parse(detachedTurnEvents(options.sessionId, turn));
  const validator = createCoderValidator(options.task);
  const verdict = await validator.validate(parsed, { iteration: 0, signal: options.signal });
  if (verdict.valid !== true) throw new Error(noWinnerMessage(options.reviewer));
  if (options.reviewer) {
    const review = await options.reviewer(parsed, options.task, { signal: options.signal });
    if (!review.approved) throw new Error(noWinnerMessage(options.reviewer));
  }
  return parsed;
}
function buildCoderGoal(args) {
  if (!args.contextHint) return args.goal;
  return [args.goal, "", "## Context", args.contextHint].join("\n");
}
function resolveExecutor(options) {
  if (options.executor && options.sandboxClient) {
    throw new Error("detachedSessionDelegate: pass exactly one of `executor` or `sandboxClient`");
  }
  if (options.executor) return options.executor;
  if (options.sandboxClient) {
    return createSiblingSandboxExecutor({ client: options.sandboxClient });
  }
  throw new Error("detachedSessionDelegate: `executor` or `sandboxClient` is required");
}
var singleShotDriver = {
  name: "mcp-single-shot",
  async plan(task, history) {
    return history.length === 0 ? [task] : [];
  },
  decide(history) {
    return history.length > 0 ? "pick-winner" : "fail";
  }
};

// src/mcp/tools/checks.ts
import {
  makeFinding
} from "@tangle-network/agent-eval";
var ANALYST_SEVERITIES = ["critical", "high", "medium", "low", "info"];
var FINDING_SCHEMA_PROMPT = [
  "Each finding is a JSON object with these fields:",
  '- severity: one of "critical" | "high" | "medium" | "low" | "info"',
  "- claim: one-sentence statement",
  '- evidence_uri: REQUIRED, never blank \u2014 exactly one of "span://<trace>/<span>", "artifact://<path>",',
  '  or "metric://<name>"; ALWAYS cite a real id from the trace. No citable id \u21D2 omit the finding.',
  "- evidence_excerpt?: a short quote from the cited evidence",
  "- confidence: number 0..1",
  "- rationale?: one sentence of reasoning",
  '- recommended_action?: a concrete imperative ("Add ...", "Replace ...", "Stop ...")',
  "Emit an empty array when there is nothing to report. Never fabricate evidence."
].join("\n");
function validateRawFinding(row) {
  if (!row || typeof row !== "object") return null;
  const r = row;
  if (typeof r.claim !== "string" || r.claim.length === 0) return null;
  if (typeof r.evidence_uri !== "string" || !/^(span|artifact|metric):\/\//.test(r.evidence_uri))
    return null;
  const sev = ANALYST_SEVERITIES.includes(r.severity) ? r.severity : "medium";
  return {
    severity: sev,
    claim: r.claim,
    evidence_uri: r.evidence_uri,
    confidence: typeof r.confidence === "number" ? r.confidence : 0.5,
    ...typeof r.evidence_excerpt === "string" ? { evidence_excerpt: r.evidence_excerpt } : {},
    ...typeof r.rationale === "string" ? { rationale: r.rationale } : {},
    ...typeof r.recommended_action === "string" ? { recommended_action: r.recommended_action } : {},
    ...typeof r.subject === "string" ? { subject: r.subject } : {}
  };
}
var defaultChecks = {
  completeness: {
    id: "completeness",
    description: "Required work the trace does not yet show done or verified.",
    area: "failure-mode",
    version: "1",
    lookFor: "every change the task requires that the trace does NOT yet show completed AND verified by a tool result. One finding per missing/unverified requirement."
  },
  correctness: {
    id: "correctness",
    description: "Tool calls that produced wrong, erroring, or contradicted results.",
    area: "correctness",
    version: "1",
    lookFor: "tool calls whose RESULT shows an error, a wrong value, or contradicts what the task required (e.g. set the wrong field, value did not take, an error was ignored)."
  },
  policy: {
    id: "policy",
    description: "Actions that violate a stated policy, constraint, or allow-list.",
    area: "safety",
    version: "1",
    lookFor: "actions in the trace that violate a policy/constraint stated in the task or system prompt (forbidden tool, missing approval, out-of-scope mutation, skipped precondition)."
  },
  efficiency: {
    id: "efficiency",
    description: "Wasted, redundant, or looping work.",
    area: "cost",
    version: "1",
    lookFor: "redundant or wasted actions \u2014 repeated identical calls, a stalled line retried the same way, work that produced no progress toward the goal."
  },
  "tool-use": {
    id: "tool-use",
    description: "Malformed or misused tool calls.",
    area: "tool-use",
    version: "1",
    lookFor: "tool calls with malformed/invalid arguments, the wrong tool for the intent, or a tool used against its contract \u2014 judged from the call + its result."
  }
};
function liftFindings(kind, rows, producedAt) {
  const findings = [];
  for (const row of rows) {
    const raw = validateRawFinding(row);
    if (!raw) continue;
    findings.push(
      makeFinding({
        analyst_id: kind.id,
        area: kind.area,
        severity: raw.severity,
        claim: raw.claim,
        confidence: raw.confidence,
        produced_at: producedAt,
        evidence_refs: evidenceRefs(raw.evidence_uri, raw.evidence_excerpt),
        ...raw.rationale ? { rationale: raw.rationale } : {},
        ...raw.recommended_action ? { recommended_action: raw.recommended_action } : {},
        ...raw.subject ? { subject: raw.subject } : {},
        metadata: { kind_version: kind.version }
      })
    );
  }
  assertTraceDerivedFindings(findings);
  return findings;
}
function evidenceRefs(uri, excerpt) {
  const scheme = uri.split("://", 1)[0];
  if (scheme === "metric")
    return [
      { kind: "metric", uri: uri.replace(/^metric:\/\//, ""), ...excerpt ? { excerpt } : {} }
    ];
  const kind = scheme === "span" ? "span" : "artifact";
  return [{ kind, uri, ...excerpt ? { excerpt } : {} }];
}
function renderTrace(trace) {
  const messages = Array.isArray(trace) ? trace : trace && typeof trace === "object" && Array.isArray(trace.messages) ? trace.messages : void 0;
  if (!messages) return JSON.stringify(trace ?? {}).slice(0, 8e3);
  return messages.map((m) => {
    const r = m;
    if (r.role === "tool") return `RESULT ${String(r.content).slice(0, 300)}`;
    const calls = r.tool_calls?.map((c) => `${c.function?.name}(${c.function?.arguments})`).join(", ");
    return calls ? `CALL ${calls}` : `SAY ${String(r.content ?? "").slice(0, 200)}`;
  }).join("\n").slice(0, 8e3);
}
async function runCheck(kind, trace, opts, producedAt) {
  const sys = `You are a trace analyst applying ONE lens: look for ${kind.lookFor}

${FINDING_SCHEMA_PROMPT}

Return ONLY a fenced \`\`\`json array of finding objects (possibly empty).`;
  const user = `WORKER TRACE:
${renderTrace(trace)}

Apply your lens and emit the findings array.`;
  const chat = opts.chat ?? defaultChat(opts);
  const content = await chat(sys, user);
  const match = content.match(/```(?:json)?\s*([\s\S]*?)```/);
  let rows = [];
  try {
    const parsed = JSON.parse((match?.[1] ?? content).trim());
    rows = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.findings) ? parsed.findings : [];
  } catch {
    rows = [];
  }
  return liftFindings(kind, rows, producedAt);
}
function defaultChat(opts) {
  return async (system, user) => {
    const res = await fetch(`${opts.routerBaseUrl.replace(/\/$/, "")}/chat/completions`, {
      method: "POST",
      headers: { "content-type": "application/json", authorization: `Bearer ${opts.routerKey}` },
      body: JSON.stringify({
        model: opts.model,
        messages: [
          { role: "system", content: system },
          { role: "user", content: user }
        ],
        temperature: 0.3
      })
    });
    if (!res.ok) throw new Error(`analyst router ${res.status}`);
    const data = await res.json();
    return data.choices?.[0]?.message?.content ?? "";
  };
}
function makeCheckRunner(kinds, opts) {
  return async (kindId, trace, producedAt) => {
    const kind = kinds[kindId];
    if (!kind)
      return {
        error: `unknown analyst kind ${JSON.stringify(kindId)} (have: ${Object.keys(kinds).join(", ")})`
      };
    return runCheck(kind, trace, opts, producedAt);
  };
}
export {
  DELEGATE_DESCRIPTION,
  DELEGATE_FEEDBACK_DESCRIPTION,
  DELEGATE_FEEDBACK_INPUT_SCHEMA,
  DELEGATE_FEEDBACK_TOOL_NAME,
  DELEGATE_INPUT_SCHEMA,
  DELEGATE_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,
  DELEGATION_TRACE_MAX_BYTES,
  DELEGATION_TRACE_MAX_SPANS,
  DelegationPersistenceError,
  DelegationStateCorruptError,
  DelegationTaskQueue,
  FileDelegationStore,
  InMemoryDelegationStore,
  InMemoryFeedbackStore,
  buildDelegationTraceSpans,
  capDelegationTrace,
  captureWorktreeDiff,
  coderTaskFromArgs,
  composeLoopTraceEmitters,
  createCoordinationTools,
  createDelegateFeedbackHandler,
  createDelegateHandler,
  createDelegateUiAuditHandler,
  createDelegationHistoryHandler,
  createDelegationStatusHandler,
  createDelegationTraceCollector,
  createDetachedTurnResumeDriver,
  createFleetWorkspaceExecutor,
  createInProcessExecutor,
  createInProcessTransport,
  createKbGate,
  createMcpServer,
  createPropagatingTraceEmitter,
  createSiblingSandboxExecutor,
  createWorktree,
  defaultChecks,
  detachedSessionDelegate,
  detachedTurnEvents,
  detectExecutor,
  eventToSnapshot,
  formatDetachedSessionRef,
  hashIdempotencyInput,
  liftFindings,
  makeCheckRunner,
  mcpToolsForRuntimeMcp,
  mcpToolsForRuntimeMcpSubset,
  parseDetachedSessionRef,
  readTraceContextFromEnv,
  removeWorktree,
  renderTrace,
  runCheck,
  runDetachedTurn,
  runLocalHarness,
  settleDetachedCoderTurn,
  traceContextToEnv,
  validateDelegateArgs,
  validateDelegateFeedbackArgs,
  validateDelegateUiAuditArgs,
  validateDelegationHistoryArgs,
  validateDelegationStatusArgs
};
//# sourceMappingURL=index.js.map