// Force strict mode and setup for ESM
"use strict";
import {
  HistoryReplayer
} from "./chunk-VUNRNRN6.js";
import {
  ChannelDeliveryError,
  MAX_CHANNEL_DELIVERY_TEXT_LENGTH
} from "./chunk-QONSRAEV.js";
import {
  redactLogCredentials
} from "./chunk-M5GB774H.js";
import {
  getUserSettingsPath,
  loadSettings
} from "./chunk-22YFMJBW.js";
import {
  getSystemDefaultsPath,
  getSystemSettingsPath
} from "./chunk-IDS7MSUP.js";
import {
  findEnvFiles,
  preResolveHomeEnvOverrides
} from "./chunk-6NE5NTHJ.js";
import {
  getResponseText,
  ideContextStore
} from "./chunk-UQDFEU47.js";
import {
  MAX_CHANNEL_DELIVERY_NAME_LENGTH,
  MAX_CHANNEL_DELIVERY_TARGET_ID_LENGTH
} from "./chunk-MOHAWIAW.js";
import {
  parseGoalSnapshotV2
} from "./chunk-HFVW54NL.js";
import {
  Storage,
  createDebugLogger
} from "./chunk-3RXUYQJI.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/runtime/workspace-remember-errors.ts
init_esbuild_shims();
var MAX_REMEMBER_ERROR_DETAILS_CHARS = 1e3;
var MAX_REMEMBER_ERROR_CAUSE_DEPTH = 50;
var REMEMBER_ERROR_FORMAT_RE = new RegExp("[\\p{Cf}]|\\p{Variation_Selector}", "gu");
var REMEMBER_ERROR_SPACE_SEPARATOR_RE = /[\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/gu;
var REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE = new RegExp("[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector}", "gu");
var REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE = new RegExp("\\b(Bearer|QQBot)(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+(?=[A-Za-z0-9._~+/=-])", "giu");
var REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE = new RegExp("\\b(Bearer|QQBot)(?:\\s|[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+((?:[A-Za-z0-9._~+/=-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9._~+/=-]+)", "giu");
var REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE = new RegExp("\\b(?:sk-|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xox[b]-|xox[p]-)(?:[A-Za-z0-9_-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9_-]+", "gu");
var REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE = new RegExp("\\b(?:AKIA|ASIA)(?:[A-Z0-9]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Z0-9]+", "gu");
var REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE = new RegExp("((?:api[_-]?key|token|secret|password|pwd)[_-]?[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)", "giu");
var REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE = new RegExp("([A-Z][A-Z0-9]{0,50}(?:_[A-Z0-9]{1,50}){0,10}_(?:KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)", "gu");
var REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE = new RegExp("(\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/)([^/@\\s]*(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+[^/@\\s]*)@", "giu");
var REMEMBER_ERROR_CONTROL_RE = /[\x00-\x1f\x7f-\x9f]/g;
var DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES = /* @__PURE__ */ new Set([
  "managed_memory_unavailable"
]);
function createWorkspaceMemoryExtractionErrorLogger(logger) {
  return (target, err) => {
    logger.warn(`Failed to extract workspace memory error ${target}:`, {
      extractionError: err instanceof Error ? err.message : String(err)
    });
  };
}
__name(createWorkspaceMemoryExtractionErrorLogger, "createWorkspaceMemoryExtractionErrorLogger");
function reportRememberErrorExtractionFailure(onExtractionError, target, err) {
  try {
    onExtractionError?.(target, err);
  } catch {
  }
}
__name(reportRememberErrorExtractionFailure, "reportRememberErrorExtractionFailure");
function errorCodeFromRecord(record) {
  if (typeof record["code"] === "string") return record["code"];
  const data = record["data"];
  if (data && typeof data === "object") {
    const dataRecord = data;
    if (typeof dataRecord["errorKind"] === "string") {
      return dataRecord["errorKind"];
    }
    if (typeof dataRecord["code"] === "string") return dataRecord["code"];
  }
  return void 0;
}
__name(errorCodeFromRecord, "errorCodeFromRecord");
function rawRememberErrorCode(err, seen, depth) {
  if (depth > MAX_REMEMBER_ERROR_CAUSE_DEPTH) return void 0;
  if (!err || typeof err !== "object") return void 0;
  if (seen.has(err)) return void 0;
  seen.add(err);
  const record = err;
  const direct = errorCodeFromRecord(record);
  if (direct) return direct;
  const cause = record["cause"];
  if (cause != null) {
    return rawRememberErrorCode(cause, seen, depth + 1);
  }
  return void 0;
}
__name(rawRememberErrorCode, "rawRememberErrorCode");
function extractRememberErrorCode(err, fallback = "remember_failed") {
  return rawRememberErrorCode(err, /* @__PURE__ */ new WeakSet(), 0) ?? fallback;
}
__name(extractRememberErrorCode, "extractRememberErrorCode");
function workspaceMemoryFailureCode(err, fallback = "remember_failed", onExtractionError) {
  try {
    return extractRememberErrorCode(err, fallback);
  } catch (extractionErr) {
    reportRememberErrorExtractionFailure(
      onExtractionError,
      "code",
      extractionErr
    );
    return fallback;
  }
}
__name(workspaceMemoryFailureCode, "workspaceMemoryFailureCode");
function detailFromRecord(record, seen, depth) {
  const data = record["data"];
  if (data && typeof data === "object") {
    const dataRecord = data;
    const details = dataRecord["details"];
    if (typeof details === "string" && details.length > 0) return details;
    const message2 = dataRecord["message"];
    if (typeof message2 === "string" && message2.length > 0) return message2;
  }
  const message = record["message"];
  if (typeof message === "string" && message.length > 0) return message;
  if (typeof data === "string" && data.length > 0) return data;
  const cause = record["cause"];
  if (cause != null) {
    return rawRememberErrorDetails(cause, seen, depth + 1);
  }
  return void 0;
}
__name(detailFromRecord, "detailFromRecord");
function rawRememberErrorDetails(err, seen, depth) {
  if (depth > MAX_REMEMBER_ERROR_CAUSE_DEPTH) return void 0;
  if (typeof err === "string" && err.length > 0) return err;
  if (!err || typeof err !== "object") return void 0;
  if (seen.has(err)) return void 0;
  seen.add(err);
  return detailFromRecord(err, seen, depth);
}
__name(rawRememberErrorDetails, "rawRememberErrorDetails");
function replaceControlChars(details) {
  return details.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE, "$1 ").replace(REMEMBER_ERROR_FORMAT_RE, "").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE, " ").replace(REMEMBER_ERROR_CONTROL_RE, " ");
}
__name(replaceControlChars, "replaceControlChars");
function replaceStackControlChars(stack) {
  return stack.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE, "$1 ").replace(REMEMBER_ERROR_FORMAT_RE, "").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE, " ").replace(
    REMEMBER_ERROR_CONTROL_RE,
    (char) => char === "\n" || char === "\r" || char === "	" ? char : " "
  );
}
__name(replaceStackControlChars, "replaceStackControlChars");
function collapseCredentialSeparators(text) {
  return text.replace(
    REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE,
    (_match, scheme, userinfo) => `${scheme}${userinfo.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE, "")}@`
  ).replace(
    REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE,
    (_match, scheme, token) => `${scheme} ${token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE, "")}`
  ).replace(
    REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE,
    (token) => token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE, "")
  ).replace(
    REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE,
    (token) => token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE, "")
  ).replace(
    REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,
    (_match, prefix, value) => `${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE, "")}`
  ).replace(
    REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,
    (_match, prefix, value) => `${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE, "")}`
  );
}
__name(collapseCredentialSeparators, "collapseCredentialSeparators");
function collapseCredentialSeparatorsByStackLine(stack) {
  return stack.split(/(\r\n|\n|\r)/).map(
    (part) => part === "\r\n" || part === "\n" || part === "\r" ? part : collapseCredentialSeparators(part)
  ).join("");
}
__name(collapseCredentialSeparatorsByStackLine, "collapseCredentialSeparatorsByStackLine");
function isHighSurrogate(codeUnit) {
  return codeUnit >= 55296 && codeUnit <= 56319;
}
__name(isHighSurrogate, "isHighSurrogate");
function isLowSurrogate(codeUnit) {
  return codeUnit >= 56320 && codeUnit <= 57343;
}
__name(isLowSurrogate, "isLowSurrogate");
function truncateBeforeDanglingSurrogate(details, cutPoint) {
  const beforeCut = details.charCodeAt(cutPoint - 1);
  const atCut = details.charCodeAt(cutPoint);
  if (isHighSurrogate(beforeCut) && isLowSurrogate(atCut)) {
    return cutPoint - 1;
  }
  return cutPoint;
}
__name(truncateBeforeDanglingSurrogate, "truncateBeforeDanglingSurrogate");
function capRememberErrorText(redacted) {
  if (redacted.length <= MAX_REMEMBER_ERROR_DETAILS_CHARS) return redacted;
  const truncationSuffix = "... [truncated]";
  const cutPoint = truncateBeforeDanglingSurrogate(
    redacted,
    MAX_REMEMBER_ERROR_DETAILS_CHARS - truncationSuffix.length
  );
  return `${redacted.slice(0, cutPoint)}${truncationSuffix}`;
}
__name(capRememberErrorText, "capRememberErrorText");
function redactAndCapRememberErrorText(normalized) {
  const redacted = redactLogCredentials(normalized).trim();
  if (!redacted) return void 0;
  return capRememberErrorText(redacted);
}
__name(redactAndCapRememberErrorText, "redactAndCapRememberErrorText");
function sanitizeRememberErrorDetails(details) {
  return redactAndCapRememberErrorText(
    replaceControlChars(collapseCredentialSeparators(details))
  );
}
__name(sanitizeRememberErrorDetails, "sanitizeRememberErrorDetails");
function sanitizeRememberErrorStack(stack) {
  return redactAndCapRememberErrorText(
    replaceStackControlChars(collapseCredentialSeparatorsByStackLine(stack))
  );
}
__name(sanitizeRememberErrorStack, "sanitizeRememberErrorStack");
function extractRememberErrorDetails(err) {
  const raw = rawRememberErrorDetails(err, /* @__PURE__ */ new WeakSet(), 0);
  if (!raw) return void 0;
  return sanitizeRememberErrorDetails(raw);
}
__name(extractRememberErrorDetails, "extractRememberErrorDetails");
function extractRememberErrorStack(err) {
  if (!(err instanceof Error) || !err.stack) return void 0;
  return sanitizeRememberErrorStack(err.stack);
}
__name(extractRememberErrorStack, "extractRememberErrorStack");
function shouldSuppressRememberErrorDetails(code) {
  return DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES.has(code);
}
__name(shouldSuppressRememberErrorDetails, "shouldSuppressRememberErrorDetails");
function workspaceMemoryFailureDiagnostics(err, onExtractionError) {
  let details;
  let stack;
  try {
    details = extractRememberErrorDetails(err);
  } catch (extractionErr) {
    reportRememberErrorExtractionFailure(
      onExtractionError,
      "details",
      extractionErr
    );
    details = void 0;
  }
  try {
    stack = extractRememberErrorStack(err);
  } catch (extractionErr) {
    reportRememberErrorExtractionFailure(
      onExtractionError,
      "stack",
      extractionErr
    );
    stack = void 0;
  }
  return {
    ...details ? { details } : {},
    debugDetails: details ?? "<details unavailable>",
    ...stack ? { stack } : {}
  };
}
__name(workspaceMemoryFailureDiagnostics, "workspaceMemoryFailureDiagnostics");

