#!/usr/bin/env node
import {
  readTraceContextFromEnv
} from "../chunk-4WXGK6GV.js";
import {
  resolveRouterBaseUrl
} from "../chunk-NURIQBJQ.js";
import {
  DelegationTaskQueue,
  FileDelegationStore,
  createMcpServer
} from "../chunk-SSA6OERV.js";
import "../chunk-UD4BHQMI.js";
import "../chunk-BZF3KQ6G.js";
import "../chunk-4J6RBI3K.js";
import "../chunk-7LO5GMAO.js";
import "../chunk-YEJR7IXO.js";
import "../chunk-DPEUKJRO.js";
import "../chunk-DGUM43GV.js";

// src/mcp/delegate-supervisor-provisioning.ts
var DEFAULT_SUPERVISOR_MODEL = "moonshotai/kimi-k2.6";
var DEFAULT_WORKER_HARNESS = "opencode";
function trimmed(value) {
  const v = value?.trim();
  return v ? v : void 0;
}
function delegateEnabled(env = process.env) {
  return env.MCP_ENABLE_DELEGATE === "1";
}
function resolveRouter(env) {
  const routerKey = trimmed(env.MCP_SUPERVISOR_ROUTER_KEY) ?? trimmed(env.TANGLE_API_KEY) ?? "";
  const base = trimmed(env.MCP_SUPERVISOR_ROUTER_BASE_URL) ?? resolveRouterBaseUrl(env);
  const routerBaseUrl = /\/v\d+\/?$/.test(base) ? base.replace(/\/$/, "") : `${base.replace(/\/$/, "")}/v1`;
  const model = trimmed(env.MCP_SUPERVISOR_MODEL) ?? trimmed(env.MCP_WORKER_MODEL) ?? trimmed(env.WORKER_MODEL) ?? DEFAULT_SUPERVISOR_MODEL;
  return { routerBaseUrl, routerKey, model };
}
function resolveDelegateSupervisor(sandboxClient, env = process.env) {
  if (!delegateEnabled(env)) return void 0;
  const router = resolveRouter(env);
  const harness = trimmed(env.MCP_DELEGATE_WORKER_HARNESS) ?? DEFAULT_WORKER_HARNESS;
  const backend = {
    backend: "sandbox",
    harness,
    sandboxClient
  };
  return {
    router,
    backend,
    model: router.model
  };
}

// src/mcp/bin.ts
var DEFAULT_SANDBOX_BASE_URL = "https://sandbox.tangle.tools";
async function main() {
  const wantDelegate = delegateEnabled(process.env);
  let sandboxClient;
  if (wantDelegate) {
    const apiKey = process.env.TANGLE_API_KEY;
    if (!apiKey && !process.env.AGENT_RUNTIME_MCP_ALLOW_NO_KEY) {
      process.stderr.write(
        "agent-runtime-mcp: TANGLE_API_KEY is required to serve `delegate`. Set AGENT_RUNTIME_MCP_ALLOW_NO_KEY=1 to run without it for diagnostics, or unset MCP_ENABLE_DELEGATE to run the queue-only subset.\n"
      );
      process.exit(2);
    }
    sandboxClient = await loadSandboxClient(apiKey);
  }
  const traceContext = readTraceContextFromEnv();
  if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {
    process.stderr.write(
      `agent-runtime-mcp: exporting loop topology \u2192 ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}
`
    );
  }
  const delegateSupervisor = wantDelegate && sandboxClient ? resolveDelegateSupervisor(sandboxClient) : void 0;
  if (wantDelegate && delegateSupervisor) {
    process.stderr.write("agent-runtime-mcp: delegate enabled \u2014 generic authoring supervisor\n");
  }
  const durableQueue = await buildDurableQueueFromEnv(traceContext);
  const server = createMcpServer({
    ...delegateSupervisor ? { delegateSupervisor } : {},
    traceContext,
    ...durableQueue ? { queue: durableQueue } : {}
  });
  const shutdown = () => {
    server.stop();
    if (durableQueue) {
      void durableQueue.flush().catch(() => {
      }).finally(() => process.exit(0));
      return;
    }
    process.exit(0);
  };
  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
  await server.serve();
}
async function buildDurableQueueFromEnv(traceContext) {
  const stateFile = process.env.AGENT_RUNTIME_DELEGATION_STATE_FILE?.trim();
  if (!stateFile) return void 0;
  const store = new FileDelegationStore({
    filePath: stateFile,
    recoverCorrupt: process.env.AGENT_RUNTIME_DELEGATION_STATE_RECOVER === "1"
  });
  const maxTerminalRecords = parseRetention(process.env.AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL);
  const queue = await DelegationTaskQueue.restore({
    store,
    traceContext,
    ...maxTerminalRecords !== void 0 ? { maxTerminalRecords } : {},
    onPersistError: (error) => {
      process.stderr.write(`agent-runtime-mcp: ${error.message}
`);
      process.exit(1);
    }
  });
  process.stderr.write(`agent-runtime-mcp: durable delegation state \u2192 ${stateFile}
`);
  return queue;
}
function parseRetention(raw) {
  if (raw === void 0 || raw.trim() === "") return void 0;
  const n = Number(raw);
  if (!Number.isInteger(n) || n < 1) {
    process.stderr.write(
      `agent-runtime-mcp: AGENT_RUNTIME_DELEGATION_RETAIN_TERMINAL must be a positive integer, got "${raw}"
`
    );
    process.exit(2);
  }
  return n;
}
async function loadSandboxClient(apiKey) {
  if (!apiKey) {
    return {
      async create() {
        throw new Error(
          "agent-runtime-mcp: TANGLE_API_KEY is unset; `delegate` is disabled in diagnostic mode. Set TANGLE_API_KEY or unset MCP_ENABLE_DELEGATE to remove the unsupported tool from the tool list."
        );
      }
    };
  }
  const mod = await import("@tangle-network/sandbox").catch((err) => {
    process.stderr.write(
      `agent-runtime-mcp: failed to load @tangle-network/sandbox (${err.message}); install the peer dependency
`
    );
    process.exit(2);
  });
  const SandboxCtor = mod.Sandbox;
  if (!SandboxCtor) {
    process.stderr.write(
      "agent-runtime-mcp: @tangle-network/sandbox does not export Sandbox; cannot construct client\n"
    );
    process.exit(2);
  }
  const baseUrl = process.env.SANDBOX_BASE_URL?.trim() || DEFAULT_SANDBOX_BASE_URL;
  return new SandboxCtor({ apiKey, baseUrl });
}
main().catch((err) => {
  process.stderr.write(`agent-runtime-mcp: ${err instanceof Error ? err.stack : String(err)}
`);
  process.exit(1);
});
//# sourceMappingURL=bin.js.map