// 重构前 index.ts 只读参考：commit 6a04144d3f5103014f75b637d7e6bc2f45bf007f，blob 56e590c1a6b5ca7ad128bf2c992f60e46c355a58；可用 `git show 6a04144d3f5103014f75b637d7e6bc2f45bf007f:src/components/microservices/code-queue/src/index.ts` 查看。

import type { DevContainerCommandLog, DevContainerPlan, JsonValue, QueueTask, RuntimeConfig } from "./types";

export interface DevContainerContext {
  config: Pick<RuntimeConfig, "devContainerDefaultProviderId">;
  appendOutput: (task: QueueTask, channel: "system" | "assistant" | "reasoning" | "command" | "diff" | "tool" | "error", text: string, method?: string, itemId?: string, append?: boolean) => unknown;
  buildDevContainerPlan: (providerId: string, body: Record<string, unknown>) => DevContainerPlan;
  containerTunnelStartScript: (plan: DevContainerPlan) => string;
  devContainerEnsurePromises: Map<string, Promise<void>>;
  devContainerPingScript: (plan: DevContainerPlan) => string;
  errorToJson: (error: unknown) => JsonValue;
  extractRecord: (value: unknown) => Record<string, unknown> | null;
  jsonResponse: (body: unknown, status?: number) => Response;
  logger: (level: "debug" | "info" | "warn" | "error", message: string, data?: JsonValue) => void;
  masterKeyReadScript: (plan: DevContainerPlan) => string;
  masterKeySetupScript: (plan: DevContainerPlan) => string;
  masterProxyEvidenceScript: (plan: DevContainerPlan) => string;
  masterProxyFinishScript: (plan: DevContainerPlan) => string;
  masterProxyPrepareScript: (plan: DevContainerPlan) => string;
  normalizeProviderId: (value: unknown) => string | null;
  providerIsMain: (providerId: string) => boolean;
  readJson: (req: Request) => Promise<unknown>;
  remoteCodexConfigInstallScript: (plan: DevContainerPlan) => string;
  remoteCodexRuntimePrepareScript: (plan: DevContainerPlan) => string;
  remoteContainerStartScript: (plan: DevContainerPlan, forceRecreate: boolean) => string;
  remoteHostWorkdirForTask: (task: QueueTask) => string;
  remoteKeyInstallScript: (plan: DevContainerPlan, privateKeyBase64: string) => string;
  runCodeQueueSsh: (providerId: string, script: string, timeoutMs: number, name: string) => Promise<DevContainerCommandLog>;
  safePreview: (value: string, max?: number) => string;
  shellQuote: (value: string) => string;
  throwIfCommandFailed: (command: DevContainerCommandLog) => void;
}

let context: DevContainerContext | null = null;

export function configureDevContainers(runtimeContext: DevContainerContext): void {
  context = runtimeContext;
}

function ctx(): DevContainerContext {
  if (context === null) throw new Error("dev-containers module is not configured");
  return context;
}

