// Force strict mode and setup for ESM
"use strict";
import {
  DaemonMetricsRing,
  computeCpuPercent
} from "./chunk-YVEDCAUE.js";
import {
  RUNTIME_STARTUP_CANCELLED_MESSAGE
} from "./chunk-QUPXZXLV.js";
import {
  CAPABILITIES_SCHEMA_VERSION,
  ClientMcpSenderRegistry,
  PathMutexRegistry,
  SERVE_CAPABILITY_REGISTRY,
  allowOriginCors,
  allowOriginMode,
  bearerAuth,
  createBridgeFileSystemAdapter,
  denyBrowserOriginCors,
  getAdvertisedServeFeatures,
  getDeviceFlowRegistry,
  getRateLimiter,
  getServeProtocolVersions,
  hostAllowlist,
  isBrowserAutomationMcpAvailable,
  listenerMaxConnections,
  parseAllowOriginPatterns,
  parseDaemonStatusDetail,
  positiveFiniteOrNull,
  require_express,
  resolveWebShellDir
} from "./chunk-KHUQZZJ6.js";
import {
  isLoopbackBind
} from "./chunk-RXFQM6FQ.js";
import {
  LOAD_REPLAY_META_KEY
} from "./chunk-PZL23GTM.js";
import {
  canonicalizeWorkspace
} from "./chunk-W7FJ3N32.js";
import {
  DEFAULT_COMPACTED_REPLAY_MAX_BYTES,
  normalizeCompactedReplayMaxBytes
} from "./chunk-COH43MRJ.js";
import "./chunk-WBL3FJEU.js";
import "./chunk-T2NCM2ET.js";
import {
  loadServeFastPathSettings,
  preResolveServeFastPathHomeEnvOverrides
} from "./chunk-3SJSQXNS.js";
import {
  getGlobalQwenDirLite,
  resolveConfigPathLite
} from "./chunk-3BTRNWWD.js";
import "./chunk-QRUIS3DN.js";
import {
  ChannelWebhookEnqueueError,
  QWEN_SERVER_TOKEN_ENV
} from "./chunk-X4NKFGFJ.js";
import {
  channelSelectionNames
} from "./chunk-TJTKSVIV.js";
import {
  sanitizeLogText
} from "./chunk-34Z3U5RQ.js";
import "./chunk-UDXSXLER.js";
import {
  isWithinRoot
} from "./chunk-RDJSGHZE.js";
import {
  getCliVersion
} from "./chunk-3AHXV67U.js";
import "./chunk-VJNBRRZG.js";
import {
  writeStderrLine,
  writeStdoutLine
} from "./chunk-YUZI3WAC.js";
import "./chunk-CU3L64TP.js";
import "./chunk-ZJE7NSL3.js";
import "./chunk-H6XPXXMH.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/workspace-inputs.ts
init_esbuild_shims();
var DuplicateWorkspaceInputError = class extends Error {
  static {
    __name(this, "DuplicateWorkspaceInputError");
  }
  constructor(workspace) {
    super(
      `Duplicate --workspace value resolves to ${JSON.stringify(workspace)}. Pass distinct --workspace values.`
    );
    this.name = "DuplicateWorkspaceInputError";
  }
};
var NestedWorkspaceInputError = class extends Error {
  static {
    __name(this, "NestedWorkspaceInputError");
  }
  constructor(parent, child) {
    super(
      `Nested --workspace values are not supported yet: ${JSON.stringify(child)} is inside ${JSON.stringify(parent)}. Pass non-nested --workspace values.`
    );
    this.name = "NestedWorkspaceInputError";
  }
};
var MissingWorkspaceInputError = class extends Error {
  static {
    __name(this, "MissingWorkspaceInputError");
  }
  constructor() {
    super("--workspace requires a value.");
    this.name = "MissingWorkspaceInputError";
  }
};
function normalizeWorkspaceInputs(workspace) {
  if (Array.isArray(workspace)) {
    if (workspace.length === 0) {
      throw new MissingWorkspaceInputError();
    }
    return workspace.map((value) => String(value));
  }
  if (workspace === void 0) return [process.cwd()];
  return [String(workspace)];
}
__name(normalizeWorkspaceInputs, "normalizeWorkspaceInputs");
function isNestedWorkspace(parent, child) {
  return parent !== child && isWithinRoot(child, parent);
}
__name(isNestedWorkspace, "isNestedWorkspace");
function rejectDuplicateOrNestedWorkspaceInputs(workspaces) {
  if (workspaces.length <= 1) return;
  let canonicalWorkspaces;
  try {
    canonicalWorkspaces = workspaces.map(
      (workspace) => canonicalizeWorkspace(workspace)
    );
  } catch {
    return;
  }
  const seen = /* @__PURE__ */ new Set();
  for (const workspace of canonicalWorkspaces) {
    if (seen.has(workspace)) {
      throw new DuplicateWorkspaceInputError(workspace);
    }
    seen.add(workspace);
  }
  for (let i = 0; i < canonicalWorkspaces.length; i++) {
    for (let j = i + 1; j < canonicalWorkspaces.length; j++) {
      const first = canonicalWorkspaces[i];
      const second = canonicalWorkspaces[j];
      if (isNestedWorkspace(first, second)) {
        throw new NestedWorkspaceInputError(first, second);
      }
      if (isNestedWorkspace(second, first)) {
        throw new NestedWorkspaceInputError(second, first);
      }
    }
  }
}
__name(rejectDuplicateOrNestedWorkspaceInputs, "rejectDuplicateOrNestedWorkspaceInputs");
function resolveWorkspaceInputs(workspace) {
  const workspaces = normalizeWorkspaceInputs(workspace);
  rejectDuplicateOrNestedWorkspaceInputs(workspaces);
  return workspaces;
}
__name(resolveWorkspaceInputs, "resolveWorkspaceInputs");

