// Force strict mode and setup for ESM
"use strict";
import {
  findCliEntryPath
} from "./chunk-AHNXYU4O.js";
import {
  RUNTIME_STARTUP_CANCELLED_MESSAGE
} from "./chunk-GHOTR7HL.js";
import {
  CAPABILITIES_SCHEMA_VERSION,
  ClientMcpSenderRegistry,
  SERVE_CAPABILITY_REGISTRY,
  allowOriginCors,
  allowOriginMode,
  bearerAuth,
  createBridgeFileSystemAdapter,
  denyBrowserOriginCors,
  getAdvertisedServeFeatures,
  getDeviceFlowRegistry,
  getRateLimiter,
  getServeProtocolVersions,
  hostAllowlist,
  listenerMaxConnections,
  parseAllowOriginPatterns,
  parseDaemonStatusDetail,
  positiveFiniteOrNull,
  require_express,
  resolveWebShellDir
} from "./chunk-N4YJQTRL.js";
import {
  isLoopbackBind
} from "./chunk-RNBYOUGV.js";
import "./chunk-3HX5LZ6R.js";
import "./chunk-7RYW5LQV.js";
import {
  loadServeFastPathSettings,
  preResolveServeFastPathHomeEnvOverrides
} from "./chunk-DNV4FSN5.js";
import {
  QWEN_SERVER_TOKEN_ENV
} from "./chunk-S6RLAIUR.js";
import {
  channelSelectionNames
} from "./chunk-MX2YXRER.js";
import {
  getGlobalQwenDirLite,
  resolveConfigPathLite
} from "./chunk-4RQIB5UZ.js";
import "./chunk-EWALXUAD.js";
import {
  canonicalizeWorkspace
} from "./chunk-SEZC2725.js";
import {
  getCliVersion
} from "./chunk-SL2P3JUA.js";
import {
  writeStderrLine,
  writeStdoutLine
} from "./chunk-Y6Z2O3WR.js";
import "./chunk-QYUE6W3T.js";
import "./chunk-5P5XGNYH.js";
import "./chunk-SKAZWEV5.js";
import "./chunk-UWCTAVOD.js";
import "./chunk-SYCJMSIJ.js";
import {
  finalizeStartupProfile,
  profileCheckpoint
} from "./chunk-ITOGNELQ.js";
import "./chunk-FXGLL2HL.js";
import "./chunk-QN5NZ3UQ.js";
import "./chunk-BR4QREVK.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name,
  __toESM
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/serve/run-qwen-serve.ts
init_esbuild_shims();
var import_express = __toESM(require_express(), 1);
import { X509Certificate } from "node:crypto";
import * as fs from "node:fs";
import * as https from "node:https";
import * as path from "node:path";
import { performance } from "node:perf_hooks";

// packages/cli/src/serve/permission-audit.ts
init_esbuild_shims();
var DEFAULT_PERMISSION_AUDIT_RING_SIZE = 512;
function takeLast(arr, limit, methodName) {
  if (limit === void 0) return arr.slice();
  if (!Number.isInteger(limit) || limit < 0) {
    throw new Error(
      `${methodName} limit must be a non-negative integer; got ${String(limit)}`
    );
  }
  return arr.slice(Math.max(0, arr.length - limit));
}
__name(takeLast, "takeLast");
var PermissionAuditRing = class {
  static {
    __name(this, "PermissionAuditRing");
  }
  buf = [];
  cap;
  constructor(capacity = DEFAULT_PERMISSION_AUDIT_RING_SIZE) {
    if (!Number.isInteger(capacity) || capacity < 1) {
      throw new Error(
        `PermissionAuditRing capacity must be a positive integer; got ${String(capacity)}`
      );
    }
    this.cap = capacity;
  }
  push(entry) {
    this.buf.push(entry);
    while (this.buf.length > this.cap) this.buf.shift();
  }
  /** Snapshot the most-recent `limit` entries (or all if omitted). */
  snapshot(limit) {
    return takeLast(this.buf, limit, "PermissionAuditRing.snapshot");
  }
  /** Subset filtered by sessionId. */
  snapshotForSession(sessionId, limit) {
    return takeLast(
      this.buf.filter((e) => e.sessionId === sessionId),
      limit,
      "PermissionAuditRing.snapshotForSession"
    );
  }
  /** Current entry count (≤ capacity). For diagnostics. */
  get size() {
    return this.buf.length;
  }
  /** Configured capacity. */
  get capacity() {
    return this.cap;
  }
};
function createPermissionAuditPublisher(deps) {
  const { ring } = deps;
  const now = deps.now ?? (() => Date.now());
  return {
    recordRequested(record, policy, votersAtIssue) {
      ring.push({
        kind: "permission.requested",
        recordedAtMs: now(),
        requestId: record.requestId,
        sessionId: record.sessionId,
        originatorClientId: record.originatorClientId,
        policy,
        votersAtIssue: Array.from(votersAtIssue),
        issuedAtMs: record.issuedAtMs,
        allowedOptionIds: Array.from(record.allowedOptionIds)
      });
    },
    recordVoted(record, vote, outcome) {
      ring.push({
        kind: "permission.voted",
        recordedAtMs: now(),
        requestId: record.requestId,
        sessionId: record.sessionId,
        clientId: vote.clientId,
        optionId: vote.optionId,
        fromLoopback: vote.fromLoopback,
        receivedAtMs: vote.receivedAtMs,
        outcome
      });
    },
    recordForbidden(record, vote, reason) {
      ring.push({
        kind: "permission.forbidden",
        recordedAtMs: now(),
        requestId: record.requestId,
        sessionId: record.sessionId,
        clientId: vote.clientId,
        optionId: vote.optionId,
        fromLoopback: vote.fromLoopback,
        reason
      });
    },
    recordResolved(record, resolution, decisionReason) {
      ring.push({
        kind: "permission.resolved",
        recordedAtMs: now(),
        requestId: record.requestId,
        sessionId: record.sessionId,
        resolution,
        decisionReason
      });
    },
    recordTimeout(record) {
      ring.push({
        kind: "permission.timeout",
        recordedAtMs: now(),
        requestId: record.requestId,
        sessionId: record.sessionId,
        issuedAtMs: record.issuedAtMs
      });
    }
  };
}
__name(createPermissionAuditPublisher, "createPermissionAuditPublisher");

// packages/cli/src/serve/daemon-logger.ts
init_esbuild_shims();
import * as nodeFs from "node:fs";
import * as nodePath from "node:path";
import * as crypto from "node:crypto";
var FIXED_CTX_ORDER = [
  "route",
  "sessionId",
  "clientId",
  "childPid",
  "channelId"
];
var FIXED_CTX_SET = new Set(FIXED_CTX_ORDER);
function renderCtxValue(value) {
  const s = String(value);
  return /[\s=]/.test(s) ? JSON.stringify(s) : s;
}
__name(renderCtxValue, "renderCtxValue");
function renderCtx(ctx) {
  if (!ctx) return "";
  const parts = [];
  for (const key of FIXED_CTX_ORDER) {
    const v = ctx[key];
    if (v !== void 0 && v !== null) {
      parts.push(`${key}=${String(v)}`);
    }
  }
  const extraKeys = Object.keys(ctx).filter(
    (k) => !FIXED_CTX_SET.has(k) && ctx[k] !== void 0 && ctx[k] !== null
  ).sort();
  for (const key of extraKeys) {
    parts.push(`${key}=${renderCtxValue(ctx[key])}`);
  }
  return parts.length > 0 ? parts.join(" ") + " " : "";
}
__name(renderCtx, "renderCtx");
function renderErr(err) {
  if (!err) return "";
  const body = err.stack ?? `${err.name ?? "Error"}: ${err.message}`;
  return body.split("\n").map((l) => `  ${l}`).join("\n") + "\n";
}
__name(renderErr, "renderErr");
function buildDaemonLogLine(args) {
  const ts = args.now.toISOString();
  const ctxStr = renderCtx(args.ctx);
  return `${ts} [${args.level}] [DAEMON] ${ctxStr}${args.message}
${renderErr(args.err)}`;
}
__name(buildDaemonLogLine, "buildDaemonLogLine");
var NOOP_LOGGER = {
  info: /* @__PURE__ */ __name(() => {
  }, "info"),
  warn: /* @__PURE__ */ __name(() => {
  }, "warn"),
  error: /* @__PURE__ */ __name(() => {
  }, "error"),
  raw: /* @__PURE__ */ __name(() => {
  }, "raw"),
  getLogPath: /* @__PURE__ */ __name(() => "", "getLogPath"),
  getDaemonId: /* @__PURE__ */ __name(() => "", "getDaemonId"),
  flush: /* @__PURE__ */ __name(() => Promise.resolve(), "flush")
};
function getRuntimeBaseDir(runtimeOutputDir, cwd) {
  const envDir = process.env["QWEN_RUNTIME_DIR"];
  if (envDir) return resolveConfigPathLite(envDir);
  if (runtimeOutputDir) return resolveConfigPathLite(runtimeOutputDir, cwd);
  return getGlobalQwenDirLite();
}
__name(getRuntimeBaseDir, "getRuntimeBaseDir");
function resolveDaemonLogBaseDir(runtimeOutputDir, cwd) {
  return nodePath.join(getRuntimeBaseDir(runtimeOutputDir, cwd), "debug");
}
__name(resolveDaemonLogBaseDir, "resolveDaemonLogBaseDir");
async function updateSymlinkBestEffort(linkPath, targetPath) {
  const linkDir = nodePath.dirname(linkPath);
  const relativeTarget = nodePath.relative(linkDir, targetPath);
  try {
    await nodeFs.promises.unlink(linkPath);
  } catch {
  }
  try {
    await nodeFs.promises.symlink(relativeTarget, linkPath);
  } catch {
  }
}
__name(updateSymlinkBestEffort, "updateSymlinkBestEffort");
function isOptedOut() {
  const raw = process.env["QWEN_DAEMON_LOG_FILE"];
  if (!raw) return false;
  return ["0", "false", "off", "no"].includes(raw.trim().toLowerCase());
}
__name(isOptedOut, "isOptedOut");
function computeDaemonId(pid, boundWorkspace) {
  const hash = crypto.createHash("sha256").update(boundWorkspace).digest("hex").slice(0, 8);
  return `serve-${pid}-${hash}`;
}
__name(computeDaemonId, "computeDaemonId");
function initDaemonLogger(opts) {
  if (isOptedOut()) return NOOP_LOGGER;
  const pid = opts.pid ?? process.pid;
  const now = opts.now ?? (() => /* @__PURE__ */ new Date());
  const stderr = opts.stderr ?? writeStderrLine;
  const baseDir = opts.baseDir ?? resolveDaemonLogBaseDir();
  const daemonId = computeDaemonId(pid, opts.boundWorkspace);
  const daemonDir = nodePath.join(baseDir, "daemon");
  const logPath = nodePath.join(daemonDir, `${daemonId}.log`);
  try {
    nodeFs.mkdirSync(daemonDir, { recursive: true });
    const firstLine = buildDaemonLogLine({
      level: "INFO",
      message: `daemon started pid=${pid} workspace=${opts.boundWorkspace}`,
      now: now()
    });
    nodeFs.appendFileSync(logPath, firstLine);
  } catch (err) {
    stderr(
      `qwen serve: daemon log disabled \u2014 init failed: ${err instanceof Error ? err.message : String(err)}`
    );
    return NOOP_LOGGER;
  }
  try {
    const aliasPath = nodePath.join(daemonDir, "latest");
    void updateSymlinkBestEffort(aliasPath, logPath);
  } catch {
  }
  let pending = Promise.resolve();
  let degraded = false;
  const enqueueAppend = /* @__PURE__ */ __name((line) => {
    pending = pending.then(
      () => nodeFs.promises.appendFile(logPath, line).catch((err) => {
        if (!degraded) {
          degraded = true;
          stderr(
            `qwen serve: daemon log write failed \u2014 entering degraded mode: ${err instanceof Error ? err.message : String(err)}`
          );
        }
      })
    );
  }, "enqueueAppend");
  const teeLine = /* @__PURE__ */ __name((level, message, ctx, err) => {
    const line = buildDaemonLogLine({ level, message, now: now(), ctx, err });
    stderr(line.trimEnd());
    enqueueAppend(line);
  }, "teeLine");
  return {
    info: /* @__PURE__ */ __name((message, ctx) => teeLine("INFO", message, ctx), "info"),
    warn: /* @__PURE__ */ __name((message, ctx) => teeLine("WARN", message, ctx), "warn"),
    error: /* @__PURE__ */ __name((message, err, ctx) => teeLine("ERROR", message, ctx, err ?? void 0), "error"),
    raw: /* @__PURE__ */ __name((line, level = "info") => {
      const upper = level.toUpperCase();
      const formatted = `${now().toISOString()} [${upper}] [DAEMON] ${line}
`;
      enqueueAppend(formatted);
    }, "raw"),
    getLogPath: /* @__PURE__ */ __name(() => logPath, "getLogPath"),
    getDaemonId: /* @__PURE__ */ __name(() => daemonId, "getDaemonId"),
    flush: /* @__PURE__ */ __name(() => pending, "flush")
  };
}
__name(initDaemonLogger, "initDaemonLogger");