async function startDevContainerPlan(plan: DevContainerPlan, options: {
  forceRecreate: boolean;
  verifyPing: boolean;
  prepareRuntime: boolean;
  onCommandStart?: (command: { name: string; providerId: string; timeoutMs: number }) => void;
  onCommandComplete?: (command: DevContainerCommandLog) => void;
}): Promise<{
  ok: boolean;
  providerId: string;
  plan: DevContainerPlan;
  commands: DevContainerCommandLog[];
  verification?: Record<string, JsonValue>;
}> {
  const commands: DevContainerCommandLog[] = [];
  const run = async (targetProviderId: string, script: string, timeoutMs: number, name: string): Promise<DevContainerCommandLog> => {
    options.onCommandStart?.({ name, providerId: targetProviderId, timeoutMs });
    const command = await ctx().runCodeQueueSsh(targetProviderId, script, timeoutMs, name);
    commands.push(command);
    options.onCommandComplete?.(command);
    ctx().throwIfCommandFailed(command);
    return command;
  };
  await run("main-server", ctx().masterKeySetupScript(plan), 45_000, "master-key-setup");
  const keyRead = await run("main-server", ctx().masterKeyReadScript(plan), 15_000, "master-key-read");
  const keyBase64 = keyRead.stdout.trim();
  if (!/^[A-Za-z0-9+/=\r\n]+$/u.test(keyBase64) || keyBase64.length < 40) throw new Error("master key read returned invalid base64");
  keyRead.stdout = "[redacted private tunnel key]\n";
  await run(plan.providerId, ctx().remoteKeyInstallScript(plan, keyBase64), 30_000, "remote-key-install");
  await run(plan.providerId, ctx().remoteCodexConfigInstallScript(plan), 30_000, "remote-codex-config-install");
  await run(plan.providerId, ctx().remoteContainerStartScript(plan, options.forceRecreate), 60_000, "remote-container-start");
  await run("main-server", ctx().masterProxyPrepareScript(plan), 30_000, "master-proxy-prepare");
  await run(plan.providerId, ctx().containerTunnelStartScript(plan), 45_000, "remote-tunnel-start");
  await run("main-server", ctx().masterProxyFinishScript(plan), 30_000, "master-proxy-finish");
  if (options.prepareRuntime) await run(plan.providerId, ctx().remoteCodexRuntimePrepareScript(plan), 1_800_000, "remote-codex-runtime-prepare");
  const verification: Record<string, JsonValue> = {};
  if (options.verifyPing) {
    const before = await run("main-server", ctx().masterProxyEvidenceScript(plan), 15_000, "master-proxy-evidence-before-ping");
    const ping = await run(plan.providerId, ctx().devContainerPingScript(plan), 20_000, "remote-container-ping-google");
    const after = await run("main-server", ctx().masterProxyEvidenceScript(plan), 15_000, "master-proxy-evidence-after-ping");
    verification.pingGoogleOk = ping.exitCode === 0 && /0% packet loss|1 packets received|1 received|bytes from/iu.test(ping.stdout);
    verification.directPingEvidence = commands.find((command) => command.name === "remote-tunnel-start")?.stdout.includes("direct_ping=failed_expected") === true
      ? `direct ${plan.providerId} container ping failed before tunnel`
      : "direct ping did not fail before tunnel";
    verification.sealedEgressEvidence = ping.stdout.includes("sealed_direct_ping=blocked_expected")
      ? `direct ${plan.providerId} container egress blocked after tunnel seal`
      : "sealed direct egress block was not observed";
    verification.masterProxyEvidenceBefore = ctx().safePreview(before.stdout, 2000);
    verification.pingGoogleLog = ping.stdout;
    verification.masterProxyEvidenceAfter = ctx().safePreview(after.stdout, 2000);
  }
  return { ok: true, providerId: plan.providerId, plan, commands, verification };
}

export async function ensureTaskExecutionContainer(task: QueueTask): Promise<void> {
  if (ctx().providerIsMain(task.providerId)) return;
  const plan = ctx().buildDevContainerPlan(task.providerId, { workdir: ctx().remoteHostWorkdirForTask(task) });
  const existing = ctx().devContainerEnsurePromises.get(plan.providerId);
  if (existing !== undefined) return existing;
  const promise = (async () => {
    ctx().appendOutput(task, "system", `ensuring provider=${plan.providerId} container=${plan.containerName} workdir=${task.cwd}\n`, "provider/container");
    const result = await startDevContainerPlan(plan, {
      forceRecreate: false,
      verifyPing: false,
      prepareRuntime: task.executionMode !== "windows-native",
      onCommandStart: (command) => {
        ctx().appendOutput(task, "system", `provider prepare start name=${command.name} target=${command.providerId} timeoutMs=${command.timeoutMs}\n`, "provider/container");
      },
      onCommandComplete: (command) => {
        const status = command.exitCode === 0 ? "ok" : `failed exit=${command.exitCode ?? "null"} signal=${command.signal ?? "null"}`;
        ctx().appendOutput(task, command.exitCode === 0 ? "system" : "error", `provider prepare ${status} name=${command.name} target=${command.providerId} durationMs=${command.durationMs}\n`, "provider/container");
      },
    });
    ctx().appendOutput(task, "system", `provider container ready provider=${plan.providerId} container=${plan.containerName} commands=${result.commands.length}\n`, "provider/container");
    ctx().logger("info", "task_provider_container_ready", {
      taskId: task.id,
      providerId: plan.providerId,
      containerName: plan.containerName,
      executionMode: task.executionMode,
      workdir: task.cwd,
      hostWorkdir: plan.workdir,
    });
  })();
  ctx().devContainerEnsurePromises.set(plan.providerId, promise);
  try {
    await promise;
  } finally {
    if (ctx().devContainerEnsurePromises.get(plan.providerId) === promise) ctx().devContainerEnsurePromises.delete(plan.providerId);
  }
}

