// Force strict mode and setup for ESM
"use strict";
import {
  getGitVersion,
  getNpmVersion
} from "./chunk-PFS2I5LF.js";
import {
  STATUS_SCHEMA_VERSION,
  mapDomainErrorToErrorKind
} from "./chunk-7MFZZRJS.js";
import {
  canUseRipgrep
} from "./chunk-IQ7FOOIH.js";
import {
  detectRuntime,
  redactProxyCredentials
} from "./chunk-D5KISTLW.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/serve/daemon-status-provider.ts
init_esbuild_shims();
import { promises as fs } from "node:fs";

// packages/acp-bridge/src/index.ts
init_esbuild_shims();

// packages/acp-bridge/src/inMemoryChannel.ts
init_esbuild_shims();

// packages/acp-bridge/src/channel.ts
init_esbuild_shims();

// packages/acp-bridge/src/bridgeOptions.ts
init_esbuild_shims();

// packages/acp-bridge/src/bridgeFileSystem.ts
init_esbuild_shims();

// packages/cli/src/serve/env-snapshot.ts
init_esbuild_shims();
import os from "node:os";
function formatMemoryUsage(bytes) {
  const gb = bytes / (1024 * 1024 * 1024);
  if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  }
  if (bytes < 1024 * 1024 * 1024) {
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }
  return `${gb.toFixed(2)} GB`;
}
__name(formatMemoryUsage, "formatMemoryUsage");
var SECRET_ENV_VARS = [
  "OPENAI_API_KEY",
  "ANTHROPIC_API_KEY",
  "GEMINI_API_KEY",
  "GOOGLE_API_KEY",
  "DASHSCOPE_API_KEY",
  "OPENROUTER_API_KEY",
  "QWEN_SERVER_TOKEN"
];
var NONSECRET_ENV_VARS = [
  "OPENAI_BASE_URL",
  "ANTHROPIC_BASE_URL",
  "OPENAI_API_BASE",
  "NODE_EXTRA_CA_CERTS",
  "TZ",
  "LANG",
  "LC_ALL",
  "TERM",
  "QWEN_CLI_ENTRY"
];
var PROXY_VARS = [
  "HTTP_PROXY",
  "HTTPS_PROXY",
  "NO_PROXY",
  "ALL_PROXY"
];
function readProxyVar(env, name) {
  return env[name] ?? env[name.toLowerCase()];
}
__name(readProxyVar, "readProxyVar");
function safeProxyValue(name, raw) {
  if (name === "NO_PROXY") return redactProxyCredentials(raw);
  try {
    const host = new URL(raw).host;
    if (host) return host;
  } catch {
  }
  try {
    const host = new URL(`http://${raw}`).host;
    if (host) return host;
  } catch {
  }
  const stripped = raw.replace(/^[^@/?#]*@/, "").split(/[/?#]/)[0] ?? "";
  return stripped || "<unparseable>";
}
__name(safeProxyValue, "safeProxyValue");
function buildEnvStatusFromProcess(workspaceCwd, acpChannelLive) {
  const env = { ...process.env };
  const cells = [];
  const runtime = detectRuntime();
  const runtimeVersion = runtime === "bun" ? process.versions["bun"] ?? process.versions.node : process.versions.node;
  cells.push({
    kind: "runtime",
    name: runtime,
    status: "ok",
    value: runtimeVersion
  });
  cells.push({
    kind: "platform",
    name: process.platform,
    status: "ok",
    value: `${process.arch} (${os.release()})`
  });
  cells.push({
    kind: "memory",
    name: "rss",
    status: "ok",
    value: formatMemoryUsage(process.memoryUsage().rss)
  });
  const sandboxName = env["SANDBOX"];
  cells.push({
    kind: "sandbox",
    name: "SANDBOX",
    status: sandboxName ? "ok" : "disabled",
    present: Boolean(sandboxName),
    ...sandboxName ? { value: sandboxName } : {}
  });
  const seatbelt = env["SEATBELT_PROFILE"];
  if (seatbelt) {
    cells.push({
      kind: "sandbox",
      name: "SEATBELT_PROFILE",
      status: "ok",
      present: true,
      value: seatbelt
    });
  }
  for (const name of PROXY_VARS) {
    const raw = readProxyVar(env, name);
    if (raw) {
      cells.push({
        kind: "proxy",
        name,
        status: "ok",
        present: true,
        value: safeProxyValue(name, raw)
      });
    } else {
      cells.push({
        kind: "proxy",
        name,
        status: "disabled",
        present: false
      });
    }
  }
  for (const name of [...SECRET_ENV_VARS, ...NONSECRET_ENV_VARS]) {
    const present = Boolean(env[name]);
    cells.push({
      kind: "env_var",
      name,
      status: present ? "ok" : "disabled",
      present
    });
  }
  return {
    v: STATUS_SCHEMA_VERSION,
    workspaceCwd,
    initialized: true,
    acpChannelLive,
    cells
  };
}
__name(buildEnvStatusFromProcess, "buildEnvStatusFromProcess");

// packages/cli/src/serve/daemon-status-provider.ts
var REQUIRED_NODE_MAJOR = 22;
function createDaemonStatusProvider() {
  return {
    async getEnvStatus(boundWorkspace, acpChannelLive) {
      return buildEnvStatusFromProcess(boundWorkspace, acpChannelLive);
    },
    async getDaemonPreflightCells(boundWorkspace) {
      return buildDaemonPreflightCells(boundWorkspace);
    }
  };
}
__name(createDaemonStatusProvider, "createDaemonStatusProvider");
async function buildDaemonPreflightCells(boundWorkspace) {
  const nodeVersionCell = /* @__PURE__ */ __name(() => {
    try {
      const nodeVersion = process.versions.node;
      const major = Number.parseInt(nodeVersion.split(".")[0] ?? "0", 10);
      if (Number.isFinite(major) && major >= REQUIRED_NODE_MAJOR) {
        return {
          kind: "node_version",
          status: "ok",
          locality: "daemon",
          detail: {
            version: nodeVersion,
            required: `>=${REQUIRED_NODE_MAJOR}`
          }
        };
      }
      return {
        kind: "node_version",
        status: "error",
        errorKind: "missing_binary",
        error: `Node ${nodeVersion} is below the required >=${REQUIRED_NODE_MAJOR}.`,
        hint: `Upgrade Node to v${REQUIRED_NODE_MAJOR} or newer.`,
        locality: "daemon",
        detail: { version: nodeVersion, required: `>=${REQUIRED_NODE_MAJOR}` }
      };
    } catch (err) {
      return {
        kind: "node_version",
        status: "error",
        error: err instanceof Error ? err.message : String(err),
        locality: "daemon"
      };
    }
  }, "nodeVersionCell");
  const cliEntryCell = /* @__PURE__ */ __name(() => {
    const cliEntry = process.env["QWEN_CLI_ENTRY"] || process.argv[1] || "";
    if (cliEntry) {
      return {
        kind: "cli_entry",
        status: "ok",
        locality: "daemon",
        detail: {
          path: cliEntry,
          source: process.env["QWEN_CLI_ENTRY"] ? "QWEN_CLI_ENTRY" : "process.argv[1]"
        }
      };
    }
    return {
      kind: "cli_entry",
      status: "error",
      errorKind: "missing_binary",
      error: "Cannot determine CLI entry path for spawning the ACP child.",
      hint: "Set QWEN_CLI_ENTRY to the absolute path of the qwen entry script.",
      locality: "daemon"
    };
  }, "cliEntryCell");
  const workspaceDirCell = /* @__PURE__ */ __name(async () => {
    try {
      const stat = await fs.stat(boundWorkspace);
      if (stat.isDirectory()) {
        return {
          kind: "workspace_dir",
          status: "ok",
          locality: "daemon",
          detail: { path: boundWorkspace }
        };
      }
      return {
        kind: "workspace_dir",
        status: "error",
        errorKind: "missing_file",
        error: `Bound workspace path is not a directory: ${boundWorkspace}`,
        locality: "daemon",
        detail: { path: boundWorkspace }
      };
    } catch (err) {
      const errorKind = mapDomainErrorToErrorKind(err);
      return {
        kind: "workspace_dir",
        status: "error",
        error: err instanceof Error ? err.message : String(err),
        ...errorKind ? { errorKind } : {},
        locality: "daemon",
        detail: { path: boundWorkspace }
      };
    }
  }, "workspaceDirCell");
  const slots = [
    { kind: "node_version", run: nodeVersionCell },
    { kind: "cli_entry", run: cliEntryCell },
    { kind: "workspace_dir", run: workspaceDirCell },
    {
      kind: "ripgrep",
      run: /* @__PURE__ */ __name(() => safeCheck("ripgrep", async () => {
        const ok = await canUseRipgrep(true);
        return ok ? { status: "ok" } : {
          status: "warning",
          hint: "Install ripgrep for faster grep tool execution."
        };
      }), "run")
    },
    {
      kind: "git",
      run: /* @__PURE__ */ __name(() => safeCheck("git", async () => {
        const v = await getGitVersion();
        return v && v !== "unknown" ? { status: "ok", detail: { version: v } } : { status: "warning", hint: "git not found on PATH." };
      }), "run")
    },
    {
      kind: "npm",
      run: /* @__PURE__ */ __name(() => safeCheck("npm", async () => {
        const v = await getNpmVersion();
        return v && v !== "unknown" ? { status: "ok", detail: { version: v } } : { status: "warning", hint: "npm not found on PATH." };
      }), "run")
    }
  ];
  const settled = await Promise.allSettled(
    slots.map((s) => Promise.resolve().then(s.run))
  );
  return settled.map((result, i) => {
    if (result.status === "fulfilled") return result.value;
    const err = result.reason;
    const errorKind = mapDomainErrorToErrorKind(err);
    return {
      kind: slots[i].kind,
      status: "error",
      locality: "daemon",
      error: err instanceof Error ? err.message : String(err),
      ...errorKind ? { errorKind } : {}
    };
  });
}
__name(buildDaemonPreflightCells, "buildDaemonPreflightCells");
async function safeCheck(kind, body) {
  try {
    const r = await body();
    return {
      kind,
      status: r.status,
      locality: "daemon",
      ...r.detail ? { detail: r.detail } : {},
      ...r.hint ? { hint: r.hint } : {}
    };
  } catch (err) {
    const errorKind = mapDomainErrorToErrorKind(err);
    return {
      kind,
      status: "error",
      error: err instanceof Error ? err.message : String(err),
      locality: "daemon",
      ...errorKind ? { errorKind } : {}
    };
  }
}
__name(safeCheck, "safeCheck");

export {
  createDaemonStatusProvider
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