// packages/cli/src/runtime/workspace-memory-remember-constants.ts
init_esbuild_shims();
var MAX_REMEMBER_CONTENT_BYTES = 64 * 1024;

// packages/cli/src/runtime/workspace-memory-summaries.ts
init_esbuild_shims();
function formatWorkspaceMemoryForgetSummary(removedEntryCount) {
  return removedEntryCount > 0 ? `Forgot ${removedEntryCount} memory entr${removedEntryCount === 1 ? "y" : "ies"}.` : "No managed auto-memory entries matched.";
}
__name(formatWorkspaceMemoryForgetSummary, "formatWorkspaceMemoryForgetSummary");
function formatWorkspaceMemoryDreamSummary(touchedTopicCount) {
  return touchedTopicCount > 0 ? "Managed auto-memory dream completed." : "No managed auto-memory topics changed.";
}
__name(formatWorkspaceMemoryDreamSummary, "formatWorkspaceMemoryDreamSummary");

// packages/cli/src/config/mcp-server-secrets.ts
init_esbuild_shims();
var REDACTED_MCP_SECRET = "__redacted__";
function recordOf(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}
__name(recordOf, "recordOf");
function redactRecord(record) {
  return record ? Object.fromEntries(
    Object.keys(record).map((key) => [key, REDACTED_MCP_SECRET])
  ) : record;
}
__name(redactRecord, "redactRecord");
function restoreRecord(incoming, prior) {
  if (!incoming) return incoming;
  const priorRecord = recordOf(prior);
  const result = {};
  for (const [key, value] of Object.entries(incoming)) {
    if (value !== REDACTED_MCP_SECRET) {
      result[key] = value;
    } else if (typeof priorRecord[key] === "string") {
      result[key] = priorRecord[key];
    }
  }
  return result;
}
__name(restoreRecord, "restoreRecord");
function redactMcpServerSecrets(server) {
  return {
    ...server,
    env: redactRecord(server.env),
    headers: redactRecord(server.headers),
    ...server.oauth?.clientSecret ? {
      oauth: {
        ...server.oauth,
        clientSecret: REDACTED_MCP_SECRET
      }
    } : {}
  };
}
__name(redactMcpServerSecrets, "redactMcpServerSecrets");
function restoreRedactedMcpSecrets(server, existing) {
  const existingOauth = recordOf(existing["oauth"]);
  const incomingSecret = server.oauth?.clientSecret;
  const restoredSecret = incomingSecret === REDACTED_MCP_SECRET ? existingOauth["clientSecret"] : incomingSecret;
  return {
    ...server,
    env: restoreRecord(server.env, existing["env"]),
    headers: restoreRecord(server.headers, existing["headers"]),
    ...server.oauth ? {
      oauth: {
        ...server.oauth,
        ...typeof restoredSecret === "string" ? { clientSecret: restoredSecret } : { clientSecret: void 0 }
      }
    } : {}
  };
}
__name(restoreRedactedMcpSecrets, "restoreRedactedMcpSecrets");
function redactMcpServersSetting(value) {
  const servers = recordOf(value);
  return Object.fromEntries(
    Object.entries(servers).map(([name, server]) => {
      const record = recordOf(server);
      return [name, redactMcpServerSecrets(record)];
    })
  );
}
__name(redactMcpServersSetting, "redactMcpServersSetting");
function restoreRedactedMcpServersSetting(value, existing) {
  const servers = recordOf(value);
  const existingServers = recordOf(existing);
  return Object.fromEntries(
    Object.entries(servers).map(([name, server]) => {
      const record = recordOf(server);
      return [
        name,
        restoreRedactedMcpSecrets(record, recordOf(existingServers[name]))
      ];
    })
  );
}
__name(restoreRedactedMcpServersSetting, "restoreRedactedMcpServersSetting");

