// Force strict mode and setup for ESM
"use strict";
import {
  CAPABILITIES_SCHEMA_VERSION,
  SERVE_CAPABILITY_REGISTRY,
  allowOriginCors,
  allowOriginMode,
  bearerAuth,
  createBridgeFileSystemAdapter,
  denyBrowserOriginCors,
  getAdvertisedServeFeatures,
  getDeviceFlowRegistry,
  getRateLimiter,
  getServeProtocolVersions,
  hostAllowlist,
  isLoopbackBind,
  listenerMaxConnections,
  parseAllowOriginPatterns,
  parseDaemonStatusDetail,
  positiveFiniteOrNull,
  require_express,
  resolveWebShellDir
} from "./chunk-FPACXT7T.js";
import "./chunk-3HX5LZ6R.js";
import "./chunk-7RYW5LQV.js";
import {
  getCliVersion
} from "./chunk-BS64PXY3.js";
import {
  canonicalizeWorkspace
} from "./chunk-SEZC2725.js";
import {
  writeStderrLine,
  writeStdoutLine
} from "./chunk-Y6Z2O3WR.js";
import {
  loadServeFastPathSettings,
  preResolveServeFastPathHomeEnvOverrides
} from "./chunk-3RJ3ZPPR.js";
import {
  getGlobalQwenDirLite,
  resolveConfigPathLite
} from "./chunk-UN3C6GOR.js";
import "./chunk-5P5XGNYH.js";
import "./chunk-SKAZWEV5.js";
import "./chunk-UWCTAVOD.js";
import "./chunk-SYCJMSIJ.js";
import {
  finalizeStartupProfile,
  profileCheckpoint
} from "./chunk-ITOGNELQ.js";
import "./chunk-FXGLL2HL.js";
import "./chunk-QN5NZ3UQ.js";
import "./chunk-BR4QREVK.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name,
  __toESM
} from "./chunk-J2S4EL5Y.js";

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

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

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