// packages/cli/src/serve/run-qwen-serve.ts
var QWEN_SERVE_CLIENT_MCP_OVER_WS_ENV = "QWEN_SERVE_CLIENT_MCP_OVER_WS";
var QWEN_SERVE_CDP_TUNNEL_OVER_WS_ENV = "QWEN_SERVE_CDP_TUNNEL_OVER_WS";
var QWEN_SERVE_PROMPT_DEADLINE_MS_ENV = "QWEN_SERVE_PROMPT_DEADLINE_MS";
var QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV = "QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS";
var SHUTDOWN_FORCE_CLOSE_MS = 5e3;
var DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS = 12e4;
var FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS = 50;
var FAST_PATH_RUNTIME_START_FALLBACK_MS = 1e3;
var RUNTIME_STARTUP_TIMEOUT_ENV = "QWEN_SERVE_RUNTIME_STARTUP_TIMEOUT_MS";
var MAX_EVENT_RING_SIZE = 1e6;
var DEFAULT_MAX_SESSIONS = 20;
var DEFAULT_MAX_PENDING_PROMPTS_PER_SESSION = 5;
var DEFAULT_EVENT_RING_SIZE = 8e3;
var DEFAULT_SESSION_IDLE_TIMEOUT_MS = 30 * 6e4;
var WORKSPACE_SETTING_SCOPE = "Workspace";
function isPositiveIntegerMs(value) {
  return Number.isFinite(value) && Number.isInteger(value) && value > 0;
}
__name(isPositiveIntegerMs, "isPositiveIntegerMs");
function isNonNegativeIntegerOrInfinity(value) {
  return value === Number.POSITIVE_INFINITY || Number.isFinite(value) && Number.isInteger(value) && value >= 0;
}
__name(isNonNegativeIntegerOrInfinity, "isNonNegativeIntegerOrInfinity");
function isNonNegativeIntegerMs(value) {
  return Number.isFinite(value) && Number.isInteger(value) && value >= 0;
}
__name(isNonNegativeIntegerMs, "isNonNegativeIntegerMs");
var MAX_TIMEOUT_MS = 2147483647;
function assertTimerDelayInRange(name, value) {
  if (value > MAX_TIMEOUT_MS) {
    throw new TypeError(
      `Invalid ${name}: ${value}. Exceeds maximum JS timer delay of ${MAX_TIMEOUT_MS} ms (~24.8 days); Node would silently compress longer delays to 1ms.`
    );
  }
}
__name(assertTimerDelayInRange, "assertTimerDelayInRange");
function parseDeadlineEnv(envName, raw) {
  if (raw === void 0) return void 0;
  const trimmed = raw.trim();
  const parsed = Number(trimmed);
  if (!isPositiveIntegerMs(parsed)) {
    throw new Error(
      `Invalid ${envName}="${raw}": must be a positive integer (milliseconds).`
    );
  }
  return parsed;
}
__name(parseDeadlineEnv, "parseDeadlineEnv");
function envFlagDisabled(raw) {
  if (raw === void 0) return false;
  const normalized = raw.trim().toLowerCase();
  return normalized === "0" || normalized === "false";
}
__name(envFlagDisabled, "envFlagDisabled");
function hasChromeExtensionOrigin(origins) {
  return origins?.some(
    (origin) => origin.trim().toLowerCase().startsWith("chrome-extension://")
  ) === true;
}
__name(hasChromeExtensionOrigin, "hasChromeExtensionOrigin");
function createDaemonTelemetryRuntimeConfig(telemetry, cliVersion, daemonSessionId, defaults) {
  return {
    getTelemetryEnabled: /* @__PURE__ */ __name(() => telemetry.enabled ?? false, "getTelemetryEnabled"),
    getTelemetryOtlpEndpoint: /* @__PURE__ */ __name(() => telemetry.otlpEndpoint ?? defaults.otlpEndpoint, "getTelemetryOtlpEndpoint"),
    getTelemetryOtlpProtocol: /* @__PURE__ */ __name(() => telemetry.otlpProtocol ?? "grpc", "getTelemetryOtlpProtocol"),
    getTelemetryOtlpTracesEndpoint: /* @__PURE__ */ __name(() => telemetry.otlpTracesEndpoint, "getTelemetryOtlpTracesEndpoint"),
    getTelemetryOtlpLogsEndpoint: /* @__PURE__ */ __name(() => telemetry.otlpLogsEndpoint, "getTelemetryOtlpLogsEndpoint"),
    getTelemetryOtlpMetricsEndpoint: /* @__PURE__ */ __name(() => telemetry.otlpMetricsEndpoint, "getTelemetryOtlpMetricsEndpoint"),
    getTelemetryTarget: /* @__PURE__ */ __name(() => telemetry.target ?? defaults.telemetryTarget, "getTelemetryTarget"),
    getTelemetryOutfile: /* @__PURE__ */ __name(() => telemetry.outfile, "getTelemetryOutfile"),
    getTelemetryIncludeSensitiveSpanAttributes: /* @__PURE__ */ __name(() => telemetry.includeSensitiveSpanAttributes ?? false, "getTelemetryIncludeSensitiveSpanAttributes"),
    getTelemetryResourceAttributes: /* @__PURE__ */ __name(() => ({
      "service.instance.id": daemonSessionId,
      ...telemetry.resourceAttributes ?? {}
    }), "getTelemetryResourceAttributes"),
    getTelemetryMetricsIncludeSessionId: /* @__PURE__ */ __name(() => telemetry.metrics?.includeSessionId ?? false, "getTelemetryMetricsIncludeSessionId"),
    getTelemetryResourceAttributeWarnings: /* @__PURE__ */ __name(() => telemetry.resourceAttributeWarnings ?? [], "getTelemetryResourceAttributeWarnings"),
    getCliVersion: /* @__PURE__ */ __name(() => cliVersion, "getCliVersion"),
    getSessionId: /* @__PURE__ */ __name(() => daemonSessionId, "getSessionId"),
    isInteractive: /* @__PURE__ */ __name(() => false, "isInteractive"),
    getOutboundCorrelationPropagateTraceContext: /* @__PURE__ */ __name(() => false, "getOutboundCorrelationPropagateTraceContext")
  };
}
__name(createDaemonTelemetryRuntimeConfig, "createDaemonTelemetryRuntimeConfig");
var InvalidPolicyConfigError = class extends Error {
  static {
    __name(this, "InvalidPolicyConfigError");
  }
  name = "InvalidPolicyConfigError";
  constructor(message) {
    super(message);
  }
};
function validatePolicyConfig(policyConfig = {}, onWarning = writeStderrLine) {
  const validSet = new Set(
    SERVE_CAPABILITY_REGISTRY.permission_mediation.modes
  );
  const permissionStrategy = policyConfig.permissionStrategy;
  const consensusQuorum = policyConfig.consensusQuorum;
  if (permissionStrategy !== void 0 && (typeof permissionStrategy !== "string" || !validSet.has(permissionStrategy))) {
    throw new InvalidPolicyConfigError(
      `qwen serve: invalid policy.permissionStrategy "${String(permissionStrategy)}"; must be one of ${Array.from(validSet).join(", ")}`
    );
  }
  if (consensusQuorum !== void 0 && (typeof consensusQuorum !== "number" || !Number.isInteger(consensusQuorum) || consensusQuorum < 1)) {
    throw new InvalidPolicyConfigError(
      `qwen serve: invalid policy.consensusQuorum ${String(consensusQuorum)}; must be a positive integer`
    );
  }
  const consensusQuorumActive = consensusQuorum !== void 0 && permissionStrategy === "consensus";
  if (consensusQuorum !== void 0 && permissionStrategy !== "consensus") {
    onWarning(
      'qwen serve: policy.consensusQuorum is set but policy.permissionStrategy is not "consensus"; the override will be ignored.'
    );
  }
  return {
    permissionPolicy: permissionStrategy,
    permissionConsensusQuorum: consensusQuorumActive ? consensusQuorum : void 0
  };
}
__name(validatePolicyConfig, "validatePolicyConfig");
function formatHostForUrl(host) {
  if (host.startsWith("[")) return host;
  if (host.includes(":")) {
    const encoded = host.includes("%") ? host.replace(/%/g, "%25") : host;
    return `[${encoded}]`;
  }
  return host;
}
__name(formatHostForUrl, "formatHostForUrl");
function formatChannelWorkerDaemonUrl(host, port) {
  const normalized = host.trim().toLowerCase();
  if (normalized === "" || normalized === "0.0.0.0" || normalized === "::" || normalized === "[::]") {
    return `http://127.0.0.1:${port}`;
  }
  return `http://${formatHostForUrl(host)}:${port}`;
}
__name(formatChannelWorkerDaemonUrl, "formatChannelWorkerDaemonUrl");
function extractContextFilename(value) {
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed === "" ? void 0 : trimmed;
  }
  if (Array.isArray(value)) {
    for (const entry of value) {
      if (typeof entry === "string") {
        const trimmed = entry.trim();
        if (trimmed !== "") return trimmed;
      }
    }
    return void 0;
  }
  return void 0;
}
__name(extractContextFilename, "extractContextFilename");
var settingsWriteLocks = /* @__PURE__ */ new Map();
function withSettingsLock(workspace, fn) {
  const prev = settingsWriteLocks.get(workspace) ?? Promise.resolve();
  const next = prev.then(fn, fn);
  settingsWriteLocks.set(workspace, next);
  return next;
}
__name(withSettingsLock, "withSettingsLock");
var channelWorkerRuntimePromise;
async function loadChannelWorkerRuntime() {
  channelWorkerRuntimePromise ??= Promise.all([
    import("./channel-worker-supervisor-JUYQ5Z4R.js"),
    import("./pidfile-CZRBNHYT.js")
  ]).then(([supervisor, pidfile]) => ({
    createChannelWorkerSupervisor: supervisor.createChannelWorkerSupervisor,
    channelServicePidfile: pidfile
  })).catch((err) => {
    channelWorkerRuntimePromise = void 0;
    throw err;
  });
  return channelWorkerRuntimePromise;
}
__name(loadChannelWorkerRuntime, "loadChannelWorkerRuntime");
function createDisabledChannelWorkerSupervisor() {
  const snapshot = {
    enabled: false,
    state: "disabled",
    channels: []
  };
  return {
    async start() {
    },
    async stop() {
    },
    killAllSync() {
    },
    snapshot: /* @__PURE__ */ __name(() => ({ ...snapshot, channels: [] }), "snapshot")
  };
}
__name(createDisabledChannelWorkerSupervisor, "createDisabledChannelWorkerSupervisor");
function writeServeChannelReservation(channelServicePidfile, channels) {
  channelServicePidfile.reserveServeServiceInfo({
    channels,
    servePid: process.pid
  });
}
__name(writeServeChannelReservation, "writeServeChannelReservation");
function channelServicePidfileConflictError(info) {
  const owner = info.owner === "serve" ? "qwen serve" : "qwen channel start";
  return new Error(
    `Channel service is already running under ${owner} (PID ${info.pid}). Stop it before starting qwen serve --channel.`
  );
}
__name(channelServicePidfileConflictError, "channelServicePidfileConflictError");
function normalizeInstallModelIds(req, provider, getDefaultModelIds) {
  const fromRequest = req.modelIds?.map((id) => id.trim()).filter((id) => id.length > 0);
  const modelIds = fromRequest && fromRequest.length > 0 ? fromRequest : getDefaultModelIds(provider);
  return [...new Set(modelIds)];
}
__name(normalizeInstallModelIds, "normalizeInstallModelIds");
function buildProviderSetupInputs(req, provider, helpers) {
  const protocol = req.protocol ?? provider.protocol;
  const baseUrl = helpers.resolveBaseUrl(provider, req.baseUrl);
  return {
    ...provider.protocolOptions ? { protocol } : {},
    baseUrl,
    apiKey: req.apiKey.trim(),
    modelIds: normalizeInstallModelIds(
      req,
      provider,
      helpers.getDefaultModelIds
    ),
    ...req.advancedConfig ? { advancedConfig: req.advancedConfig } : {}
  };
}
__name(buildProviderSetupInputs, "buildProviderSetupInputs");
function shouldPreheatBridge(deps) {
  if (deps.preheatBridge !== void 0) return deps.preheatBridge;
  return process.env["VITEST_WORKER_ID"] === void 0;
}
__name(shouldPreheatBridge, "shouldPreheatBridge");
var coreRuntimePromise;
function loadCoreRuntime() {
  coreRuntimePromise ??= import("./src-OJMXXMHL.js");
  return coreRuntimePromise;
}
__name(loadCoreRuntime, "loadCoreRuntime");
async function resolveDaemonLogBaseDirForRun(input) {
  if (input.deps.daemonLogBaseDir) {
    return input.deps.daemonLogBaseDir;
  }
  if (input.deps.bootSettings === void 0) {
    const core2 = await loadCoreRuntime();
    if (core2.Storage.getRuntimeBaseDir() !== core2.Storage.getGlobalQwenDir()) {
      return core2.Storage.getGlobalDebugDir();
    }
  }
  if (input.bootSettings?.advanced?.runtimeOutputDir !== void 0) {
    return resolveDaemonLogBaseDir(
      input.bootSettings.advanced.runtimeOutputDir,
      input.boundWorkspace
    );
  }
  if (input.deps.bootSettings !== void 0) {
    return resolveDaemonLogBaseDir(void 0, input.boundWorkspace);
  }
  const core = await loadCoreRuntime();
  return core.Storage.getGlobalDebugDir();
}
__name(resolveDaemonLogBaseDirForRun, "resolveDaemonLogBaseDirForRun");
var settingsRuntimePromise;
function loadSettingsRuntimeModules() {
  settingsRuntimePromise ??= Promise.all([
    import("./settings-3LVM6L4S.js"),
    import("./loadedSettingsAdapter-TDBWWUN2.js"),
    import("./trustedFolders-MBJNZEIE.js")
  ]).then(([settings, loadedSettingsAdapter, trustedFolders]) => ({
    settings,
    loadedSettingsAdapter,
    trustedFolders
  }));
  return settingsRuntimePromise;
}
__name(loadSettingsRuntimeModules, "loadSettingsRuntimeModules");
async function loadServeRuntimeModules() {
  const [
    serverModule,
    bridgeModule,
    spawnChannelModule,
    workspaceModule,
    workspaceTypesModule,
    daemonStatusProviderModule,
    workspaceProvidersStatusModule,
    workspaceSkillsStatusModule
  ] = await Promise.all([
    import("./server-ZNTDV77Y.js"),
    import("./bridge-JKXXHEYJ.js"),
    import("./spawnChannel-GYC4APRS.js"),
    import("./workspace-service-AU2SKJBS.js"),
    import("./types-QX5C3CHJ.js"),
    import("./daemon-status-provider-46CFFDT7.js"),
    import("./workspace-providers-status-VGS5FUWA.js"),
    import("./workspace-skills-status-OMM4TSBD.js")
  ]);
  return {
    createServeApp: serverModule.createServeApp,
    getActiveSseCount: serverModule.getActiveSseCount,
    resolveBridgeFsFactory: serverModule.resolveBridgeFsFactory,
    createAcpSessionBridge: bridgeModule.createAcpSessionBridge,
    createSpawnChannelFactory: spawnChannelModule.createSpawnChannelFactory,
    createDaemonWorkspaceService: workspaceModule.createDaemonWorkspaceService,
    WorkspaceSettingsPartialPersistError: workspaceTypesModule.WorkspaceSettingsPartialPersistError,
    createDaemonStatusProvider: daemonStatusProviderModule.createDaemonStatusProvider,
    createWorkspaceProvidersStatusProvider: workspaceProvidersStatusModule.createWorkspaceProvidersStatusProvider,
    createWorkspaceSkillsStatusProvider: workspaceSkillsStatusModule.createWorkspaceSkillsStatusProvider
  };
}
__name(loadServeRuntimeModules, "loadServeRuntimeModules");
function advertisedMaxSessions(value) {
  if (value === void 0) return DEFAULT_MAX_SESSIONS;
  if (value === 0 || value === Number.POSITIVE_INFINITY) return null;
  return value;
}
__name(advertisedMaxSessions, "advertisedMaxSessions");
function advertisedMaxPendingPromptsPerSession(value) {
  if (value === void 0) return DEFAULT_MAX_PENDING_PROMPTS_PER_SESSION;
  if (value === 0 || value === Number.POSITIVE_INFINITY) return null;
  return value;
}
__name(advertisedMaxPendingPromptsPerSession, "advertisedMaxPendingPromptsPerSession");
function channelIdleTimeoutMs(value) {
  return value !== void 0 && Number.isFinite(value) && value > 0 ? Math.min(value, MAX_TIMEOUT_MS) : 0;
}
__name(channelIdleTimeoutMs, "channelIdleTimeoutMs");
function sessionIdleTimeoutMs(value) {
  return value !== void 0 ? channelIdleTimeoutMs(value) : DEFAULT_SESSION_IDLE_TIMEOUT_MS;
}
__name(sessionIdleTimeoutMs, "sessionIdleTimeoutMs");
function currentServeFeaturesForRunQwenServe(opts, sessionShellCommandEnabled) {
  return getAdvertisedServeFeatures(void 0, {
    requireAuth: opts.requireAuth === true,
    mcpPoolActive: opts.mcpPoolActive !== false,
    allowOriginActive: opts.allowOrigins !== void 0 && opts.allowOrigins.length > 0,
    ...opts.promptDeadlineMs !== void 0 ? { promptDeadlineMs: opts.promptDeadlineMs } : {},
    ...opts.writerIdleTimeoutMs !== void 0 ? { writerIdleTimeoutMs: opts.writerIdleTimeoutMs } : {},
    persistSettingAvailable: true,
    sessionShellCommandEnabled,
    rateLimit: opts.rateLimit === true,
    reloadAvailable: true,
    // Advertise the same WS feature flags as the runtime path (serve-features.ts)
    // so the bootstrap `/capabilities` window doesn't briefly under-report them.
    clientMcpOverWsEnabled: opts.clientMcpOverWs === true,
    cdpTunnelOverWsEnabled: opts.cdpTunnelOverWs === true
  });
}
__name(currentServeFeaturesForRunQwenServe, "currentServeFeaturesForRunQwenServe");
function createBootstrapCapabilities(input) {
  return {
    v: CAPABILITIES_SCHEMA_VERSION,
    protocolVersions: getServeProtocolVersions(),
    ...input.qwenCodeVersion ? { qwenCodeVersion: input.qwenCodeVersion } : {},
    mode: input.opts.mode,
    features: currentServeFeaturesForRunQwenServe(
      input.opts,
      input.sessionShellCommandEnabled
    ),
    modelServices: [],
    workspaceCwd: input.boundWorkspace,
    transports: ["rest"],
    policy: { permission: input.permissionPolicy ?? "first-responder" },
    limits: {
      maxPendingPromptsPerSession: advertisedMaxPendingPromptsPerSession(
        input.opts.maxPendingPromptsPerSession
      )
    }
  };
}
__name(createBootstrapCapabilities, "createBootstrapCapabilities");
function validateRateLimitOptions(opts) {
  if (opts.rateLimit !== true) return;
  for (const [name, value] of [
    ["rateLimitPrompt", opts.rateLimitPrompt],
    ["rateLimitMutation", opts.rateLimitMutation],
    ["rateLimitRead", opts.rateLimitRead]
  ]) {
    if (value !== void 0 && (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0)) {
      throw new TypeError(
        `Invalid ${name}: ${value}. Must be a positive integer.`
      );
    }
  }
  if (opts.rateLimitWindowMs !== void 0 && (!Number.isFinite(opts.rateLimitWindowMs) || !Number.isInteger(opts.rateLimitWindowMs) || opts.rateLimitWindowMs < 1e3)) {
    throw new TypeError(
      `Invalid rateLimitWindowMs: ${opts.rateLimitWindowMs}. Must be an integer >= 1000.`
    );
  }
}
__name(validateRateLimitOptions, "validateRateLimitOptions");
function installSameOriginOriginStrip(app, getPort) {
  let cachedStripPort = -1;
  let cachedSelfOrigins = /* @__PURE__ */ new Set();
  app.use((req, _res, next) => {
    const origin = req.headers.origin;
    if (origin) {
      const port = getPort();
      if (port !== cachedStripPort) {
        cachedStripPort = port;
        cachedSelfOrigins = /* @__PURE__ */ new Set([
          `http://127.0.0.1:${port}`,
          `http://localhost:${port}`,
          `http://[::1]:${port}`,
          `http://host.docker.internal:${port}`,
          `https://127.0.0.1:${port}`,
          `https://localhost:${port}`,
          `https://[::1]:${port}`,
          `https://host.docker.internal:${port}`
        ]);
        if (port === 80 || port === 443) {
          for (const host of [
            "127.0.0.1",
            "localhost",
            "[::1]",
            "host.docker.internal"
          ]) {
            cachedSelfOrigins.add(`http://${host}`);
            cachedSelfOrigins.add(`https://${host}`);
          }
        }
      }
      if (cachedSelfOrigins.has(origin)) {
        delete req.headers.origin;
      }
    }
    next();
  });
}
__name(installSameOriginOriginStrip, "installSameOriginOriginStrip");
function createLazyBridgeProxy(getBridge, getStartupError = () => void 0) {
  return new Proxy(
    {},
    {
      get(_target, prop) {
        const bridge = getBridge();
        if (!bridge) {
          const startupError = getStartupError();
          if (startupError) {
            throw new Error(
              `Daemon bridge runtime is not available: ${startupError}`
            );
          }
          throw new Error("Daemon bridge runtime is still starting.");
        }
        const value = Reflect.get(bridge, prop, bridge);
        return typeof value === "function" ? value.bind(bridge) : value;
      }
    }
  );
}
__name(createLazyBridgeProxy, "createLazyBridgeProxy");
function resolveRuntimeStartupTimeoutMs(override) {
  if (override !== void 0) {
    return Number.isFinite(override) && override > 0 ? override : 0;
  }
  const raw = process.env[RUNTIME_STARTUP_TIMEOUT_ENV];
  if (raw === void 0 || raw.trim() === "") {
    return DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS;
  }
  const trimmed = raw.trim();
  if (trimmed === "0") return 0;
  const parsed = Number(trimmed);
  return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS;
}
__name(resolveRuntimeStartupTimeoutMs, "resolveRuntimeStartupTimeoutMs");
async function waitForRuntimeStartingForShutdown(runtimeStarting, daemonLog, timeoutMs = SHUTDOWN_FORCE_CLOSE_MS) {
  if (!runtimeStarting) return;
  let timer;
  await Promise.race([
    runtimeStarting,
    new Promise((resolve) => {
      timer = setTimeout(() => {
        daemonLog.warn(
          `${timeoutMs}ms runtime-startup wait reached during shutdown; continuing listener close`
        );
        resolve();
      }, timeoutMs);
      timer.unref();
    })
  ]).finally(() => {
    if (timer) clearTimeout(timer);
  });
}
__name(waitForRuntimeStartingForShutdown, "waitForRuntimeStartingForShutdown");
var BOOTSTRAP_HEALTH_PATH = "/health";
var BOOTSTRAP_CAPABILITIES_PATH = "/capabilities";
var BOOTSTRAP_DAEMON_STATUS_PATH = "/daemon/status";
var BOOTSTRAP_SERVE_PATHS = /* @__PURE__ */ new Set([
  BOOTSTRAP_HEALTH_PATH,
  BOOTSTRAP_CAPABILITIES_PATH,
  BOOTSTRAP_DAEMON_STATUS_PATH
]);
function createBootstrapServeApp(input) {
  const {
    opts,
    getPort,
    boundWorkspace,
    startup,
    daemonLog,
    qwenCodeVersion,
    sessionShellCommandEnabled,
    permissionPolicy,
    getRuntimeError,
    getChannelWorkerSnapshot,
    onHealthServed
  } = input;
  const app = (0, import_express.default)();
  installSameOriginOriginStrip(app, getPort);
  if (opts.allowOrigins && opts.allowOrigins.length > 0) {
    app.use(allowOriginCors(parseAllowOriginPatterns(opts.allowOrigins)));
  } else {
    app.use(denyBrowserOriginCors);
  }
  app.use(hostAllowlist(opts.hostname, getPort));
  const healthHandler = /* @__PURE__ */ __name((_req, res) => {
    const runtimeError = getRuntimeError();
    if (runtimeError !== void 0) {
      res.status(503).json({
        status: "degraded",
        error: runtimeError
      });
      return;
    }
    if (onHealthServed) {
      res.once("finish", onHealthServed);
    }
    res.status(200).json({ status: "ok" });
  }, "healthHandler");
  const loopback = isLoopbackBind(opts.hostname);
  const exposeHealthPreAuth = loopback && !opts.requireAuth;
  if (exposeHealthPreAuth) {
    app.get(BOOTSTRAP_HEALTH_PATH, healthHandler);
  }
  app.use(bearerAuth(opts.token));
  if (!exposeHealthPreAuth) {
    app.get(BOOTSTRAP_HEALTH_PATH, healthHandler);
  }
  app.get(BOOTSTRAP_CAPABILITIES_PATH, (_req, res) => {
    res.status(200).json(
      createBootstrapCapabilities({
        opts,
        boundWorkspace,
        qwenCodeVersion,
        sessionShellCommandEnabled,
        permissionPolicy
      })
    );
  });
  app.get(BOOTSTRAP_DAEMON_STATUS_PATH, (req, res) => {
    const detail = parseDaemonStatusDetail(req.query["detail"]);
    if (!detail.ok || !detail.detail) {
      res.status(400).json({
        error: "detail must be one of: summary, full",
        code: "invalid_detail"
      });
      return;
    }
    const runtimeError = getRuntimeError();
    const channelWorker = getChannelWorkerSnapshot();
    const runtimeFailed = runtimeError !== void 0;
    const issue = runtimeError ? {
      code: "daemon_runtime_failed",
      severity: "error",
      message: runtimeError
    } : {
      code: "daemon_runtime_starting",
      severity: "warning",
      message: "Daemon runtime is still starting."
    };
    const response = {
      v: 1,
      detail: detail.detail,
      generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
      status: runtimeFailed ? "error" : "warning",
      issues: [issue],
      daemon: {
        pid: process.pid,
        uptimeMs: Math.round(process.uptime() * 1e3),
        mode: opts.mode,
        workspaceCwd: boundWorkspace,
        startup: {
          ...startup,
          preheat: { ...startup.preheat }
        },
        ...qwenCodeVersion ? { qwenCodeVersion } : {},
        ...daemonLog.getDaemonId() ? { daemonId: daemonLog.getDaemonId() } : {},
        ...detail.detail === "full" && daemonLog.getLogPath() ? { logPath: daemonLog.getLogPath() } : {}
      },
      security: {
        tokenConfigured: Boolean(opts.token),
        requireAuth: opts.requireAuth === true,
        loopbackBind: loopback,
        allowOriginConfigured: opts.allowOrigins !== void 0 && opts.allowOrigins.length > 0,
        allowOriginMode: allowOriginMode(opts.allowOrigins),
        sessionShellCommandEnabled
      },
      limits: {
        maxSessions: advertisedMaxSessions(opts.maxSessions),
        maxPendingPromptsPerSession: advertisedMaxPendingPromptsPerSession(
          opts.maxPendingPromptsPerSession
        ),
        listenerMaxConnections: listenerMaxConnections(opts.maxConnections),
        eventRingSize: opts.eventRingSize ?? DEFAULT_EVENT_RING_SIZE,
        promptDeadlineMs: positiveFiniteOrNull(opts.promptDeadlineMs),
        writerIdleTimeoutMs: positiveFiniteOrNull(opts.writerIdleTimeoutMs),
        channelIdleTimeoutMs: channelIdleTimeoutMs(opts.channelIdleTimeoutMs),
        sessionIdleTimeoutMs: sessionIdleTimeoutMs(opts.sessionIdleTimeoutMs),
        acpConnectionCap: null
      },
      capabilities: {
        protocolVersions: getServeProtocolVersions(),
        features: currentServeFeaturesForRunQwenServe(
          opts,
          sessionShellCommandEnabled
        )
      },
      runtime: {
        loading: runtimeError === void 0,
        ...runtimeError ? { error: runtimeError } : {},
        sessions: { active: 0 },
        permissions: {
          pending: 0,
          policy: permissionPolicy ?? "first-responder"
        },
        channel: { live: false },
        channelWorker,
        transport: {
          restSseActive: 0,
          acp: {
            enabled: false,
            connections: 0,
            connectionStreams: 0,
            sessionStreams: 0,
            sseStreams: 0,
            wsStreams: 0,
            pendingClientRequests: 0
          }
        },
        rateLimit: {
          enabled: opts.rateLimit === true,
          rejectedSinceStart: {
            prompt: 0,
            mutation: 0,
            read: 0
          }
        },
        process: process.memoryUsage()
      },
      ...detail.detail === "full" ? {
        full: {
          sessions: [],
          acpConnections: [],
          workspace: {},
          auth: {
            supportedDeviceFlowProviders: [],
            pendingDeviceFlowCount: 0
          }
        }
      } : {}
    };
    res.status(200).json(response);
  });
  app.use((_req, res) => {
    const runtimeError = getRuntimeError();
    res.status(503).json({
      error: runtimeError ? "Daemon runtime failed to start" : "Daemon runtime is still starting",
      code: runtimeError ? "daemon_runtime_failed" : "daemon_runtime_starting"
    });
  });
  return app;
}
__name(createBootstrapServeApp, "createBootstrapServeApp");
function createDelegatingServeApp(bootstrapApp, getRuntimeApp, options = {}) {
  const app = (0, import_express.default)();
  app.use((req, res, next) => {
    const dispatch = /* @__PURE__ */ __name(async () => {
      let target = getRuntimeApp();
      if (!target && options.waitForDeferredRuntimeRoutes === true && !isBootstrapServeRoute(req) && !isCorsPreflightRequest(req) && options.startRuntime && options.runtimeReady) {
        if (options.authenticateDeferredRuntimeRequest && !runSynchronousRequestGate(
          options.authenticateDeferredRuntimeRequest,
          req,
          res,
          next
        )) {
          return;
        }
        options.startRuntime();
        try {
          await options.runtimeReady;
        } catch {
        }
        target = getRuntimeApp();
      }
      const handler = target ?? bootstrapApp;
      handler(req, res, next);
    }, "dispatch");
    void dispatch().catch(next);
  });
  return app;
}
__name(createDelegatingServeApp, "createDelegatingServeApp");
function isBootstrapServeRoute(req) {
  const path2 = req.path.length > 1 && req.path.endsWith("/") ? req.path.slice(0, -1) : req.path;
  return BOOTSTRAP_SERVE_PATHS.has(path2);
}
__name(isBootstrapServeRoute, "isBootstrapServeRoute");
function isCorsPreflightRequest(req) {
  return req.method === "OPTIONS" && Boolean(req.headers.origin) && Boolean(
    req.headers["access-control-request-method"] || req.headers["access-control-request-headers"]
  );
}
__name(isCorsPreflightRequest, "isCorsPreflightRequest");
function runSynchronousRequestGate(handler, req, res, next) {
  let passed = false;
  handler(req, res, (err) => {
    if (err) {
      next(err);
      return;
    }
    passed = true;
  });
  return passed;
}
__name(runSynchronousRequestGate, "runSynchronousRequestGate");
async function runQwenServe(optsIn, deps = {}) {
  const runStartedAt = performance.now();
  const shouldPreheat = !deps.bridge && shouldPreheatBridge(deps);
  const startup = {
    processStartedAt: new Date(
      Date.now() - Math.round(process.uptime() * 1e3)
    ).toISOString(),
    preheat: {
      status: deps.bridge ? "external_bridge" : shouldPreheat ? "scheduled" : "not_scheduled"
    }
  };
  preResolveServeFastPathHomeEnvOverrides();
  const rawToken = optsIn.token ?? process.env[QWEN_SERVER_TOKEN_ENV];
  const token = typeof rawToken === "string" && rawToken.trim().length > 0 ? rawToken.trim() : void 0;
  const sessionShellCommandEnabled = optsIn.enableSessionShell === true && token !== void 0;
  if (optsIn.enableSessionShell === true && token === void 0) {
    writeStderrLine(
      `qwen serve: --enable-session-shell ignored because no bearer token is configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token to enable direct session shell.`
    );
  }
  const promptDeadlineMs = optsIn.promptDeadlineMs ?? parseDeadlineEnv(
    QWEN_SERVE_PROMPT_DEADLINE_MS_ENV,
    process.env[QWEN_SERVE_PROMPT_DEADLINE_MS_ENV]
  );
  const writerIdleTimeoutMs = optsIn.writerIdleTimeoutMs ?? parseDeadlineEnv(
    QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV,
    process.env[QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV]
  );
  const clientMcpOverWsEnv = process.env[QWEN_SERVE_CLIENT_MCP_OVER_WS_ENV];
  const cdpTunnelOverWsEnv = process.env[QWEN_SERVE_CDP_TUNNEL_OVER_WS_ENV];
  const chromeExtensionOriginAllowed = hasChromeExtensionOrigin(
    optsIn.allowOrigins
  );
  const opts = {
    ...optsIn,
    token,
    promptDeadlineMs,
    writerIdleTimeoutMs,
    clientMcpOverWs: optsIn.clientMcpOverWs ?? (!envFlagDisabled(clientMcpOverWsEnv) && clientMcpOverWsEnv !== void 0),
    cdpTunnelOverWs: optsIn.cdpTunnelOverWs ?? (!envFlagDisabled(cdpTunnelOverWsEnv) && (cdpTunnelOverWsEnv !== void 0 || chromeExtensionOriginAllowed))
  };
  const channelRuntime = opts.channelSelection ? await loadChannelWorkerRuntime() : void 0;
  const channelServicePidfile = deps.channelServicePidfile ?? channelRuntime?.channelServicePidfile;
  let channelPidfileReserved = false;
  const removeCurrentServePidfile = /* @__PURE__ */ __name(() => {
    if (!opts.channelSelection || !channelServicePidfile) return;
    if (!channelPidfileReserved) return;
    if (channelServicePidfile.removeServeServiceInfo) {
      if (channelServicePidfile.removeServeServiceInfo(process.pid)) {
        channelPidfileReserved = false;
      }
      return;
    }
    const info = channelServicePidfile.readServiceInfo();
    if (info?.owner === "serve" && info.pid === process.pid && info.servePid === process.pid) {
      channelServicePidfile.removeServiceInfo();
      channelPidfileReserved = false;
    }
  }, "removeCurrentServePidfile");
  const reserveChannelServicePidfile = /* @__PURE__ */ __name(() => {
    if (!opts.channelSelection) return;
    if (!channelServicePidfile) {
      throw new Error("Channel service pidfile runtime is not available.");
    }
    const channelPidfileNames = channelSelectionNames(opts.channelSelection);
    const existingChannelService = channelServicePidfile.readServiceInfo();
    if (existingChannelService) {
      throw channelServicePidfileConflictError(existingChannelService);
    }
    try {
      writeServeChannelReservation(channelServicePidfile, channelPidfileNames);
      channelPidfileReserved = true;
    } catch (err) {
      if (err && typeof err === "object" && "code" in err) {
        const code = err.code;
        if (code === "EEXIST") {
          const info = channelServicePidfile.readServiceInfo();
          if (info) {
            throw channelServicePidfileConflictError(info);
          }
          try {
            writeServeChannelReservation(
              channelServicePidfile,
              channelPidfileNames
            );
            channelPidfileReserved = true;
            return;
          } catch (retryErr) {
            if (retryErr && typeof retryErr === "object" && "code" in retryErr && retryErr.code === "EEXIST") {
              throw new Error(
                "Channel service is already starting. Retry after the current startup finishes."
              );
            }
            throw retryErr;
          }
        }
      }
      throw err;
    }
  }, "reserveChannelServicePidfile");
  validateRateLimitOptions(opts);
  if (!opts.hostname.startsWith("[") && opts.hostname.split(":").length === 2) {
    const [host, port] = opts.hostname.split(":");
    throw new Error(
      `Invalid --hostname "${opts.hostname}": looks like a "host:port" combination. Use --port for the port, e.g. "--hostname ${host} --port ${port}".`
    );
  }
  let tlsOptions;
  if (opts.tlsCert && !opts.tlsKey || !opts.tlsCert && opts.tlsKey) {
    throw new Error(
      `--tls-cert and --tls-key must be provided together (got only --tls-${opts.tlsCert ? "cert" : "key"}).`
    );
  }
  if (opts.tlsCert && opts.tlsKey) {
    let cert;
    let key;
    try {
      cert = fs.readFileSync(opts.tlsCert);
    } catch (err) {
      throw new Error(
        `Failed to read --tls-cert "${opts.tlsCert}": ${err instanceof Error ? err.message : String(err)}`
      );
    }
    try {
      key = fs.readFileSync(opts.tlsKey);
    } catch (err) {
      throw new Error(
        `Failed to read --tls-key "${opts.tlsKey}": ${err instanceof Error ? err.message : String(err)}`
      );
    }
    let x509;
    try {
      x509 = new X509Certificate(cert);
    } catch (err) {
      throw new Error(
        `--tls-cert "${opts.tlsCert}" is not a valid certificate: ${err instanceof Error ? err.message : String(err)}`
      );
    }
    const now = Date.now();
    if (new Date(x509.validTo).getTime() < now) {
      throw new Error(
        `--tls-cert "${opts.tlsCert}" expired on ${x509.validTo}. Renew the certificate and restart.`
      );
    }
    if (new Date(x509.validFrom).getTime() > now) {
      throw new Error(
        `--tls-cert "${opts.tlsCert}" is not yet valid (validFrom: ${x509.validFrom}). Check the certificate's notBefore date or the system clock.`
      );
    }
    tlsOptions = { cert, key };
  }
  if (!isLoopbackBind(opts.hostname) && !token) {
    throw new Error(
      `Refusing to bind ${opts.hostname}:${opts.port} without a bearer token. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or rebind to loopback (127.0.0.1, localhost, ::1, or [::1]).`
    );
  }
  if (opts.requireAuth && !token) {
    throw new Error(
      `Refusing to start with --require-auth set but no bearer token configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or omit --require-auth to keep the loopback developer default.`
    );
  }
  if (opts.allowOrigins && opts.allowOrigins.length > 0) {
    const parsed = parseAllowOriginPatterns(opts.allowOrigins);
    if (parsed.allowAny && !token) {
      throw new Error(
        `Refusing to start with --allow-origin '*' but no bearer token configured. '*' admits any cross-origin browser to the API; without a token, any local page can drive the daemon. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or list specific origins instead of '*'.`
      );
    }
    writeStderrLine(
      `qwen serve: --allow-origin: ${opts.allowOrigins.join(", ")}` + (parsed.allowAny ? " (WARNING: `*` admits any cross-origin browser \u2014 bearer token gates API routes; /health and /demo remain pre-auth on loopback unless --require-auth is set)" : "")
    );
  }
  if (opts.allowPrivateAuthBaseUrl) {
    writeStderrLine(
      "qwen serve: --allow-private-auth-base-url enabled; /workspace/auth/provider may install localhost/private-network model endpoints. Use only for local development with trusted clients."
    );
  }
  const rawWorkspace = opts.workspace ?? process.cwd();
  if (!path.isAbsolute(rawWorkspace)) {
    throw new Error(
      `Invalid --workspace "${rawWorkspace}": must be an absolute path.`
    );
  }
  try {
    const stats = fs.statSync(rawWorkspace);
    if (!stats.isDirectory()) {
      throw new Error(
        `Invalid --workspace "${rawWorkspace}": exists but is not a directory.`
      );
    }
  } catch (err) {
    if (err && typeof err === "object" && "code" in err) {
      const code = err.code;
      if (code === "ENOENT") {
        throw new Error(
          `Invalid --workspace "${rawWorkspace}": directory does not exist.`
        );
      }
      if (code === "EACCES" || code === "EPERM") {
        throw new Error(
          `Invalid --workspace "${rawWorkspace}": permission denied (${String(code)}). The path exists but cannot be stat'd by the current user.`
        );
      }
    }
    throw err;
  }
  const boundWorkspace = canonicalizeWorkspace(rawWorkspace);
  let contextFilenameForInit;
  let permissionPolicy;
  let permissionConsensusQuorum;
  let bootSettings;
  try {
    bootSettings = deps.bootSettings ?? loadServeFastPathSettings(boundWorkspace);
    contextFilenameForInit = extractContextFilename(
      bootSettings.context?.fileName
    );
    const policyConfig = bootSettings.policy ?? {};
    const resolved = validatePolicyConfig(policyConfig);
    permissionPolicy = resolved.permissionPolicy;
    permissionConsensusQuorum = resolved.permissionConsensusQuorum;
  } catch (err) {
    if (err instanceof InvalidPolicyConfigError) {
      throw err;
    }
    writeStderrLine(
      `qwen serve: could not read settings for context.fileName / policy.* (${err instanceof Error ? err.message : String(err)}); falling back to defaults. Restart with a valid settings.json to apply context.fileName / policy.* overrides.`
    );
  }
  const daemonLogBaseDir = await resolveDaemonLogBaseDirForRun({
    deps,
    bootSettings,
    boundWorkspace
  });
  const daemonLog = initDaemonLogger({
    boundWorkspace,
    baseDir: daemonLogBaseDir
  });
  writeStderrLine(
    `qwen serve: daemon log \u2192 ${daemonLog.getLogPath() || "(disabled)"}`
  );
  if (opts.mcpClientBudget !== void 0) {
    if (!Number.isFinite(opts.mcpClientBudget) || !Number.isInteger(opts.mcpClientBudget) || opts.mcpClientBudget <= 0) {
      throw new TypeError(
        `Invalid mcpClientBudget: ${opts.mcpClientBudget}. Must be a positive integer.`
      );
    }
  }
  if (opts.mcpBudgetMode === "enforce" && opts.mcpClientBudget === void 0) {
    throw new Error(
      'mcpBudgetMode="enforce" requires a positive mcpClientBudget. Pass mcpClientBudget=N, or set mcpBudgetMode to "warn" or "off".'
    );
  }
  if (opts.promptDeadlineMs !== void 0) {
    if (!isPositiveIntegerMs(opts.promptDeadlineMs)) {
      throw new TypeError(
        `Invalid promptDeadlineMs: ${opts.promptDeadlineMs}. Must be a positive integer (milliseconds).`
      );
    }
    assertTimerDelayInRange("promptDeadlineMs", opts.promptDeadlineMs);
  }
  if (opts.maxSessions !== void 0) {
    if (Number.isNaN(opts.maxSessions) || opts.maxSessions < 0) {
      throw new TypeError(
        `Invalid maxSessions: ${opts.maxSessions}. Must be a number >= 0 (0 / Infinity = unlimited).`
      );
    }
  }
  if (opts.maxPendingPromptsPerSession !== void 0) {
    if (!isNonNegativeIntegerOrInfinity(opts.maxPendingPromptsPerSession)) {
      throw new TypeError(
        `Invalid maxPendingPromptsPerSession: ${opts.maxPendingPromptsPerSession}. Must be a non-negative integer (0 / Infinity = unlimited).`
      );
    }
  }
  if (opts.eventRingSize !== void 0) {
    if (!Number.isInteger(opts.eventRingSize) || opts.eventRingSize < 1 || opts.eventRingSize > MAX_EVENT_RING_SIZE) {
      throw new TypeError(
        `Invalid eventRingSize: ${opts.eventRingSize}. Must be a positive integer in [1, ${MAX_EVENT_RING_SIZE}].`
      );
    }
  }
  if (opts.writerIdleTimeoutMs !== void 0) {
    if (!isPositiveIntegerMs(opts.writerIdleTimeoutMs)) {
      throw new TypeError(
        `Invalid writerIdleTimeoutMs: ${opts.writerIdleTimeoutMs}. Must be a positive integer (milliseconds).`
      );
    }
  }
  if (opts.channelIdleTimeoutMs !== void 0) {
    if (!Number.isFinite(opts.channelIdleTimeoutMs) || !Number.isInteger(opts.channelIdleTimeoutMs) || opts.channelIdleTimeoutMs < 0) {
      throw new TypeError(
        `Invalid channelIdleTimeoutMs: ${opts.channelIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = immediate kill).`
      );
    }
  }
  if (opts.sessionReapIntervalMs !== void 0) {
    if (!isNonNegativeIntegerMs(opts.sessionReapIntervalMs)) {
      throw new TypeError(
        `Invalid sessionReapIntervalMs: ${opts.sessionReapIntervalMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`
      );
    }
  }
  if (opts.sessionIdleTimeoutMs !== void 0) {
    if (!isNonNegativeIntegerMs(opts.sessionIdleTimeoutMs)) {
      throw new TypeError(
        `Invalid sessionIdleTimeoutMs: ${opts.sessionIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`
      );
    }
  }
  if (opts.permissionResponseTimeoutMs !== void 0) {
    if (!Number.isFinite(opts.permissionResponseTimeoutMs) || !Number.isInteger(opts.permissionResponseTimeoutMs) || opts.permissionResponseTimeoutMs < 0) {
      throw new TypeError(
        `Invalid permissionResponseTimeoutMs: ${opts.permissionResponseTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = disabled / wait forever).`
      );
    }
  }
  const inheritedNoPool = process.env["QWEN_SERVE_NO_MCP_POOL"] === "1";
  if (opts.mcpPoolActive === void 0 && inheritedNoPool) {
    opts.mcpPoolActive = false;
  }
  const childEnvOverrides = {
    QWEN_SERVE_MCP_CLIENT_BUDGET: opts.mcpClientBudget !== void 0 ? String(opts.mcpClientBudget) : void 0,
    QWEN_SERVE_MCP_BUDGET_MODE: opts.mcpBudgetMode,
    QWEN_SERVE_CDP_TUNNEL_OVER_WS: opts.cdpTunnelOverWs ? "1" : void 0
  };
  const cliVersionPromise = getCliVersion();
  let cliVersion;
  const diagnosticSink = /* @__PURE__ */ __name((line, level) => daemonLog.raw(line, level), "diagnosticSink");
  let actualPort = opts.port;
  const webShellDir = opts.serveWebShell === false ? void 0 : resolveWebShellDir();
  if (opts.serveWebShell !== false) {
    if (!webShellDir) {
      writeStderrLine(
        "qwen serve: Web Shell assets not found; serving API only. Build the web-shell workspace (npm run build) or pass --no-web to silence this."
      );
    } else {
      writeStderrLine(`qwen serve: Web Shell UI served from ${webShellDir}`);
      if (!isLoopbackBind(opts.hostname)) {
        writeStderrLine(
          "qwen serve: Web Shell UI is served WITHOUT auth on a non-loopback bind (the static shell has no secrets; the API stays token-gated). Pass --no-web to disable the UI."
        );
        if (!opts.allowOrigins || opts.allowOrigins.length === 0) {
          writeStderrLine(
            "qwen serve: without --allow-origin the Web Shell is read-only on a non-loopback bind \u2014 same-origin POSTs are blocked by CORS (403). Pass --allow-origin <origin> or front it with a same-origin proxy."
          );
        }
      }
    }
  }
  const webShellMounted = !!webShellDir;
  let runtimeApp;
  let runtimeAppForCleanup;
  let bridgeRef = deps.bridge;
  let daemonEventLoopMonitor;
  let runtimeStartupError;
  let runtimeStarting;
  let markRuntimeReady;
  let markRuntimeFailed;
  let runtimeStartupSettled = false;
  let startRuntimeAfterHealth;
  let startRuntimeForRequest;
  const deferRuntimeUntilFirstHealth = deps.resolveOnListen === true && deps.deferRuntimeUntilFirstHealth === true;
  const runtimeReady = new Promise((resolve, reject) => {
    markRuntimeReady = resolve;
    markRuntimeFailed = reject;
  });
  void runtimeReady.catch(() => {
  });
  const disposeDaemonEventLoopMonitor = /* @__PURE__ */ __name(() => {
    daemonEventLoopMonitor?.dispose();
    daemonEventLoopMonitor = void 0;
  }, "disposeDaemonEventLoopMonitor");
  let channelWorker = createDisabledChannelWorkerSupervisor();
  const getChannelWorkerSnapshot = /* @__PURE__ */ __name(() => channelWorker.snapshot(), "getChannelWorkerSnapshot");
  const writeChannelWorkerPidfile = /* @__PURE__ */ __name((snapshot = channelWorker.snapshot(), options = {}) => {
    if (!opts.channelSelection || !channelServicePidfile) return;
    try {
      channelServicePidfile.writeServeServiceInfo({
        channels: snapshot.channels,
        servePid: process.pid,
        ...!options.clearWorkerPid && snapshot.pid !== void 0 ? { workerPid: snapshot.pid } : {}
      });
    } catch (err) {
      daemonLog.warn(
        `failed to write channel worker pidfile metadata: ${err instanceof Error ? err.message : String(err)}`
      );
    }
  }, "writeChannelWorkerPidfile");
  const handleBridge = deps.bridge ?? createLazyBridgeProxy(
    () => bridgeRef,
    () => runtimeStartupError
  );
  const buildRuntime = /* @__PURE__ */ __name(async () => {
    const [runtime, core, settingsRuntime, resolvedCliVersion] = await Promise.all([
      loadServeRuntimeModules(),
      loadCoreRuntime(),
      loadSettingsRuntimeModules(),
      cliVersionPromise
    ]);
    cliVersion = resolvedCliVersion;
    let runtimeBootSettings;
    try {
      runtimeBootSettings = settingsRuntime.settings.loadSettings(boundWorkspace);
    } catch (err) {
      writeStderrLine(
        `qwen serve: could not read full settings for runtime startup (${err instanceof Error ? err.message : String(err)}); falling back to defaults.`
      );
    }
    const trustedWorkspace = deps.trustedWorkspace ?? (runtimeBootSettings ? settingsRuntime.trustedFolders.getWorkspaceTrustStatus(
      runtimeBootSettings.merged,
      boundWorkspace
    ).effective.state === "trusted" : true);
    if (deps.trustedWorkspace === void 0 && runtimeBootSettings && !trustedWorkspace) {
      daemonLog.warn(
        "workspace file writes are disabled because the bound workspace is not trusted",
        { workspace: boundWorkspace }
      );
    }
    const daemonWorkspaceHash = core.hashDaemonWorkspace(boundWorkspace);
    let daemonTelemetrySettings;
    try {
      daemonTelemetrySettings = await core.resolveTelemetrySettings({
        env: process.env,
        settings: runtimeBootSettings?.merged.telemetry
      });
    } catch (err) {
      if (err instanceof core.FatalConfigError) {
        throw new core.FatalConfigError(
          `Invalid telemetry configuration: ${err.message}.`
        );
      }
      throw err;
    }
    core.initializeTelemetry(
      createDaemonTelemetryRuntimeConfig(
        daemonTelemetrySettings,
        resolvedCliVersion,
        `daemon:${daemonWorkspaceHash}:${process.pid}`,
        {
          otlpEndpoint: core.DEFAULT_OTLP_ENDPOINT,
          telemetryTarget: core.DEFAULT_TELEMETRY_TARGET
        }
      )
    );
    core.initializeDaemonMetrics();
    daemonEventLoopMonitor?.dispose();
    daemonEventLoopMonitor = core.startEventLoopLagMonitor({
      onNewMaxStall: /* @__PURE__ */ __name((maxMs) => {
        daemonLog.warn("daemon event loop stall detected", { maxMs });
      }, "onNewMaxStall")
    });
    const currentDaemonEventLoopMonitor = daemonEventLoopMonitor;
    core.registerDaemonEventLoopLagGauge(
      () => currentDaemonEventLoopMonitor.snapshot()
    );
    const pipeStats = {
      inbound: { count: 0, totalBytes: 0, maxBytes: 0 },
      outbound: { count: 0, totalBytes: 0, maxBytes: 0 }
    };
    const recordPipeMessage = /* @__PURE__ */ __name((direction, bytes) => {
      const stats = pipeStats[direction];
      stats.count += 1;
      stats.totalBytes += bytes;
      stats.maxBytes = Math.max(stats.maxBytes, bytes);
      core.recordDaemonPipeMessage(direction, bytes);
    }, "recordPipeMessage");
    const daemonTelemetry = core.createDaemonBridgeTelemetry();
    daemonTelemetry.metrics = {
      sessionLifecycle(action) {
        core.recordDaemonSessionLifecycle(action);
        core.emitDaemonLog(
          `Session ${action}.`,
          {
            "qwen-code.workspace.hash": daemonWorkspaceHash
          },
          {
            eventName: `qwen-code.daemon.session.${action}`
          }
        );
      },
      channelLifecycle(action, expected) {
        core.recordDaemonChannelLifecycle(action, expected);
        core.emitDaemonLog(
          action === "spawn" ? "ACP channel spawned." : `ACP channel exited (expected=${expected ?? true}).`,
          {
            ...action === "exit" ? { "qwen-code.daemon.channel.expected": expected ?? true } : {}
          },
          {
            eventName: `qwen-code.daemon.channel.${action}`,
            ...expected === false && action === "exit" ? { severityNumber: 13 } : {}
          }
        );
      },
      promptQueueWait: core.recordDaemonPromptQueueWait,
      promptDuration: core.recordDaemonPromptDuration,
      cancelled: core.recordDaemonCancel
    };
    const permissionAuditRing = new PermissionAuditRing();
    const permissionAuditPublisher = createPermissionAuditPublisher({
      ring: permissionAuditRing
    });
    const customIgnoreFiles = runtimeBootSettings?.merged.context?.fileFiltering?.customIgnoreFiles;
    const fsFactory = runtime.resolveBridgeFsFactory({
      boundWorkspace,
      injected: deps.fsFactory,
      trusted: trustedWorkspace,
      emit: deps.fsAuditEmit,
      ...customIgnoreFiles !== void 0 ? { customIgnoreFiles } : {}
    });
    const channelFactory = runtime.createSpawnChannelFactory({
      onDiagnosticLine: diagnosticSink,
      pipeHooks: {
        onMessageSent: /* @__PURE__ */ __name((bytes) => recordPipeMessage("outbound", bytes), "onMessageSent"),
        onMessageReceived: /* @__PURE__ */ __name((bytes) => recordPipeMessage("inbound", bytes), "onMessageReceived")
      },
      ...opts.experimentalLsp === true ? { extraArgs: ["--experimental-lsp"] } : {}
    });
    const statusProvider = runtime.createDaemonStatusProvider();
    const workspaceProvidersStatusProvider = runtime.createWorkspaceProvidersStatusProvider();
    const workspaceSkillsStatusProvider = runtime.createWorkspaceSkillsStatusProvider();
    const clientMcpSenderRegistry = new ClientMcpSenderRegistry();
    const persistDisabledToolsFn = /* @__PURE__ */ __name((workspace, toolName, enabled) => withSettingsLock(workspace, async () => {
      const fresh = settingsRuntime.settings.loadSettings(workspace);
      const wsScope = fresh.forScope(WORKSPACE_SETTING_SCOPE).settings;
      const wsDisabled = wsScope.tools?.disabled;
      const current = Array.isArray(wsDisabled) ? wsDisabled.filter((v) => typeof v === "string") : [];
      const next = new Set(current);
      if (enabled) next.delete(toolName);
      else next.add(toolName);
      fresh.setValue(
        WORKSPACE_SETTING_SCOPE,
        "tools.disabled",
        [...next].sort()
      );
    }), "persistDisabledToolsFn");
    const persistSettingFn = /* @__PURE__ */ __name((workspace, scope, key, value) => withSettingsLock(workspace, async () => {
      const fresh = settingsRuntime.settings.loadSettings(workspace);
      fresh.setValue(scope, key, value);
      return fresh;
    }), "persistSettingFn");
    const persistSettingsFn = /* @__PURE__ */ __name((workspace, writes) => withSettingsLock(workspace, async () => {
      const fresh = settingsRuntime.settings.loadSettings(workspace);
      const writesByScope = /* @__PURE__ */ new Map();
      for (const write of writes) {
        writesByScope.set(
          write.scope,
          (writesByScope.get(write.scope) ?? 0) + 1
        );
      }
      const committedScopes = /* @__PURE__ */ new Set();
      let committed = 0;
      try {
        fresh.setValues(writes, (scope) => {
          committedScopes.add(scope);
          committed += writesByScope.get(scope) ?? 0;
        });
      } catch (err) {
        const failedWrite = writes.find((write) => !committedScopes.has(write.scope)) ?? writes[committed];
        const message = `persistSettings partial failure (workspace=${workspace}, committed=${committed}/${writes.length}, failedKey=${failedWrite?.key ?? "<unknown>"}, failedScope=${failedWrite?.scope ?? "<unknown>"}): ${err instanceof Error ? err.message : String(err)}`;
        writeStderrLine(`qwen serve: ${message}`);
        throw new runtime.WorkspaceSettingsPartialPersistError(
          message,
          writes.filter((write) => committedScopes.has(write.scope)),
          err
        );
      }
    }), "persistSettingsFn");
    const bridge = deps.bridge ?? runtime.createAcpSessionBridge({
      // Reverse tool channel: let `BridgeClient.extMethod` reach the WS
      // connection that hosts a named client MCP server (#5626).
      clientMcpSender: clientMcpSenderRegistry.lookup,
      maxSessions: opts.maxSessions,
      ...opts.maxPendingPromptsPerSession !== void 0 ? { maxPendingPromptsPerSession: opts.maxPendingPromptsPerSession } : {},
      ...opts.eventRingSize !== void 0 ? { eventRingSize: opts.eventRingSize } : {},
      ...opts.channelIdleTimeoutMs !== void 0 ? { channelIdleTimeoutMs: opts.channelIdleTimeoutMs } : {},
      ...opts.sessionReapIntervalMs !== void 0 ? { sessionReapIntervalMs: opts.sessionReapIntervalMs } : {},
      ...opts.sessionIdleTimeoutMs !== void 0 ? { sessionIdleTimeoutMs: opts.sessionIdleTimeoutMs } : {},
      ...opts.permissionResponseTimeoutMs !== void 0 ? { permissionResponseTimeoutMs: opts.permissionResponseTimeoutMs } : {},
      boundWorkspace,
      sessionShellCommandEnabled,
      childEnvOverrides,
      channelFactory,
      onDiagnosticLine: diagnosticSink,
      telemetry: daemonTelemetry,
      ...permissionPolicy !== void 0 ? { permissionPolicy } : {},
      ...permissionConsensusQuorum !== void 0 ? { permissionConsensusQuorum } : {},
      permissionAudit: permissionAuditPublisher,
      statusProvider,
      fileSystem: createBridgeFileSystemAdapter(fsFactory),
      persistApprovalMode: /* @__PURE__ */ __name((workspace, mode) => withSettingsLock(workspace, async () => {
        const fresh = settingsRuntime.settings.loadSettings(workspace);
        fresh.setValue(WORKSPACE_SETTING_SCOPE, "tools.approvalMode", mode);
      }), "persistApprovalMode")
    });
    if (!deps.bridge) {
      bridgeRef = bridge;
    }
    const workspaceService = runtime.createDaemonWorkspaceService({
      boundWorkspace,
      contextFilename: contextFilenameForInit ?? "QWEN.md",
      statusProvider,
      workspaceProvidersStatusProvider,
      workspaceSkillsStatusProvider,
      isChannelLive: /* @__PURE__ */ __name(() => bridge.isChannelLive(), "isChannelLive"),
      persistDisabledTools: persistDisabledToolsFn,
      persistSetting: persistSettingFn,
      persistSettings: persistSettingsFn,
      reloadDaemonEnv: /* @__PURE__ */ __name((workspace) => withSettingsLock(workspace, async () => {
        const fresh = settingsRuntime.settings.loadSettings(workspace, {
          skipLoadEnvironment: true
        });
        return settingsRuntime.settings.reloadEnvironment(
          fresh.merged,
          workspace
        );
      }), "reloadDaemonEnv"),
      queryWorkspaceStatus: /* @__PURE__ */ __name((method, idle) => bridge.queryWorkspaceStatus(method, idle), "queryWorkspaceStatus"),
      invokeWorkspaceCommand: /* @__PURE__ */ __name((method, params, invokeOpts) => bridge.invokeWorkspaceCommand(method, params, invokeOpts), "invokeWorkspaceCommand"),
      refreshExtensionsForAllSessions: /* @__PURE__ */ __name(() => bridge.refreshExtensionsForAllSessions(), "refreshExtensionsForAllSessions"),
      publishWorkspaceEvent: /* @__PURE__ */ __name((event) => bridge.publishWorkspaceEvent(event), "publishWorkspaceEvent")
    });
    core.registerDaemonGaugeCallbacks({
      sessionCount: /* @__PURE__ */ __name(() => bridge.sessionCount, "sessionCount"),
      sseCount: /* @__PURE__ */ __name(() => runtime.getActiveSseCount(), "sseCount"),
      heapUsed: /* @__PURE__ */ __name(() => process.memoryUsage().heapUsed, "heapUsed")
    });
    const app2 = runtime.createServeApp(opts, () => actualPort, {
      bridge,
      webShellDir,
      boundWorkspace,
      qwenCodeVersion: resolvedCliVersion,
      startup,
      fsFactory,
      daemonLog,
      getChannelWorkerSnapshot,
      getPerfSnapshot: /* @__PURE__ */ __name(() => ({
        eventLoop: currentDaemonEventLoopMonitor.snapshot(),
        pipe: {
          inbound: { ...pipeStats.inbound },
          outbound: { ...pipeStats.outbound }
        }
      }), "getPerfSnapshot"),
      workspace: workspaceService,
      // Reverse tool channel (#5626): the SAME registry wired into `bridge` above,
      // so the WS provider and the child-answering bridge share one sender map.
      clientMcpSenderRegistry,
      persistDisabledTools: persistDisabledToolsFn,
      persistSetting: persistSettingFn,
      persistSettings: persistSettingsFn,
      installAuthProvider: /* @__PURE__ */ __name((req) => withSettingsLock(
        boundWorkspace,
        async () => {
          const provider = core.findProviderById(req.providerId);
          if (!provider) {
            throw new Error(`Unsupported auth provider: ${req.providerId}`);
          }
          const inputs = buildProviderSetupInputs(req, provider, {
            getDefaultModelIds: core.getDefaultModelIds,
            resolveBaseUrl: core.resolveBaseUrl
          });
          const plan = core.buildInstallPlan(provider, inputs);
          const fresh = settingsRuntime.settings.loadSettings(boundWorkspace);
          const adapter = settingsRuntime.loadedSettingsAdapter.createLoadedSettingsAdapter(
            fresh
          );
          await core.applyProviderInstallPlan(plan, {
            settings: adapter,
            doRefreshAuth: false
          });
          core.emitDaemonLog("Auth provider installed.", {
            "qwen-code.daemon.auth.provider_id": provider.id,
            "qwen-code.daemon.auth.auth_type": plan.authType
          });
          const effectiveModelId = adapter.getValue("model.name") ?? plan.modelSelection?.modelId;
          const effectiveBaseUrl = adapter.getValue("model.baseUrl") ?? plan.modelSelection?.baseUrl ?? inputs.baseUrl;
          return {
            v: 1,
            providerId: provider.id,
            providerLabel: provider.label,
            authType: plan.authType,
            ...effectiveModelId ? { modelId: effectiveModelId } : {},
            ...effectiveBaseUrl ? { baseUrl: effectiveBaseUrl } : {},
            message: `Successfully configured ${provider.label}. Use /model to switch models.`
          };
        }
      ), "installAuthProvider")
    });
    return { app: app2, bridge };
  }, "buildRuntime");
  if (deps.bridge) {
    const runtime = await buildRuntime();
    runtimeAppForCleanup = runtime.app;
    runtimeApp = runtime.app;
    bridgeRef = runtime.bridge;
    if (!opts.channelSelection) {
      runtimeStartupSettled = true;
      markRuntimeReady();
    }
  }
  cliVersion ??= await cliVersionPromise;
  const bootstrapApp = createBootstrapServeApp({
    opts,
    getPort: /* @__PURE__ */ __name(() => actualPort, "getPort"),
    boundWorkspace,
    startup,
    daemonLog,
    qwenCodeVersion: cliVersion,
    sessionShellCommandEnabled,
    permissionPolicy,
    getRuntimeError: /* @__PURE__ */ __name(() => runtimeStartupError, "getRuntimeError"),
    getChannelWorkerSnapshot,
    onHealthServed: deferRuntimeUntilFirstHealth ? () => startRuntimeAfterHealth?.() : void 0
  });
  const app = runtimeApp ?? createDelegatingServeApp(bootstrapApp, () => runtimeApp, {
    waitForDeferredRuntimeRoutes: deferRuntimeUntilFirstHealth,
    startRuntime: /* @__PURE__ */ __name(() => startRuntimeForRequest?.(), "startRuntime"),
    runtimeReady,
    authenticateDeferredRuntimeRequest: bearerAuth(opts.token)
  });
  let listenHostname = opts.hostname;
  if (opts.hostname.startsWith("[")) {
    const inner = opts.hostname.slice(1, -1);
    if (!opts.hostname.endsWith("]") || inner.length === 0 || inner.includes("]")) {
      throw new Error(
        `Invalid --hostname "${opts.hostname}": brackets indicate an IPv6 literal but the value isn't a clean [addr] form. Pass the address without a trailing :port (use --port for that), e.g. "--hostname [::1] --port 4170".`
      );
    }
    listenHostname = inner;
  }
  if (opts.maxConnections !== void 0 && (Number.isNaN(opts.maxConnections) || opts.maxConnections < 0)) {
    throw new TypeError(
      `Invalid maxConnections: ${opts.maxConnections}. Must be >= 0 (0 / Infinity = unlimited).`
    );
  }
  reserveChannelServicePidfile();
  return await new Promise((resolve, reject) => {
    const onListening = /* @__PURE__ */ __name(() => {
      startup.listenerReadyAt = (/* @__PURE__ */ new Date()).toISOString();
      startup.processToListenMs = Math.round(process.uptime() * 1e3);
      startup.runQwenServeToListenMs = Math.round(
        performance.now() - runStartedAt
      );
      profileCheckpoint("serve_listener_ready");
      finalizeStartupProfile(daemonLog.getDaemonId() || "serve");
      const cap = opts.maxConnections ?? 256;
      if (cap > 0 && Number.isFinite(cap)) {
        server.maxConnections = cap;
      }
      const addr = server.address();
      actualPort = typeof addr === "object" && addr ? addr.port : opts.port;
      const scheme = tlsOptions ? "https" : "http";
      const url = `${scheme}://${formatHostForUrl(opts.hostname)}:${actualPort}`;
      try {
        if (opts.channelSelection) {
          const createSupervisor = deps.channelWorkerSupervisorFactory ?? channelRuntime?.createChannelWorkerSupervisor;
          if (!createSupervisor) {
            throw new Error(
              "Channel worker supervisor runtime is not available."
            );
          }
          channelWorker = createSupervisor({
            cliEntryPath: findCliEntryPath(),
            daemonUrl: formatChannelWorkerDaemonUrl(opts.hostname, actualPort),
            ...token ? { daemonToken: token } : {},
            workspace: boundWorkspace,
            selection: opts.channelSelection,
            onReady: /* @__PURE__ */ __name((snapshot) => {
              writeChannelWorkerPidfile(snapshot);
            }, "onReady"),
            onLog: /* @__PURE__ */ __name(({ stream, line }) => {
              const message = `channel worker ${stream}: ${line}`;
              if (stream === "stderr") {
                daemonLog.warn(message);
              } else {
                daemonLog.info(message);
              }
            }, "onLog"),
            onExit: /* @__PURE__ */ __name((snapshot) => {
              daemonLog.warn(
                `channel worker exited (state=${snapshot.state}, pid=${snapshot.pid ?? "unknown"}, code=${snapshot.exitCode ?? "null"}, signal=${snapshot.signal ?? "null"}, error=${snapshot.error ?? "none"}, restartCount=${snapshot.restartCount ?? 0}, nextRestartAt=${snapshot.nextRestartAt ?? "none"}, staleHeartbeatAt=${snapshot.staleHeartbeatAt ?? "none"})`
              );
              writeChannelWorkerPidfile(snapshot, { clearWorkerPid: true });
            }, "onExit")
          });
        }
      } catch (err) {
        removeCurrentServePidfile();
        const error = err instanceof Error ? err : new Error(String(err));
        server.close((closeErr) => {
          if (closeErr) {
            daemonLog.error(
              "server close after channel worker setup error failed",
              closeErr
            );
          }
          reject(error);
        });
        return;
      }
      writeStdoutLine(
        `qwen serve listening on ${url} (mode=${opts.mode}, workspace=${boundWorkspace})`
      );
      writeStderrLine(
        `qwen serve: bound to workspace ${JSON.stringify(boundWorkspace)}`
      );
      writeStderrLine(
        `qwen serve: startup timing: processToListenMs=${startup.processToListenMs} runQwenServeToListenMs=${startup.runQwenServeToListenMs}`
      );
      if (!token) {
        writeStderrLine(
          `qwen serve: bearer auth disabled (loopback default). Set ${QWEN_SERVER_TOKEN_ENV} to enable.`
        );
        if (opts.clientMcpOverWs === true) {
          writeStderrLine(
            `qwen serve: client-hosted MCP tools are accepted over the WebSocket without auth. Set ${QWEN_SERVE_CLIENT_MCP_OVER_WS_ENV}=0 to disable.`
          );
        }
      } else if (opts.requireAuth) {
        writeStderrLine(
          "qwen serve: --require-auth enabled (bearer token mandatory on every route, including loopback /health)."
        );
      }
      let shuttingDown = false;
      let closePromise;
      let runtimeStartupTimer;
      let runtimeStartAfterHealthTimer;
      let runtimeStartFallbackTimer;
      const runtimeStartupTimeoutMs = resolveRuntimeStartupTimeoutMs(
        deps.runtimeStartupTimeoutMs
      );
      const clearRuntimeStartupTimer = /* @__PURE__ */ __name(() => {
        if (!runtimeStartupTimer) return;
        clearTimeout(runtimeStartupTimer);
        runtimeStartupTimer = void 0;
      }, "clearRuntimeStartupTimer");
      const clearRuntimeStartFallbackTimer = /* @__PURE__ */ __name(() => {
        if (!runtimeStartFallbackTimer) return;
        clearTimeout(runtimeStartFallbackTimer);
        runtimeStartFallbackTimer = void 0;
      }, "clearRuntimeStartFallbackTimer");
      const clearRuntimeStartAfterHealthTimer = /* @__PURE__ */ __name(() => {
        if (!runtimeStartAfterHealthTimer) return;
        clearTimeout(runtimeStartAfterHealthTimer);
        runtimeStartAfterHealthTimer = void 0;
      }, "clearRuntimeStartAfterHealthTimer");
      const cancelDeferredRuntimeStartup = /* @__PURE__ */ __name(() => {
        if (!deferRuntimeUntilFirstHealth || runtimeStarting || runtimeStartupSettled)
          return;
        daemonLog.info(
          "deferred runtime: cancelled, server closed before startup"
        );
        runtimeStartupSettled = true;
        const error = new Error(RUNTIME_STARTUP_CANCELLED_MESSAGE);
        runtimeStartupError = error.message;
        markRuntimeFailed(error);
      }, "cancelDeferredRuntimeStartup");
      const shutdownBridgeAfterFailedStartup = /* @__PURE__ */ __name(async (bridge) => {
        if (!bridge || deps.bridge) return;
        try {
          await bridge.shutdown();
        } catch (shutdownErr) {
          daemonLog.error(
            "bridge shutdown after runtime startup error failed",
            shutdownErr instanceof Error ? shutdownErr : null
          );
        } finally {
          if (bridgeRef === bridge) {
            bridgeRef = void 0;
          }
        }
      }, "shutdownBridgeAfterFailedStartup");
      const stopChannelWorkerAfterFailedStartup = /* @__PURE__ */ __name(async () => {
        await channelWorker.stop().catch((stopErr) => {
          daemonLog.error(
            "channel worker stop after runtime startup error failed",
            stopErr instanceof Error ? stopErr : null
          );
        });
      }, "stopChannelWorkerAfterFailedStartup");
      const failRuntimeStartup = /* @__PURE__ */ __name(async (err, bridgeForCleanup) => {
        const error = err instanceof Error ? err : new Error(String(err));
        if (runtimeStartupSettled) {
          await shutdownBridgeAfterFailedStartup(bridgeForCleanup);
          return;
        }
        runtimeStartupSettled = true;
        clearRuntimeStartupTimer();
        const message = error.message;
        runtimeStartupError = message;
        if (startup.preheat.status === "scheduled" || startup.preheat.status === "running") {
          startup.preheat.status = "failed";
          startup.preheat.error = message;
        }
        writeStderrLine(`qwen serve: runtime startup failed: ${message}`);
        daemonLog.error("runtime startup failed", error);
        await stopChannelWorkerAfterFailedStartup();
        disposeDaemonEventLoopMonitor();
        removeCurrentServePidfile();
        await shutdownBridgeAfterFailedStartup(bridgeForCleanup ?? bridgeRef);
        markRuntimeFailed(error);
      }, "failRuntimeStartup");
      const armRuntimeStartupTimer = /* @__PURE__ */ __name(() => {
        if (runtimeStartupTimeoutMs <= 0 || runtimeStartupTimer) return;
        runtimeStartupTimer = setTimeout(() => {
          void failRuntimeStartup(
            new Error(
              `Daemon runtime startup timed out after ${runtimeStartupTimeoutMs}ms.`
            )
          );
        }, runtimeStartupTimeoutMs);
        runtimeStartupTimer.unref();
      }, "armRuntimeStartupTimer");
      const completeRuntimeStartup = /* @__PURE__ */ __name(async () => {
        if (runtimeStartupSettled) return;
        if (opts.channelSelection) {
          await channelWorker.start();
          if (runtimeStartupSettled) return;
        }
        if (runtimeStartupSettled) return;
        runtimeStartupSettled = true;
        clearRuntimeStartupTimer();
        markRuntimeReady();
      }, "completeRuntimeStartup");
      const startBridgePreheat = /* @__PURE__ */ __name((bridge) => {
        startup.preheat.status = "running";
        const preheatStartedAt = performance.now();
        bridge.preheat().then(() => {
          startup.preheat.status = "succeeded";
          startup.preheat.durationMs = Math.round(
            performance.now() - preheatStartedAt
          );
        }).catch((err) => {
          const message = err instanceof Error ? err.message : String(err);
          startup.preheat.status = "failed";
          startup.preheat.durationMs = Math.round(
            performance.now() - preheatStartedAt
          );
          startup.preheat.error = message;
          writeStderrLine(
            `qwen serve: ACP preheat failed, will retry on first session: ${message}`
          );
        });
      }, "startBridgePreheat");
      const startRuntime = /* @__PURE__ */ __name(() => {
        if (runtimeStarting) return;
        armRuntimeStartupTimer();
        clearRuntimeStartAfterHealthTimer();
        clearRuntimeStartFallbackTimer();
        runtimeStarting = buildRuntime().then(async (runtime) => {
          if (runtimeStartupSettled) {
            await shutdownBridgeAfterFailedStartup(runtime.bridge);
            return;
          }
          bridgeRef = runtime.bridge;
          runtimeAppForCleanup = runtime.app;
          if (shuttingDown) {
            await failRuntimeStartup(
              new Error("Daemon runtime stopped before mounting."),
              runtime.bridge
            );
            return;
          }
          runtimeApp = runtime.app;
          const acpHandle = runtime.app.locals?.["acpHandle"];
          acpHandle?.attachServer?.(server);
          if (shouldPreheat) {
            startBridgePreheat(runtime.bridge);
          }
          await completeRuntimeStartup();
        }).catch((err) => failRuntimeStartup(err));
      }, "startRuntime");
      startRuntimeForRequest = startRuntime;
      const scheduleRuntimeStartFallback = /* @__PURE__ */ __name(() => {
        if (shuttingDown || runtimeStarting || runtimeStartFallbackTimer)
          return;
        daemonLog.info(
          `deferred runtime: scheduling fallback start in ${FAST_PATH_RUNTIME_START_FALLBACK_MS}ms`
        );
        runtimeStartFallbackTimer = setTimeout(() => {
          runtimeStartFallbackTimer = void 0;
          if (shuttingDown) return;
          daemonLog.info("deferred runtime: fallback timer fired, starting");
          startRuntime();
        }, FAST_PATH_RUNTIME_START_FALLBACK_MS);
        runtimeStartFallbackTimer.unref();
      }, "scheduleRuntimeStartFallback");
      startRuntimeAfterHealth = /* @__PURE__ */ __name(() => {
        if (shuttingDown || runtimeStarting || runtimeStartAfterHealthTimer) {
          return;
        }
        clearRuntimeStartFallbackTimer();
        daemonLog.info(
          `deferred runtime: health served, scheduling start in ${FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS}ms`
        );
        runtimeStartAfterHealthTimer = setTimeout(() => {
          runtimeStartAfterHealthTimer = void 0;
          if (shuttingDown) return;
          daemonLog.info("deferred runtime: health timer fired, starting");
          startRuntime();
        }, FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS);
        runtimeStartAfterHealthTimer.unref();
      }, "startRuntimeAfterHealth");
      const onSignal = /* @__PURE__ */ __name(async (signal) => {
        if (shuttingDown) {
          daemonLog.warn(`received ${signal} during drain \u2014 forcing exit`);
          try {
            channelWorker.killAllSync();
            bridgeRef?.killAllSync();
            removeCurrentServePidfile();
          } catch (err) {
            daemonLog.error(
              "force-kill error",
              err instanceof Error ? err : null
            );
          }
          await daemonLog.flush().catch(() => {
          });
          process.exit(1);
          return;
        }
        daemonLog.warn(`received ${signal}, draining`);
        try {
          await handle.close();
          await daemonLog.flush();
          process.exit(0);
        } catch (err) {
          daemonLog.error("shutdown error", err instanceof Error ? err : null);
          await daemonLog.flush().catch(() => {
          });
          process.exit(1);
        }
      }, "onSignal");
      const onUncaughtExceptionMonitor = /* @__PURE__ */ __name(() => {
        if (process.listenerCount("uncaughtException") === 0) {
          removeCurrentServePidfile();
        }
      }, "onUncaughtExceptionMonitor");
      const handle = {
        server,
        url,
        bridge: handleBridge,
        webShellMounted,
        resolvedToken: token,
        runtimeReady,
        close: /* @__PURE__ */ __name(() => {
          if (closePromise) return closePromise;
          closePromise = new Promise((res, rej) => {
            shuttingDown = true;
            clearRuntimeStartAfterHealthTimer();
            clearRuntimeStartFallbackTimer();
            cancelDeferredRuntimeStartup();
            let settled = false;
            let bridgeShutdownError;
            const finish = /* @__PURE__ */ __name((err) => {
              if (settled) return;
              settled = true;
              process.removeListener("SIGINT", onSignal);
              process.removeListener("SIGTERM", onSignal);
              process.removeListener(
                "uncaughtExceptionMonitor",
                onUncaughtExceptionMonitor
              );
              void (coreRuntimePromise ? coreRuntimePromise.then((core) => core.shutdownTelemetry()) : Promise.resolve()).catch((telemetryErr) => {
                writeStderrLine(
                  `qwen serve: telemetry shutdown error: ${telemetryErr instanceof Error ? telemetryErr.message : String(telemetryErr)}`
                );
              }).finally(() => daemonLog.flush().catch(() => {
              })).finally(() => {
                const finalErr = err ?? bridgeShutdownError;
                if (finalErr) rej(finalErr);
                else res();
              });
            }, "finish");
            void (coreRuntimePromise ? coreRuntimePromise.then((core) => core.forceFlushMetrics()) : Promise.resolve()).catch((flushErr) => {
              daemonLog.warn(
                `pre-shutdown metrics flush failed: ${flushErr instanceof Error ? flushErr.message : String(flushErr)}`
              );
            });
            Promise.resolve().then(async () => {
              await waitForRuntimeStartingForShutdown(
                runtimeStarting,
                daemonLog
              );
              const appForCleanup = runtimeApp ?? runtimeAppForCleanup;
              const deviceFlowRegistry = appForCleanup ? getDeviceFlowRegistry(appForCleanup) : void 0;
              if (deviceFlowRegistry) {
                try {
                  deviceFlowRegistry.dispose();
                } catch (err) {
                  daemonLog.warn(
                    `device-flow registry dispose error: ${err instanceof Error ? err.message : String(err)}`
                  );
                }
              }
              const acpHandle = appForCleanup?.locals?.["acpHandle"];
              if (acpHandle?.dispose) {
                try {
                  acpHandle.dispose();
                } catch (err) {
                  daemonLog.warn(
                    `ACP handle dispose error: ${err instanceof Error ? err.message : String(err)}`
                  );
                }
              }
              const rl = appForCleanup ? getRateLimiter(appForCleanup) : void 0;
              if (rl) {
                rl.setDraining(true);
                rl.dispose();
              }
              disposeDaemonEventLoopMonitor();
              await channelWorker.stop().catch((err) => {
                daemonLog.error(
                  "channel worker stop error",
                  err instanceof Error ? err : null
                );
              });
              removeCurrentServePidfile();
              const bridgeForShutdown = bridgeRef;
              if (bridgeForShutdown) {
                await bridgeForShutdown.shutdown().catch((err) => {
                  daemonLog.error(
                    "bridge shutdown error",
                    err instanceof Error ? err : null
                  );
                  bridgeShutdownError = err instanceof Error ? err : new Error(String(err));
                });
              }
            }).finally(() => {
              const SECONDARY_DEADLINE_MS = 2e3;
              let secondaryTimer;
              const forceTimer = setTimeout(() => {
                daemonLog.warn(
                  `${SHUTDOWN_FORCE_CLOSE_MS}ms listener-drain timeout reached; force-closing remaining connections`
                );
                server.closeAllConnections();
                secondaryTimer = setTimeout(() => {
                  daemonLog.warn(
                    `server.close did not fire ${SECONDARY_DEADLINE_MS}ms after force-close; resolving anyway`
                  );
                  finish();
                }, SECONDARY_DEADLINE_MS);
                secondaryTimer.unref();
              }, SHUTDOWN_FORCE_CLOSE_MS);
              forceTimer.unref();
              server.close((err) => {
                clearTimeout(forceTimer);
                if (secondaryTimer) clearTimeout(secondaryTimer);
                finish(err);
              });
            });
          });
          return closePromise;
        }, "close")
      };
      process.on("SIGINT", onSignal);
      process.on("SIGTERM", onSignal);
      process.on("uncaughtExceptionMonitor", onUncaughtExceptionMonitor);
      server.removeAllListeners("error");
      server.on("error", (err) => {
        daemonLog.error("server error", err instanceof Error ? err : null);
      });
      if (runtimeApp && bridgeRef) {
        const acpHandle = runtimeApp.locals?.["acpHandle"];
        acpHandle?.attachServer?.(server);
        if (shouldPreheat) {
          startBridgePreheat(bridgeRef);
        }
        if (opts.channelSelection && !runtimeStartupSettled) {
          armRuntimeStartupTimer();
          runtimeStarting = completeRuntimeStartup().catch(
            (err) => failRuntimeStartup(err, bridgeRef)
          );
        }
      } else if (deferRuntimeUntilFirstHealth) {
        scheduleRuntimeStartFallback();
      } else {
        startRuntime();
      }
      if (deps.resolveOnListen) {
        resolve(handle);
      } else {
        void runtimeReady.then(
          () => resolve(handle),
          (err) => {
            void handle.close().catch((closeErr) => {
              daemonLog.error(
                "shutdown after runtime startup error failed",
                closeErr instanceof Error ? closeErr : null
              );
            }).finally(() => {
              reject(err instanceof Error ? err : new Error(String(err)));
            });
          }
        );
      }
    }, "onListening");
    let server;
    if (tlsOptions) {
      let httpsServer;
      try {
        httpsServer = https.createServer(tlsOptions, app);
      } catch (err) {
        reject(
          new Error(
            `--tls-cert "${opts.tlsCert}" and --tls-key "${opts.tlsKey}" could not be loaded (do they match?): ${err instanceof Error ? err.message : String(err)}`
          )
        );
        return;
      }
      server = httpsServer.listen(opts.port, listenHostname, onListening);
    } else {
      server = app.listen(opts.port, listenHostname, onListening);
    }
    server.once("error", (err) => {
      removeCurrentServePidfile();
      reject(err);
    });
  });
}
__name(runQwenServe, "runQwenServe");
export {
  InvalidPolicyConfigError,
  createLazyBridgeProxy,
  extractContextFilename,
  formatChannelWorkerDaemonUrl,
  resolveRuntimeStartupTimeoutMs,
  runQwenServe,
  validatePolicyConfig,
  waitForRuntimeStartingForShutdown
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