export async function startDevContainer(req: Request, providerFromPath: string | null): Promise<Response> {
  const body = ctx().extractRecord(await ctx().readJson(req)) ?? {};
  const providerFromBody = ctx().normalizeProviderId(body.providerId);
  const providerId = ctx().normalizeProviderId(providerFromPath ?? "") ?? providerFromBody ?? ctx().normalizeProviderId(ctx().config.devContainerDefaultProviderId) ?? "D601";
  const plan = ctx().buildDevContainerPlan(providerId, body);
  try {
    const result = await startDevContainerPlan(plan, { forceRecreate: true, verifyPing: true, prepareRuntime: false });
    ctx().logger("info", "dev_container_started", {
      providerId,
      containerName: plan.containerName,
      masterHost: plan.masterHost,
      tunName: plan.tunName,
      natChain: plan.natChain,
      pingPreview: ctx().safePreview(String(result.verification?.pingGoogleLog ?? ""), 600),
      natAfterPreview: ctx().safePreview(String(result.verification?.masterProxyEvidenceAfter ?? ""), 600),
    });
    return ctx().jsonResponse({
      ok: true,
      providerId,
      container: {
        name: plan.containerName,
        image: plan.image,
        workdir: plan.workdir,
        containerWorkdir: plan.containerWorkdir,
      },
      masterProxy: {
        mode: "ssh-tun-nat-sealed",
        masterHost: plan.masterHost,
        tunId: plan.tunId,
        tunName: plan.tunName,
        serverIp: plan.serverIp,
        clientIp: plan.clientIp,
        natChain: plan.natChain,
        egressFirewallChain: plan.egressFirewallChain,
      },
      verification: result.verification,
      commands: result.commands,
    });
  } catch (error) {
    ctx().logger("error", "dev_container_start_failed", { providerId, containerName: plan.containerName, error: ctx().errorToJson(error) });
    return ctx().jsonResponse({
      ok: false,
      error: error instanceof Error ? error.message : String(error),
      providerId,
      containerName: plan.containerName,
      masterProxy: {
        mode: "ssh-tun-nat-sealed",
        masterHost: plan.masterHost,
        tunName: plan.tunName,
        clientIp: plan.clientIp,
        natChain: plan.natChain,
        egressFirewallChain: plan.egressFirewallChain,
      },
    }, 500);
  }
}

export async function devContainerStatus(providerFromPath: string | null): Promise<Response> {
  const providerId = ctx().normalizeProviderId(providerFromPath ?? "") ?? ctx().normalizeProviderId(ctx().config.devContainerDefaultProviderId) ?? "D601";
  const plan = ctx().buildDevContainerPlan(providerId, {});
  const commands: DevContainerCommandLog[] = [];
  const statusScript = `set -euo pipefail
CONTAINER=${ctx().shellQuote(plan.containerName)}
docker inspect "$CONTAINER" --format 'container={{.Name}} state={{.State.Status}} image={{.Config.Image}} workdir={{ index .Config.Labels "unidesk.workdir" }} started={{.State.StartedAt}}' 2>/dev/null || true
if docker inspect "$CONTAINER" >/dev/null 2>&1; then
  docker exec "$CONTAINER" bash -lc 'export PATH=/tmp/unidesk-tools:$PATH; source /tmp/unidesk-dev-egress.env 2>/dev/null || true; echo default=$(ip route show default | head -1); echo route_8_8_8_8=$(ip route get 8.8.8.8 | head -1); echo resolv=$(tr "\\n" " " </etc/resolv.conf); echo pwd=$(pwd); command -v codex || true; ip addr show ${plan.tunName} 2>/dev/null || true; if [ -n "\${EGRESS_CHAIN:-}" ]; then iptables -S "$EGRESS_CHAIN" 2>/dev/null || true; iptables -S OUTPUT 2>/dev/null | grep "$EGRESS_CHAIN" || true; fi' || true
fi`;
  commands.push(await ctx().runCodeQueueSsh(providerId, statusScript, 15_000, "remote-container-status"));
  commands.push(await ctx().runCodeQueueSsh("main-server", ctx().masterProxyEvidenceScript(plan), 15_000, "master-proxy-status"));
  return ctx().jsonResponse({
    ok: commands.every((command) => command.exitCode === 0),
    providerId,
    containerName: plan.containerName,
    masterProxy: {
      mode: "ssh-tun-nat-sealed",
      masterHost: plan.masterHost,
      tunName: plan.tunName,
      clientIp: plan.clientIp,
      natChain: plan.natChain,
      egressFirewallChain: plan.egressFirewallChain,
    },
    commands,
  });
}