// packages/cli/src/serve/run-qwen-serve.ts
var QWEN_SERVER_TOKEN_ENV = "QWEN_SERVER_TOKEN";
var QWEN_SERVE_PROMPT_DEADLINE_MS_ENV = "QWEN_SERVE_PROMPT_DEADLINE_MS";
var QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV = "QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS";
var SHUTDOWN_FORCE_CLOSE_MS = 5e3;
var DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS = 12e4;
var RUNTIME_STARTUP_TIMEOUT_ENV = "QWEN_SERVE_RUNTIME_STARTUP_TIMEOUT_MS";
var MAX_EVENT_RING_SIZE = 1e6;
var DEFAULT_MAX_SESSIONS = 20;
var DEFAULT_MAX_PENDING_PROMPTS_PER_SESSION = 5;
var DEFAULT_EVENT_RING_SIZE = 8e3;
var DEFAULT_SESSION_IDLE_TIMEOUT_MS = 30 * 6e4;
var WORKSPACE_SETTING_SCOPE = "Workspace";
function isPositiveIntegerMs(value) {
  return Number.isFinite(value) && Number.isInteger(value) && value > 0;
}
__name(isPositiveIntegerMs, "isPositiveIntegerMs");
function isNonNegativeIntegerOrInfinity(value) {
  return value === Number.POSITIVE_INFINITY || Number.isFinite(value) && Number.isInteger(value) && value >= 0;
}
__name(isNonNegativeIntegerOrInfinity, "isNonNegativeIntegerOrInfinity");
function isNonNegativeIntegerMs(value) {
  return Number.isFinite(value) && Number.isInteger(value) && value >= 0;
}
__name(isNonNegativeIntegerMs, "isNonNegativeIntegerMs");
var MAX_TIMEOUT_MS = 2147483647;
function assertTimerDelayInRange(name, value) {
  if (value > MAX_TIMEOUT_MS) {
    throw new TypeError(
      `Invalid ${name}: ${value}. Exceeds maximum JS timer delay of ${MAX_TIMEOUT_MS} ms (~24.8 days); Node would silently compress longer delays to 1ms.`
    );
  }
}
__name(assertTimerDelayInRange, "assertTimerDelayInRange");
function parseDeadlineEnv(envName, raw) {
  if (raw === void 0) return void 0;
  const trimmed = raw.trim();
  const parsed = Number(trimmed);
  if (!isPositiveIntegerMs(parsed)) {
    throw new Error(
      `Invalid ${envName}="${raw}": must be a positive integer (milliseconds).`
    );
  }
  return parsed;
}
__name(parseDeadlineEnv, "parseDeadlineEnv");
function 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 extractContextFilename(value) {
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed === "" ? void 0 : trimmed;
  }
  if (Array.isArray(value)) {
    for (const entry of value) {
      if (typeof entry === "string") {
        const trimmed = entry.trim();
        if (trimmed !== "") return trimmed;
      }
    }
    return void 0;
  }
  return void 0;
}
__name(extractContextFilename, "extractContextFilename");
var settingsWriteLocks = /* @__PURE__ */ new Map();
function withSettingsLock(workspace, fn) {
  const prev = settingsWriteLocks.get(workspace) ?? Promise.resolve();
  const next = prev.then(fn, fn);
  settingsWriteLocks.set(workspace, next);
  return next;
}
__name(withSettingsLock, "withSettingsLock");
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-HPC4EWSM.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-FJF76ER5.js"),
    import("./loadedSettingsAdapter-7AXPXEDD.js")
  ]).then(([settings, loadedSettingsAdapter]) => ({
    settings,
    loadedSettingsAdapter
  }));
  return settingsRuntimePromise;
}
__name(loadSettingsRuntimeModules, "loadSettingsRuntimeModules");
async function loadServeRuntimeModules() {
  const [
    serverModule,
    bridgeModule,
    spawnChannelModule,
    workspaceModule,
    daemonStatusProviderModule,
    workspaceProvidersStatusModule
  ] = await Promise.all([
    import("./server-OG7BK4QM.js"),
    import("./bridge-65SZRIVE.js"),
    import("./spawnChannel-5XBSWF3U.js"),
    import("./workspace-service-X43MJCOZ.js"),
    import("./daemon-status-provider-MHTSYGCV.js"),
    import("./workspace-providers-status-XT33DXIT.js")
  ]);
  return {
    createServeApp: serverModule.createServeApp,
    getActiveSseCount: serverModule.getActiveSseCount,
    resolveBridgeFsFactory: serverModule.resolveBridgeFsFactory,
    createAcpSessionBridge: bridgeModule.createAcpSessionBridge,
    createSpawnChannelFactory: spawnChannelModule.createSpawnChannelFactory,
    createDaemonWorkspaceService: workspaceModule.createDaemonWorkspaceService,
    createDaemonStatusProvider: daemonStatusProviderModule.createDaemonStatusProvider,
    createWorkspaceProvidersStatusProvider: workspaceProvidersStatusModule.createWorkspaceProvidersStatusProvider
  };
}
__name(loadServeRuntimeModules, "loadServeRuntimeModules");
function advertisedMaxSessions(value) {
  if (value === void 0) return DEFAULT_MAX_SESSIONS;
  if (value === 0 || value === Number.POSITIVE_INFINITY) return null;
  return value;
}
__name(advertisedMaxSessions, "advertisedMaxSessions");
function advertisedMaxPendingPromptsPerSession(value) {
  if (value === void 0) return DEFAULT_MAX_PENDING_PROMPTS_PER_SESSION;
  if (value === 0 || value === Number.POSITIVE_INFINITY) return null;
  return value;
}
__name(advertisedMaxPendingPromptsPerSession, "advertisedMaxPendingPromptsPerSession");
function channelIdleTimeoutMs(value) {
  return value !== void 0 && Number.isFinite(value) && value > 0 ? Math.min(value, MAX_TIMEOUT_MS) : 0;
}
__name(channelIdleTimeoutMs, "channelIdleTimeoutMs");
function sessionIdleTimeoutMs(value) {
  return value !== void 0 ? channelIdleTimeoutMs(value) : DEFAULT_SESSION_IDLE_TIMEOUT_MS;
}
__name(sessionIdleTimeoutMs, "sessionIdleTimeoutMs");
function currentServeFeaturesForRunQwenServe(opts, sessionShellCommandEnabled) {
  return getAdvertisedServeFeatures(void 0, {
    requireAuth: opts.requireAuth === true,
    mcpPoolActive: opts.mcpPoolActive !== false,
    allowOriginActive: opts.allowOrigins !== void 0 && opts.allowOrigins.length > 0,
    ...opts.promptDeadlineMs !== void 0 ? { promptDeadlineMs: opts.promptDeadlineMs } : {},
    ...opts.writerIdleTimeoutMs !== void 0 ? { writerIdleTimeoutMs: opts.writerIdleTimeoutMs } : {},
    persistSettingAvailable: true,
    sessionShellCommandEnabled,
    rateLimit: opts.rateLimit === true,
    reloadAvailable: true
  });
}
__name(currentServeFeaturesForRunQwenServe, "currentServeFeaturesForRunQwenServe");
function createBootstrapCapabilities(input) {
  return {
    v: CAPABILITIES_SCHEMA_VERSION,
    protocolVersions: getServeProtocolVersions(),
    ...input.qwenCodeVersion ? { qwenCodeVersion: input.qwenCodeVersion } : {},
    mode: input.opts.mode,
    features: currentServeFeaturesForRunQwenServe(
      input.opts,
      input.sessionShellCommandEnabled
    ),
    modelServices: [],
    workspaceCwd: input.boundWorkspace,
    transports: ["rest"],
    policy: { permission: input.permissionPolicy ?? "first-responder" },
    limits: {
      maxPendingPromptsPerSession: advertisedMaxPendingPromptsPerSession(
        input.opts.maxPendingPromptsPerSession
      )
    }
  };
}
__name(createBootstrapCapabilities, "createBootstrapCapabilities");
function validateRateLimitOptions(opts) {
  if (opts.rateLimit !== true) return;
  for (const [name, value] of [
    ["rateLimitPrompt", opts.rateLimitPrompt],
    ["rateLimitMutation", opts.rateLimitMutation],
    ["rateLimitRead", opts.rateLimitRead]
  ]) {
    if (value !== void 0 && (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0)) {
      throw new TypeError(
        `Invalid ${name}: ${value}. Must be a positive integer.`
      );
    }
  }
  if (opts.rateLimitWindowMs !== void 0 && (!Number.isFinite(opts.rateLimitWindowMs) || !Number.isInteger(opts.rateLimitWindowMs) || opts.rateLimitWindowMs < 1e3)) {
    throw new TypeError(
      `Invalid rateLimitWindowMs: ${opts.rateLimitWindowMs}. Must be an integer >= 1000.`
    );
  }
}
__name(validateRateLimitOptions, "validateRateLimitOptions");
function installSameOriginOriginStrip(app, getPort) {
  let cachedStripPort = -1;
  let cachedSelfOrigins = /* @__PURE__ */ new Set();
  app.use((req, _res, next) => {
    const origin = req.headers.origin;
    if (origin) {
      const port = getPort();
      if (port !== cachedStripPort) {
        cachedStripPort = port;
        cachedSelfOrigins = /* @__PURE__ */ new Set([
          `http://127.0.0.1:${port}`,
          `http://localhost:${port}`,
          `http://[::1]:${port}`,
          `http://host.docker.internal:${port}`
        ]);
      }
      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");
function createBootstrapServeApp(input) {
  const {
    opts,
    getPort,
    boundWorkspace,
    startup,
    daemonLog,
    qwenCodeVersion,
    sessionShellCommandEnabled,
    permissionPolicy,
    getRuntimeError
  } = 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;
    }
    res.status(200).json({ status: "ok" });
  }, "healthHandler");
  const loopback = isLoopbackBind(opts.hostname);
  const exposeHealthPreAuth = loopback && !opts.requireAuth;
  if (exposeHealthPreAuth) {
    app.get("/health", healthHandler);
  }
  app.use(bearerAuth(opts.token));
  if (!exposeHealthPreAuth) {
    app.get("/health", healthHandler);
  }
  app.get("/capabilities", (_req, res) => {
    res.status(200).json(
      createBootstrapCapabilities({
        opts,
        boundWorkspace,
        qwenCodeVersion,
        sessionShellCommandEnabled,
        permissionPolicy
      })
    );
  });
  app.get("/daemon/status", (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 runtimeFailed = runtimeError !== void 0;
    const issue = runtimeError ? {
      code: "daemon_runtime_failed",
      severity: "error",
      message: runtimeError
    } : {
      code: "daemon_runtime_starting",
      severity: "warning",
      message: "Daemon runtime is still starting."
    };
    const response = {
      v: 1,
      detail: detail.detail,
      generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
      status: runtimeFailed ? "error" : "warning",
      issues: [issue],
      daemon: {
        pid: process.pid,
        uptimeMs: Math.round(process.uptime() * 1e3),
        mode: opts.mode,
        workspaceCwd: boundWorkspace,
        startup: {
          ...startup,
          preheat: { ...startup.preheat }
        },
        ...qwenCodeVersion ? { qwenCodeVersion } : {},
        ...daemonLog.getDaemonId() ? { daemonId: daemonLog.getDaemonId() } : {},
        ...detail.detail === "full" && daemonLog.getLogPath() ? { logPath: daemonLog.getLogPath() } : {}
      },
      security: {
        tokenConfigured: Boolean(opts.token),
        requireAuth: opts.requireAuth === true,
        loopbackBind: loopback,
        allowOriginConfigured: opts.allowOrigins !== void 0 && opts.allowOrigins.length > 0,
        allowOriginMode: allowOriginMode(opts.allowOrigins),
        sessionShellCommandEnabled
      },
      limits: {
        maxSessions: advertisedMaxSessions(opts.maxSessions),
        maxPendingPromptsPerSession: advertisedMaxPendingPromptsPerSession(
          opts.maxPendingPromptsPerSession
        ),
        listenerMaxConnections: listenerMaxConnections(opts.maxConnections),
        eventRingSize: opts.eventRingSize ?? DEFAULT_EVENT_RING_SIZE,
        promptDeadlineMs: positiveFiniteOrNull(opts.promptDeadlineMs),
        writerIdleTimeoutMs: positiveFiniteOrNull(opts.writerIdleTimeoutMs),
        channelIdleTimeoutMs: channelIdleTimeoutMs(opts.channelIdleTimeoutMs),
        sessionIdleTimeoutMs: sessionIdleTimeoutMs(opts.sessionIdleTimeoutMs),
        acpConnectionCap: null
      },
      capabilities: {
        protocolVersions: getServeProtocolVersions(),
        features: currentServeFeaturesForRunQwenServe(
          opts,
          sessionShellCommandEnabled
        )
      },
      runtime: {
        loading: runtimeError === void 0,
        ...runtimeError ? { error: runtimeError } : {},
        sessions: { active: 0 },
        permissions: {
          pending: 0,
          policy: permissionPolicy ?? "first-responder"
        },
        channel: { live: false },
        transport: {
          restSseActive: 0,
          acp: {
            enabled: false,
            connections: 0,
            connectionStreams: 0,
            sessionStreams: 0,
            sseStreams: 0,
            wsStreams: 0,
            pendingClientRequests: 0
          }
        },
        rateLimit: {
          enabled: opts.rateLimit === true,
          rejectedSinceStart: {
            prompt: 0,
            mutation: 0,
            read: 0
          }
        },
        process: process.memoryUsage()
      },
      ...detail.detail === "full" ? {
        full: {
          sessions: [],
          acpConnections: [],
          workspace: {},
          auth: {
            supportedDeviceFlowProviders: [],
            pendingDeviceFlowCount: 0
          }
        }
      } : {}
    };
    res.status(200).json(response);
  });
  app.use((_req, res) => {
    const runtimeError = getRuntimeError();
    res.status(503).json({
      error: runtimeError ? "Daemon runtime failed to start" : "Daemon runtime is still starting",
      code: runtimeError ? "daemon_runtime_failed" : "daemon_runtime_starting"
    });
  });
  return app;
}
__name(createBootstrapServeApp, "createBootstrapServeApp");
function createDelegatingServeApp(bootstrapApp, getRuntimeApp) {
  const app = (0, import_express.default)();
  app.use((req, res, next) => {
    const target = getRuntimeApp() ?? bootstrapApp;
    const handler = target;
    handler(req, res, next);
  });
  return app;
}
__name(createDelegatingServeApp, "createDelegatingServeApp");
async function runQwenServe(optsIn, deps = {}) {
  const runStartedAt = performance.now();
  const shouldPreheat = !deps.bridge && shouldPreheatBridge(deps);
  const startup = {
    processStartedAt: new Date(
      Date.now() - Math.round(process.uptime() * 1e3)
    ).toISOString(),
    preheat: {
      status: deps.bridge ? "external_bridge" : shouldPreheat ? "scheduled" : "not_scheduled"
    }
  };
  preResolveServeFastPathHomeEnvOverrides();
  const rawToken = optsIn.token ?? process.env[QWEN_SERVER_TOKEN_ENV];
  const token = typeof rawToken === "string" && rawToken.trim().length > 0 ? rawToken.trim() : void 0;
  const sessionShellCommandEnabled = optsIn.enableSessionShell === true && token !== void 0;
  if (optsIn.enableSessionShell === true && token === void 0) {
    writeStderrLine(
      `qwen serve: --enable-session-shell ignored because no bearer token is configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token to enable direct session shell.`
    );
  }
  const promptDeadlineMs = optsIn.promptDeadlineMs ?? parseDeadlineEnv(
    QWEN_SERVE_PROMPT_DEADLINE_MS_ENV,
    process.env[QWEN_SERVE_PROMPT_DEADLINE_MS_ENV]
  );
  const writerIdleTimeoutMs = optsIn.writerIdleTimeoutMs ?? parseDeadlineEnv(
    QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV,
    process.env[QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV]
  );
  const opts = {
    ...optsIn,
    token,
    promptDeadlineMs,
    writerIdleTimeoutMs
  };
  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}".`
    );
  }
  if (!isLoopbackBind(opts.hostname) && !token) {
    throw new Error(
      `Refusing to bind ${opts.hostname}:${opts.port} without a bearer token. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or rebind to loopback (127.0.0.1, localhost, ::1, or [::1]).`
    );
  }
  if (opts.requireAuth && !token) {
    throw new Error(
      `Refusing to start with --require-auth set but no bearer token configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or omit --require-auth to keep the loopback developer default.`
    );
  }
  if (opts.allowOrigins && opts.allowOrigins.length > 0) {
    const parsed = parseAllowOriginPatterns(opts.allowOrigins);
    if (parsed.allowAny && !token) {
      throw new Error(
        `Refusing to start with --allow-origin '*' but no bearer token configured. '*' admits any cross-origin browser to the API; without a token, any local page can drive the daemon. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or list specific origins instead of '*'.`
      );
    }
    writeStderrLine(
      `qwen serve: --allow-origin: ${opts.allowOrigins.join(", ")}` + (parsed.allowAny ? " (WARNING: `*` admits any cross-origin browser \u2014 bearer token gates API routes; /health and /demo remain pre-auth on loopback unless --require-auth is set)" : "")
    );
  }
  if (opts.allowPrivateAuthBaseUrl) {
    writeStderrLine(
      "qwen serve: --allow-private-auth-base-url enabled; /workspace/auth/provider may install localhost/private-network model endpoints. Use only for local development with trusted clients."
    );
  }
  const rawWorkspace = opts.workspace ?? process.cwd();
  if (!path.isAbsolute(rawWorkspace)) {
    throw new Error(
      `Invalid --workspace "${rawWorkspace}": must be an absolute path.`
    );
  }
  try {
    const stats = fs.statSync(rawWorkspace);
    if (!stats.isDirectory()) {
      throw new Error(
        `Invalid --workspace "${rawWorkspace}": exists but is not a directory.`
      );
    }
  } catch (err) {
    if (err && typeof err === "object" && "code" in err) {
      const code = err.code;
      if (code === "ENOENT") {
        throw new Error(
          `Invalid --workspace "${rawWorkspace}": directory does not exist.`
        );
      }
      if (code === "EACCES" || code === "EPERM") {
        throw new Error(
          `Invalid --workspace "${rawWorkspace}": permission denied (${String(code)}). The path exists but cannot be stat'd by the current user.`
        );
      }
    }
    throw err;
  }
  const boundWorkspace = canonicalizeWorkspace(rawWorkspace);
  let contextFilenameForInit;
  let permissionPolicy;
  let permissionConsensusQuorum;
  let bootSettings;
  try {
    bootSettings = deps.bootSettings ?? loadServeFastPathSettings(boundWorkspace);
    contextFilenameForInit = extractContextFilename(
      bootSettings.context?.fileName
    );
    const policyConfig = bootSettings.policy ?? {};
    const resolved = validatePolicyConfig(policyConfig);
    permissionPolicy = resolved.permissionPolicy;
    permissionConsensusQuorum = resolved.permissionConsensusQuorum;
  } catch (err) {
    if (err instanceof InvalidPolicyConfigError) {
      throw err;
    }
    writeStderrLine(
      `qwen serve: could not read settings for context.fileName / policy.* (${err instanceof Error ? err.message : String(err)}); falling back to defaults. Restart with a valid settings.json to apply context.fileName / policy.* overrides.`
    );
  }
  const daemonLogBaseDir = await resolveDaemonLogBaseDirForRun({
    deps,
    bootSettings,
    boundWorkspace
  });
  const daemonLog = initDaemonLogger({
    boundWorkspace,
    baseDir: daemonLogBaseDir
  });
  writeStderrLine(
    `qwen serve: daemon log \u2192 ${daemonLog.getLogPath() || "(disabled)"}`
  );
  if (opts.mcpClientBudget !== void 0) {
    if (!Number.isFinite(opts.mcpClientBudget) || !Number.isInteger(opts.mcpClientBudget) || opts.mcpClientBudget <= 0) {
      throw new TypeError(
        `Invalid mcpClientBudget: ${opts.mcpClientBudget}. Must be a positive integer.`
      );
    }
  }
  if (opts.mcpBudgetMode === "enforce" && opts.mcpClientBudget === void 0) {
    throw new Error(
      'mcpBudgetMode="enforce" requires a positive mcpClientBudget. Pass mcpClientBudget=N, or set mcpBudgetMode to "warn" or "off".'
    );
  }
  if (opts.promptDeadlineMs !== void 0) {
    if (!isPositiveIntegerMs(opts.promptDeadlineMs)) {
      throw new TypeError(
        `Invalid promptDeadlineMs: ${opts.promptDeadlineMs}. Must be a positive integer (milliseconds).`
      );
    }
    assertTimerDelayInRange("promptDeadlineMs", opts.promptDeadlineMs);
  }
  if (opts.maxSessions !== void 0) {
    if (Number.isNaN(opts.maxSessions) || opts.maxSessions < 0) {
      throw new TypeError(
        `Invalid maxSessions: ${opts.maxSessions}. Must be a number >= 0 (0 / Infinity = unlimited).`
      );
    }
  }
  if (opts.maxPendingPromptsPerSession !== void 0) {
    if (!isNonNegativeIntegerOrInfinity(opts.maxPendingPromptsPerSession)) {
      throw new TypeError(
        `Invalid maxPendingPromptsPerSession: ${opts.maxPendingPromptsPerSession}. Must be a non-negative integer (0 / Infinity = unlimited).`
      );
    }
  }
  if (opts.eventRingSize !== void 0) {
    if (!Number.isInteger(opts.eventRingSize) || opts.eventRingSize < 1 || opts.eventRingSize > MAX_EVENT_RING_SIZE) {
      throw new TypeError(
        `Invalid eventRingSize: ${opts.eventRingSize}. Must be a positive integer in [1, ${MAX_EVENT_RING_SIZE}].`
      );
    }
  }
  if (opts.writerIdleTimeoutMs !== void 0) {
    if (!isPositiveIntegerMs(opts.writerIdleTimeoutMs)) {
      throw new TypeError(
        `Invalid writerIdleTimeoutMs: ${opts.writerIdleTimeoutMs}. Must be a positive integer (milliseconds).`
      );
    }
  }
  if (opts.channelIdleTimeoutMs !== void 0) {
    if (!Number.isFinite(opts.channelIdleTimeoutMs) || !Number.isInteger(opts.channelIdleTimeoutMs) || opts.channelIdleTimeoutMs < 0) {
      throw new TypeError(
        `Invalid channelIdleTimeoutMs: ${opts.channelIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = immediate kill).`
      );
    }
  }
  if (opts.sessionReapIntervalMs !== void 0) {
    if (!isNonNegativeIntegerMs(opts.sessionReapIntervalMs)) {
      throw new TypeError(
        `Invalid sessionReapIntervalMs: ${opts.sessionReapIntervalMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`
      );
    }
  }
  if (opts.sessionIdleTimeoutMs !== void 0) {
    if (!isNonNegativeIntegerMs(opts.sessionIdleTimeoutMs)) {
      throw new TypeError(
        `Invalid sessionIdleTimeoutMs: ${opts.sessionIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`
      );
    }
  }
  if (opts.permissionResponseTimeoutMs !== void 0) {
    if (!Number.isFinite(opts.permissionResponseTimeoutMs) || !Number.isInteger(opts.permissionResponseTimeoutMs) || opts.permissionResponseTimeoutMs < 0) {
      throw new TypeError(
        `Invalid permissionResponseTimeoutMs: ${opts.permissionResponseTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = disabled / wait forever).`
      );
    }
  }
  const inheritedNoPool = process.env["QWEN_SERVE_NO_MCP_POOL"] === "1";
  if (opts.mcpPoolActive === void 0 && inheritedNoPool) {
    opts.mcpPoolActive = false;
  }
  const childEnvOverrides = {
    QWEN_SERVE_MCP_CLIENT_BUDGET: opts.mcpClientBudget !== void 0 ? String(opts.mcpClientBudget) : void 0,
    QWEN_SERVE_MCP_BUDGET_MODE: opts.mcpBudgetMode
  };
  const cliVersion = await getCliVersion();
  const trustedWorkspace = deps.trustedWorkspace ?? true;
  const diagnosticSink = /* @__PURE__ */ __name((line, level) => daemonLog.raw(line, level), "diagnosticSink");
  let actualPort = opts.port;
  const webShellDir = opts.serveWebShell === false ? void 0 : resolveWebShellDir();
  if (opts.serveWebShell !== false) {
    if (!webShellDir) {
      writeStderrLine(
        "qwen serve: Web Shell assets not found; serving API only. Build the web-shell workspace (npm run build) or pass --no-web to silence this."
      );
    } else {
      writeStderrLine(`qwen serve: Web Shell UI served from ${webShellDir}`);
      if (!isLoopbackBind(opts.hostname)) {
        writeStderrLine(
          "qwen serve: Web Shell UI is served WITHOUT auth on a non-loopback bind (the static shell has no secrets; the API stays token-gated). Pass --no-web to disable the UI."
        );
        if (!opts.allowOrigins || opts.allowOrigins.length === 0) {
          writeStderrLine(
            "qwen serve: without --allow-origin the Web Shell is read-only on a non-loopback bind \u2014 same-origin POSTs are blocked by CORS (403). Pass --allow-origin <origin> or front it with a same-origin proxy."
          );
        }
      }
    }
  }
  const webShellMounted = !!webShellDir;
  let runtimeApp;
  let runtimeAppForCleanup;
  let bridgeRef = deps.bridge;
  let runtimeStartupError;
  let runtimeStarting;
  let markRuntimeReady;
  let markRuntimeFailed;
  let runtimeStartupSettled = false;
  const runtimeReady = new Promise((resolve, reject) => {
    markRuntimeReady = resolve;
    markRuntimeFailed = reject;
  });
  void runtimeReady.catch(() => {
  });
  const handleBridge = deps.bridge ?? createLazyBridgeProxy(
    () => bridgeRef,
    () => runtimeStartupError
  );
  const buildRuntime = /* @__PURE__ */ __name(async () => {
    const [runtime, core, settingsRuntime] = await Promise.all([
      loadServeRuntimeModules(),
      loadCoreRuntime(),
      loadSettingsRuntimeModules()
    ]);
    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 daemonWorkspaceHash = core.hashDaemonWorkspace(boundWorkspace);
    const daemonTelemetrySettings = await core.resolveTelemetrySettings({
      env: process.env,
      settings: runtimeBootSettings?.merged.telemetry
    });
    core.initializeTelemetry(
      createDaemonTelemetryRuntimeConfig(
        daemonTelemetrySettings,
        cliVersion,
        `daemon:${daemonWorkspaceHash}:${process.pid}`,
        {
          otlpEndpoint: core.DEFAULT_OTLP_ENDPOINT,
          telemetryTarget: core.DEFAULT_TELEMETRY_TARGET
        }
      )
    );
    core.initializeDaemonMetrics();
    const daemonTelemetry = core.createDaemonBridgeTelemetry();
    daemonTelemetry.metrics = {
      sessionLifecycle(action) {
        core.recordDaemonSessionLifecycle(action);
        core.emitDaemonLog(
          `Session ${action}.`,
          {
            "qwen-code.workspace.hash": daemonWorkspaceHash
          },
          {
            eventName: `qwen-code.daemon.session.${action}`
          }
        );
      },
      channelLifecycle(action, expected) {
        core.recordDaemonChannelLifecycle(action, expected);
        core.emitDaemonLog(
          action === "spawn" ? "ACP channel spawned." : `ACP channel exited (expected=${expected ?? true}).`,
          {
            ...action === "exit" ? { "qwen-code.daemon.channel.expected": expected ?? true } : {}
          },
          {
            eventName: `qwen-code.daemon.channel.${action}`,
            ...expected === false && action === "exit" ? { severityNumber: 13 } : {}
          }
        );
      },
      promptQueueWait: core.recordDaemonPromptQueueWait,
      promptDuration: core.recordDaemonPromptDuration,
      cancelled: core.recordDaemonCancel
    };
    const permissionAuditRing = new PermissionAuditRing();
    const permissionAuditPublisher = createPermissionAuditPublisher({
      ring: permissionAuditRing
    });
    const customIgnoreFiles = runtimeBootSettings?.merged.context?.fileFiltering?.customIgnoreFiles;
    const fsFactory = runtime.resolveBridgeFsFactory({
      boundWorkspace,
      injected: deps.fsFactory,
      trusted: trustedWorkspace,
      emit: deps.fsAuditEmit,
      ...customIgnoreFiles !== void 0 ? { customIgnoreFiles } : {}
    });
    const channelFactory = runtime.createSpawnChannelFactory({
      onDiagnosticLine: diagnosticSink,
      ...opts.experimentalLsp === true ? { extraArgs: ["--experimental-lsp"] } : {}
    });
    const statusProvider = runtime.createDaemonStatusProvider();
    const workspaceProvidersStatusProvider = runtime.createWorkspaceProvidersStatusProvider();
    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 bridge = deps.bridge ?? runtime.createAcpSessionBridge({
      maxSessions: opts.maxSessions,
      ...opts.maxPendingPromptsPerSession !== void 0 ? { maxPendingPromptsPerSession: opts.maxPendingPromptsPerSession } : {},
      ...opts.eventRingSize !== void 0 ? { eventRingSize: opts.eventRingSize } : {},
      ...opts.channelIdleTimeoutMs !== void 0 ? { channelIdleTimeoutMs: opts.channelIdleTimeoutMs } : {},
      ...opts.sessionReapIntervalMs !== void 0 ? { sessionReapIntervalMs: opts.sessionReapIntervalMs } : {},
      ...opts.sessionIdleTimeoutMs !== void 0 ? { sessionIdleTimeoutMs: opts.sessionIdleTimeoutMs } : {},
      ...opts.permissionResponseTimeoutMs !== void 0 ? { permissionResponseTimeoutMs: opts.permissionResponseTimeoutMs } : {},
      boundWorkspace,
      sessionShellCommandEnabled,
      childEnvOverrides,
      channelFactory,
      onDiagnosticLine: diagnosticSink,
      telemetry: daemonTelemetry,
      ...permissionPolicy !== void 0 ? { permissionPolicy } : {},
      ...permissionConsensusQuorum !== void 0 ? { permissionConsensusQuorum } : {},
      permissionAudit: permissionAuditPublisher,
      statusProvider,
      fileSystem: createBridgeFileSystemAdapter(fsFactory),
      persistApprovalMode: /* @__PURE__ */ __name((workspace, mode) => withSettingsLock(workspace, async () => {
        const fresh = settingsRuntime.settings.loadSettings(workspace);
        fresh.setValue(WORKSPACE_SETTING_SCOPE, "tools.approvalMode", mode);
      }), "persistApprovalMode")
    });
    if (!deps.bridge) {
      bridgeRef = bridge;
    }
    const workspaceService = runtime.createDaemonWorkspaceService({
      boundWorkspace,
      contextFilename: contextFilenameForInit ?? "QWEN.md",
      statusProvider,
      workspaceProvidersStatusProvider,
      isChannelLive: /* @__PURE__ */ __name(() => bridge.isChannelLive(), "isChannelLive"),
      persistDisabledTools: persistDisabledToolsFn,
      reloadDaemonEnv: /* @__PURE__ */ __name((workspace) => withSettingsLock(workspace, async () => {
        const fresh = settingsRuntime.settings.loadSettings(workspace, {
          skipLoadEnvironment: true
        });
        return settingsRuntime.settings.reloadEnvironment(
          fresh.merged,
          workspace
        );
      }), "reloadDaemonEnv"),
      queryWorkspaceStatus: /* @__PURE__ */ __name((method, idle) => bridge.queryWorkspaceStatus(method, idle), "queryWorkspaceStatus"),
      invokeWorkspaceCommand: /* @__PURE__ */ __name((method, params, invokeOpts) => bridge.invokeWorkspaceCommand(method, params, invokeOpts), "invokeWorkspaceCommand"),
      refreshExtensionsForAllSessions: /* @__PURE__ */ __name(() => bridge.refreshExtensionsForAllSessions(), "refreshExtensionsForAllSessions"),
      publishWorkspaceEvent: /* @__PURE__ */ __name((event) => bridge.publishWorkspaceEvent(event), "publishWorkspaceEvent")
    });
    core.registerDaemonGaugeCallbacks({
      sessionCount: /* @__PURE__ */ __name(() => bridge.sessionCount, "sessionCount"),
      sseCount: /* @__PURE__ */ __name(() => runtime.getActiveSseCount(), "sseCount"),
      heapUsed: /* @__PURE__ */ __name(() => process.memoryUsage().heapUsed, "heapUsed")
    });
    const app2 = runtime.createServeApp(opts, () => actualPort, {
      bridge,
      webShellDir,
      boundWorkspace,
      qwenCodeVersion: cliVersion,
      startup,
      fsFactory,
      daemonLog,
      workspace: workspaceService,
      persistDisabledTools: persistDisabledToolsFn,
      persistSetting: /* @__PURE__ */ __name((workspace, scope, key, value) => withSettingsLock(workspace, async () => {
        const fresh = settingsRuntime.settings.loadSettings(workspace);
        fresh.setValue(scope, key, value);
      }), "persistSetting"),
      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);
          await core.applyProviderInstallPlan(plan, {
            settings: settingsRuntime.loadedSettingsAdapter.createLoadedSettingsAdapter(
              fresh
            ),
            doRefreshAuth: false
          });
          core.emitDaemonLog("Auth provider installed.", {
            "qwen-code.daemon.auth.provider_id": provider.id,
            "qwen-code.daemon.auth.auth_type": plan.authType
          });
          return {
            v: 1,
            providerId: provider.id,
            providerLabel: provider.label,
            authType: plan.authType,
            ...plan.modelSelection?.modelId ? { modelId: plan.modelSelection.modelId } : {},
            ...inputs.baseUrl ? { baseUrl: inputs.baseUrl } : {},
            message: `Successfully configured ${provider.label}. Use /model to switch models.`
          };
        }
      ), "installAuthProvider")
    });
    return { app: app2, bridge };
  }, "buildRuntime");
  if (deps.bridge) {
    const runtime = await buildRuntime();
    runtimeAppForCleanup = runtime.app;
    runtimeApp = runtime.app;
    bridgeRef = runtime.bridge;
    runtimeStartupSettled = true;
    markRuntimeReady();
  }
  const bootstrapApp = createBootstrapServeApp({
    opts,
    getPort: /* @__PURE__ */ __name(() => actualPort, "getPort"),
    boundWorkspace,
    startup,
    daemonLog,
    qwenCodeVersion: cliVersion,
    sessionShellCommandEnabled,
    permissionPolicy,
    getRuntimeError: /* @__PURE__ */ __name(() => runtimeStartupError, "getRuntimeError")
  });
  const app = runtimeApp ?? createDelegatingServeApp(bootstrapApp, () => runtimeApp);
  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).`
    );
  }
  return await new Promise((resolve, reject) => {
    const server = app.listen(opts.port, listenHostname, () => {
      startup.listenerReadyAt = (/* @__PURE__ */ new Date()).toISOString();
      startup.processToListenMs = Math.round(process.uptime() * 1e3);
      startup.runQwenServeToListenMs = Math.round(
        performance.now() - runStartedAt
      );
      profileCheckpoint("serve_listener_ready");
      finalizeStartupProfile(daemonLog.getDaemonId() || "serve");
      const cap = opts.maxConnections ?? 256;
      if (cap > 0 && Number.isFinite(cap)) {
        server.maxConnections = cap;
      }
      const addr = server.address();
      actualPort = typeof addr === "object" && addr ? addr.port : opts.port;
      const url = `http://${formatHostForUrl(opts.hostname)}:${actualPort}`;
      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.`
        );
      } 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;
      const runtimeStartupTimeoutMs = resolveRuntimeStartupTimeoutMs(
        deps.runtimeStartupTimeoutMs
      );
      const clearRuntimeStartupTimer = /* @__PURE__ */ __name(() => {
        if (!runtimeStartupTimer) return;
        clearTimeout(runtimeStartupTimer);
        runtimeStartupTimer = void 0;
      }, "clearRuntimeStartupTimer");
      const shutdownBridgeAfterFailedStartup = /* @__PURE__ */ __name(async (bridge) => {
        if (!bridge || deps.bridge) return;
        try {
          await bridge.shutdown();
        } catch (shutdownErr) {
          daemonLog.error(
            "bridge shutdown after runtime startup error failed",
            shutdownErr instanceof Error ? shutdownErr : null
          );
        } finally {
          if (bridgeRef === bridge) {
            bridgeRef = void 0;
          }
        }
      }, "shutdownBridgeAfterFailedStartup");
      const 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);
        markRuntimeFailed(error);
        await shutdownBridgeAfterFailedStartup(bridgeForCleanup ?? bridgeRef);
      }, "failRuntimeStartup");
      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;
        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);
          }
          runtimeStartupSettled = true;
          clearRuntimeStartupTimer();
          markRuntimeReady();
        }).catch((err) => failRuntimeStartup(err));
        if (runtimeStartupTimeoutMs > 0) {
          runtimeStartupTimer = setTimeout(() => {
            void failRuntimeStartup(
              new Error(
                `Daemon runtime startup timed out after ${runtimeStartupTimeoutMs}ms.`
              )
            );
          }, runtimeStartupTimeoutMs);
          runtimeStartupTimer.unref();
        }
      }, "startRuntime");
      const onSignal = /* @__PURE__ */ __name(async (signal) => {
        if (shuttingDown) {
          daemonLog.warn(`received ${signal} during drain \u2014 forcing exit`);
          try {
            bridgeRef?.killAllSync();
          } catch (err) {
            daemonLog.error(
              "force-kill error",
              err instanceof Error ? err : null
            );
          }
          await daemonLog.flush().catch(() => {
          });
          process.exit(1);
          return;
        }
        daemonLog.warn(`received ${signal}, draining`);
        try {
          await handle.close();
          await daemonLog.flush();
          process.exit(0);
        } catch (err) {
          daemonLog.error("shutdown error", err instanceof Error ? err : null);
          await daemonLog.flush().catch(() => {
          });
          process.exit(1);
        }
      }, "onSignal");
      const handle = {
        server,
        url,
        bridge: handleBridge,
        webShellMounted,
        resolvedToken: token,
        runtimeReady,
        close: /* @__PURE__ */ __name(() => {
          if (closePromise) return closePromise;
          closePromise = new Promise((res, rej) => {
            shuttingDown = true;
            let settled = false;
            let bridgeShutdownError;
            const finish = /* @__PURE__ */ __name((err) => {
              if (settled) return;
              settled = true;
              process.removeListener("SIGINT", onSignal);
              process.removeListener("SIGTERM", onSignal);
              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();
              }
              const bridgeForShutdown = bridgeRef;
              if (bridgeForShutdown) {
                await bridgeForShutdown.shutdown().catch((err) => {
                  daemonLog.error(
                    "bridge shutdown error",
                    err instanceof Error ? err : null
                  );
                  bridgeShutdownError = err instanceof Error ? err : new Error(String(err));
                });
              }
            }).finally(() => {
              const SECONDARY_DEADLINE_MS = 2e3;
              let secondaryTimer;
              const forceTimer = setTimeout(() => {
                daemonLog.warn(
                  `${SHUTDOWN_FORCE_CLOSE_MS}ms listener-drain timeout reached; force-closing remaining connections`
                );
                server.closeAllConnections();
                secondaryTimer = setTimeout(() => {
                  daemonLog.warn(
                    `server.close did not fire ${SECONDARY_DEADLINE_MS}ms after force-close; resolving anyway`
                  );
                  finish();
                }, SECONDARY_DEADLINE_MS);
                secondaryTimer.unref();
              }, SHUTDOWN_FORCE_CLOSE_MS);
              forceTimer.unref();
              server.close((err) => {
                clearTimeout(forceTimer);
                if (secondaryTimer) clearTimeout(secondaryTimer);
                finish(err);
              });
            });
          });
          return closePromise;
        }, "close")
      };
      process.on("SIGINT", onSignal);
      process.on("SIGTERM", onSignal);
      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);
        }
      } 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)));
            });
          }
        );
      }
    });
    server.once("error", reject);
  });
}
__name(runQwenServe, "runQwenServe");
export {
  InvalidPolicyConfigError,
  createLazyBridgeProxy,
  extractContextFilename,
  resolveRuntimeStartupTimeoutMs,
  runQwenServe,
  validatePolicyConfig,
  waitForRuntimeStartingForShutdown
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
