// Force strict mode and setup for ESM
"use strict";
import {
  DaemonMetricsRing,
  computeCpuPercent
} from "./chunk-HGT6JR3U.js";
import {
  CAPABILITIES_SCHEMA_VERSION,
  ClientMcpSenderRegistry,
  PathMutexRegistry,
  SERVE_CAPABILITY_REGISTRY,
  WorkspaceVoiceCoordinator,
  allowOriginCors,
  allowOriginMode,
  bearerAuth,
  createBridgeFileSystemAdapter,
  denyBrowserOriginCors,
  getAdvertisedServeFeatures,
  getDeviceFlowRegistry,
  getRateLimiter,
  getServeProtocolVersions,
  hostAllowlist,
  isBrowserAutomationMcpAvailable,
  isDeepHealthQuery,
  listenerMaxConnections,
  parseAllowOriginPatterns,
  parseDaemonStatusDetail,
  positiveFiniteOrNull,
  require_express,
  resolveWebShellDir
} from "./chunk-KXYJPRT5.js";
import {
  isLoopbackBind
} from "./chunk-RXFQM6FQ.js";
import {
  RUNTIME_STARTUP_CANCELLED_MESSAGE
} from "./chunk-QUPXZXLV.js";
import {
  LOAD_REPLAY_META_KEY
} from "./chunk-PZL23GTM.js";
import {
  DEFAULT_COMPACTED_REPLAY_MAX_BYTES,
  normalizeCompactedReplayMaxBytes
} from "./chunk-COH43MRJ.js";
import "./chunk-WBL3FJEU.js";
import {
  resolveChannelCwd
} from "./chunk-FNX3LGAK.js";
import {
  MAX_REGISTERED_WORKSPACES,
  resolveWorkspaceInputs,
  workspaceRegistrationId
} from "./chunk-OK2LM4HC.js";
import {
  canonicalizeWorkspace
} from "./chunk-W7FJ3N32.js";
import "./chunk-TIOE2OPE.js";
import "./chunk-6WGZDD67.js";
import {
  ChannelWebhookEnqueueError,
  QWEN_SERVER_TOKEN_ENV
} from "./chunk-KSZKSE23.js";
import {
  channelSelectionNames
} from "./chunk-TJTKSVIV.js";
import "./chunk-M5GB774H.js";
import "./chunk-5HBA2Z7V.js";
import "./chunk-T2NCM2ET.js";
import {
  sanitizeLogText
} from "./chunk-ZQIYGQCG.js";
import "./chunk-UDXSXLER.js";
import {
  loadServeFastPathSettings,
  preResolveServeFastPathHomeEnvOverrides
} from "./chunk-PEJWA3QQ.js";
import "./chunk-GOXKNSDZ.js";
import {
  getGlobalQwenDirLite,
  resolveConfigPathLite
} from "./chunk-IDS7MSUP.js";
import "./chunk-QRUIS3DN.js";
import "./chunk-ALGGS7UH.js";
import {
  isWithinRoot
} from "./chunk-MR3PXB6E.js";
import {
  writeStderrLine,
  writeStdoutLine
} from "./chunk-YUZI3WAC.js";
import {
  getCliVersion
} from "./chunk-GLNHPRZT.js";
import "./chunk-VJNBRRZG.js";
import "./chunk-T4TZQJ7W.js";
import "./chunk-H6XPXXMH.js";
import "./chunk-5M6IDOMF.js";
import "./chunk-E2UVIFI2.js";
import "./chunk-CR3C7WXL.js";
import "./chunk-XWRJCPHC.js";
import {
  finalizeStartupProfile,
  profileCheckpoint
} from "./chunk-QSWDGAIC.js";
import "./chunk-Q7YDKOGY.js";
import "./chunk-DMTGGOSA.js";
import "./chunk-YQ3U5MUC.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.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, createHash as createHash2, timingSafeEqual } from "node:crypto";
import * as fs from "node:fs";
import * as https from "node:https";
import * as path from "node:path";
import * as os from "node:os";
import { monitorEventLoopDelay, 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 computeWorkspaceHash(boundWorkspace) {
  return crypto.createHash("sha256").update(boundWorkspace).digest("hex").slice(0, 8);
}
__name(computeWorkspaceHash, "computeWorkspaceHash");
function computeDaemonId(pid) {
  return `daemon:${pid}`;
}
__name(computeDaemonId, "computeDaemonId");
function computeDaemonLogFileName(pid) {
  return `serve-${pid}.log`;
}
__name(computeDaemonLogFileName, "computeDaemonLogFileName");
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);
  const workspaceHash = computeWorkspaceHash(opts.boundWorkspace);
  const daemonDir = nodePath.join(baseDir, "daemon");
  const logPath = nodePath.join(daemonDir, computeDaemonLogFileName(pid));
  try {
    nodeFs.mkdirSync(daemonDir, { recursive: true });
    const firstLine = buildDaemonLogLine({
      level: "INFO",
      message: `daemon started pid=${pid}`,
      now: now(),
      ctx: { workspace: opts.boundWorkspace, workspaceHash }
    });
    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/large-pipe-frame-observer.ts
init_esbuild_shims();
var LARGE_PIPE_FRAME_THRESHOLD_BYTES = 256 * 1024;
var LARGE_PIPE_FRAME_LOG_LIMIT = 50;
var LARGE_PIPE_FRAME_LOG_WINDOW_MS = 6e4;
var LARGE_PIPE_FRAME_EVENT_NAME = "qwen-code.daemon.pipe.large_frame";
var MAX_ATTR_STRING_LENGTH = 128;
var MAX_CONTENT_DEPTH = 32;
var MAX_JSON_APPROX_DEPTH = 32;
var MAX_RAW_OUTPUT_APPROX_BYTES = LARGE_PIPE_FRAME_THRESHOLD_BYTES;
var MAX_SUMMARIZED_UPDATES = 500;
var SUMMARIZED_UPDATE_PREFIX_COUNT = Math.ceil(MAX_SUMMARIZED_UPDATES / 2);
var SUMMARIZED_UPDATE_SUFFIX_COUNT = MAX_SUMMARIZED_UPDATES - SUMMARIZED_UPDATE_PREFIX_COUNT;
function createLargePipeFrameObserver(options) {
  const thresholdBytes = options.thresholdBytes ?? LARGE_PIPE_FRAME_THRESHOLD_BYTES;
  const windowMs = options.windowMs ?? LARGE_PIPE_FRAME_LOG_WINDOW_MS;
  const logLimit = options.logLimit ?? LARGE_PIPE_FRAME_LOG_LIMIT;
  const now = options.now ?? Date.now;
  let windowStartedAt = now();
  let emittedInWindow = 0;
  let suppressedCount = 0;
  let suppressedWindowStartMs;
  return (observation) => {
    try {
      if (observation.bytes < thresholdBytes) return;
      const currentTime = now();
      if (currentTime - windowStartedAt >= windowMs) {
        windowStartedAt = currentTime;
        emittedInWindow = 0;
      }
      if (emittedInWindow >= logLimit) {
        suppressedCount += 1;
        suppressedWindowStartMs ??= windowStartedAt;
        return;
      }
      const context = classifyLargePipeFrame(observation, thresholdBytes);
      if (!context) return;
      if (suppressedCount > 0) {
        context["suppressedCount"] = suppressedCount;
        if (suppressedWindowStartMs !== void 0) {
          context["suppressedWindowStartMs"] = suppressedWindowStartMs;
        }
        suppressedCount = 0;
        suppressedWindowStartMs = void 0;
      }
      emittedInWindow += 1;
      try {
        options.daemonLog.warn("large ACP pipe frame observed", context);
      } catch {
      }
      try {
        options.emitTelemetryLog?.("Large ACP pipe frame observed.", context, {
          eventName: LARGE_PIPE_FRAME_EVENT_NAME
        });
      } catch {
      }
    } catch {
    }
  };
}
__name(createLargePipeFrameObserver, "createLargePipeFrameObserver");
function classifyLargePipeFrame(observation, thresholdBytes = LARGE_PIPE_FRAME_THRESHOLD_BYTES) {
  if (observation.bytes < thresholdBytes) return void 0;
  const message = asRecord(observation.message);
  const messageKind = message ? getMessageKind(message) : "unknown";
  const method = message ? stringValue(message["method"]) : void 0;
  const classification = classifySource(message, messageKind, method);
  const context = {
    direction: observation.direction,
    bytes: observation.bytes,
    thresholdBytes,
    messageKind,
    sourceClass: classification.sourceClass
  };
  addString(context, "method", method);
  if (classification.sourceClass === "session_update_notification") {
    addUpdateSummary(context, summarizeUpdate(classification.update));
  } else if (classification.sourceClass === "load_session_bulk_replay_response") {
    addUpdatesSummary(context, classification.replay?.["updates"]);
  } else if (classification.sourceClass === "load_updates_response") {
    addUpdatesSummary(context, classification.result?.["updates"]);
  }
  return context;
}
__name(classifyLargePipeFrame, "classifyLargePipeFrame");
function classifySource(message, messageKind, method) {
  if (!message) return { sourceClass: "unknown" };
  const params = asRecord(message["params"]);
  const update = asRecord(params?.["update"]);
  if (messageKind === "notification" && method === "session/update" && update) {
    return { sourceClass: "session_update_notification", update };
  }
  if (messageKind === "response") {
    const replay = getBulkReplay(message);
    if (replay) {
      return { sourceClass: "load_session_bulk_replay_response", replay };
    }
    const result = asRecord(message["result"]);
    if (isLoadUpdatesResult(result)) {
      return { sourceClass: "load_updates_response", result };
    }
    return { sourceClass: "jsonrpc_response" };
  }
  if (method) return { sourceClass: "jsonrpc_request" };
  return { sourceClass: "unknown" };
}
__name(classifySource, "classifySource");
function getMessageKind(message) {
  const method = stringValue(message["method"]);
  const hasId = Object.hasOwn(message, "id");
  if (method) return hasId ? "request" : "notification";
  if (hasId && (Object.hasOwn(message, "result") || Object.hasOwn(message, "error"))) {
    return "response";
  }
  return "unknown";
}
__name(getMessageKind, "getMessageKind");
function getBulkReplay(message) {
  const result = asRecord(message?.["result"]);
  const meta = asRecord(result?.["_meta"]);
  return asRecord(meta?.[LOAD_REPLAY_META_KEY]);
}
__name(getBulkReplay, "getBulkReplay");
function isLoadUpdatesResult(result) {
  if (!Array.isArray(result?.["updates"])) return false;
  return typeof result["startTime"] === "string" || typeof result["lastUpdated"] === "string" || typeof result["replayError"] === "string" || typeof result["partial"] === "boolean";
}
__name(isLoadUpdatesResult, "isLoadUpdatesResult");
function addUpdatesSummary(context, updates) {
  if (!Array.isArray(updates)) return;
  context["updateCount"] = updates.length;
  const sampledIndexes = sampleUpdateIndexes(updates.length);
  if (sampledIndexes.length < updates.length) {
    context["summarizedUpdateCount"] = sampledIndexes.length;
    context["summarizedUpdateStrategy"] = "prefix_and_suffix";
  }
  const summary = {};
  for (const index of sampledIndexes) {
    mergeUpdateSummary(summary, summarizeUpdate(asRecord(updates[index])));
  }
  addUpdateSummary(context, summary);
}
__name(addUpdatesSummary, "addUpdatesSummary");
function sampleUpdateIndexes(updateCount) {
  if (updateCount <= MAX_SUMMARIZED_UPDATES) {
    return Array.from({ length: updateCount }, (_, index) => index);
  }
  const indexes = [];
  for (let i = 0; i < SUMMARIZED_UPDATE_PREFIX_COUNT; i += 1) {
    indexes.push(i);
  }
  for (let i = updateCount - SUMMARIZED_UPDATE_SUFFIX_COUNT; i < updateCount; i += 1) {
    indexes.push(i);
  }
  return indexes;
}
__name(sampleUpdateIndexes, "sampleUpdateIndexes");
function summarizeUpdate(update) {
  if (!update) return {};
  const meta = asRecord(update["_meta"]);
  const summary = {};
  summary.sessionUpdate = stringValue(update["sessionUpdate"]);
  summary.toolName = stringValue(meta?.["toolName"]);
  summary.toolProvenance = stringValue(meta?.["provenance"]);
  const contentBytes = contentTextBytes(update["content"]);
  if (contentBytes > 0) {
    summary.maxContentTextBytes = contentBytes;
  }
  summary.maxObservedUpdateBytes = contentBytes;
  if (Object.hasOwn(update, "rawOutput")) {
    const rawOutput = update["rawOutput"];
    summary.rawOutputKind = rawOutputKind(rawOutput);
    if (typeof rawOutput === "string") {
      const rawOutputTextBytes = Buffer.byteLength(rawOutput, "utf8");
      summary.maxRawOutputTextBytes = rawOutputTextBytes;
      summary.maxRawOutputObservedBytes = rawOutputTextBytes;
      summary.maxObservedUpdateBytes = Math.max(
        summary.maxObservedUpdateBytes,
        rawOutputTextBytes
      );
    } else {
      const rawOutputApprox = approximateJsonByteLength(rawOutput);
      if (rawOutputApprox !== void 0) {
        summary.maxRawOutputApproxBytes = rawOutputApprox.bytes;
        if (rawOutputApprox.capped) {
          summary.maxRawOutputApproxBytesCapped = true;
        }
        summary.maxRawOutputObservedBytes = rawOutputApprox.bytes;
        summary.maxObservedUpdateBytes = Math.max(
          summary.maxObservedUpdateBytes,
          rawOutputApprox.bytes
        );
      }
    }
  }
  return summary;
}
__name(summarizeUpdate, "summarizeUpdate");
function mergeUpdateSummary(target, next) {
  if (next.sessionUpdate && target.sessionUpdate && next.sessionUpdate !== target.sessionUpdate) {
    target.mixedSessionUpdate = true;
  }
  if (next.mixedSessionUpdate) {
    target.mixedSessionUpdate = true;
  }
  if (next.maxObservedUpdateBytes !== void 0 && (target.maxObservedUpdateBytes === void 0 || next.maxObservedUpdateBytes > target.maxObservedUpdateBytes)) {
    target.maxObservedUpdateBytes = next.maxObservedUpdateBytes;
    target.sessionUpdate = next.sessionUpdate ?? target.sessionUpdate;
    target.toolName = next.toolName ?? target.toolName;
    target.toolProvenance = next.toolProvenance ?? target.toolProvenance;
  }
  if (next.maxContentTextBytes !== void 0 && (target.maxContentTextBytes === void 0 || next.maxContentTextBytes > target.maxContentTextBytes)) {
    target.maxContentTextBytes = next.maxContentTextBytes;
  }
  if (next.maxRawOutputTextBytes !== void 0 && (target.maxRawOutputTextBytes === void 0 || next.maxRawOutputTextBytes > target.maxRawOutputTextBytes)) {
    target.maxRawOutputTextBytes = next.maxRawOutputTextBytes;
  }
  if (next.maxRawOutputApproxBytes !== void 0 && (target.maxRawOutputApproxBytes === void 0 || next.maxRawOutputApproxBytes > target.maxRawOutputApproxBytes)) {
    target.maxRawOutputApproxBytes = next.maxRawOutputApproxBytes;
  }
  if (next.maxRawOutputApproxBytesCapped) {
    target.maxRawOutputApproxBytesCapped = true;
  }
  if (next.maxRawOutputObservedBytes !== void 0 && (target.maxRawOutputObservedBytes === void 0 || next.maxRawOutputObservedBytes > target.maxRawOutputObservedBytes)) {
    target.maxRawOutputObservedBytes = next.maxRawOutputObservedBytes;
    target.rawOutputKind = next.rawOutputKind;
  }
}
__name(mergeUpdateSummary, "mergeUpdateSummary");
function addUpdateSummary(context, summary) {
  addString(context, "sessionUpdate", summary.sessionUpdate);
  addString(context, "toolName", summary.toolName);
  addString(context, "toolProvenance", summary.toolProvenance);
  if (summary.mixedSessionUpdate) context["mixedSessionUpdate"] = true;
  addNumber(context, "maxContentTextBytes", summary.maxContentTextBytes);
  addNumber(context, "maxRawOutputTextBytes", summary.maxRawOutputTextBytes);
  addNumber(
    context,
    "maxRawOutputApproxBytes",
    summary.maxRawOutputApproxBytes
  );
  if (summary.maxRawOutputApproxBytesCapped) {
    context["maxRawOutputApproxBytesCapped"] = true;
  }
  addString(context, "rawOutputKind", summary.rawOutputKind);
}
__name(addUpdateSummary, "addUpdateSummary");
function contentTextBytes(value, depth = 0) {
  if (depth > MAX_CONTENT_DEPTH) return 0;
  if (typeof value === "string") return Buffer.byteLength(value, "utf8");
  if (Array.isArray(value)) {
    return value.reduce(
      (sum, item) => sum + contentTextBytes(item, depth + 1),
      0
    );
  }
  const record = asRecord(value);
  if (!record) return 0;
  let total = 0;
  const text = stringValue(record["text"]);
  if (text) total += Buffer.byteLength(text, "utf8");
  if (Object.hasOwn(record, "content")) {
    total += contentTextBytes(record["content"], depth + 1);
  }
  return total;
}
__name(contentTextBytes, "contentTextBytes");
function approximateJsonByteLength(value) {
  const state = {
    budget: MAX_RAW_OUTPUT_APPROX_BYTES,
    bytes: 0,
    capped: false,
    seen: /* @__PURE__ */ new WeakSet()
  };
  if (!addJsonValueBytes(value, state, 0)) return void 0;
  return { bytes: state.bytes, capped: state.capped };
}
__name(approximateJsonByteLength, "approximateJsonByteLength");
function addJsonValueBytes(value, state, depth) {
  if (state.capped) return true;
  switch (typeof value) {
    case "string":
      addJsonStringBytes(value, state);
      return true;
    case "number":
      addJsonBytes(state, Number.isFinite(value) ? String(value).length : 4);
      return true;
    case "boolean":
      addJsonBytes(state, value ? 4 : 5);
      return true;
    case "object":
      if (value === null) {
        addJsonBytes(state, 4);
        return true;
      }
      if (depth >= MAX_JSON_APPROX_DEPTH) {
        capJsonBytes(state);
        return true;
      }
      if (Array.isArray(value)) {
        addJsonArrayBytes(value, state, depth);
      } else {
        addJsonObjectBytes(value, state, depth);
      }
      return true;
    default:
      return false;
  }
}
__name(addJsonValueBytes, "addJsonValueBytes");
function addJsonArrayBytes(value, state, depth) {
  if (state.seen.has(value)) {
    capJsonBytes(state);
    return;
  }
  state.seen.add(value);
  addJsonBytes(state, 1);
  for (let i = 0; i < value.length && !state.capped; i += 1) {
    if (i > 0) addJsonBytes(state, 1);
    if (!addJsonValueBytes(value[i], state, depth + 1)) {
      addJsonBytes(state, 4);
    }
  }
  addJsonBytes(state, 1);
  state.seen.delete(value);
}
__name(addJsonArrayBytes, "addJsonArrayBytes");
function addJsonObjectBytes(value, state, depth) {
  if (state.seen.has(value)) {
    capJsonBytes(state);
    return;
  }
  state.seen.add(value);
  addJsonBytes(state, 1);
  const record = value;
  let propertyCount = 0;
  for (const key in record) {
    if (state.capped) break;
    if (!Object.hasOwn(record, key)) continue;
    const item = record[key];
    if (isOmittedJsonObjectValue(item)) continue;
    if (propertyCount > 0) addJsonBytes(state, 1);
    addJsonStringBytes(key, state);
    addJsonBytes(state, 1);
    if (!addJsonValueBytes(item, state, depth + 1)) {
      addJsonBytes(state, 4);
    }
    propertyCount += 1;
  }
  addJsonBytes(state, 1);
  state.seen.delete(value);
}
__name(addJsonObjectBytes, "addJsonObjectBytes");
function addJsonStringBytes(value, state) {
  addJsonBytes(state, 1);
  if (state.capped) return;
  const remainingForContent = Math.max(0, state.budget - state.bytes - 1);
  const sampleLength = Math.min(value.length, remainingForContent);
  const sample = sampleLength < value.length ? value.slice(0, sampleLength) : value;
  addJsonBytes(state, Buffer.byteLength(sample, "utf8"));
  if (sampleLength < value.length) {
    capJsonBytes(state);
    return;
  }
  addJsonBytes(state, 1);
}
__name(addJsonStringBytes, "addJsonStringBytes");
function addJsonBytes(state, bytes) {
  if (state.capped || bytes <= 0) return;
  const nextBytes = state.bytes + bytes;
  if (nextBytes >= state.budget) {
    capJsonBytes(state);
    return;
  }
  state.bytes = nextBytes;
}
__name(addJsonBytes, "addJsonBytes");
function capJsonBytes(state) {
  state.bytes = state.budget;
  state.capped = true;
}
__name(capJsonBytes, "capJsonBytes");
function isOmittedJsonObjectValue(value) {
  return typeof value === "undefined" || typeof value === "function" || typeof value === "symbol";
}
__name(isOmittedJsonObjectValue, "isOmittedJsonObjectValue");
function rawOutputKind(value) {
  if (Array.isArray(value)) return "array";
  if (value === null) return "null";
  return typeof value;
}
__name(rawOutputKind, "rawOutputKind");
function addString(context, key, value) {
  if (value === void 0) return;
  context[key] = value.length > MAX_ATTR_STRING_LENGTH ? value.slice(0, MAX_ATTR_STRING_LENGTH) : value;
}
__name(addString, "addString");
function addNumber(context, key, value) {
  if (value !== void 0) context[key] = value;
}
__name(addNumber, "addNumber");
function stringValue(value) {
  return typeof value === "string" ? value : void 0;
}
__name(stringValue, "stringValue");
function asRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
}
__name(asRecord, "asRecord");