// 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/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-WSOAAYUO.js"),
    import("./pidfile-REI5HWTE.js"),
    import("./cli-entry-path-4VJ3Y6T2.js")
  ]).then(([supervisor, pidfile, cliEntryPath]) => ({
    createChannelWorkerSupervisor: supervisor.createChannelWorkerSupervisor,
    channelServicePidfile: pidfile,
    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 new Error(
    `Channel service is already running under ${owner} (PID ${info.pid}). Stop it before starting qwen serve --channel.`
  );
}
__name(channelServicePidfileConflictError, "channelServicePidfileConflictError");
function normalizeInstallModelIds(req, provider, getDefaultModelIds) {
  const fromRequest = req.modelIds?.map((id) => id.trim()).filter((id) => id.length > 0);
  const modelIds = fromRequest && fromRequest.length > 0 ? fromRequest : getDefaultModelIds(provider);
  return [...new Set(modelIds)];
}
__name(normalizeInstallModelIds, "normalizeInstallModelIds");
function buildProviderSetupInputs(req, provider, helpers) {
  const protocol = req.protocol ?? provider.protocol;
  const baseUrl = helpers.resolveBaseUrl(provider, req.baseUrl);
  return {
    ...provider.protocolOptions ? { protocol } : {},
    baseUrl,
    apiKey: req.apiKey.trim(),
    modelIds: normalizeInstallModelIds(
      req,
      provider,
      helpers.getDefaultModelIds
    ),
    ...req.advancedConfig ? { advancedConfig: req.advancedConfig } : {}
  };
}
__name(buildProviderSetupInputs, "buildProviderSetupInputs");
function shouldPreheatBridge(deps) {
  if (deps.preheatBridge !== void 0) return deps.preheatBridge;
  return process.env["VITEST_WORKER_ID"] === void 0;
}
__name(shouldPreheatBridge, "shouldPreheatBridge");
var coreRuntimePromise;
function loadCoreRuntime() {
  coreRuntimePromise ??= import("./src-JJQRUKVF.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-GLLAIND6.js"),
    import("./environment-3JLUZ5OR.js"),
    import("./loadedSettingsAdapter-H522UAVK.js"),
    import("./trustedFolders-4ZDDTHBX.js")
  ]).then(([settings, environment, loadedSettingsAdapter, trustedFolders]) => ({
    settings,
    environment,
    loadedSettingsAdapter,
    trustedFolders
  }));
  return settingsRuntimePromise;
}
__name(loadSettingsRuntimeModules, "loadSettingsRuntimeModules");
var channelWebhookConfigRuntimePromise;
function loadChannelWebhookConfigRuntime() {
  channelWebhookConfigRuntimePromise ??= Promise.all([
    import("./runtime-U57ARJAE.js"),
    import("./config-utils-NV2SVGPB.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-IV5H3HLM.js"),
    import("./bridge-JRW5QFCO.js"),
    import("./spawnChannel-UEVDPXFU.js"),
    import("./workspace-service-HUM472FR.js"),
    import("./types-JNKGKUJT.js"),
    import("./daemon-status-provider-PBZIEZHY.js"),
    import("./workspace-providers-status-CIDX7LZP.js"),
    import("./workspace-skills-status-NCXXJURJ.js"),
    import("./total-session-admission-PZI5UU2M.js"),
    import("./workspace-registry-DREMLEKQ.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,
    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,
    rateLimit: opts.rateLimit === true,
    reloadAvailable: true,
    channelReloadAvailable: opts.channelSelection !== void 0,
    // 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,
    onHealthServed
  } = input;
  const app = (0, import_express.default)();
  installSameOriginOriginStrip(app, getPort);
  if (opts.allowOrigins && opts.allowOrigins.length > 0) {
    app.use(allowOriginCors(parseAllowOriginPatterns(opts.allowOrigins)));
  } else {
    app.use(denyBrowserOriginCors);
  }
  app.use(hostAllowlist(opts.hostname, getPort));
  const healthHandler = /* @__PURE__ */ __name((_req, res) => {
    const runtimeError = getRuntimeError();
    if (runtimeError !== void 0) {
      res.status(503).json({
        status: "degraded",
        error: runtimeError
      });
      return;
    }
    if (onHealthServed) {
      res.once("finish", onHealthServed);
    }
    res.status(200).json({ status: "ok" });
  }, "healthHandler");
  const loopback = isLoopbackBind(opts.hostname);
  const exposeHealthPreAuth = loopback && !opts.requireAuth;
  if (exposeHealthPreAuth) {
    app.get(BOOTSTRAP_HEALTH_PATH, healthHandler);
  }
  app.use(bearerAuth(opts.token));
  if (!exposeHealthPreAuth) {
    app.get(BOOTSTRAP_HEALTH_PATH, healthHandler);
  }
  app.get(BOOTSTRAP_CAPABILITIES_PATH, (_req, res) => {
    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 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,
        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(workspace, 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 secret = readDeferredWebhookSecret(
      runtime,
      workspace,
      channelName,
      source
    );
    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) {
  try {
    const rawConfig = runtime.loadChannelsConfig(workspace)[channelName];
    if (typeof rawConfig !== "object" || rawConfig === null) {
      return void 0;
    }
    return runtime.parseChannelWebhookConfig(
      channelName,
      rawConfig
    )?.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))
  };
  const channelRuntime = opts.channelSelection ? await loadChannelWorkerRuntime() : void 0;
  const channelServicePidfile = deps.channelServicePidfile ?? channelRuntime?.channelServicePidfile;
  let channelPidfileReserved = false;
  const removeCurrentServePidfile = /* @__PURE__ */ __name(() => {
    if (!opts.channelSelection || !channelServicePidfile) return;
    if (!channelPidfileReserved) return;
    if (channelServicePidfile.removeServeServiceInfo) {
      if (channelServicePidfile.removeServeServiceInfo(process.pid)) {
        channelPidfileReserved = false;
      }
      return;
    }
    const info = channelServicePidfile.readServiceInfo();
    if (info?.owner === "serve" && info.pid === process.pid && info.servePid === process.pid) {
      channelServicePidfile.removeServiceInfo();
      channelPidfileReserved = false;
    }
  }, "removeCurrentServePidfile");
  const reserveChannelServicePidfile = /* @__PURE__ */ __name(() => {
    if (!opts.channelSelection) return;
    if (!channelServicePidfile) {
      throw new Error("Channel service pidfile runtime is not available.");
    }
    const channelPidfileNames = channelSelectionNames(opts.channelSelection);
    const existingChannelService = channelServicePidfile.readServiceInfo();
    if (existingChannelService) {
      throw channelServicePidfileConflictError(existingChannelService);
    }
    try {
      writeServeChannelReservation(channelServicePidfile, channelPidfileNames);
      channelPidfileReserved = true;
    } catch (err) {
      if (err && typeof err === "object" && "code" in err) {
        const code = err.code;
        if (code === "EEXIST") {
          const info = channelServicePidfile.readServiceInfo();
          if (info) {
            throw channelServicePidfileConflictError(info);
          }
          try {
            writeServeChannelReservation(
              channelServicePidfile,
              channelPidfileNames
            );
            channelPidfileReserved = true;
            return;
          } catch (retryErr) {
            if (retryErr && typeof retryErr === "object" && "code" in retryErr && retryErr.code === "EEXIST") {
              throw new Error(
                "Channel service is already starting. Retry after the current startup finishes."
              );
            }
            throw retryErr;
          }
        }
      }
      throw err;
    }
  }, "reserveChannelServicePidfile");
  validateRateLimitOptions(opts);
  if (!opts.hostname.startsWith("[") && opts.hostname.split(":").length === 2) {
    const [host, port] = opts.hostname.split(":");
    throw new Error(
      `Invalid --hostname "${opts.hostname}": looks like a "host:port" combination. Use --port for the port, e.g. "--hostname ${host} --port ${port}".`
    );
  }
  let tlsOptions;
  if (opts.tlsCert && !opts.tlsKey || !opts.tlsCert && opts.tlsKey) {
    throw new Error(
      `--tls-cert and --tls-key must be provided together (got only --tls-${opts.tlsCert ? "cert" : "key"}).`
    );
  }
  if (opts.tlsCert && opts.tlsKey) {
    let cert;
    let key;
    try {
      cert = fs.readFileSync(opts.tlsCert);
    } catch (err) {
      throw new Error(
        `Failed to read --tls-cert "${opts.tlsCert}": ${err instanceof Error ? err.message : String(err)}`
      );
    }
    try {
      key = fs.readFileSync(opts.tlsKey);
    } catch (err) {
      throw new Error(
        `Failed to read --tls-key "${opts.tlsKey}": ${err instanceof Error ? err.message : String(err)}`
      );
    }
    let x509;
    try {
      x509 = new X509Certificate(cert);
    } catch (err) {
      throw new Error(
        `--tls-cert "${opts.tlsCert}" is not a valid certificate: ${err instanceof Error ? err.message : String(err)}`
      );
    }
    const now = Date.now();
    if (new Date(x509.validTo).getTime() < now) {
      throw new Error(
        `--tls-cert "${opts.tlsCert}" expired on ${x509.validTo}. Renew the certificate and restart.`
      );
    }
    if (new Date(x509.validFrom).getTime() > now) {
      throw new Error(
        `--tls-cert "${opts.tlsCert}" is not yet valid (validFrom: ${x509.validFrom}). Check the certificate's notBefore date or the system clock.`
      );
    }
    tlsOptions = { cert, key };
  }
  if (!isLoopbackBind(opts.hostname) && !token) {
    throw new Error(
      `Refusing to bind ${opts.hostname}:${opts.port} without a bearer token. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or rebind to loopback (127.0.0.1, localhost, ::1, or [::1]).`
    );
  }
  if (opts.requireAuth && !token) {
    throw new Error(
      `Refusing to start with --require-auth set but no bearer token configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or omit --require-auth to keep the loopback developer default.`
    );
  }
  if (opts.allowOrigins && opts.allowOrigins.length > 0) {
    const parsed = parseAllowOriginPatterns(opts.allowOrigins);
    if (parsed.allowAny && !token) {
      throw new Error(
        `Refusing to start with --allow-origin '*' but no bearer token configured. '*' admits any cross-origin browser to the API; without a token, any local page can drive the daemon. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or list specific origins instead of '*'.`
      );
    }
    writeStderrLine(
      `qwen serve: --allow-origin: ${opts.allowOrigins.join(", ")}` + (parsed.allowAny ? " (WARNING: `*` admits any cross-origin browser \u2014 bearer token gates API routes; /health and /demo remain pre-auth on loopback unless --require-auth is set)" : "")
    );
  }
  if (opts.allowPrivateAuthBaseUrl) {
    writeStderrLine(
      "qwen serve: --allow-private-auth-base-url enabled; /workspace/auth/provider may install localhost/private-network model endpoints. Use only for local development with trusted clients."
    );
  }
  const 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)
  }));
  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 > 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(() => {
    daemonEventLoopMonitor?.dispose();
    daemonEventLoopMonitor = void 0;
    daemonMetricsSampler?.dispose();
    daemonMetricsSampler = void 0;
  }, "disposeDaemonEventLoopMonitor");
  let channelWorker = createDisabledChannelWorkerSupervisor();
  const getChannelWorkerSnapshot = /* @__PURE__ */ __name(() => channelWorker.snapshot(), "getChannelWorkerSnapshot");
  const reloadChannelWorker = /* @__PURE__ */ __name(() => channelWorker.restart(), "reloadChannelWorker");
  const writeChannelWorkerPidfile = /* @__PURE__ */ __name((snapshot = channelWorker.snapshot(), options = {}) => {
    if (!opts.channelSelection || !channelServicePidfile) return;
    try {
      channelServicePidfile.writeServeServiceInfo({
        channels: snapshot.channels,
        servePid: process.pid,
        ...!options.clearWorkerPid && snapshot.pid !== void 0 ? { workerPid: snapshot.pid } : {}
      });
    } catch (err) {
      daemonLog.warn(
        `failed to write channel worker pidfile metadata: ${err instanceof Error ? err.message : String(err)}`
      );
    }
  }, "writeChannelWorkerPidfile");
  const handleBridge = deps.bridge ?? createLazyBridgeProxy(
    () => bridgeRef,
    () => runtimeStartupError
  );
  const shutdownBridges = /* @__PURE__ */ new WeakSet();
  const getRuntimeBridgesForCleanup = /* @__PURE__ */ __name(() => {
    const appForCleanup = runtimeApp ?? runtimeAppForCleanup;
    const registry = appForCleanup?.locals?.["workspaceRegistry"];
    const bridges = [
      ...registry ? registry.list().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.
        tokenUsage(inputTokens, outputTokens, durationMs) {
          metricsRing.recordTokens(inputTokens, outputTokens);
          if (typeof durationMs === "number") {
            metricsRing.recordLlmDuration(durationMs);
          }
        }
      };
      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 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-RP5EKWYS.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);
    const workspaceService = runtime.createDaemonWorkspaceService({
      boundWorkspace,
      contextFilename: contextFilenameForInit ?? "QWEN.md",
      statusProvider,
      workspaceProvidersStatusProvider,
      workspaceSkillsStatusProvider,
      isChannelLive: /* @__PURE__ */ __name(() => bridge.isChannelLive(), "isChannelLive"),
      persistDisabledTools: persistDisabledToolsFn,
      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) => bridge.publishWorkspaceEvent(event), "publishWorkspaceEvent")
    });
    const workspaceRuntimes = [
      {
        workspaceId: daemonWorkspaceHash,
        workspaceCwd: boundWorkspace,
        primary: true,
        trusted: trustedWorkspace,
        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 = [];
    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);
      const secondaryWorkspaceService = runtime.createDaemonWorkspaceService({
        boundWorkspace: workspaceInput.cwd,
        contextFilename: contextFilenameForInit ?? "QWEN.md",
        statusProvider: secondaryStatusProvider,
        workspaceProvidersStatusProvider: runtime.createWorkspaceProvidersStatusProvider({
          env: secondaryEnv.effectiveEnv
        }),
        workspaceSkillsStatusProvider: runtime.createWorkspaceSkillsStatusProvider(),
        isChannelLive: /* @__PURE__ */ __name(() => secondaryBridge.isChannelLive(), "isChannelLive"),
        preheatAcpChild: /* @__PURE__ */ __name(() => secondaryBridge.preheat(), "preheatAcpChild"),
        persistDisabledTools: persistDisabledToolsFn,
        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,
        env: secondaryEnv.metadata,
        bridge: secondaryBridge,
        workspaceService: secondaryWorkspaceService,
        routeFileSystemFactory: secondaryBridgeFsFactory,
        clientMcpSenderRegistry: secondaryClientMcpSenderRegistry
      });
    }
    const workspaceRegistry = runtime.createWorkspaceRegistry(workspaceRuntimes, {
      sessionOwnerIndex
    });
    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"]?.registry.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
      });
      const 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")
      });
      wsBridgeRef = wsBridge;
      const wsService = runtime.createDaemonWorkspaceService({
        boundWorkspace: cwd,
        contextFilename: contextFilenameForInit ?? "QWEN.md",
        statusProvider: runtime.createDaemonStatusProvider({
          env: wsEnv.effectiveEnv
        }),
        workspaceProvidersStatusProvider: runtime.createWorkspaceProvidersStatusProvider({
          env: wsEnv.effectiveEnv
        }),
        workspaceSkillsStatusProvider: runtime.createWorkspaceSkillsStatusProvider(),
        isChannelLive: /* @__PURE__ */ __name(() => wsBridge.isChannelLive(), "isChannelLive"),
        preheatAcpChild: /* @__PURE__ */ __name(() => wsBridge.preheat(), "preheatAcpChild"),
        persistDisabledTools: persistDisabledToolsFn,
        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")
      });
      runtimeBridges.push(wsBridge);
      internalRuntimeBridgesForCleanup.push(wsBridge);
      subSessionStoppers.push(wsSubSessionLauncher.stop);
      return {
        workspaceId: wsHash,
        workspaceCwd: cwd,
        primary: false,
        trusted,
        env: wsEnv.metadata,
        bridge: wsBridge,
        workspaceService: wsService,
        routeFileSystemFactory: wsFsFactory,
        clientMcpSenderRegistry: wsClientMcpRegistry
      };
    }, "createDynamicWorkspaceRuntime");
    const app2 = runtime.createServeApp(opts, () => actualPort, {
      workspaceRegistry,
      createWorkspaceRuntime: createDynamicWorkspaceRuntime,
      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,
      enqueueChannelWebhookTask: /* @__PURE__ */ __name((task) => channelWorker.enqueueWebhookTask(task), "enqueueChannelWebhookTask"),
      // Gate both the `channel_reload` capability and the reload route on the
      // presence of this dep, so it is advertised only when a channel worker
      // exists to reload.
      ...opts.channelSelection ? { 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,
      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")
    });
    app2.locals.subSessionStoppers = subSessionStoppers;
    subSessionStoppers.push(subSessionLauncher.stop);
    return { app: app2, bridge };
  }, "buildRuntime");
  if (deps.bridge) {
    const runtime = await buildRuntime();
    runtimeAppForCleanup = runtime.app;
    runtimeApp = runtime.app;
    bridgeRef = runtime.bridge;
    if (!opts.channelSelection) {
      runtimeStartupSettled = true;
      markRuntimeReady();
    }
  }
  cliVersion ??= await cliVersionPromise;
  const bootstrapApp = createBootstrapServeApp({
    opts,
    getPort: /* @__PURE__ */ __name(() => actualPort, "getPort"),
    boundWorkspace,
    startup,
    daemonLog,
    qwenCodeVersion: cliVersion,
    sessionShellCommandEnabled,
    sessionArtifactsPersistenceAvailable,
    permissionPolicy,
    multiWorkspaceCapabilitiesRequireRuntime: workspaceInputs.length > 1,
    getRuntimeError: /* @__PURE__ */ __name(() => runtimeStartupError, "getRuntimeError"),
    getChannelWorkerSnapshot,
    onHealthServed: deferRuntimeUntilFirstHealth ? () => startRuntimeAfterHealth?.() : void 0
  });
  const deferredChannelWebhookAuth = deferRuntimeUntilFirstHealth ? createDeferredChannelWebhookAuth(
    boundWorkspace,
    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).`
    );
  }
  reserveChannelServicePidfile();
  return await new Promise((resolve, reject) => {
    const onListening = /* @__PURE__ */ __name(() => {
      startup.listenerReadyAt = (/* @__PURE__ */ new Date()).toISOString();
      startup.processToListenMs = Math.round(process.uptime() * 1e3);
      startup.runQwenServeToListenMs = Math.round(
        performance.now() - runStartedAt
      );
      profileCheckpoint("serve_listener_ready");
      finalizeStartupProfile(`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 {
        if (opts.channelSelection) {
          const createSupervisor = deps.channelWorkerSupervisorFactory ?? channelRuntime?.createChannelWorkerSupervisor;
          const findCliEntryPath = channelRuntime?.findCliEntryPath;
          if (!createSupervisor || !findCliEntryPath) {
            throw new Error(
              "Channel worker supervisor runtime is not available."
            );
          }
          channelWorker = createSupervisor({
            cliEntryPath: findCliEntryPath(),
            daemonUrl: formatChannelWorkerDaemonUrl(opts.hostname, actualPort),
            ...token ? { daemonToken: token } : {},
            workspace: boundWorkspace,
            selection: opts.channelSelection,
            onReady: /* @__PURE__ */ __name((snapshot) => {
              writeChannelWorkerPidfile(snapshot);
            }, "onReady"),
            onLog: /* @__PURE__ */ __name(({ stream, line }) => {
              const message = `channel worker ${stream}: ${line}`;
              if (stream === "stderr") {
                daemonLog.warn(message);
              } else {
                daemonLog.info(message);
              }
            }, "onLog"),
            onExit: /* @__PURE__ */ __name((snapshot) => {
              daemonLog.warn(
                `channel worker exited (state=${snapshot.state}, pid=${snapshot.pid ?? "unknown"}, code=${snapshot.exitCode ?? "null"}, signal=${snapshot.signal ?? "null"}, error=${snapshot.error ?? "none"}, restartCount=${snapshot.restartCount ?? 0}, nextRestartAt=${snapshot.nextRestartAt ?? "none"}, staleHeartbeatAt=${snapshot.staleHeartbeatAt ?? "none"})`
              );
              writeChannelWorkerPidfile(snapshot, { clearWorkerPid: true });
            }, "onExit")
          });
        }
      } catch (err) {
        removeCurrentServePidfile();
        const error = err instanceof Error ? err : new Error(String(err));
        server.close((closeErr) => {
          if (closeErr) {
            daemonLog.error(
              "server close after channel worker setup error failed",
              closeErr
            );
          }
          reject(error);
        });
        return;
      }
      writeStdoutLine(
        `qwen serve listening on ${url} (mode=${opts.mode}, workspace=${boundWorkspace})`
      );
      writeStderrLine(
        `qwen serve: bound to workspace ${JSON.stringify(boundWorkspace)}`
      );
      writeStderrLine(
        `qwen serve: startup timing: processToListenMs=${startup.processToListenMs} runQwenServeToListenMs=${startup.runQwenServeToListenMs}`
      );
      if (!token) {
        writeStderrLine(
          `qwen serve: bearer auth disabled (loopback default). Set ${QWEN_SERVER_TOKEN_ENV} to enable.`
        );
        if (opts.clientMcpOverWs === true) {
          writeStderrLine(
            `qwen serve: client-hosted MCP tools are accepted over the WebSocket without auth. Set ${QWEN_SERVE_CLIENT_MCP_OVER_WS_ENV}=0 to disable.`
          );
        }
      } else if (opts.requireAuth) {
        writeStderrLine(
          "qwen serve: --require-auth enabled (bearer token mandatory on every route, including loopback /health)."
        );
      }
      let shuttingDown = false;
      let closePromise;
      let runtimeStartupTimer;
      let runtimeStartAfterHealthTimer;
      let runtimeStartFallbackTimer;
      const runtimeStartupTimeoutMs = resolveRuntimeStartupTimeoutMs(
        deps.runtimeStartupTimeoutMs
      );
      const clearRuntimeStartupTimer = /* @__PURE__ */ __name(() => {
        if (!runtimeStartupTimer) return;
        clearTimeout(runtimeStartupTimer);
        runtimeStartupTimer = void 0;
      }, "clearRuntimeStartupTimer");
      const clearRuntimeStartFallbackTimer = /* @__PURE__ */ __name(() => {
        if (!runtimeStartFallbackTimer) return;
        clearTimeout(runtimeStartFallbackTimer);
        runtimeStartFallbackTimer = void 0;
      }, "clearRuntimeStartFallbackTimer");
      const clearRuntimeStartAfterHealthTimer = /* @__PURE__ */ __name(() => {
        if (!runtimeStartAfterHealthTimer) return;
        clearTimeout(runtimeStartAfterHealthTimer);
        runtimeStartAfterHealthTimer = void 0;
      }, "clearRuntimeStartAfterHealthTimer");
      const cancelDeferredRuntimeStartup = /* @__PURE__ */ __name(() => {
        if (!deferRuntimeUntilFirstHealth || runtimeStarting || runtimeStartupSettled)
          return;
        daemonLog.info(
          "deferred runtime: cancelled, server closed before startup"
        );
        runtimeStartupSettled = true;
        const error = new Error(RUNTIME_STARTUP_CANCELLED_MESSAGE);
        runtimeStartupError = error.message;
        markRuntimeFailed(error);
      }, "cancelDeferredRuntimeStartup");
      const shutdownBridgeAfterFailedStartup = /* @__PURE__ */ __name(async (bridge) => {
        if (!bridge || deps.bridge) return;
        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 () => {
        await channelWorker.stop().catch((stopErr) => {
          daemonLog.error(
            "channel worker stop after runtime startup error failed",
            stopErr instanceof Error ? stopErr : null
          );
        });
      }, "stopChannelWorkerAfterFailedStartup");
      const failRuntimeStartup = /* @__PURE__ */ __name(async (err, bridgeForCleanup) => {
        const error = err instanceof Error ? err : new Error(String(err));
        if (runtimeStartupSettled) {
          await shutdownBridgeAfterFailedStartup(bridgeForCleanup);
          return;
        }
        runtimeStartupSettled = true;
        clearRuntimeStartupTimer();
        const message = error.message;
        runtimeStartupError = message;
        if (startup.preheat.status === "scheduled" || startup.preheat.status === "running") {
          startup.preheat.status = "failed";
          startup.preheat.error = message;
        }
        writeStderrLine(`qwen serve: runtime startup failed: ${message}`);
        daemonLog.error("runtime startup failed", error);
        await stopChannelWorkerAfterFailedStartup();
        disposeDaemonEventLoopMonitor();
        removeCurrentServePidfile();
        const bridgesForCleanup = bridgeForCleanup ? [bridgeForCleanup, ...getRuntimeBridgesForCleanup()] : getRuntimeBridgesForCleanup();
        for (const bridge of [...new Set(bridgesForCleanup)]) {
          await shutdownBridgeAfterFailedStartup(bridge);
        }
        markRuntimeFailed(error);
      }, "failRuntimeStartup");
      const armRuntimeStartupTimer = /* @__PURE__ */ __name(() => {
        if (runtimeStartupTimeoutMs <= 0 || runtimeStartupTimer) return;
        runtimeStartupTimer = setTimeout(() => {
          void failRuntimeStartup(
            new Error(
              `Daemon runtime startup timed out after ${runtimeStartupTimeoutMs}ms.`
            )
          );
        }, runtimeStartupTimeoutMs);
        runtimeStartupTimer.unref();
      }, "armRuntimeStartupTimer");
      const completeRuntimeStartup = /* @__PURE__ */ __name(async () => {
        if (runtimeStartupSettled) return;
        if (opts.channelSelection) {
          await channelWorker.start();
          if (runtimeStartupSettled) return;
        }
        if (runtimeStartupSettled) return;
        runtimeStartupSettled = true;
        clearRuntimeStartupTimer();
        markRuntimeReady();
      }, "completeRuntimeStartup");
      const startBridgePreheat = /* @__PURE__ */ __name((bridge) => {
        startup.preheat.status = "running";
        const preheatStartedAt = performance.now();
        bridge.preheat().then(() => {
          startup.preheat.status = "succeeded";
          startup.preheat.durationMs = Math.round(
            performance.now() - preheatStartedAt
          );
        }).catch((err) => {
          const message = err instanceof Error ? err.message : String(err);
          startup.preheat.status = "failed";
          startup.preheat.durationMs = Math.round(
            performance.now() - preheatStartedAt
          );
          startup.preheat.error = message;
          writeStderrLine(
            `qwen serve: ACP preheat failed, will retry on first session: ${message}`
          );
        });
      }, "startBridgePreheat");
      const startRuntime = /* @__PURE__ */ __name(() => {
        if (runtimeStarting) return;
        armRuntimeStartupTimer();
        clearRuntimeStartAfterHealthTimer();
        clearRuntimeStartFallbackTimer();
        runtimeStarting = buildRuntime().then(async (runtime) => {
          if (runtimeStartupSettled) {
            await shutdownBridgeAfterFailedStartup(runtime.bridge);
            return;
          }
          bridgeRef = runtime.bridge;
          runtimeAppForCleanup = runtime.app;
          if (shuttingDown) {
            await failRuntimeStartup(
              new Error("Daemon runtime stopped before mounting."),
              runtime.bridge
            );
            return;
          }
          runtimeApp = runtime.app;
          const acpHandle = runtime.app.locals?.["acpHandle"];
          acpHandle?.attachServer?.(server);
          if (shouldPreheat) {
            startBridgePreheat(runtime.bridge);
          }
          await completeRuntimeStartup();
        }).catch((err) => failRuntimeStartup(err));
      }, "startRuntime");
      startRuntimeForRequest = startRuntime;
      const scheduleRuntimeStartFallback = /* @__PURE__ */ __name(() => {
        if (shuttingDown || runtimeStarting || runtimeStartFallbackTimer)
          return;
        daemonLog.info(
          `deferred runtime: scheduling fallback start in ${FAST_PATH_RUNTIME_START_FALLBACK_MS}ms`
        );
        runtimeStartFallbackTimer = setTimeout(() => {
          runtimeStartFallbackTimer = void 0;
          if (shuttingDown) return;
          daemonLog.info("deferred runtime: fallback timer fired, starting");
          startRuntime();
        }, FAST_PATH_RUNTIME_START_FALLBACK_MS);
        runtimeStartFallbackTimer.unref();
      }, "scheduleRuntimeStartFallback");
      startRuntimeAfterHealth = /* @__PURE__ */ __name(() => {
        if (shuttingDown || runtimeStarting || runtimeStartAfterHealthTimer) {
          return;
        }
        clearRuntimeStartFallbackTimer();
        daemonLog.info(
          `deferred runtime: health served, scheduling start in ${FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS}ms`
        );
        runtimeStartAfterHealthTimer = setTimeout(() => {
          runtimeStartAfterHealthTimer = void 0;
          if (shuttingDown) return;
          daemonLog.info("deferred runtime: health timer fired, starting");
          startRuntime();
        }, FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS);
        runtimeStartAfterHealthTimer.unref();
      }, "startRuntimeAfterHealth");
      const onSignal = /* @__PURE__ */ __name(async (signal) => {
        if (shuttingDown) {
          daemonLog.warn(`received ${signal} during drain \u2014 forcing exit`);
          try {
            channelWorker.killAllSync();
            for (const runtimeBridge of getRuntimeBridgesForCleanup()) {
              runtimeBridge.killAllSync();
            }
            removeCurrentServePidfile();
          } catch (err) {
            daemonLog.error(
              "force-kill error",
              err instanceof Error ? err : null
            );
          }
          await daemonLog.flush().catch(() => {
          });
          process.exit(1);
          return;
        }
        daemonLog.warn(`received ${signal}, draining`);
        try {
          await handle.close();
          await daemonLog.flush();
          process.exit(0);
        } catch (err) {
          daemonLog.error("shutdown error", err instanceof Error ? err : null);
          await daemonLog.flush().catch(() => {
          });
          process.exit(1);
        }
      }, "onSignal");
      const onUncaughtExceptionMonitor = /* @__PURE__ */ __name(() => {
        if (process.listenerCount("uncaughtException") === 0) {
          removeCurrentServePidfile();
        }
      }, "onUncaughtExceptionMonitor");
      const handle = {
        server,
        url,
        bridge: handleBridge,
        webShellMounted,
        resolvedToken: token,
        runtimeReady,
        close: /* @__PURE__ */ __name(() => {
          if (closePromise) return closePromise;
          closePromise = new Promise((res, rej) => {
            shuttingDown = true;
            app.locals.stopScheduledTaskKeepalive?.();
            const stoppers = app.locals.subSessionStoppers;
            if (stoppers) {
              for (const stop of stoppers) stop();
            }
            clearRuntimeStartAfterHealthTimer();
            clearRuntimeStartFallbackTimer();
            cancelDeferredRuntimeStartup();
            let settled = false;
            let bridgeShutdownError;
            const finish = /* @__PURE__ */ __name((err) => {
              if (settled) return;
              settled = true;
              process.removeListener("SIGINT", onSignal);
              process.removeListener("SIGTERM", onSignal);
              process.removeListener(
                "uncaughtExceptionMonitor",
                onUncaughtExceptionMonitor
              );
              void (coreRuntimePromise ? coreRuntimePromise.then((core) => core.shutdownTelemetry()) : Promise.resolve()).catch((telemetryErr) => {
                writeStderrLine(
                  `qwen serve: telemetry shutdown error: ${telemetryErr instanceof Error ? telemetryErr.message : String(telemetryErr)}`
                );
              }).finally(() => daemonLog.flush().catch(() => {
              })).finally(() => {
                const finalErr = err ?? bridgeShutdownError;
                if (finalErr) rej(finalErr);
                else res();
              });
            }, "finish");
            void (coreRuntimePromise ? coreRuntimePromise.then((core) => core.forceFlushMetrics()) : Promise.resolve()).catch((flushErr) => {
              daemonLog.warn(
                `pre-shutdown metrics flush failed: ${flushErr instanceof Error ? flushErr.message : String(flushErr)}`
              );
            });
            Promise.resolve().then(async () => {
              await waitForRuntimeStartingForShutdown(
                runtimeStarting,
                daemonLog
              );
              const appForCleanup = runtimeApp ?? runtimeAppForCleanup;
              const deviceFlowRegistry = appForCleanup ? getDeviceFlowRegistry(appForCleanup) : void 0;
              if (deviceFlowRegistry) {
                try {
                  deviceFlowRegistry.dispose();
                } catch (err) {
                  daemonLog.warn(
                    `device-flow registry dispose error: ${err instanceof Error ? err.message : String(err)}`
                  );
                }
              }
              const acpHandle = appForCleanup?.locals?.["acpHandle"];
              if (acpHandle?.dispose) {
                try {
                  acpHandle.dispose();
                } catch (err) {
                  daemonLog.warn(
                    `ACP handle dispose error: ${err instanceof Error ? err.message : String(err)}`
                  );
                }
              }
              const rl = appForCleanup ? getRateLimiter(appForCleanup) : void 0;
              if (rl) {
                rl.setDraining(true);
                rl.dispose();
              }
              disposeDaemonEventLoopMonitor();
              await channelWorker.stop().catch((err) => {
                daemonLog.error(
                  "channel worker stop error",
                  err instanceof Error ? err : null
                );
              });
              removeCurrentServePidfile();
              for (const bridgeForShutdown of getRuntimeBridgesForCleanup()) {
                if (shutdownBridges.has(bridgeForShutdown)) continue;
                shutdownBridges.add(bridgeForShutdown);
                await bridgeForShutdown.shutdown().catch((err) => {
                  daemonLog.error(
                    "bridge shutdown error",
                    err instanceof Error ? err : null
                  );
                  bridgeShutdownError = err instanceof Error ? err : new Error(String(err));
                });
              }
            }).finally(() => {
              const SECONDARY_DEADLINE_MS = 2e3;
              let secondaryTimer;
              const forceTimer = setTimeout(() => {
                daemonLog.warn(
                  `${SHUTDOWN_FORCE_CLOSE_MS}ms listener-drain timeout reached; force-closing remaining connections`
                );
                server.closeAllConnections();
                secondaryTimer = setTimeout(() => {
                  daemonLog.warn(
                    `server.close did not fire ${SECONDARY_DEADLINE_MS}ms after force-close; resolving anyway`
                  );
                  finish();
                }, SECONDARY_DEADLINE_MS);
                secondaryTimer.unref();
              }, SHUTDOWN_FORCE_CLOSE_MS);
              forceTimer.unref();
              server.close((err) => {
                clearTimeout(forceTimer);
                if (secondaryTimer) clearTimeout(secondaryTimer);
                finish(err);
              });
            });
          });
          return closePromise;
        }, "close")
      };
      process.on("SIGINT", onSignal);
      process.on("SIGTERM", onSignal);
      process.on("uncaughtExceptionMonitor", onUncaughtExceptionMonitor);
      server.removeAllListeners("error");
      server.on("error", (err) => {
        daemonLog.error("server error", err instanceof Error ? err : null);
      });
      if (runtimeApp && bridgeRef) {
        const acpHandle = runtimeApp.locals?.["acpHandle"];
        acpHandle?.attachServer?.(server);
        if (shouldPreheat) {
          startBridgePreheat(bridgeRef);
        }
        if (opts.channelSelection && !runtimeStartupSettled) {
          armRuntimeStartupTimer();
          runtimeStarting = completeRuntimeStartup().catch(
            (err) => failRuntimeStartup(err, bridgeRef)
          );
        }
      } else if (deferRuntimeUntilFirstHealth) {
        scheduleRuntimeStartFallback();
      } else {
        startRuntime();
      }
      if (deps.resolveOnListen) {
        resolve(handle);
      } else {
        void runtimeReady.then(
          () => resolve(handle),
          (err) => {
            void handle.close().catch((closeErr) => {
              daemonLog.error(
                "shutdown after runtime startup error failed",
                closeErr instanceof Error ? closeErr : null
              );
            }).finally(() => {
              reject(err instanceof Error ? err : new Error(String(err)));
            });
          }
        );
      }
    }, "onListening");
    let server;
    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 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