// packages/cli/src/runtime/validate-server-name.ts
init_esbuild_shims();
var VALID_SERVER_NAME = /^[A-Za-z0-9_-]+$/;
var RESERVED_SERVER_NAMES = /* @__PURE__ */ new Set([
  "__proto__",
  "constructor",
  "prototype"
]);
function isValidServerName(name) {
  return typeof name === "string" && name.length > 0 && name.length <= 256 && VALID_SERVER_NAME.test(name) && !RESERVED_SERVER_NAMES.has(name);
}
__name(isValidServerName, "isValidServerName");

// packages/cli/src/acp-integration/generation.ts
init_esbuild_shims();
var GENERATION_MAX_PROMPT_BYTES = 32 * 1024;
var GENERATION_TIMEOUT_MS = 6e4;
async function executeGeneration(config, requestId, prompt, signal, emit) {
  const fastModel = config.getFastModel();
  const mainModel = config.getModel();
  const client = config.getBaseLlmClient();
  let modelSource = fastModel ? "fast" : "main";
  let resolved;
  if (fastModel) {
    try {
      resolved = await client.resolveForModel(fastModel, { failClosed: true });
    } catch {
      modelSource = "main";
    }
  }
  resolved ??= await client.resolveForModel(mainModel, { failClosed: true });
  const { contentGenerator, model } = resolved;
  await emit({ type: "started", model, modelSource });
  const stream = await contentGenerator.generateContentStream(
    {
      model,
      contents: [{ role: "user", parts: [{ text: prompt }] }],
      config: {
        abortSignal: signal,
        tools: [],
        thinkingConfig: { thinkingBudget: 0, includeThoughts: false },
        temperature: 0.2
      }
    },
    `generation:${requestId}`
  );
  let seq = 0;
  let thinkingEmitted = false;
  let usage;
  for await (const chunk of stream) {
    if (!thinkingEmitted && chunk.candidates?.some(
      (candidate) => candidate.content?.parts?.some((part) => part.thought === true)
    )) {
      thinkingEmitted = true;
      await emit({ type: "thinking" });
    }
    const text = getResponseText(chunk) ?? "";
    if (text) {
      await emit({ type: "delta", seq: seq++, text });
    }
    if (chunk.usageMetadata) usage = chunk.usageMetadata;
  }
  return {
    model,
    modelSource,
    ...usage?.promptTokenCount !== void 0 ? { inputTokens: usage.promptTokenCount } : {},
    ...usage?.candidatesTokenCount !== void 0 ? { outputTokens: usage.candidatesTokenCount } : {}
  };
}
__name(executeGeneration, "executeGeneration");