// packages/cli/src/serve/channel-workspace-grouping.ts
init_esbuild_shims();
function resolveChannelOwnerCwd(rawCwd, workspaceCwd) {
  return canonicalizeWorkspace(resolveChannelCwd(rawCwd, workspaceCwd));
}
__name(resolveChannelOwnerCwd, "resolveChannelOwnerCwd");
function rawChannelCwd(entry) {
  if (!entry || typeof entry !== "object") return void 0;
  const cwd = entry.cwd;
  return typeof cwd === "string" && cwd.length > 0 ? cwd : void 0;
}
__name(rawChannelCwd, "rawChannelCwd");
function resolveChannelWorkspaceGroups(input) {
  const { workspaces, selection, loadChannelsConfig } = input;
  const primary = workspaces.find((workspace) => workspace.primary);
  if (!primary) {
    return {
      ok: false,
      error: {
        code: "no_primary_workspace",
        message: "No primary workspace is registered."
      }
    };
  }
  if (selection.mode === "all") {
    if (!primary.trusted) {
      return {
        ok: false,
        error: {
          code: "untrusted_workspace",
          message: `Primary workspace "${primary.workspaceCwd}" is not trusted; cannot host channels.`
        }
      };
    }
    return {
      ok: true,
      groups: [
        { workspaceCwd: primary.workspaceCwd, selection: { mode: "all" } }
      ]
    };
  }
  const channelsConfigByWorkspace = /* @__PURE__ */ new Map();
  for (const workspace of workspaces) {
    channelsConfigByWorkspace.set(
      workspace.workspaceCwd,
      loadChannelsConfig(workspace.workspaceCwd)
    );
  }
  const namesByWorkspace = /* @__PURE__ */ new Map();
  for (const name of selection.names) {
    const owners = [];
    for (const workspace of workspaces) {
      const entry = (channelsConfigByWorkspace.get(workspace.workspaceCwd) ?? {})[name];
      if (!entry || typeof entry !== "object") continue;
      let ownerCwd;
      try {
        ownerCwd = resolveChannelOwnerCwd(
          rawChannelCwd(entry),
          workspace.workspaceCwd
        );
      } catch {
        continue;
      }
      if (ownerCwd === workspace.workspaceCwd) {
        owners.push(workspace);
      }
    }
    if (owners.length === 0) {
      return {
        ok: false,
        error: {
          code: "channel_workspace_mismatch",
          channel: name,
          message: `Channel "${name}" is not configured in any registered workspace, or its "cwd" points outside them.`
        }
      };
    }
    if (owners.length > 1) {
      return {
        ok: false,
        error: {
          code: "ambiguous_channel_workspace",
          channel: name,
          message: `Channel "${name}" is configured in multiple registered workspaces (${owners.map((owner2) => owner2.workspaceCwd).join(
            ", "
          )}). Define it in one workspace's settings or set an explicit "cwd".`
        }
      };
    }
    const owner = owners[0];
    if (!owner.trusted) {
      return {
        ok: false,
        error: {
          code: "untrusted_workspace",
          channel: name,
          message: `Channel "${name}" targets untrusted workspace "${owner.workspaceCwd}".`
        }
      };
    }
    const names = namesByWorkspace.get(owner.workspaceCwd) ?? [];
    names.push(name);
    namesByWorkspace.set(owner.workspaceCwd, names);
  }
  return {
    ok: true,
    groups: [...namesByWorkspace.entries()].map(([workspaceCwd, names]) => ({
      workspaceCwd,
      selection: { mode: "names", names }
    }))
  };
}
__name(resolveChannelWorkspaceGroups, "resolveChannelWorkspaceGroups");

// 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;
function daemonPipeDirection(direction) {
  switch (direction) {
    case "sent":
      return "outbound";
    case "received":
      return "inbound";
    default: {
      const exhaustive = direction;
      return exhaustive;
    }
  }
}
__name(daemonPipeDirection, "daemonPipeDirection");
var DAEMON_METRICS_SAMPLE_MS = 5e3;
var DAEMON_METRICS_CAPACITY = 180;
function safeCpuUsage() {
  try {
    return process.cpuUsage();
  } catch {
    return null;
  }
}
__name(safeCpuUsage, "safeCpuUsage");
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 deriveDefaultMaxTotalSessions(maxSessionsPerWorkspace, workspaceCount) {
  if (workspaceCount <= 1) return void 0;
  const perWorkspace = maxSessionsPerWorkspace ?? DEFAULT_MAX_SESSIONS;
  if (perWorkspace === 0 || perWorkspace === Number.POSITIVE_INFINITY) {
    return void 0;
  }
  return perWorkspace * workspaceCount;
}
__name(deriveDefaultMaxTotalSessions, "deriveDefaultMaxTotalSessions");
function isNonNegativeIntegerMs(value) {
  return Number.isFinite(value) && Number.isInteger(value) && value >= 0;
}
__name(isNonNegativeIntegerMs, "isNonNegativeIntegerMs");
var MAX_TIMEOUT_MS = 2147483647;
var MAX_PORT_ATTEMPTS = 10;
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");
function sessionArtifactsPersistenceAvailableFromSettings(settings) {
  return settings?.general?.chatRecording !== false;
}
__name(sessionArtifactsPersistenceAvailableFromSettings, "sessionArtifactsPersistenceAvailableFromSettings");
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-XW6MHJBQ.js"),
    import("./pidfile-FWFATD4D.js"),
    import("./runtime-YN2SZXTX.js"),
    import("./cli-entry-path-4VJ3Y6T2.js"),
    import("./channel-worker-group-SOUWTFHC.js"),
    import("./channel-worker-manager-LOVSV3WW.js")
  ]).then(
    ([
      supervisor,
      pidfile,
      channelRuntime,
      cliEntryPath,
      workerGroup,
      workerManager
    ]) => ({
      createChannelWorkerSupervisor: supervisor.createChannelWorkerSupervisor,
      channelServicePidfile: pidfile,
      loadChannelsConfig: channelRuntime.loadChannelsConfig,
      createChannelWorkerGroup: workerGroup.createChannelWorkerGroup,
      createChannelWorkerManager: workerManager.createChannelWorkerManager,
      findCliEntryPath: cliEntryPath.findCliEntryPath
    })
  ).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() {
    },
    async restart() {
      return { ...snapshot, channels: [] };
    },
    killAllSync() {
    },
    snapshot: /* @__PURE__ */ __name(() => ({ ...snapshot, channels: [] }), "snapshot"),
    async enqueueWebhookTask() {
      throw new ChannelWebhookEnqueueError(
        "channel_worker_unavailable",
        "Channel worker is not running."
      );
    }
  };
}
__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 Object.assign(
    new Error(
      `Channel service is already running under ${owner} (PID ${info.pid}). Stop it before enabling daemon-managed channels.`
    ),
    { code: "channel_service_conflict", owner: info.owner, pid: info.pid }
  );
}
__name(channelServicePidfileConflictError, "channelServicePidfileConflictError");
function channelServiceStartingConflictError() {
  return Object.assign(
    new Error(
      "Channel service is already starting. Retry after the current startup finishes."
    ),
    { code: "channel_service_conflict" }
  );
}
__name(channelServiceStartingConflictError, "channelServiceStartingConflictError");
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-O6NJAI32.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-BGGN4RKW.js"),
    import("./environment-OACDAE4N.js"),
    import("./loadedSettingsAdapter-7HXNKCTM.js"),
    import("./trustedFolders-PAVROFQB.js")
  ]).then(([settings, environment, loadedSettingsAdapter, trustedFolders]) => ({
    settings,
    environment,
    loadedSettingsAdapter,
    trustedFolders
  }));
  return settingsRuntimePromise;
}
__name(loadSettingsRuntimeModules, "loadSettingsRuntimeModules");
var channelWebhookConfigRuntimePromise;
function loadChannelWebhookConfigRuntime() {
  channelWebhookConfigRuntimePromise ??= Promise.all([
    import("./runtime-YN2SZXTX.js"),
    import("./config-utils-IQQT3GCI.js")
  ]).then(([channelRuntime, configUtils]) => ({
    loadChannelsConfig: channelRuntime.loadChannelsConfig,
    parseChannelWebhookConfig: configUtils.parseChannelWebhookConfig
  })).catch((err) => {
    channelWebhookConfigRuntimePromise = void 0;
    throw err;
  });
  return channelWebhookConfigRuntimePromise;
}
__name(loadChannelWebhookConfigRuntime, "loadChannelWebhookConfigRuntime");
async function loadServeRuntimeModules() {
  const [
    serverModule,
    bridgeModule,
    spawnChannelModule,
    workspaceModule,
    workspaceTypesModule,
    daemonStatusProviderModule,
    workspaceProvidersStatusModule,
    workspaceSkillsStatusModule,
    totalSessionAdmissionModule,
    workspaceRegistryModule
  ] = await Promise.all([
    import("./server-AW6I453Y.js"),
    import("./bridge-BY7DSFSY.js"),
    import("./spawnChannel-LG5MJUCC.js"),
    import("./workspace-service-OXWCJJE7.js"),
    import("./types-ML3TRJQ5.js"),
    import("./daemon-status-provider-A3GFXMKF.js"),
    import("./workspace-providers-status-OSQFBCBV.js"),
    import("./workspace-skills-status-7OQEYK75.js"),
    import("./total-session-admission-UERS4HVX.js"),
    import("./workspace-registry-XM3PWJRJ.js")
  ]);
  return {
    createServeApp: serverModule.createServeApp,
    getActiveSseCount: serverModule.getActiveSseCount,
    resolveBoundWorkspacesFromIdeEnv: serverModule.resolveBoundWorkspacesFromIdeEnv,
    resolveBridgeFsFactory: serverModule.resolveBridgeFsFactory,
    createAcpSessionBridge: bridgeModule.createAcpSessionBridge,
    createSpawnChannelFactory: spawnChannelModule.createSpawnChannelFactory,
    createDaemonWorkspaceService: workspaceModule.createDaemonWorkspaceService,
    WorkspaceSettingsPartialPersistError: workspaceTypesModule.WorkspaceSettingsPartialPersistError,
    WorkspaceSkillNotToggleableError: workspaceTypesModule.WorkspaceSkillNotToggleableError,
    createDaemonStatusProvider: daemonStatusProviderModule.createDaemonStatusProvider,
    createWorkspaceProvidersStatusProvider: workspaceProvidersStatusModule.createWorkspaceProvidersStatusProvider,
    createWorkspaceSkillsStatusProvider: workspaceSkillsStatusModule.createWorkspaceSkillsStatusProvider,
    createTotalSessionAdmissionController: totalSessionAdmissionModule.createTotalSessionAdmissionController,
    createWorkspaceRegistry: workspaceRegistryModule.createWorkspaceRegistry,
    createWorkspaceSessionOwnerIndex: workspaceRegistryModule.createWorkspaceSessionOwnerIndex
  };
}
__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, sessionArtifactsPersistenceAvailable, env) {
  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,
    sessionArtifactsPersistenceAvailable,
    sessionGenerationAvailable: true,
    rateLimit: opts.rateLimit === true,
    reloadAvailable: true,
    channelReloadAvailable: opts.channelSelection !== void 0,
    channelControlAvailable: true,
    persistentWorkspaceRegistrationAvailable: true,
    workspaceRuntimeRemovalAvailable: 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,
    browserAutomationMcpAvailable: isBrowserAutomationMcpAvailable(opts, env)
  });
}
__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,
      input.sessionArtifactsPersistenceAvailable,
      input.env
    ),
    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,
    sessionArtifactsPersistenceAvailable,
    permissionPolicy,
    multiWorkspaceCapabilitiesRequireRuntime,
    getRuntimeError,
    getChannelWorkerSnapshot,
    getChannelWorkerSnapshots,
    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);
    }
    if (isDeepHealthQuery(req.query["deep"])) {
      res.setHeader("Retry-After", "1");
      res.status(503).json({ status: "degraded", reason: "bootstrap" });
      return;
    }
    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) => {
    if (multiWorkspaceCapabilitiesRequireRuntime) {
      const runtimeError = getRuntimeError();
      if (runtimeError === void 0) {
        res.setHeader("Retry-After", "1");
      }
      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;
    }
    res.status(200).json(
      createBootstrapCapabilities({
        opts,
        boundWorkspace,
        qwenCodeVersion,
        sessionShellCommandEnabled,
        sessionArtifactsPersistenceAvailable,
        permissionPolicy,
        env: process.env
      })
    );
  });
  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 channelWorkers = getChannelWorkerSnapshots();
    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),
        maxTotalSessions: positiveFiniteOrNull(opts.maxTotalSessions),
        maxPendingPromptsPerSession: advertisedMaxPendingPromptsPerSession(
          opts.maxPendingPromptsPerSession
        ),
        listenerMaxConnections: listenerMaxConnections(opts.maxConnections),
        eventRingSize: opts.eventRingSize ?? DEFAULT_EVENT_RING_SIZE,
        compactedReplayMaxBytes: opts.compactedReplayMaxBytes ?? DEFAULT_COMPACTED_REPLAY_MAX_BYTES,
        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,
          sessionArtifactsPersistenceAvailable,
          process.env
        )
      },
      runtime: {
        loading: runtimeError === void 0,
        ...runtimeError ? { error: runtimeError } : {},
        sessions: { active: 0 },
        permissions: {
          pending: 0,
          policy: permissionPolicy ?? "first-responder"
        },
        channel: { live: false },
        channelWorker,
        ...channelWorkers.length > 0 ? { channelWorkers } : {},
        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
          }
        },
        activity: {
          activePrompts: 0,
          pendingPrompts: 0,
          queuedPrompts: 0,
          lastActivityAt: null,
          idleSinceMs: null
        },
        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) {
        const webhookRequest = isChannelWebhookRequest(req);
        const authGate = webhookRequest ? options.authenticateDeferredChannelWebhookRequest ?? options.authenticateDeferredRuntimeRequest : options.authenticateDeferredRuntimeRequest;
        if (authGate) {
          if (!runSynchronousRequestGate(authGate, 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 isChannelWebhookRequest(req) {
  return req.method === "POST" && /^\/channels\/[^/]+\/webhooks\/[^/]+\/?$/u.test(req.path);
}
__name(isChannelWebhookRequest, "isChannelWebhookRequest");
function createDeferredChannelWebhookAuth(resolveSource, runtime, daemonLog) {
  return (req, res, next) => {
    const match = /^\/channels\/([^/]+)\/webhooks\/([^/]+)\/?$/u.exec(req.path);
    const channelName = decodeDeferredWebhookPathSegment(match?.[1]);
    const source = decodeDeferredWebhookPathSegment(match?.[2]);
    if (!channelName || !source) {
      daemonLog.warn("deferred webhook auth failed", {
        channelName: channelName ?? "unknown",
        source: source ?? "unknown",
        reason: "invalid webhook path"
      });
      res.status(401).json({ error: "Invalid webhook secret" });
      return;
    }
    const configSource = resolveSource(channelName);
    const secret = readDeferredWebhookSecret(
      runtime,
      configSource.workspaceCwd,
      channelName,
      source,
      configSource.env
    );
    if (!matchesWebhookSecret(req.get("x-qwen-webhook-secret"), secret)) {
      daemonLog.warn("deferred webhook auth failed", {
        channelName,
        source,
        reason: secret ? "secret mismatch" : "source not configured"
      });
      res.status(401).json({ error: "Invalid webhook secret" });
      return;
    }
    next();
  };
}
__name(createDeferredChannelWebhookAuth, "createDeferredChannelWebhookAuth");
function decodeDeferredWebhookPathSegment(segment) {
  if (segment === void 0) return void 0;
  try {
    return decodeURIComponent(segment);
  } catch {
    return void 0;
  }
}
__name(decodeDeferredWebhookPathSegment, "decodeDeferredWebhookPathSegment");
function readDeferredWebhookSecret(runtime, workspace, channelName, source, env) {
  try {
    const rawConfig = runtime.loadChannelsConfig(workspace)[channelName];
    if (typeof rawConfig !== "object" || rawConfig === null) {
      return void 0;
    }
    return runtime.parseChannelWebhookConfig(
      channelName,
      rawConfig,
      env
    )?.sources[source]?.secret;
  } catch (err) {
    const reason = err instanceof Error ? err.message : String(err);
    writeStderrLine(
      `[webhook-secret] failed to read deferred webhook secret for ${sanitizeLogText(channelName, 128)}/${sanitizeLogText(source, 128)}: ${sanitizeLogText(reason, 512)}`
    );
    return void 0;
  }
}
__name(readDeferredWebhookSecret, "readDeferredWebhookSecret");
function matchesWebhookSecret(candidate, expected) {
  if (typeof candidate !== "string" || typeof expected !== "string" || expected.length === 0) {
    return false;
  }
  const expectedDigest = createHash2("sha256").update(expected).digest();
  const candidateDigest = createHash2("sha256").update(candidate).digest();
  return timingSafeEqual(expectedDigest, candidateDigest);
}
__name(matchesWebhookSecret, "matchesWebhookSecret");
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 daemonRuntimeBaseEnv = Object.freeze({
    ...process.env
  });
  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 rawWorkspaces = resolveWorkspaceInputs(optsIn.workspace);
  const rawWorkspace = rawWorkspaces[0];
  const opts = {
    ...optsIn,
    token,
    promptDeadlineMs,
    writerIdleTimeoutMs,
    workspace: rawWorkspace,
    clientMcpOverWs: optsIn.clientMcpOverWs ?? (!envFlagDisabled(clientMcpOverWsEnv) && clientMcpOverWsEnv !== void 0),
    cdpTunnelOverWs: optsIn.cdpTunnelOverWs ?? (!envFlagDisabled(cdpTunnelOverWsEnv) && (cdpTunnelOverWsEnv !== void 0 || chromeExtensionOriginAllowed))
  };
  let channelRuntime = opts.channelSelection ? await loadChannelWorkerRuntime() : void 0;
  let channelServicePidfile = deps.channelServicePidfile ?? channelRuntime?.channelServicePidfile;
  const ensureChannelRuntime = /* @__PURE__ */ __name(async () => {
    channelRuntime ??= await loadChannelWorkerRuntime();
    channelServicePidfile ??= channelRuntime.channelServicePidfile;
    return channelRuntime;
  }, "ensureChannelRuntime");
  let channelPidfileReserved = false;
  const removeCurrentServePidfile = /* @__PURE__ */ __name(() => {
    if (!channelServicePidfile) return;
    if (!channelPidfileReserved) return;
    if (channelServicePidfile.removeServeServiceInfo) {
      if (channelServicePidfile.removeServeServiceInfo(process.pid)) {
        channelPidfileReserved = false;
      } else {
        const info2 = channelServicePidfile.readServiceInfo();
        if (!info2 || info2.owner !== "serve" || info2.pid !== process.pid || info2.servePid !== process.pid) {
          channelPidfileReserved = false;
        }
      }
      return;
    }
    const info = channelServicePidfile.readServiceInfo();
    if (info?.owner === "serve" && info.pid === process.pid && info.servePid === process.pid) {
      channelServicePidfile.removeServiceInfo();
      const remaining = channelServicePidfile.readServiceInfo();
      channelPidfileReserved = remaining?.owner === "serve" && remaining.pid === process.pid && remaining.servePid === process.pid;
    } else {
      channelPidfileReserved = false;
    }
  }, "removeCurrentServePidfile");
  const reserveChannelServicePidfile = /* @__PURE__ */ __name((selection) => {
    if (!channelServicePidfile) {
      throw new Error("Channel service pidfile runtime is not available.");
    }
    const channelPidfileNames = channelSelectionNames(selection);
    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 channelServiceStartingConflictError();
            }
            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 validateAndCanonicalizeWorkspace = /* @__PURE__ */ __name((workspace) => {
    if (!path.isAbsolute(workspace)) {
      throw new Error(
        `Invalid --workspace "${workspace}": must be an absolute path.`
      );
    }
    try {
      const stats = fs.statSync(workspace);
      if (!stats.isDirectory()) {
        throw new Error(
          `Invalid --workspace "${workspace}": 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 "${workspace}": directory does not exist.`
          );
        }
        if (code === "EACCES" || code === "EPERM") {
          throw new Error(
            `Invalid --workspace "${workspace}": permission denied (${String(code)}). The path exists but cannot be stat'd by the current user.`
          );
        }
      }
      throw err;
    }
    return canonicalizeWorkspace(workspace);
  }, "validateAndCanonicalizeWorkspace");
  const workspaceInputs = rawWorkspaces.map((workspace) => ({
    raw: workspace,
    cwd: validateAndCanonicalizeWorkspace(workspace),
    removable: false,
    registrationIds: []
  }));
  const boundWorkspace = workspaceInputs[0].cwd;
  const seenCanonicalWorkspaces = /* @__PURE__ */ new Set();
  for (const workspace of workspaceInputs) {
    if (seenCanonicalWorkspaces.has(workspace.cwd)) {
      throw new Error(
        `Duplicate --workspace value resolves to ${JSON.stringify(
          workspace.cwd
        )}.`
      );
    }
    seenCanonicalWorkspaces.add(workspace.cwd);
  }
  for (let i = 0; i < workspaceInputs.length; i++) {
    for (let j = i + 1; j < workspaceInputs.length; j++) {
      const first = workspaceInputs[i].cwd;
      const second = workspaceInputs[j].cwd;
      const firstRel = path.relative(first, second);
      const secondRel = path.relative(second, first);
      if (firstRel && !firstRel.startsWith("..") && !path.isAbsolute(firstRel)) {
        throw new Error(
          `Nested --workspace values are not supported: ${JSON.stringify(second)} is inside ${JSON.stringify(first)}.`
        );
      }
      if (secondRel && !secondRel.startsWith("..") && !path.isAbsolute(secondRel)) {
        throw new Error(
          `Nested --workspace values are not supported: ${JSON.stringify(first)} is inside ${JSON.stringify(second)}.`
        );
      }
    }
  }
  if (workspaceInputs.length > MAX_REGISTERED_WORKSPACES) {
    throw new Error(
      `At most ${MAX_REGISTERED_WORKSPACES} --workspace values may be registered.`
    );
  }
  let workspaceRegistrationStore = deps.workspaceRegistrationStore;
  if (workspaceRegistrationStore === void 0 && process.env["QWEN_SERVE_NO_PERSISTENT_REGISTRATION"] !== "1") {
    const { WorkspaceRegistrationStore } = await import("./workspace-registration-store-VYUUGJD6.js");
    workspaceRegistrationStore = new WorkspaceRegistrationStore(boundWorkspace);
  }
  if (workspaceRegistrationStore) {
    try {
      const stored = await workspaceRegistrationStore.read();
      for (const storedWorkspace of stored.workspaces) {
        const registrationId = workspaceRegistrationId(storedWorkspace);
        let cwd;
        try {
          cwd = validateAndCanonicalizeWorkspace(storedWorkspace);
        } catch (err) {
          writeStderrLine(
            `qwen serve: skipping persisted workspace registration ${JSON.stringify(
              storedWorkspace
            )}: ${err instanceof Error ? err.message : String(err)}`
          );
          continue;
        }
        const existingInput = workspaceInputs.find(
          (workspace) => workspace.cwd === cwd
        );
        if (existingInput) {
          existingInput.registrationIds.push(registrationId);
          continue;
        }
        const nested = workspaceInputs.some(
          (workspace) => isWithinRoot(cwd, workspace.cwd) || isWithinRoot(workspace.cwd, cwd)
        );
        if (nested) {
          writeStderrLine(
            `qwen serve: skipping persisted workspace registration ${JSON.stringify(
              storedWorkspace
            )}: path nests with an explicit or earlier restored workspace`
          );
          continue;
        }
        if (workspaceInputs.length >= MAX_REGISTERED_WORKSPACES) {
          writeStderrLine(
            `qwen serve: skipping persisted workspace registration ${JSON.stringify(
              storedWorkspace
            )}: workspace limit reached`
          );
          continue;
        }
        workspaceInputs.push({
          raw: storedWorkspace,
          cwd,
          removable: true,
          registrationIds: [registrationId]
        });
      }
    } catch (err) {
      writeStderrLine(
        `qwen serve: failed to read persisted workspace registrations: ${err instanceof Error ? err.message : String(err)}; continuing with explicit workspaces only`
      );
    }
  }
  if (workspaceInputs.length > 1 && deps.bridge) {
    throw new Error(
      "Injected bridge dependencies are only supported with a single workspace; multiple --workspace values require runQwenServe to construct one bridge per workspace."
    );
  }
  let contextFilenameForInit;
  let permissionPolicy;
  let permissionConsensusQuorum;
  let bootSettings;
  let sessionArtifactsPersistenceAvailable = true;
  try {
    bootSettings = deps.bootSettings ?? loadServeFastPathSettings(boundWorkspace);
    sessionArtifactsPersistenceAvailable = sessionArtifactsPersistenceAvailableFromSettings(bootSettings);
    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.maxTotalSessions !== void 0) {
    if (!isNonNegativeIntegerOrInfinity(opts.maxTotalSessions)) {
      throw new TypeError(
        `Invalid maxTotalSessions: ${opts.maxTotalSessions}. Must be a non-negative integer (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.compactedReplayMaxBytes !== void 0) {
    normalizeCompactedReplayMaxBytes(opts.compactedReplayMaxBytes);
  }
  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).`
      );
    }
  }
  opts.maxTotalSessions ??= deriveDefaultMaxTotalSessions(
    opts.maxSessions,
    workspaceInputs.length
  );
  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;
  const internalRuntimeBridgesForCleanup = [];
  let daemonEventLoopMonitor;
  let daemonMetricsSampler;
  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(() => {
    const eventLoopMonitor = daemonEventLoopMonitor;
    daemonEventLoopMonitor = void 0;
    const metricsSampler = daemonMetricsSampler;
    daemonMetricsSampler = void 0;
    try {
      eventLoopMonitor?.dispose();
    } catch (err) {
      daemonLog.warn(
        `event loop monitor dispose error: ${err instanceof Error ? err.message : String(err)}`
      );
    }
    try {
      metricsSampler?.dispose();
    } catch (err) {
      daemonLog.warn(
        `metrics sampler dispose error: ${err instanceof Error ? err.message : String(err)}`
      );
    }
  }, "disposeDaemonEventLoopMonitor");
  let channelWorkerManager;
  let channelWorkerManagerStarting;
  let channelControlDraining = false;
  let channelWorkspaceGroups;
  const channelWebhookEnvByWorkspace = /* @__PURE__ */ new Map();
  let channelWebhookConfigVersion = 0;
  let refreshChannelWebhookConfigs;
  let ensureChannelWorkerManager;
  const getChannelWebhookConfigSources = /* @__PURE__ */ __name(() => {
    const app2 = runtimeApp ?? runtimeAppForCleanup;
    const registry = app2?.locals?.["workspaceRegistry"];
    return (channelWorkspaceGroups ?? []).map((group) => {
      const env = registry?.getByWorkspaceCwd(group.workspaceCwd)?.env.effectiveEnv ?? channelWebhookEnvByWorkspace.get(group.workspaceCwd);
      return {
        workspaceCwd: group.workspaceCwd,
        ...group.selection.mode === "names" ? { channelNames: group.selection.names } : {},
        ...env ? { env } : {}
      };
    });
  }, "getChannelWebhookConfigSources");
  const resolveChannelWebhookConfigSource = /* @__PURE__ */ __name((channelName) => {
    const source = getChannelWebhookConfigSources().find(
      (source2) => !source2.channelNames || source2.channelNames.includes(channelName)
    );
    if (source) return source;
    const env = channelWebhookEnvByWorkspace.get(boundWorkspace);
    return {
      workspaceCwd: boundWorkspace,
      ...env ? { env } : {}
    };
  }, "resolveChannelWebhookConfigSource");
  let closeServerAfterChannelWorkerStartupFailure = false;
  let runtimeFailureListenerClose;
  const getChannelWorkerSnapshot = /* @__PURE__ */ __name(() => channelWorkerManager?.primarySnapshot() ?? {
    enabled: false,
    state: "disabled",
    channels: []
  }, "getChannelWorkerSnapshot");
  const getChannelWorkerSnapshots = /* @__PURE__ */ __name(() => channelWorkerManager?.snapshots() ?? [], "getChannelWorkerSnapshots");
  const getChannelWorkerControl = /* @__PURE__ */ __name(() => channelWorkerManager?.state() ?? {
    enabled: false,
    selection: null,
    transition: "idle",
    workers: []
  }, "getChannelWorkerControl");
  const daemonDrainingError = /* @__PURE__ */ __name(() => Object.assign(new Error("Daemon is shutting down."), {
    code: "daemon_draining"
  }), "daemonDrainingError");
  const setChannelWorkerSelection = /* @__PURE__ */ __name(async (selection) => {
    if (channelControlDraining) throw daemonDrainingError();
    const manager = await ensureChannelWorkerManager?.();
    if (!manager) throw new Error("Channel worker manager is unavailable.");
    if (channelControlDraining) {
      await manager.shutdown().catch(() => void 0);
      throw daemonDrainingError();
    }
    return manager.setSelection(selection);
  }, "setChannelWorkerSelection");
  const stopChannelWorker = /* @__PURE__ */ __name(async () => {
    if (channelControlDraining) throw daemonDrainingError();
    const manager = channelWorkerManager ?? await channelWorkerManagerStarting;
    if (channelControlDraining) {
      await manager?.shutdown().catch(() => void 0);
      throw daemonDrainingError();
    }
    if (!manager) {
      return { changed: false, state: getChannelWorkerControl() };
    }
    return manager.stopSelection();
  }, "stopChannelWorker");
  const reloadChannelWorker = /* @__PURE__ */ __name(async () => {
    if (channelControlDraining) throw daemonDrainingError();
    const manager = channelWorkerManager ?? await channelWorkerManagerStarting;
    if (channelControlDraining) {
      await manager?.shutdown().catch(() => void 0);
      throw daemonDrainingError();
    }
    if (!manager) {
      return { enabled: false, state: "disabled", channels: [] };
    }
    try {
      return await manager.reload();
    } finally {
      writeChannelWorkerPidfile();
    }
  }, "reloadChannelWorker");
  const isLiveWorker = /* @__PURE__ */ __name((snapshot) => snapshot.state === "running" || snapshot.state === "starting", "isLiveWorker");
  let channelWorkerPidfileUsesWorkers = workspaceInputs.length > 1;
  const writeChannelWorkerPidfile = /* @__PURE__ */ __name(() => {
    if (runtimeStartupError !== void 0) return;
    if (!channelPidfileReserved || !channelServicePidfile) return;
    const snapshots = getChannelWorkerSnapshots();
    const workers = snapshots.map((snapshot) => ({
      workspaceId: snapshot.workspaceId,
      workspaceCwd: snapshot.workspaceCwd,
      channels: snapshot.channels,
      // Drop a stale pid (worker exited/failed/stopped) so readers never signal
      // a dead process — mirrors the pre-4b clear-on-exit behavior.
      ...isLiveWorker(snapshot) && snapshot.pid !== void 0 ? { workerPid: snapshot.pid } : {}
    }));
    const channels = [
      ...new Set(snapshots.flatMap((snapshot) => snapshot.channels))
    ];
    const primary = snapshots.find((snapshot) => snapshot.primary);
    if (workers.length > 1 || snapshots.some((snapshot) => !snapshot.primary)) {
      channelWorkerPidfileUsesWorkers = true;
    }
    const includeWorkers = channelWorkerPidfileUsesWorkers && workers.length > 0;
    try {
      channelServicePidfile.writeServeServiceInfo({
        channels,
        servePid: process.pid,
        ...primary && isLiveWorker(primary) && primary.pid !== void 0 ? { workerPid: primary.pid } : {},
        ...includeWorkers ? { workers } : {}
      });
    } 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 shutdownBridges = /* @__PURE__ */ new WeakSet();
  const disposedRuntimeApps = /* @__PURE__ */ new WeakSet();
  const stoppedRuntimeAppProducers = /* @__PURE__ */ new WeakSet();
  const stoppedExtensionReconcilers = /* @__PURE__ */ new WeakSet();
  const stopExtensionReconciler = /* @__PURE__ */ __name((app2) => {
    if (!app2 || stoppedExtensionReconcilers.has(app2)) return;
    stoppedExtensionReconcilers.add(app2);
    const stopExtensionGenerationReconciler = app2.locals?.["stopExtensionGenerationReconciler"];
    try {
      stopExtensionGenerationReconciler?.();
    } catch (err) {
      daemonLog.warn(
        `extension generation reconciler dispose error: ${err instanceof Error ? err.message : String(err)}`
      );
    }
  }, "stopExtensionReconciler");
  const stopRuntimeAppProducers = /* @__PURE__ */ __name((app2) => {
    if (!app2 || stoppedRuntimeAppProducers.has(app2)) return;
    stoppedRuntimeAppProducers.add(app2);
    const locals = app2.locals;
    const stopSafely = /* @__PURE__ */ __name((name, stop) => {
      try {
        stop?.();
      } catch (err) {
        daemonLog.warn(
          `${name} dispose error: ${err instanceof Error ? err.message : String(err)}`
        );
      }
    }, "stopSafely");
    stopSafely("scheduled-task keepalive", locals.stopScheduledTaskKeepalive);
    stopSafely("workspace git state", locals.stopWorkspaceGitState);
    for (const stop of locals.subSessionStoppers ?? []) {
      stopSafely("sub-session launcher", stop);
    }
    stopExtensionReconciler(app2);
  }, "stopRuntimeAppProducers");
  const disposeRuntimeAppResources = /* @__PURE__ */ __name((app2) => {
    if (!app2 || disposedRuntimeApps.has(app2)) return;
    disposedRuntimeApps.add(app2);
    stopRuntimeAppProducers(app2);
    const deviceFlowRegistry = getDeviceFlowRegistry(app2);
    if (deviceFlowRegistry) {
      try {
        deviceFlowRegistry.dispose();
      } catch (err) {
        daemonLog.warn(
          `device-flow registry dispose error: ${err instanceof Error ? err.message : String(err)}`
        );
      }
    }
    const acpHandle = app2.locals?.["acpHandle"];
    if (acpHandle?.dispose) {
      try {
        acpHandle.dispose();
      } catch (err) {
        daemonLog.warn(
          `ACP handle dispose error: ${err instanceof Error ? err.message : String(err)}`
        );
      }
    }
    const rateLimiter = getRateLimiter(app2);
    if (rateLimiter) {
      try {
        rateLimiter.setDraining(true);
        rateLimiter.dispose();
      } catch (err) {
        daemonLog.warn(
          `rate limiter dispose error: ${err instanceof Error ? err.message : String(err)}`
        );
      }
    }
    disposeDaemonEventLoopMonitor();
  }, "disposeRuntimeAppResources");
  const getRuntimeBridgesForCleanup = /* @__PURE__ */ __name(() => {
    const appForCleanup = runtimeApp ?? runtimeAppForCleanup;
    const registry = appForCleanup?.locals?.["workspaceRegistry"];
    const bridges = [
      ...registry ? registry.listManaged().map((runtime) => runtime.bridge) : [],
      ...bridgeRef ? [bridgeRef] : [],
      ...internalRuntimeBridgesForCleanup
    ];
    return [...new Set(bridges)];
  }, "getRuntimeBridgesForCleanup");
  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 runtimeEnvSnapshot = runtimeBootSettings ? settingsRuntime.environment.buildRuntimeEnvironment(
      runtimeBootSettings.merged,
      boundWorkspace,
      daemonRuntimeBaseEnv
    ) : {
      effectiveEnv: { ...daemonRuntimeBaseEnv },
      overlayKeys: Object.freeze([]),
      envFilePaths: Object.freeze([]),
      envFileReadFailed: false,
      envFileReadFailures: Object.freeze([])
    };
    const logRuntimeEnvFileReadFailures = /* @__PURE__ */ __name((workspace, snapshot) => {
      if (!snapshot.envFileReadFailed) return;
      const failedFiles = snapshot.envFileReadFailures ?? [];
      daemonLog.warn("one or more runtime env files could not be read", {
        workspace,
        ...failedFiles.length > 0 ? { failedFiles } : {}
      });
    }, "logRuntimeEnvFileReadFailures");
    logRuntimeEnvFileReadFailures(boundWorkspace, runtimeEnvSnapshot);
    const runtimeEffectiveEnv = {
      ...runtimeEnvSnapshot.effectiveEnv
    };
    const replaceRuntimeEffectiveEnv = /* @__PURE__ */ __name((nextEnv) => {
      for (const key of Object.keys(runtimeEffectiveEnv)) {
        delete runtimeEffectiveEnv[key];
      }
      Object.assign(runtimeEffectiveEnv, nextEnv);
    }, "replaceRuntimeEffectiveEnv");
    const primaryRuntimeEnv = {
      mode: "runtime-overlay",
      overlayKeys: [...runtimeEnvSnapshot.overlayKeys],
      effectiveEnv: runtimeEffectiveEnv,
      envFilePaths: [...runtimeEnvSnapshot.envFilePaths],
      envFileReadFailed: runtimeEnvSnapshot.envFileReadFailed,
      envFileReadFailures: [...runtimeEnvSnapshot.envFileReadFailures]
    };
    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:${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 metricsRing = new DaemonMetricsRing({
      capacity: DAEMON_METRICS_CAPACITY
    });
    const pipeStats = {
      inbound: { count: 0, totalBytes: 0, maxBytes: 0 },
      outbound: { count: 0, totalBytes: 0, maxBytes: 0 }
    };
    const promptQueueWaitStats = {
      count: 0,
      totalMs: 0,
      maxMs: 0,
      lastMs: null
    };
    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);
      metricsRing.recordPipe(direction, bytes);
    }, "recordPipeMessage");
    const observeLargePipeFrame = createLargePipeFrameObserver({
      daemonLog,
      emitTelemetryLog: core.emitDaemonLog
    });
    const recordPromptQueueWait = /* @__PURE__ */ __name((durationMs) => {
      promptQueueWaitStats.count += 1;
      promptQueueWaitStats.totalMs += durationMs;
      promptQueueWaitStats.maxMs = Math.max(
        promptQueueWaitStats.maxMs,
        durationMs
      );
      promptQueueWaitStats.lastMs = durationMs;
      core.recordDaemonPromptQueueWait(durationMs);
    }, "recordPromptQueueWait");
    const createRuntimeBridgeTelemetry = /* @__PURE__ */ __name((workspaceHash) => {
      const telemetry = core.createDaemonBridgeTelemetry();
      telemetry.metrics = {
        sessionLifecycle(action) {
          core.recordDaemonSessionLifecycle(action);
          core.emitDaemonLog(
            `Session ${action}.`,
            {
              "qwen-code.workspace.hash": workspaceHash
            },
            {
              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(durationMs) {
          recordPromptQueueWait(durationMs);
          metricsRing.recordPromptQueueWait(durationMs);
        },
        promptDuration(durationMs) {
          core.recordDaemonPromptDuration(durationMs);
          metricsRing.recordPromptDuration(durationMs);
        },
        cancelled: core.recordDaemonCancel,
        // Per-round model token usage + LLM round-trip time sniffed off
        // `agent_message_chunk._meta` (`usage` + `durationMs`) at the bridge's
        // single session/update fan-in. Increments (not cumulative), so the ring
        // sums tokens per window (token-burn chart) and pools the round-trip times
        // for the LLM-latency percentiles. `apiErrors` / `apiRetries` ride the
        // same frame (per-round increments, 0 when none) and window into the
        // model-API-health chart.
        tokenUsage(inputTokens, outputTokens, durationMs, apiErrors, apiRetries) {
          metricsRing.recordTokens(inputTokens, outputTokens);
          if (typeof durationMs === "number") {
            metricsRing.recordLlmDuration(durationMs);
          }
          metricsRing.recordApiActivity(apiErrors ?? 0, apiRetries ?? 0);
        }
      };
      return telemetry;
    }, "createRuntimeBridgeTelemetry");
    const daemonTelemetry = createRuntimeBridgeTelemetry(daemonWorkspaceHash);
    const permissionAuditRing = new PermissionAuditRing();
    const permissionAuditPublisher = createPermissionAuditPublisher({
      ring: permissionAuditRing
    });
    const customIgnoreFiles = runtimeBootSettings?.merged.context?.fileFiltering?.customIgnoreFiles;
    const boundWorkspaces = runtime.resolveBoundWorkspacesFromIdeEnv(
      boundWorkspace,
      void 0,
      (workspace, index) => {
        if (index === 0) return true;
        if (!runtimeBootSettings) {
          daemonLog.warn(
            "excluding secondary workspace root because trust settings are unavailable",
            { workspace }
          );
          return false;
        }
        const trustedSecondary = settingsRuntime.trustedFolders.getWorkspaceTrustStatus(
          runtimeBootSettings.merged,
          workspace
        ).effective.state === "trusted";
        if (!trustedSecondary) {
          daemonLog.warn(
            "excluding untrusted secondary workspace root from file-system access",
            { workspace }
          );
        }
        return trustedSecondary;
      }
    );
    daemonLog.info("daemon workspace roots initialized", {
      primary: boundWorkspaces[0],
      secondary: boundWorkspaces.slice(1),
      ideEnvPresent: !!process.env["QWEN_CODE_IDE_WORKSPACE_PATH"]
    });
    const sharedPathLocks = new PathMutexRegistry();
    const fsFactory = runtime.resolveBridgeFsFactory({
      // Secondary roots share a write-capable factory only after their own
      // folder trust check passes; untrusted secondary roots stay outside.
      boundWorkspaces,
      injected: deps.fsFactory,
      trusted: trustedWorkspace,
      emit: deps.fsAuditEmit,
      pathLocks: sharedPathLocks,
      ...customIgnoreFiles !== void 0 ? { customIgnoreFiles } : {}
    });
    const routeFsFactory = runtime.resolveBridgeFsFactory({
      // REST routes still return primary-relative paths, so keep their
      // filesystem boundary primary-only until responses carry root IDs.
      boundWorkspaces: [boundWorkspace],
      trusted: trustedWorkspace,
      emit: deps.fsAuditEmit,
      pathLocks: sharedPathLocks,
      ...customIgnoreFiles !== void 0 ? { customIgnoreFiles } : {}
    });
    const channelFactory = runtime.createSpawnChannelFactory({
      sourceEnv: runtimeEffectiveEnv,
      onDiagnosticLine: diagnosticSink,
      pipeHooks: {
        onMessageSent: /* @__PURE__ */ __name((bytes) => recordPipeMessage("outbound", bytes), "onMessageSent"),
        onMessageReceived: /* @__PURE__ */ __name((bytes) => recordPipeMessage("inbound", bytes), "onMessageReceived"),
        onMessageObserved: /* @__PURE__ */ __name(({ direction, bytes, message }) => observeLargePipeFrame({
          direction: daemonPipeDirection(direction),
          bytes,
          message
        }), "onMessageObserved")
      },
      ...opts.experimentalLsp === true ? { extraArgs: ["--experimental-lsp"] } : {}
    });
    const statusProvider = runtime.createDaemonStatusProvider({
      env: runtimeEffectiveEnv
    });
    const workspaceProvidersStatusProvider = runtime.createWorkspaceProvidersStatusProvider({
      env: runtimeEffectiveEnv
    });
    const workspaceSkillsStatusProvider = runtime.createWorkspaceSkillsStatusProvider();
    const clientMcpSenderRegistry = new ClientMcpSenderRegistry();
    const runtimeBridges = [];
    const totalSessionAdmission = runtime.createTotalSessionAdmissionController(
      {
        maxTotalSessions: opts.maxTotalSessions,
        getBridges: /* @__PURE__ */ __name(() => runtimeBridges.length > 0 ? runtimeBridges : bridgeRef ? [bridgeRef] : [], "getBridges")
      }
    );
    const sessionOwnerIndex = runtime.createWorkspaceSessionOwnerIndex();
    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 persistDisabledSkillsFn = /* @__PURE__ */ __name((workspace, skillName, enabled) => withSettingsLock(workspace, async () => {
      const fresh = settingsRuntime.settings.loadSettings(workspace);
      const normalizedName = skillName.trim().toLowerCase();
      const disabledNames = /* @__PURE__ */ __name((value) => Array.isArray(value) ? value.filter(
        (entry) => typeof entry === "string"
      ) : [], "disabledNames");
      const lockedScopes = [
        ["system", fresh.system.settings.skills?.disabled],
        ["user", fresh.user.settings.skills?.disabled],
        ["systemDefaults", fresh.systemDefaults.settings.skills?.disabled]
      ];
      for (const [scope, names] of lockedScopes) {
        if (disabledNames(names).some(
          (name) => name.trim().toLowerCase() === normalizedName
        )) {
          throw new runtime.WorkspaceSkillNotToggleableError(
            skillName,
            "locked",
            scope
          );
        }
      }
      const workspaceDisabled = disabledNames(
        fresh.workspace.settings.skills?.disabled
      );
      const next = [];
      let found = false;
      let changed = false;
      for (const name of workspaceDisabled) {
        if (name.trim().toLowerCase() !== normalizedName) {
          next.push(name);
          continue;
        }
        if (enabled) {
          changed = true;
          continue;
        }
        if (!found) {
          next.push(skillName);
          found = true;
          if (name !== skillName) changed = true;
        } else {
          changed = true;
        }
      }
      if (!enabled && !found) {
        next.push(skillName);
        changed = true;
      }
      if (!changed) return { changed: false, disabled: workspaceDisabled };
      fresh.setValue(
        WORKSPACE_SETTING_SCOPE,
        "skills.disabled",
        next.length > 0 ? next : void 0
      );
      return { changed: true, disabled: next };
    }), "persistDisabledSkillsFn");
    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 { createSubSessionLauncher } = await import("./create-sub-session-45AINZHP.js");
    const subSessionLauncher = createSubSessionLauncher({
      getBridge: /* @__PURE__ */ __name(() => bridgeRef, "getBridge"),
      boundWorkspace
    });
    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,
      onCreateSubSession: subSessionLauncher.launch,
      maxSessions: opts.maxSessions,
      freshSessionAdmission: totalSessionAdmission.admit,
      sessionLifecycle: sessionOwnerIndex.handleBridgeSessionLifecycle,
      ...opts.maxPendingPromptsPerSession !== void 0 ? { maxPendingPromptsPerSession: opts.maxPendingPromptsPerSession } : {},
      ...opts.eventRingSize !== void 0 ? { eventRingSize: opts.eventRingSize } : {},
      ...opts.compactedReplayMaxBytes !== void 0 ? { compactedReplayMaxBytes: opts.compactedReplayMaxBytes } : {},
      ...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;
      internalRuntimeBridgesForCleanup.push(bridge);
    }
    runtimeBridges.push(bridge);
    let invalidatePrimaryServeFeaturesCache = /* @__PURE__ */ __name(() => {
    }, "invalidatePrimaryServeFeaturesCache");
    const workspaceService = runtime.createDaemonWorkspaceService({
      boundWorkspace,
      contextFilename: contextFilenameForInit ?? "QWEN.md",
      statusProvider,
      workspaceProvidersStatusProvider,
      workspaceSkillsStatusProvider,
      voiceEnv: runtimeEffectiveEnv,
      isChannelLive: /* @__PURE__ */ __name(() => bridge.isChannelLive(), "isChannelLive"),
      persistDisabledTools: persistDisabledToolsFn,
      persistDisabledSkills: persistDisabledSkillsFn,
      persistSetting: persistSettingFn,
      persistSettings: persistSettingsFn,
      preheatAcpChild: /* @__PURE__ */ __name(() => bridge.preheat(), "preheatAcpChild"),
      reloadDaemonEnv: /* @__PURE__ */ __name((workspace) => withSettingsLock(workspace, async () => {
        const fresh = settingsRuntime.settings.loadSettings(workspace, {
          skipLoadEnvironment: true
        });
        const result = settingsRuntime.settings.reloadEnvironment(
          fresh.merged,
          workspace
        );
        let refreshedRuntimeEnv;
        let fallbackReason;
        try {
          refreshedRuntimeEnv = settingsRuntime.environment.buildRuntimeEnvironment(
            fresh.merged,
            workspace,
            daemonRuntimeBaseEnv
          );
        } catch (err) {
          fallbackReason = err instanceof Error ? err.message : String(err);
          daemonLog.warn(
            "failed to rebuild runtime env snapshot after daemon env reload; preserving previous runtime env",
            {
              error: fallbackReason
            }
          );
          refreshedRuntimeEnv = {
            effectiveEnv: { ...runtimeEffectiveEnv },
            overlayKeys: [...primaryRuntimeEnv.overlayKeys],
            envFilePaths: [...primaryRuntimeEnv.envFilePaths],
            envFileReadFailed: primaryRuntimeEnv.envFileReadFailed ?? false,
            envFileReadFailures: [
              ...primaryRuntimeEnv.envFileReadFailures ?? []
            ]
          };
        }
        logRuntimeEnvFileReadFailures(workspace, refreshedRuntimeEnv);
        replaceRuntimeEffectiveEnv(refreshedRuntimeEnv.effectiveEnv);
        if (fallbackReason) {
          primaryRuntimeEnv.fallbackReason = fallbackReason;
        } else {
          delete primaryRuntimeEnv.fallbackReason;
        }
        primaryRuntimeEnv.envFileReadFailed = refreshedRuntimeEnv.envFileReadFailed;
        primaryRuntimeEnv.envFileReadFailures.splice(
          0,
          primaryRuntimeEnv.envFileReadFailures.length,
          ...refreshedRuntimeEnv.envFileReadFailures
        );
        primaryRuntimeEnv.overlayKeys.splice(
          0,
          primaryRuntimeEnv.overlayKeys.length,
          ...refreshedRuntimeEnv.overlayKeys
        );
        primaryRuntimeEnv.envFilePaths.splice(
          0,
          primaryRuntimeEnv.envFilePaths.length,
          ...refreshedRuntimeEnv.envFilePaths
        );
        return result;
      }), "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) => {
        if (event.type === "settings_changed" || event.type === "settings_reloaded") {
          invalidatePrimaryServeFeaturesCache();
        }
        bridge.publishWorkspaceEvent(event);
      }, "publishWorkspaceEvent")
    });
    const workspaceRuntimes = [
      {
        workspaceId: daemonWorkspaceHash,
        workspaceCwd: boundWorkspace,
        primary: true,
        trusted: trustedWorkspace,
        removable: false,
        registrationIds: workspaceInputs[0]?.registrationIds ?? [],
        env: primaryRuntimeEnv,
        bridge,
        workspaceService,
        routeFileSystemFactory: routeFsFactory,
        clientMcpSenderRegistry
      }
    ];
    const createRuntimeEnvMetadata = /* @__PURE__ */ __name((workspace, settings) => {
      const snapshot = settings ? settingsRuntime.environment.buildRuntimeEnvironment(
        settings.merged,
        workspace,
        daemonRuntimeBaseEnv
      ) : {
        effectiveEnv: { ...daemonRuntimeBaseEnv },
        overlayKeys: Object.freeze([]),
        envFilePaths: Object.freeze([]),
        envFileReadFailed: false,
        envFileReadFailures: Object.freeze([])
      };
      logRuntimeEnvFileReadFailures(workspace, snapshot);
      const effectiveEnv = { ...snapshot.effectiveEnv };
      const metadata = {
        mode: "runtime-overlay",
        overlayKeys: [...snapshot.overlayKeys],
        effectiveEnv,
        envFilePaths: [...snapshot.envFilePaths],
        envFileReadFailed: snapshot.envFileReadFailed,
        envFileReadFailures: [...snapshot.envFileReadFailures]
      };
      return {
        metadata,
        effectiveEnv,
        replace(nextEnv) {
          for (const key of Object.keys(effectiveEnv)) {
            delete effectiveEnv[key];
          }
          Object.assign(effectiveEnv, nextEnv);
        }
      };
    }, "createRuntimeEnvMetadata");
    const subSessionStoppers = [];
    const subSessionStoppersByWorkspace = /* @__PURE__ */ new Map();
    const runtimeCleanupPromises = /* @__PURE__ */ new WeakMap();
    const removeArrayValue = /* @__PURE__ */ __name((values, value) => {
      const index = values.indexOf(value);
      if (index >= 0) values.splice(index, 1);
    }, "removeArrayValue");
    for (const workspaceInput of workspaceInputs.slice(1)) {
      let secondarySettings;
      try {
        secondarySettings = settingsRuntime.settings.loadSettings(
          workspaceInput.cwd
        );
      } catch (err) {
        writeStderrLine(
          `qwen serve: could not read full settings for secondary workspace ${workspaceInput.cwd} (${err instanceof Error ? err.message : String(err)}); falling back to defaults.`
        );
      }
      const secondaryTrusted = secondarySettings ? settingsRuntime.trustedFolders.getWorkspaceTrustStatus(
        secondarySettings.merged,
        workspaceInput.cwd
      ).effective.state === "trusted" : false;
      if (!secondaryTrusted) {
        daemonLog.warn("secondary workspace is not trusted", {
          workspace: workspaceInput.cwd,
          trustSettingsAvailable: secondarySettings !== void 0
        });
      }
      const secondaryEnv = createRuntimeEnvMetadata(
        workspaceInput.cwd,
        secondarySettings
      );
      const secondaryWorkspaceHash = core.hashDaemonWorkspace(
        workspaceInput.cwd
      );
      const secondaryStatusProvider = runtime.createDaemonStatusProvider({
        env: secondaryEnv.effectiveEnv
      });
      const secondaryBridgeFsFactory = runtime.resolveBridgeFsFactory({
        boundWorkspaces: [workspaceInput.cwd],
        trusted: secondaryTrusted,
        emit: deps.fsAuditEmit,
        pathLocks: sharedPathLocks,
        ...customIgnoreFiles !== void 0 ? { customIgnoreFiles } : {}
      });
      const secondaryChannelFactory = runtime.createSpawnChannelFactory({
        sourceEnv: secondaryEnv.effectiveEnv,
        onDiagnosticLine: diagnosticSink,
        pipeHooks: {
          onMessageSent: /* @__PURE__ */ __name((bytes) => recordPipeMessage("outbound", bytes), "onMessageSent"),
          onMessageReceived: /* @__PURE__ */ __name((bytes) => recordPipeMessage("inbound", bytes), "onMessageReceived"),
          onMessageObserved: /* @__PURE__ */ __name(({ direction, bytes, message }) => observeLargePipeFrame({
            direction: daemonPipeDirection(direction),
            bytes,
            message
          }), "onMessageObserved")
        },
        ...opts.experimentalLsp === true ? { extraArgs: ["--experimental-lsp"] } : {}
      });
      const secondaryClientMcpSenderRegistry = new ClientMcpSenderRegistry();
      let secondaryBridgeRef;
      const secondarySubSessionLauncher = createSubSessionLauncher({
        getBridge: /* @__PURE__ */ __name(() => secondaryBridgeRef, "getBridge"),
        boundWorkspace: workspaceInput.cwd
      });
      const secondaryBridge = runtime.createAcpSessionBridge({
        clientMcpSender: secondaryClientMcpSenderRegistry.lookup,
        onCreateSubSession: secondarySubSessionLauncher.launch,
        maxSessions: opts.maxSessions,
        freshSessionAdmission: totalSessionAdmission.admit,
        sessionLifecycle: sessionOwnerIndex.handleBridgeSessionLifecycle,
        ...opts.maxPendingPromptsPerSession !== void 0 ? { maxPendingPromptsPerSession: opts.maxPendingPromptsPerSession } : {},
        ...opts.eventRingSize !== void 0 ? { eventRingSize: opts.eventRingSize } : {},
        ...opts.compactedReplayMaxBytes !== void 0 ? { compactedReplayMaxBytes: opts.compactedReplayMaxBytes } : {},
        ...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: workspaceInput.cwd,
        sessionShellCommandEnabled,
        childEnvOverrides,
        channelFactory: secondaryChannelFactory,
        onDiagnosticLine: diagnosticSink,
        telemetry: createRuntimeBridgeTelemetry(secondaryWorkspaceHash),
        ...permissionPolicy !== void 0 ? { permissionPolicy } : {},
        ...permissionConsensusQuorum !== void 0 ? {
          permissionConsensusQuorum
        } : {},
        permissionAudit: permissionAuditPublisher,
        statusProvider: secondaryStatusProvider,
        fileSystem: createBridgeFileSystemAdapter(secondaryBridgeFsFactory),
        persistApprovalMode: /* @__PURE__ */ __name((workspace, mode) => withSettingsLock(workspace, async () => {
          const fresh = settingsRuntime.settings.loadSettings(workspace);
          fresh.setValue(WORKSPACE_SETTING_SCOPE, "tools.approvalMode", mode);
        }), "persistApprovalMode")
      });
      secondaryBridgeRef = secondaryBridge;
      runtimeBridges.push(secondaryBridge);
      internalRuntimeBridgesForCleanup.push(secondaryBridge);
      subSessionStoppers.push(secondarySubSessionLauncher.stop);
      subSessionStoppersByWorkspace.set(
        workspaceInput.cwd,
        secondarySubSessionLauncher.stop
      );
      const secondaryWorkspaceService = runtime.createDaemonWorkspaceService({
        boundWorkspace: workspaceInput.cwd,
        contextFilename: contextFilenameForInit ?? "QWEN.md",
        statusProvider: secondaryStatusProvider,
        workspaceProvidersStatusProvider: runtime.createWorkspaceProvidersStatusProvider({
          env: secondaryEnv.effectiveEnv
        }),
        workspaceSkillsStatusProvider: runtime.createWorkspaceSkillsStatusProvider(),
        voiceEnv: secondaryEnv.effectiveEnv,
        voiceSettingsScope: WORKSPACE_SETTING_SCOPE,
        isChannelLive: /* @__PURE__ */ __name(() => secondaryBridge.isChannelLive(), "isChannelLive"),
        preheatAcpChild: /* @__PURE__ */ __name(() => secondaryBridge.preheat(), "preheatAcpChild"),
        persistDisabledTools: persistDisabledToolsFn,
        persistDisabledSkills: persistDisabledSkillsFn,
        persistSetting: persistSettingFn,
        persistSettings: persistSettingsFn,
        reloadDaemonEnv: /* @__PURE__ */ __name((workspace) => withSettingsLock(workspace, async () => {
          const fresh = settingsRuntime.settings.loadSettings(workspace, {
            skipLoadEnvironment: true
          });
          const result = settingsRuntime.settings.reloadEnvironment(
            fresh.merged,
            workspace
          );
          try {
            const refreshedRuntimeEnv = settingsRuntime.environment.buildRuntimeEnvironment(
              fresh.merged,
              workspace,
              daemonRuntimeBaseEnv
            );
            logRuntimeEnvFileReadFailures(workspace, refreshedRuntimeEnv);
            secondaryEnv.replace(refreshedRuntimeEnv.effectiveEnv);
            secondaryEnv.metadata.envFileReadFailed = refreshedRuntimeEnv.envFileReadFailed;
            secondaryEnv.metadata.envFileReadFailures.splice(
              0,
              secondaryEnv.metadata.envFileReadFailures.length,
              ...refreshedRuntimeEnv.envFileReadFailures
            );
            secondaryEnv.metadata.overlayKeys.splice(
              0,
              secondaryEnv.metadata.overlayKeys.length,
              ...refreshedRuntimeEnv.overlayKeys
            );
            secondaryEnv.metadata.envFilePaths.splice(
              0,
              secondaryEnv.metadata.envFilePaths.length,
              ...refreshedRuntimeEnv.envFilePaths
            );
            delete secondaryEnv.metadata.fallbackReason;
          } catch (err) {
            secondaryEnv.metadata.fallbackReason = err instanceof Error ? err.message : String(err);
            daemonLog.warn(
              "failed to rebuild secondary runtime env snapshot after daemon env reload; preserving previous runtime env",
              {
                workspace,
                error: secondaryEnv.metadata.fallbackReason
              }
            );
          }
          return result;
        }), "reloadDaemonEnv"),
        queryWorkspaceStatus: /* @__PURE__ */ __name((method, idle) => secondaryBridge.queryWorkspaceStatus(method, idle), "queryWorkspaceStatus"),
        invokeWorkspaceCommand: /* @__PURE__ */ __name((method, params, invokeOpts) => secondaryBridge.invokeWorkspaceCommand(method, params, invokeOpts), "invokeWorkspaceCommand"),
        refreshExtensionsForAllSessions: /* @__PURE__ */ __name(() => secondaryBridge.refreshExtensionsForAllSessions(), "refreshExtensionsForAllSessions"),
        publishWorkspaceEvent: /* @__PURE__ */ __name((event) => secondaryBridge.publishWorkspaceEvent(event), "publishWorkspaceEvent")
      });
      workspaceRuntimes.push({
        workspaceId: secondaryWorkspaceHash,
        workspaceCwd: workspaceInput.cwd,
        primary: false,
        trusted: secondaryTrusted,
        removable: workspaceInput.removable,
        registrationIds: workspaceInput.registrationIds,
        env: secondaryEnv.metadata,
        bridge: secondaryBridge,
        workspaceService: secondaryWorkspaceService,
        routeFileSystemFactory: secondaryBridgeFsFactory,
        clientMcpSenderRegistry: secondaryClientMcpSenderRegistry
      });
    }
    const workspaceRegistry = runtime.createWorkspaceRegistry(workspaceRuntimes, {
      sessionOwnerIndex
    });
    const workspaceVoiceCoordinator = new WorkspaceVoiceCoordinator();
    core.registerDaemonGaugeCallbacks({
      sessionCount: /* @__PURE__ */ __name(() => workspaceRegistry.list().reduce((sum, item) => sum + item.bridge.sessionCount, 0), "sessionCount"),
      sseCount: /* @__PURE__ */ __name(() => runtime.getActiveSseCount(), "sseCount"),
      heapUsed: /* @__PURE__ */ __name(() => process.memoryUsage().heapUsed, "heapUsed")
    });
    daemonMetricsSampler?.dispose();
    const metricsLoopDelay = monitorEventLoopDelay({ resolution: 20 });
    metricsLoopDelay.enable();
    const cpuCoreCount = os.availableParallelism?.() ?? os.cpus().length ?? 1;
    let prevCpu = safeCpuUsage();
    let prevCpuAt = Date.now();
    let prevRateRejected;
    const metricsSamplerTimer = setInterval(() => {
      const nowMs = Date.now();
      const eventLoopLagP99Ms = metricsLoopDelay.percentile(99) / 1e6;
      try {
        const mem = process.memoryUsage();
        const cpu = safeCpuUsage();
        const cpuPercent = computeCpuPercent(
          prevCpu,
          cpu,
          nowMs - prevCpuAt,
          cpuCoreCount
        );
        if (cpu) {
          prevCpu = cpu;
          prevCpuAt = nowMs;
        }
        const acp = app2.locals?.["acpHandle"]?.getSnapshot();
        const hits = getRateLimiter(app2)?.getHitCounts();
        const rejectedTotal = hits ? hits.prompt + hits.mutation + hits.read : 0;
        const rateLimitRejected = prevRateRejected === void 0 ? 0 : Math.max(0, rejectedTotal - prevRateRejected);
        prevRateRejected = rejectedTotal;
        const child = bridge.getChildResourceSnapshot?.();
        if (runtime.getActiveSseCount() > 0 || (acp?.wsStreams ?? 0) > 0) {
          void bridge.refreshChildResource?.();
        }
        metricsRing.sample(nowMs, {
          cpuPercent,
          rssBytes: mem.rss,
          heapUsedBytes: mem.heapUsed,
          activeSessions: workspaceRegistry.list().reduce((sum, item) => sum + item.bridge.sessionCount, 0),
          activePrompts: workspaceRegistry.list().reduce(
            (sum, item) => sum + (item.bridge.activePromptCount ?? 0),
            0
          ),
          queuedPrompts: workspaceRegistry.list().reduce(
            (sum, item) => sum + (item.bridge.pendingPromptTotal ?? 0),
            0
          ),
          eventLoopLagP99Ms,
          sseConnections: runtime.getActiveSseCount(),
          wsConnections: acp?.wsStreams ?? 0,
          acpConnections: acp?.connectionCount ?? 0,
          rateLimitRejected,
          childCpuPercent: child?.cpuPercent ?? 0,
          childRssBytes: child?.rssBytes ?? 0
        });
      } catch (err) {
        daemonLog.warn(
          `metrics sampler tick failed: ${err instanceof Error ? err.message : String(err)}`
        );
        try {
          metricsRing.sample(nowMs, {
            cpuPercent: 0,
            rssBytes: 0,
            heapUsedBytes: 0,
            activeSessions: 0,
            activePrompts: 0,
            queuedPrompts: 0,
            eventLoopLagP99Ms,
            sseConnections: 0,
            wsConnections: 0,
            acpConnections: 0,
            rateLimitRejected: 0,
            childCpuPercent: 0,
            childRssBytes: 0
          });
        } catch {
        }
      } finally {
        metricsLoopDelay.reset();
      }
    }, DAEMON_METRICS_SAMPLE_MS);
    metricsSamplerTimer.unref();
    daemonMetricsSampler = {
      dispose() {
        clearInterval(metricsSamplerTimer);
        metricsLoopDelay.disable();
      }
    };
    const createDynamicWorkspaceRuntime = /* @__PURE__ */ __name(async (cwd) => {
      let wsSettings;
      try {
        wsSettings = settingsRuntime.settings.loadSettings(cwd);
      } catch (err) {
        writeStderrLine(
          `qwen serve: could not read full settings for dynamic workspace ${cwd} (${err instanceof Error ? err.message : String(err)}); falling back to defaults.`
        );
      }
      const trusted = wsSettings ? settingsRuntime.trustedFolders.getWorkspaceTrustStatus(
        wsSettings.merged,
        cwd
      ).effective.state === "trusted" : false;
      const wsEnv = createRuntimeEnvMetadata(cwd, wsSettings);
      const wsHash = core.hashDaemonWorkspace(cwd);
      const wsFsFactory = runtime.resolveBridgeFsFactory({
        boundWorkspaces: [cwd],
        trusted,
        emit: deps.fsAuditEmit,
        pathLocks: sharedPathLocks,
        ...customIgnoreFiles !== void 0 ? { customIgnoreFiles } : {}
      });
      const wsChannelFactory = runtime.createSpawnChannelFactory({
        sourceEnv: wsEnv.effectiveEnv,
        onDiagnosticLine: diagnosticSink,
        pipeHooks: {
          onMessageSent: /* @__PURE__ */ __name((bytes) => recordPipeMessage("outbound", bytes), "onMessageSent"),
          onMessageReceived: /* @__PURE__ */ __name((bytes) => recordPipeMessage("inbound", bytes), "onMessageReceived"),
          onMessageObserved: /* @__PURE__ */ __name(({ direction, bytes, message }) => observeLargePipeFrame({
            direction: daemonPipeDirection(direction),
            bytes,
            message
          }), "onMessageObserved")
        },
        ...opts.experimentalLsp === true ? { extraArgs: ["--experimental-lsp"] } : {}
      });
      const wsClientMcpRegistry = new ClientMcpSenderRegistry();
      let wsBridgeRef;
      const wsSubSessionLauncher = createSubSessionLauncher({
        getBridge: /* @__PURE__ */ __name(() => wsBridgeRef, "getBridge"),
        boundWorkspace: cwd
      });
      let wsBridge;
      try {
        wsBridge = runtime.createAcpSessionBridge({
          clientMcpSender: wsClientMcpRegistry.lookup,
          onCreateSubSession: wsSubSessionLauncher.launch,
          maxSessions: opts.maxSessions,
          freshSessionAdmission: totalSessionAdmission.admit,
          sessionLifecycle: sessionOwnerIndex.handleBridgeSessionLifecycle,
          ...opts.maxPendingPromptsPerSession !== void 0 ? { maxPendingPromptsPerSession: opts.maxPendingPromptsPerSession } : {},
          ...opts.eventRingSize !== void 0 ? { eventRingSize: opts.eventRingSize } : {},
          ...opts.compactedReplayMaxBytes !== void 0 ? { compactedReplayMaxBytes: opts.compactedReplayMaxBytes } : {},
          ...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: cwd,
          sessionShellCommandEnabled,
          childEnvOverrides,
          channelFactory: wsChannelFactory,
          onDiagnosticLine: diagnosticSink,
          telemetry: createRuntimeBridgeTelemetry(wsHash),
          ...permissionPolicy !== void 0 ? { permissionPolicy } : {},
          ...permissionConsensusQuorum !== void 0 ? { permissionConsensusQuorum } : {},
          permissionAudit: permissionAuditPublisher,
          statusProvider: runtime.createDaemonStatusProvider({
            env: wsEnv.effectiveEnv
          }),
          fileSystem: createBridgeFileSystemAdapter(wsFsFactory),
          persistApprovalMode: /* @__PURE__ */ __name((workspace, mode) => withSettingsLock(workspace, async () => {
            const fresh = settingsRuntime.settings.loadSettings(workspace);
            fresh.setValue(
              WORKSPACE_SETTING_SCOPE,
              "tools.approvalMode",
              mode
            );
          }), "persistApprovalMode")
        });
      } catch (err) {
        wsSubSessionLauncher.stop();
        throw err;
      }
      wsBridgeRef = wsBridge;
      let wsService;
      try {
        wsService = runtime.createDaemonWorkspaceService({
          boundWorkspace: cwd,
          contextFilename: contextFilenameForInit ?? "QWEN.md",
          statusProvider: runtime.createDaemonStatusProvider({
            env: wsEnv.effectiveEnv
          }),
          workspaceProvidersStatusProvider: runtime.createWorkspaceProvidersStatusProvider({
            env: wsEnv.effectiveEnv
          }),
          workspaceSkillsStatusProvider: runtime.createWorkspaceSkillsStatusProvider(),
          voiceEnv: wsEnv.effectiveEnv,
          voiceSettingsScope: WORKSPACE_SETTING_SCOPE,
          isChannelLive: /* @__PURE__ */ __name(() => wsBridge.isChannelLive(), "isChannelLive"),
          preheatAcpChild: /* @__PURE__ */ __name(() => wsBridge.preheat(), "preheatAcpChild"),
          persistDisabledTools: persistDisabledToolsFn,
          persistDisabledSkills: persistDisabledSkillsFn,
          persistSetting: persistSettingFn,
          persistSettings: persistSettingsFn,
          reloadDaemonEnv: /* @__PURE__ */ __name((workspace) => withSettingsLock(workspace, async () => {
            const fresh = settingsRuntime.settings.loadSettings(workspace, {
              skipLoadEnvironment: true
            });
            const result = settingsRuntime.settings.reloadEnvironment(
              fresh.merged,
              workspace
            );
            try {
              const refreshedRuntimeEnv = settingsRuntime.environment.buildRuntimeEnvironment(
                fresh.merged,
                workspace,
                daemonRuntimeBaseEnv
              );
              logRuntimeEnvFileReadFailures(workspace, refreshedRuntimeEnv);
              wsEnv.replace(refreshedRuntimeEnv.effectiveEnv);
              wsEnv.metadata.envFileReadFailed = refreshedRuntimeEnv.envFileReadFailed;
              wsEnv.metadata.envFileReadFailures.splice(
                0,
                wsEnv.metadata.envFileReadFailures.length,
                ...refreshedRuntimeEnv.envFileReadFailures
              );
              wsEnv.metadata.overlayKeys.splice(
                0,
                wsEnv.metadata.overlayKeys.length,
                ...refreshedRuntimeEnv.overlayKeys
              );
              wsEnv.metadata.envFilePaths.splice(
                0,
                wsEnv.metadata.envFilePaths.length,
                ...refreshedRuntimeEnv.envFilePaths
              );
              delete wsEnv.metadata.fallbackReason;
            } catch (err) {
              wsEnv.metadata.fallbackReason = err instanceof Error ? err.message : String(err);
              daemonLog.warn(
                "failed to rebuild dynamic runtime env snapshot after daemon env reload; preserving previous runtime env",
                {
                  workspace,
                  error: wsEnv.metadata.fallbackReason
                }
              );
            }
            return result;
          }), "reloadDaemonEnv"),
          queryWorkspaceStatus: /* @__PURE__ */ __name((method, idle) => wsBridge.queryWorkspaceStatus(method, idle), "queryWorkspaceStatus"),
          invokeWorkspaceCommand: /* @__PURE__ */ __name((method, params, invokeOpts) => wsBridge.invokeWorkspaceCommand(method, params, invokeOpts), "invokeWorkspaceCommand"),
          refreshExtensionsForAllSessions: /* @__PURE__ */ __name(() => wsBridge.refreshExtensionsForAllSessions(), "refreshExtensionsForAllSessions"),
          publishWorkspaceEvent: /* @__PURE__ */ __name((event) => wsBridge.publishWorkspaceEvent(event), "publishWorkspaceEvent")
        });
      } catch (err) {
        wsSubSessionLauncher.stop();
        await wsBridge.shutdown().catch(() => {
          try {
            wsBridge.killAllSync();
          } catch {
          }
        });
        throw err;
      }
      runtimeBridges.push(wsBridge);
      internalRuntimeBridgesForCleanup.push(wsBridge);
      subSessionStoppers.push(wsSubSessionLauncher.stop);
      subSessionStoppersByWorkspace.set(cwd, wsSubSessionLauncher.stop);
      return {
        workspaceId: wsHash,
        workspaceCwd: cwd,
        primary: false,
        trusted,
        removable: true,
        registrationIds: [],
        env: wsEnv.metadata,
        bridge: wsBridge,
        workspaceService: wsService,
        routeFileSystemFactory: wsFsFactory,
        clientMcpSenderRegistry: wsClientMcpRegistry
      };
    }, "createDynamicWorkspaceRuntime");
    const workspaceRuntimeRemoval = {
      async runtimeAdded(runtimeAdded) {
        const app3 = runtimeApp ?? runtimeAppForCleanup;
        const startScheduledTaskKeepaliveForWorkspace = app3?.locals?.["startScheduledTaskKeepaliveForWorkspace"];
        startScheduledTaskKeepaliveForWorkspace?.(runtimeAdded);
        if (!channelWorkerManager) return;
        try {
          await channelWorkerManager.restoreWorkspace(
            runtimeAdded.workspaceCwd
          );
          await channelWorkerManager.refreshWorkspaces();
        } catch (err) {
          daemonLog.error(
            "workspace channel worker startup error",
            err instanceof Error ? err : null
          );
        } finally {
          writeChannelWorkerPidfile();
        }
      },
      beginDrain(runtimeToDrain) {
        totalSessionAdmission.beginWorkspaceDrain(runtimeToDrain.workspaceCwd);
        channelWorkerManager?.beginWorkspaceDrain(runtimeToDrain.workspaceCwd);
        workspaceVoiceCoordinator.beginWorkspaceDrain(runtimeToDrain);
      },
      cancelDrain(runtimeToDrain) {
        channelWorkerManager?.cancelWorkspaceDrain(runtimeToDrain.workspaceCwd);
        totalSessionAdmission.cancelWorkspaceDrain(runtimeToDrain.workspaceCwd);
        workspaceVoiceCoordinator.cancelWorkspaceDrain(runtimeToDrain);
      },
      completeDrain(runtimeToDrain) {
        totalSessionAdmission.completeWorkspaceDrain(
          runtimeToDrain.workspaceCwd
        );
        workspaceVoiceCoordinator.completeWorkspaceDrain(runtimeToDrain);
      },
      getActivity(runtimeToDrain) {
        return {
          pendingSessionStarts: totalSessionAdmission.snapshotForWorkspace(
            runtimeToDrain.workspaceCwd
          ).inFlight,
          channelWorkers: channelWorkerManager?.workspaceActivity(
            runtimeToDrain.workspaceCwd
          ) ?? 0,
          voiceSessions: workspaceVoiceCoordinator.getWorkspaceActivity(runtimeToDrain)
        };
      },
      disposeRuntime(runtimeToDrain, reason = "workspace_removed") {
        const existing = runtimeCleanupPromises.get(runtimeToDrain);
        if (existing) return existing;
        const cleanup = (async () => {
          await workspaceVoiceCoordinator.disposeRuntime(
            runtimeToDrain,
            reason
          );
          const stopSubSessions = subSessionStoppersByWorkspace.get(
            runtimeToDrain.workspaceCwd
          );
          try {
            stopSubSessions?.();
          } catch {
          }
          if (reason === "workspace_removed" && channelWorkerManager) {
            await channelWorkerManager.removeWorkspace(runtimeToDrain.workspaceCwd).catch((err) => {
              daemonLog.error(
                "workspace channel worker cleanup error",
                err instanceof Error ? err : null
              );
            });
            try {
              await channelWorkerManager.refreshWorkspaces();
            } catch (err) {
              channelWorkspaceGroups = (channelWorkspaceGroups ?? []).filter(
                (group) => group.workspaceCwd !== runtimeToDrain.workspaceCwd
              );
              channelWebhookConfigVersion += 1;
              refreshChannelWebhookConfigs?.();
              daemonLog.error(
                "workspace channel worker topology refresh error",
                err instanceof Error ? err : null
              );
            }
            writeChannelWorkerPidfile();
          }
          if (reason === "workspace_removed") {
            const app3 = runtimeApp ?? runtimeAppForCleanup;
            const stopWorkspaceGitStateForWorkspace = app3?.locals?.["stopWorkspaceGitStateForWorkspace"];
            const stopScheduledTaskKeepaliveForWorkspace = app3?.locals?.["stopScheduledTaskKeepaliveForWorkspace"];
            stopWorkspaceGitStateForWorkspace?.(runtimeToDrain.workspaceCwd);
            stopScheduledTaskKeepaliveForWorkspace?.(
              runtimeToDrain.workspaceCwd
            );
          }
          let bridgeStopped = false;
          try {
            if (!shutdownBridges.has(runtimeToDrain.bridge)) {
              await runtimeToDrain.bridge.shutdown({ reason });
            }
            bridgeStopped = true;
          } finally {
            if (bridgeStopped || reason === "workspace_removed") {
              subSessionStoppersByWorkspace.delete(runtimeToDrain.workspaceCwd);
              if (stopSubSessions) {
                removeArrayValue(subSessionStoppers, stopSubSessions);
              }
              removeArrayValue(runtimeBridges, runtimeToDrain.bridge);
              removeArrayValue(
                internalRuntimeBridgesForCleanup,
                runtimeToDrain.bridge
              );
              shutdownBridges.add(runtimeToDrain.bridge);
            }
          }
        })();
        runtimeCleanupPromises.set(runtimeToDrain, cleanup);
        void cleanup.catch(() => {
          if (reason === "daemon_shutdown" && runtimeCleanupPromises.get(runtimeToDrain) === cleanup) {
            runtimeCleanupPromises.delete(runtimeToDrain);
          }
        });
        return cleanup;
      }
    };
    const app2 = runtime.createServeApp(opts, () => actualPort, {
      workspaceRegistry,
      createWorkspaceRuntime: createDynamicWorkspaceRuntime,
      workspaceRegistrationStore,
      workspaceRuntimeRemoval,
      voiceCoordinator: workspaceVoiceCoordinator,
      bridge,
      webShellDir,
      boundWorkspace,
      qwenCodeVersion: resolvedCliVersion,
      startup,
      // The real long-running daemon keeps scheduled-task sessions resident
      // (keepalive) and reloads them on boot (rehydration). Off by default so
      // direct createServeApp embeds/tests don't spawn sessions.
      manageScheduledTaskSessions: true,
      fsFactory: routeFsFactory,
      primaryWorkspaceTrusted: trustedWorkspace,
      primaryRuntimeEnv,
      daemonLog,
      getChannelWorkerSnapshot,
      getChannelWorkerSnapshots,
      getChannelWorkerControl,
      isChannelControlDraining: /* @__PURE__ */ __name(() => channelControlDraining, "isChannelControlDraining"),
      isChannelControlInitializing: /* @__PURE__ */ __name(() => channelWorkerManagerStarting !== void 0, "isChannelControlInitializing"),
      setChannelWorkerSelection,
      stopChannelWorker,
      getChannelWebhookConfigSources,
      getChannelWebhookConfigVersion: /* @__PURE__ */ __name(() => channelWebhookConfigVersion, "getChannelWebhookConfigVersion"),
      registerChannelWebhookConfigRefresh: /* @__PURE__ */ __name((refresh) => {
        refreshChannelWebhookConfigs = refresh;
      }, "registerChannelWebhookConfigRefresh"),
      enqueueChannelWebhookTask: /* @__PURE__ */ __name(async (task) => {
        if (!channelWorkerManager) {
          throw new ChannelWebhookEnqueueError(
            "channel_worker_unavailable",
            "Channel worker is not running."
          );
        }
        return channelWorkerManager.enqueueWebhookTask(task);
      }, "enqueueChannelWebhookTask"),
      reloadChannelWorker,
      getPerfSnapshot: /* @__PURE__ */ __name(() => ({
        eventLoop: currentDaemonEventLoopMonitor.snapshot(),
        promptQueueWait: {
          count: promptQueueWaitStats.count,
          meanMs: promptQueueWaitStats.count === 0 ? 0 : promptQueueWaitStats.totalMs / promptQueueWaitStats.count,
          maxMs: promptQueueWaitStats.maxMs,
          lastMs: promptQueueWaitStats.lastMs
        },
        pipe: {
          inbound: { ...pipeStats.inbound },
          outbound: { ...pipeStats.outbound }
        }
      }), "getPerfSnapshot"),
      getMetricsSeries: /* @__PURE__ */ __name(() => metricsRing.snapshot(), "getMetricsSeries"),
      getTotalSessionAdmissionSnapshot: totalSessionAdmission.snapshot,
      recordDaemonRequest: /* @__PURE__ */ __name((durationMs, statusCode) => metricsRing.recordRequest(durationMs, statusCode), "recordDaemonRequest"),
      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,
      persistDisabledSkills: persistDisabledSkillsFn,
      persistSetting: persistSettingFn,
      persistSettings: persistSettingsFn,
      sessionArtifactsPersistenceAvailable: sessionArtifactsPersistenceAvailableFromSettings(
        runtimeBootSettings?.merged
      ),
      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")
    });
    invalidatePrimaryServeFeaturesCache = app2.locals.invalidateServeFeaturesCache ?? invalidatePrimaryServeFeaturesCache;
    app2.locals.subSessionStoppers = subSessionStoppers;
    subSessionStoppers.push(subSessionLauncher.stop);
    subSessionStoppersByWorkspace.set(boundWorkspace, subSessionLauncher.stop);
    return { app: app2, bridge };
  }, "buildRuntime");
  if (deps.bridge) {
    const runtime = await buildRuntime();
    runtimeAppForCleanup = runtime.app;
    bridgeRef = runtime.bridge;
    if (!opts.channelSelection) {
      runtimeApp = runtime.app;
      runtimeStartupSettled = true;
      markRuntimeReady();
    }
  }
  cliVersion ??= await cliVersionPromise;
  const bootstrapApp = createBootstrapServeApp({
    opts,
    getPort: /* @__PURE__ */ __name(() => actualPort, "getPort"),
    boundWorkspace,
    startup,
    daemonLog,
    qwenCodeVersion: cliVersion,
    sessionShellCommandEnabled,
    sessionArtifactsPersistenceAvailable,
    permissionPolicy,
    multiWorkspaceCapabilitiesRequireRuntime: workspaceInputs.length > 1,
    getRuntimeError: /* @__PURE__ */ __name(() => runtimeStartupError, "getRuntimeError"),
    getChannelWorkerSnapshot,
    getChannelWorkerSnapshots,
    onHealthServed: deferRuntimeUntilFirstHealth ? () => startRuntimeAfterHealth?.() : void 0
  });
  const deferredChannelWebhookAuth = deferRuntimeUntilFirstHealth ? createDeferredChannelWebhookAuth(
    resolveChannelWebhookConfigSource,
    await loadChannelWebhookConfigRuntime(),
    daemonLog
  ) : void 0;
  const app = runtimeApp ?? createDelegatingServeApp(bootstrapApp, () => runtimeApp, {
    waitForDeferredRuntimeRoutes: deferRuntimeUntilFirstHealth,
    startRuntime: /* @__PURE__ */ __name(() => startRuntimeForRequest?.(), "startRuntime"),
    runtimeReady,
    authenticateDeferredRuntimeRequest: bearerAuth(opts.token),
    authenticateDeferredChannelWebhookRequest: deferredChannelWebhookAuth
  });
  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).`
    );
  }
  const channelValidationSettingsRuntime = opts.channelSelection ? await loadSettingsRuntimeModules() : void 0;
  const resolveChannelWorkspaceGroupsAtListen = /* @__PURE__ */ __name(() => {
    if (!opts.channelSelection || !channelValidationSettingsRuntime || !channelRuntime) {
      return void 0;
    }
    const settingsByWorkspace = /* @__PURE__ */ new Map();
    if (workspaceInputs.length === 1) {
      const workspace = workspaceInputs[0];
      const settings = channelValidationSettingsRuntime.settings.loadSettings(
        workspace.cwd
      );
      channelWebhookEnvByWorkspace.set(
        workspace.cwd,
        channelValidationSettingsRuntime.environment.buildRuntimeEnvironment(
          settings.merged,
          workspace.cwd,
          daemonRuntimeBaseEnv
        ).effectiveEnv
      );
      return void 0;
    }
    const workspaces = workspaceInputs.map((workspace, index) => {
      const settings = channelValidationSettingsRuntime.settings.loadSettings(
        workspace.cwd
      );
      settingsByWorkspace.set(workspace.cwd, settings);
      channelWebhookEnvByWorkspace.set(
        workspace.cwd,
        channelValidationSettingsRuntime.environment.buildRuntimeEnvironment(
          settings.merged,
          workspace.cwd,
          daemonRuntimeBaseEnv
        ).effectiveEnv
      );
      const trusted = index === 0 && deps.trustedWorkspace !== void 0 ? deps.trustedWorkspace : channelValidationSettingsRuntime.trustedFolders.getWorkspaceTrustStatus(
        settings.merged,
        workspace.cwd
      ).effective.state === "trusted";
      return {
        workspaceCwd: workspace.cwd,
        primary: index === 0,
        trusted
      };
    });
    const grouping = resolveChannelWorkspaceGroups({
      workspaces,
      selection: opts.channelSelection,
      loadChannelsConfig: /* @__PURE__ */ __name((cwd) => {
        const settings = settingsByWorkspace.get(cwd);
        if (!settings) return {};
        return channelRuntime.loadChannelsConfig(cwd, settings);
      }, "loadChannelsConfig")
    });
    if (!grouping.ok) {
      throw Object.assign(new Error(grouping.error.message), {
        code: grouping.error.code,
        ...grouping.error.channel ? { channel: grouping.error.channel } : {}
      });
    }
    return grouping.groups;
  }, "resolveChannelWorkspaceGroupsAtListen");
  if (opts.channelSelection) {
    reserveChannelServicePidfile(opts.channelSelection);
  }
  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(`serve-${process.pid}`);
      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 {
        channelWorkspaceGroups = resolveChannelWorkspaceGroupsAtListen();
      } 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 validation error failed",
              closeErr
            );
          }
          reject(error);
        });
        return;
      }
      if (channelWorkspaceGroups) {
        for (const group of channelWorkspaceGroups) {
          daemonLog.info("channel worker group assigned", {
            workspace: group.workspaceCwd,
            channels: group.selection.mode === "all" ? ["all"] : group.selection.names
          });
        }
        if (opts.channelSelection?.mode === "all") {
          writeStderrLine(
            "qwen serve: --channel all is primary-workspace only; non-primary workspace channels are not hosted."
          );
        }
      }
      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;
        if (shutdownBridges.has(bridge)) return;
        shutdownBridges.add(bridge);
        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 () => {
        if (!channelWorkerManager) return true;
        try {
          await channelWorkerManager.shutdown();
          return true;
        } catch (stopErr) {
          daemonLog.error(
            "channel worker stop after runtime startup error failed",
            stopErr instanceof Error ? stopErr : null
          );
          return false;
        }
      }, "stopChannelWorkerAfterFailedStartup");
      const failRuntimeStartup = /* @__PURE__ */ __name(async (err, bridgeForCleanup) => {
        const error = err instanceof Error ? err : new Error(String(err));
        if (runtimeStartupSettled) {
          disposeRuntimeAppResources(runtimeApp ?? runtimeAppForCleanup);
          await shutdownBridgeAfterFailedStartup(bridgeForCleanup);
          return;
        }
        runtimeStartupSettled = true;
        disposeRuntimeAppResources(runtimeApp ?? runtimeAppForCleanup);
        runtimeApp = void 0;
        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);
        markRuntimeFailed(error);
        if (closeServerAfterChannelWorkerStartupFailure && server.listening) {
          runtimeFailureListenerClose = new Promise((resolve2) => {
            server.close((closeErr) => {
              if (closeErr) {
                daemonLog.error(
                  "server close after runtime startup error failed",
                  closeErr
                );
              }
              resolve2();
            });
          });
          server.closeAllConnections();
        }
        const channelWorkerStopped = await stopChannelWorkerAfterFailedStartup();
        disposeDaemonEventLoopMonitor();
        if (channelWorkerStopped) removeCurrentServePidfile();
        const bridgesForCleanup = bridgeForCleanup ? [bridgeForCleanup, ...getRuntimeBridgesForCleanup()] : getRuntimeBridgesForCleanup();
        for (const bridge of [...new Set(bridgesForCleanup)]) {
          await shutdownBridgeAfterFailedStartup(bridge);
        }
      }, "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 resolveRuntimeChannelGroups = /* @__PURE__ */ __name(async (channelSelection, candidateApp, operation) => {
        const registry = candidateApp.locals?.["workspaceRegistry"];
        if (!registry) {
          throw new Error(
            "Workspace registry is not available for channel workers."
          );
        }
        const runtimes = registry.list();
        if (runtimes.length <= 1 && operation === "initial") {
          return [
            {
              workspaceCwd: registry.primary.workspaceCwd,
              selection: channelSelection
            }
          ];
        }
        const workerRuntime = await ensureChannelRuntime();
        const settingsRuntime = await loadSettingsRuntimeModules();
        const settingsByWorkspace = /* @__PURE__ */ new Map();
        const grouping = resolveChannelWorkspaceGroups({
          workspaces: runtimes.map((runtime) => {
            const settings = settingsRuntime.settings.loadSettings(
              runtime.workspaceCwd
            );
            settingsByWorkspace.set(runtime.workspaceCwd, settings);
            return {
              workspaceCwd: runtime.workspaceCwd,
              primary: runtime.primary,
              trusted: runtime.trusted
            };
          }),
          selection: channelSelection,
          loadChannelsConfig: /* @__PURE__ */ __name((cwd) => {
            const settings = settingsByWorkspace.get(cwd);
            return settings ? workerRuntime.loadChannelsConfig(cwd, settings) : {};
          }, "loadChannelsConfig")
        });
        if (!grouping.ok) {
          throw Object.assign(new Error(grouping.error.message), {
            code: grouping.error.code,
            ...grouping.error.channel ? { channel: grouping.error.channel } : {}
          });
        }
        return grouping.groups;
      }, "resolveRuntimeChannelGroups");
      ensureChannelWorkerManager = /* @__PURE__ */ __name(() => {
        if (channelWorkerManager) return Promise.resolve(channelWorkerManager);
        if (channelWorkerManagerStarting) return channelWorkerManagerStarting;
        const starting = (async () => {
          const candidateApp = runtimeApp ?? runtimeAppForCleanup;
          const registry = candidateApp?.locals?.["workspaceRegistry"];
          if (!candidateApp || !registry) {
            throw new Error(
              "Workspace registry is not available for channels."
            );
          }
          const workerRuntime = await ensureChannelRuntime();
          const createSupervisor = deps.channelWorkerSupervisorFactory ?? workerRuntime.createChannelWorkerSupervisor;
          const createGroup = /* @__PURE__ */ __name((groups) => workerRuntime.createChannelWorkerGroup({
            groups,
            registry,
            createSupervisor,
            shared: {
              cliEntryPath: workerRuntime.findCliEntryPath(),
              daemonUrl: formatChannelWorkerDaemonUrl(
                opts.hostname,
                actualPort
              ),
              ...token ? { daemonToken: token } : {}
            },
            onReady: /* @__PURE__ */ __name((snapshot) => {
              if (runtimeStartupError !== void 0) return;
              if (workspaceInputs.length > 1) {
                daemonLog.info("channel worker ready", {
                  workspace: snapshot.workspaceCwd,
                  pid: snapshot.pid,
                  channels: snapshot.channels
                });
              }
              channelWorkerManager?.workerChanged();
              if (!runtimeStartupSettled) writeChannelWorkerPidfile();
            }, "onReady"),
            onExit: /* @__PURE__ */ __name((snapshot) => {
              const workspacePrefix = workspaceInputs.length > 1 ? `workspace=${snapshot.workspaceCwd}, ` : "";
              daemonLog.warn(
                `channel worker exited (${workspacePrefix}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"})`
              );
              channelWorkerManager?.workerChanged();
              if (!runtimeStartupSettled) writeChannelWorkerPidfile();
            }, "onExit"),
            onStateChange: /* @__PURE__ */ __name(() => {
              channelWorkerManager?.workerChanged();
              if (!runtimeStartupSettled) writeChannelWorkerPidfile();
            }, "onStateChange"),
            onLog: /* @__PURE__ */ __name(({ stream, line, workspaceCwd }) => {
              const message = workspaceInputs.length > 1 ? `channel worker [${workspaceCwd}] ${stream}: ${line}` : `channel worker ${stream}: ${line}`;
              if (stream === "stderr") daemonLog.warn(message);
              else daemonLog.info(message);
            }, "onLog")
          }), "createGroup");
          channelWorkerManager = workerRuntime.createChannelWorkerManager({
            resolveGroups: /* @__PURE__ */ __name((selection, operation) => resolveRuntimeChannelGroups(selection, candidateApp, operation), "resolveGroups"),
            createGroup,
            reserveLease: reserveChannelServicePidfile,
            releaseLease: /* @__PURE__ */ __name(() => {
              removeCurrentServePidfile();
              if (channelPidfileReserved) {
                throw new Error("Failed to release the channel service lease.");
              }
            }, "releaseLease"),
            initialLeaseReserved: channelPidfileReserved,
            onCommittedSelection: /* @__PURE__ */ __name((_selection, groups) => {
              channelWorkspaceGroups = groups;
              channelWebhookConfigVersion += 1;
              refreshChannelWebhookConfigs?.();
            }, "onCommittedSelection"),
            onStateChange: /* @__PURE__ */ __name(() => {
              if (runtimeStartupSettled) writeChannelWorkerPidfile();
            }, "onStateChange")
          });
          return channelWorkerManager;
        })();
        channelWorkerManagerStarting = starting;
        void starting.then(
          () => {
            if (channelWorkerManagerStarting === starting) {
              channelWorkerManagerStarting = void 0;
            }
          },
          () => {
            if (channelWorkerManagerStarting === starting) {
              channelWorkerManagerStarting = void 0;
            }
          }
        );
        return starting;
      }, "ensureChannelWorkerManager");
      const completeRuntimeStartup = /* @__PURE__ */ __name(async (candidateApp) => {
        if (runtimeStartupSettled) return;
        runtimeApp = candidateApp;
        const acpHandle = candidateApp.locals?.["acpHandle"];
        acpHandle?.attachServer?.(server);
        if (opts.channelSelection) {
          closeServerAfterChannelWorkerStartupFailure = true;
          const manager = await ensureChannelWorkerManager();
          await manager.startInitial(opts.channelSelection);
          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) {
            disposeRuntimeAppResources(runtime.app);
            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;
          }
          if (shouldPreheat) {
            startBridgePreheat(runtime.bridge);
          }
          await completeRuntimeStartup(runtime.app);
        }).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 {
            channelWorkerManager?.killAllSync();
            for (const runtimeBridge of getRuntimeBridgesForCleanup()) {
              runtimeBridge.killAllSync();
            }
          } 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(runtimeStartupError === void 0 ? 0 : 1);
        } catch (err) {
          daemonLog.error("shutdown error", err instanceof Error ? err : null);
          await daemonLog.flush().catch(() => {
          });
          if (channelWorkerManager?.state().enabled) {
            daemonLog.error(
              "refusing to exit while a channel worker or service lease remains; signal again to retry after the child exits (another signal during that retry forces exit)"
            );
            await daemonLog.flush().catch(() => {
            });
            return;
          }
          process.exit(1);
        }
      }, "onSignal");
      const onUncaughtExceptionMonitor = /* @__PURE__ */ __name(() => {
        if (process.listenerCount("uncaughtException") === 0 && !channelWorkerManager?.state().enabled) {
          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;
            channelControlDraining = true;
            const initiallyMountedApp = runtimeApp ?? runtimeAppForCleanup;
            const initiallyMountedManagement = initiallyMountedApp?.locals?.["workspaceManagementHandle"];
            const initialManagementWait = initiallyMountedManagement?.sealAndWait?.();
            clearRuntimeStartAfterHealthTimer();
            clearRuntimeStartFallbackTimer();
            cancelDeferredRuntimeStartup();
            let settled = false;
            let bridgeShutdownError;
            let channelWorkerShutdownError;
            const finish = /* @__PURE__ */ __name((err) => {
              if (settled) return;
              settled = true;
              const preserveSignalHandlers = channelWorkerShutdownError !== void 0 && channelWorkerManager?.state().enabled === true;
              if (!preserveSignalHandlers) {
                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 ?? channelWorkerShutdownError;
                if (finalErr) {
                  if (channelWorkerShutdownError && channelWorkerManager?.state().enabled) {
                    closePromise = void 0;
                    shuttingDown = false;
                    channelControlDraining = false;
                  }
                  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 workspaceManagementHandle = appForCleanup?.locals?.["workspaceManagementHandle"];
              await initialManagementWait;
              if (workspaceManagementHandle !== initiallyMountedManagement) {
                await workspaceManagementHandle?.sealAndWait?.();
              }
              disposeRuntimeAppResources(appForCleanup);
              disposeDaemonEventLoopMonitor();
              if (channelWorkerManager) {
                await channelWorkerManager.shutdown().catch((err) => {
                  daemonLog.error(
                    "channel worker stop error",
                    err instanceof Error ? err : null
                  );
                  channelWorkerShutdownError = err instanceof Error ? err : new Error(String(err));
                });
              } else {
                removeCurrentServePidfile();
              }
              const runtimeRemoval = appForCleanup?.locals?.["workspaceRuntimeRemoval"];
              const workspaceRegistry = appForCleanup?.locals?.["workspaceRegistry"];
              const managedRuntimeBridges = /* @__PURE__ */ new Set();
              if (runtimeRemoval && workspaceRegistry) {
                const managedRuntimes = workspaceRegistry.listManaged();
                for (const workspaceRuntime of managedRuntimes) {
                  managedRuntimeBridges.add(workspaceRuntime.bridge);
                }
                await Promise.all(
                  managedRuntimes.map(
                    (workspaceRuntime) => runtimeRemoval.disposeRuntime(workspaceRuntime, "daemon_shutdown").catch((err) => {
                      daemonLog.error(
                        "workspace runtime shutdown error",
                        err instanceof Error ? err : null
                      );
                      bridgeShutdownError = err instanceof Error ? err : new Error(String(err));
                      try {
                        workspaceRuntime.bridge.killAllSync();
                      } catch {
                      }
                    })
                  )
                );
              }
              for (const bridgeForShutdown of getRuntimeBridgesForCleanup()) {
                if (managedRuntimeBridges.has(bridgeForShutdown)) continue;
                if (shutdownBridges.has(bridgeForShutdown)) continue;
                shutdownBridges.add(bridgeForShutdown);
                await bridgeForShutdown.shutdown().catch((err) => {
                  shutdownBridges.delete(bridgeForShutdown);
                  daemonLog.error(
                    "bridge shutdown error",
                    err instanceof Error ? err : null
                  );
                  bridgeShutdownError = err instanceof Error ? err : new Error(String(err));
                });
              }
            }).finally(() => {
              if (!server.listening) {
                void (runtimeFailureListenerClose ?? Promise.resolve()).then(
                  () => finish()
                );
                return;
              }
              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);
      });
      const preparedRuntimeApp = runtimeApp ?? runtimeAppForCleanup;
      if (preparedRuntimeApp && bridgeRef && deps.bridge) {
        if (shouldPreheat) {
          startBridgePreheat(bridgeRef);
        }
        if (opts.channelSelection && !runtimeStartupSettled) {
          armRuntimeStartupTimer();
          runtimeStarting = completeRuntimeStartup(preparedRuntimeApp).catch(
            (err) => failRuntimeStartup(err, bridgeRef)
          );
        } else {
          const acpHandle = preparedRuntimeApp.locals?.["acpHandle"];
          acpHandle?.attachServer?.(server);
        }
      } else if (deferRuntimeUntilFirstHealth) {
        scheduleRuntimeStartFallback();
      } else {
        startRuntime();
      }
      if (deps.resolveOnListen) {
        resolve(handle);
      } else {
        void runtimeReady.then(
          () => resolve(handle),
          (err) => {
            void handle.close().then(
              () => {
                reject(err instanceof Error ? err : new Error(String(err)));
              },
              (closeErr) => {
                daemonLog.error(
                  "shutdown after runtime startup error failed",
                  closeErr instanceof Error ? closeErr : null
                );
                if (channelWorkerManager?.state().enabled) {
                  daemonLog.error(
                    "runtime startup failed, but qwen serve remains alive to retain the channel service lease until worker exit is confirmed"
                  );
                  return;
                }
                reject(err instanceof Error ? err : new Error(String(err)));
              }
            );
          }
        );
      }
    }, "onListening");
    let server;
    let httpsServer;
    if (tlsOptions) {
      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;
      }
    }
    const tryListen = /* @__PURE__ */ __name((attemptPort, attempt) => {
      try {
        if (httpsServer) {
          httpsServer.removeAllListeners("listening");
          server = httpsServer.listen(attemptPort, listenHostname, onListening);
        } else {
          server = app.listen(attemptPort, listenHostname, onListening);
        }
      } catch (err) {
        removeCurrentServePidfile();
        reject(err instanceof Error ? err : new Error(String(err)));
        return;
      }
      server.once("error", (err) => {
        server.close();
        const nextPort = attemptPort + 1;
        if (err.code === "EADDRINUSE" && opts.port !== 0 && nextPort <= 65535 && attempt < MAX_PORT_ATTEMPTS - 1) {
          writeStderrLine(
            `qwen serve: port ${attemptPort} is in use, trying ${nextPort}...`
          );
          tryListen(nextPort, attempt + 1);
        } else {
          if (err.code === "EADDRINUSE" && attempt > 0) {
            writeStderrLine(
              `qwen serve: all ports ${opts.port}\u2013${attemptPort} are in use`
            );
          }
          removeCurrentServePidfile();
          reject(err);
        }
      });
    }, "tryListen");
    tryListen(opts.port, 0);
  });
}
__name(runQwenServe, "runQwenServe");
export {
  InvalidPolicyConfigError,
  createDisabledChannelWorkerSupervisor,
  createLazyBridgeProxy,
  extractContextFilename,
  formatChannelWorkerDaemonUrl,
  resolveRuntimeStartupTimeoutMs,
  runQwenServe,
  validatePolicyConfig,
  waitForRuntimeStartingForShutdown
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