// packages/cli/src/config/settings-cache.ts
init_esbuild_shims();
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
var MAX_CACHE_ENTRIES = 64;
var debugLogger = createDebugLogger("SETTINGS_CACHE");
var cache = /* @__PURE__ */ new Map();
function statSig(filePath) {
  const st = fs.statSync(filePath, { throwIfNoEntry: false });
  return st ? `${st.mtimeMs}:${st.size}:${st.ino}` : "missing";
}
__name(statSig, "statSig");
function realpathOr(p) {
  try {
    return fs.realpathSync(p);
  } catch {
    return path.resolve(p);
  }
}
__name(realpathOr, "realpathOr");
function settingsFileSigs(workspaceDir) {
  const filePaths = [
    getSystemSettingsPath(),
    getSystemDefaultsPath(),
    getUserSettingsPath(),
    new Storage(workspaceDir).getWorkspaceSettingsPath()
  ];
  return filePaths.map((filePath) => ({ filePath, sig: statSig(filePath) }));
}
__name(settingsFileSigs, "settingsFileSigs");
function envFileSigs(settings, workspaceDir) {
  return findEnvFiles(settings.merged, workspaceDir).map((filePath) => ({
    filePath,
    sig: statSig(filePath)
  }));
}
__name(envFileSigs, "envFileSigs");
function sameFileSigs(a, b) {
  if (a.length !== b.length) {
    return false;
  }
  return a.every(
    (sig, i) => sig.filePath === b[i].filePath && sig.sig === b[i].sig
  );
}
__name(sameFileSigs, "sameFileSigs");
function isEntryFresh(key, entry) {
  const fp = entry.fingerprint;
  return ideContextStore.get()?.workspaceState?.isTrusted === fp.ideTrust && realpathOr(key) === fp.realCwd && // homeDir guards the corner where nothing else moves: QWEN_HOME set (so
  // settings paths don't follow HOME), no .env files anywhere, and the new
  // home equals the workspace dir — which flips workspaceSettingsActive.
  realpathOr(os.homedir()) === fp.homeDir && sameFileSigs(settingsFileSigs(key), fp.settingsFiles) && sameFileSigs(envFileSigs(entry.settings, key), fp.envFiles);
}
__name(isEntryFresh, "isEntryFresh");
function loadSettingsCached(workspaceDir) {
  preResolveHomeEnvOverrides();
  const key = path.resolve(workspaceDir);
  const entry = cache.get(key);
  if (entry) {
    let isFresh = false;
    try {
      isFresh = isEntryFresh(key, entry);
    } catch (error) {
      debugLogger.warn(
        `fingerprint check failed for ${key}; reloading:`,
        error
      );
    }
    if (isFresh) {
      cache.delete(key);
      cache.set(key, entry);
      debugLogger.debug(`hit ${key}`);
      return entry.settings;
    }
    cache.delete(key);
  }
  debugLogger.debug(`miss ${key}`);
  let preLoadSigs;
  try {
    preLoadSigs = settingsFileSigs(key);
  } catch (error) {
    debugLogger.warn(`pre-load signing failed for ${key}; not caching:`, error);
  }
  const settings = loadSettings(key);
  if (preLoadSigs) {
    try {
      cache.set(key, {
        settings,
        fingerprint: {
          settingsFiles: preLoadSigs,
          // .env discovery needs the merged settings (trust), so it can only
          // be signed after the load — see difference (2) in the module doc.
          envFiles: envFileSigs(settings, key),
          ideTrust: ideContextStore.get()?.workspaceState?.isTrusted,
          realCwd: realpathOr(key),
          homeDir: realpathOr(os.homedir())
        }
      });
      if (cache.size > MAX_CACHE_ENTRIES) {
        const oldest = cache.keys().next().value;
        if (oldest !== void 0) {
          cache.delete(oldest);
          debugLogger.debug(`evicted LRU entry ${oldest}`);
        }
      }
    } catch (error) {
      cache.delete(key);
      debugLogger.warn(`caching failed for ${key}; serving uncached:`, error);
    }
  }
  return settings;
}
__name(loadSettingsCached, "loadSettingsCached");

// packages/cli/src/acp-integration/session/history-replay-page.ts
init_esbuild_shims();
function createReplayCumulativeUsage() {
  return {
    promptTokens: 0,
    cachedTokens: 0,
    candidateTokens: 0,
    apiTimeMs: 0
  };
}
__name(createReplayCumulativeUsage, "createReplayCumulativeUsage");
function copyCumulativeUsage(target, source) {
  target.promptTokens = source.promptTokens;
  target.cachedTokens = source.cachedTokens;
  target.candidateTokens = source.candidateTokens;
  target.apiTimeMs = source.apiTimeMs;
}
__name(copyCumulativeUsage, "copyCumulativeUsage");
function isObjectRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isObjectRecord, "isObjectRecord");
function isCumulativeUsage(value) {
  if (!isObjectRecord(value)) return false;
  return typeof value["promptTokens"] === "number" && Number.isFinite(value["promptTokens"]) && typeof value["cachedTokens"] === "number" && Number.isFinite(value["cachedTokens"]) && typeof value["candidateTokens"] === "number" && Number.isFinite(value["candidateTokens"]) && typeof value["apiTimeMs"] === "number" && Number.isFinite(value["apiTimeMs"]);
}
__name(isCumulativeUsage, "isCumulativeUsage");
function isPendingReplayToolCall(value) {
  if (!isObjectRecord(value)) return false;
  return typeof value["callId"] === "string" && typeof value["toolName"] === "string" && (value["timestamp"] === void 0 || typeof value["timestamp"] === "string") && typeof value["recordId"] === "string";
}
__name(isPendingReplayToolCall, "isPendingReplayToolCall");
function isCurrentPendingReplayToolCall(value) {
  if (!isObjectRecord(value)) return false;
  return typeof value["callId"] === "string" && typeof value["toolName"] === "string" && typeof value["sourceRecordId"] === "string" && (value["sourceTimestamp"] === void 0 || typeof value["sourceTimestamp"] === "string");
}
__name(isCurrentPendingReplayToolCall, "isCurrentPendingReplayToolCall");
function parseTranscriptReplayState(replay, logger) {
  if (!isObjectRecord(replay)) {
    return {
      pendingToolCalls: [],
      cumulativeUsage: createReplayCumulativeUsage()
    };
  }
  if ("v" in replay && replay["v"] !== 1) {
    throw new TypeError("Unsupported transcript replay state version.");
  }
  const rawPending = replay["pendingToolCalls"];
  const pendingToolCalls = Array.isArray(rawPending) ? rawPending.flatMap((pending) => {
    if (isPendingReplayToolCall(pending)) return [pending];
    if (isCurrentPendingReplayToolCall(pending)) {
      return [
        {
          callId: pending.callId,
          toolName: pending.toolName,
          recordId: pending.sourceRecordId,
          ...pending.sourceTimestamp ? { timestamp: pending.sourceTimestamp } : {}
        }
      ];
    }
    return [];
  }) : [];
  if (logger && Array.isArray(rawPending) && pendingToolCalls.length !== rawPending.length) {
    const dropped = rawPending.length - pendingToolCalls.length;
    logger.warn(
      `[transcript] replay state dropped ${dropped} of ${rawPending.length} malformed pending tool calls`
    );
  }
  const cumulativeUsage = isCumulativeUsage(replay["cumulativeUsage"]) ? { ...replay["cumulativeUsage"] } : createReplayCumulativeUsage();
  const rawGoalState = replay["goalState"];
  const goalState = rawGoalState === void 0 ? void 0 : parseGoalSnapshotV2(rawGoalState);
  if (logger && rawGoalState !== void 0 && !goalState) {
    logger.warn("[transcript] replay state dropped a malformed Goal state");
  }
  return {
    pendingToolCalls,
    cumulativeUsage,
    ...goalState ? { goalState } : {}
  };
}
__name(parseTranscriptReplayState, "parseTranscriptReplayState");
function replayContext(sessionId, updates, cumulativeUsage, config) {
  let activeRecordId = null;
  return {
    sessionId,
    sendUpdate: /* @__PURE__ */ __name(async (update) => {
      if (activeRecordId === null) {
        updates.push(update);
        return;
      }
      const record = update;
      const meta = isObjectRecord(record["_meta"]) ? record["_meta"] : {};
      updates.push({
        ...record,
        _meta: { ...meta, "qwen.session.recordId": activeRecordId }
      });
    }, "sendUpdate"),
    setActiveRecordId: /* @__PURE__ */ __name((recordId) => {
      activeRecordId = recordId;
    }, "setActiveRecordId"),
    cumulativeUsage,
    ...config ? { config } : {}
  };
}
__name(replayContext, "replayContext");
async function collectHistoryReplayUpdates({
  sessionId,
  config,
  records,
  gaps,
  cumulativeUsage,
  logger,
  supersedeUnrestorableGoal
}) {
  const updates = [];
  try {
    await new HistoryReplayer(
      replayContext(sessionId, updates, cumulativeUsage, config),
      { supersedeUnrestorableGoal }
    ).replay(records, gaps);
  } catch (error) {
    const replayError = error instanceof Error ? error.message : String(error);
    logger?.warn(
      "[historyReplay] History replay failed for session %s (partial updates: %d):",
      sessionId,
      updates.length,
      error
    );
    return { updates: liftSessionUpdateTimestamps(updates), replayError };
  }
  return { updates: liftSessionUpdateTimestamps(updates) };
}
__name(collectHistoryReplayUpdates, "collectHistoryReplayUpdates");
function liftSessionUpdateTimestamps(updates) {
  return updates.map((update) => {
    const record = update;
    const meta = record["_meta"];
    const timestamp = isObjectRecord(meta) ? meta["timestamp"] : void 0;
    return typeof timestamp === "number" || typeof timestamp === "string" ? { ...record, timestamp } : update;
  });
}
__name(liftSessionUpdateTimestamps, "liftSessionUpdateTimestamps");
async function replayTranscriptRecordPage({
  sessionId,
  page,
  config,
  encodeCursor,
  logger
}) {
  const state = parseTranscriptReplayState(page.replay, logger);
  const updates = [];
  const replayer = new HistoryReplayer(
    replayContext(sessionId, updates, state.cumulativeUsage, config)
  );
  let replayState;
  let replayError;
  try {
    const replayPageState = await replayer.replayPage(page.records, {
      pendingToolCalls: page.direction === "backward" ? [] : state.pendingToolCalls,
      finalizeDangling: page.direction === "backward" || !page.hasMore,
      gaps: page.gaps,
      ...state.goalState ? { goalState: state.goalState } : {}
    });
    replayState = replayPageState.replay;
  } catch (error) {
    logger?.warn(
      "[historyReplay] Paged history replay failed for session %s (partial updates: %d):",
      sessionId,
      updates.length,
      error
    );
    replayState = replayer.getReplayState();
    replayError = "Replay conversion failed for this page";
  }
  const nextCursor = page.nextCursorState && replayError === void 0 ? encodeCursor({
    ...page.nextCursorState,
    ...page.direction === "backward" ? {} : { replay: replayState }
  }) : void 0;
  return {
    updates: liftSessionUpdateTimestamps(updates),
    ...nextCursor ? { nextCursor } : {},
    hasMore: replayError === void 0 && page.hasMore,
    startTime: page.startTime,
    lastUpdated: page.lastUpdated,
    ...replayError ? { partial: true, replayError } : {}
  };
}
__name(replayTranscriptRecordPage, "replayTranscriptRecordPage");

// packages/cli/src/runtime/channel-delivery.ts
init_esbuild_shims();
var TRUNCATED_TEXT_SUFFIX = "\n\n[Channel delivery truncated because the result exceeded the delivery size limit.]";
function isBoundedString(value, maxLength) {
  return typeof value === "string" && value.trim().length > 0 && value.length <= maxLength;
}
__name(isBoundedString, "isBoundedString");
function parseChannelDelivery(value) {
  if (typeof value !== "object" || value === null) {
    throw new ChannelDeliveryError(
      "channel_delivery_invalid",
      "Invalid channel delivery."
    );
  }
  const delivery = value;
  const rawTarget = delivery["target"];
  if (delivery["kind"] !== "channel" || typeof rawTarget !== "object" || rawTarget === null || !Object.keys(delivery).every((key) => key === "kind" || key === "target")) {
    throw new ChannelDeliveryError(
      "channel_delivery_invalid",
      "Invalid channel delivery."
    );
  }
  const target = rawTarget;
  if (!isBoundedString(target["channelName"], MAX_CHANNEL_DELIVERY_NAME_LENGTH) || target["type"] !== "user" && target["type"] !== "chat" || !isBoundedString(target["id"], MAX_CHANNEL_DELIVERY_TARGET_ID_LENGTH) || !Object.keys(target).every(
    (key) => key === "channelName" || key === "type" || key === "id"
  )) {
    throw new ChannelDeliveryError(
      "channel_delivery_invalid",
      "Invalid channel delivery."
    );
  }
  return {
    kind: "channel",
    target: {
      channelName: target["channelName"],
      type: target["type"],
      id: target["id"]
    }
  };
}
__name(parseChannelDelivery, "parseChannelDelivery");
function normalizeChannelDeliveryText(text) {
  if (text.length <= MAX_CHANNEL_DELIVERY_TEXT_LENGTH) return text;
  const prefixLimit = MAX_CHANNEL_DELIVERY_TEXT_LENGTH - TRUNCATED_TEXT_SUFFIX.length;
  let prefix = text.slice(0, prefixLimit);
  const lastCodeUnit = prefix.charCodeAt(prefix.length - 1);
  if (lastCodeUnit >= 55296 && lastCodeUnit <= 56319) {
    prefix = prefix.slice(0, -1);
  }
  return `${prefix}${TRUNCATED_TEXT_SUFFIX}`;
}
__name(normalizeChannelDeliveryText, "normalizeChannelDeliveryText");
function normalizeChannelDelivery(deliveryId, delivery, text) {
  if (typeof text !== "string" || text.trim().length === 0) {
    throw new ChannelDeliveryError(
      "channel_delivery_invalid",
      "Channel delivery text is empty."
    );
  }
  return {
    deliveryId,
    channelName: delivery.target.channelName,
    target: { type: delivery.target.type, id: delivery.target.id },
    text: normalizeChannelDeliveryText(text)
  };
}
__name(normalizeChannelDelivery, "normalizeChannelDelivery");

export {
  createWorkspaceMemoryExtractionErrorLogger,
  extractRememberErrorCode,
  workspaceMemoryFailureCode,
  shouldSuppressRememberErrorDetails,
  workspaceMemoryFailureDiagnostics,
  MAX_REMEMBER_CONTENT_BYTES,
  formatWorkspaceMemoryForgetSummary,
  formatWorkspaceMemoryDreamSummary,
  REDACTED_MCP_SECRET,
  redactMcpServerSecrets,
  restoreRedactedMcpSecrets,
  redactMcpServersSetting,
  restoreRedactedMcpServersSetting,
  isValidServerName,
  GENERATION_MAX_PROMPT_BYTES,
  GENERATION_TIMEOUT_MS,
  executeGeneration,
  loadSettingsCached,
  parseChannelDelivery,
  normalizeChannelDeliveryText,
  normalizeChannelDelivery,
  createReplayCumulativeUsage,
  copyCumulativeUsage,
  collectHistoryReplayUpdates,
  replayTranscriptRecordPage
};
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
