// Force strict mode and setup for ESM
"use strict";
import {
  createDebugLogger
} from "./chunk-OQB4EXO4.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/core/src/core/tokenLimits.ts
init_esbuild_shims();
var DEFAULT_TOKEN_LIMIT = 2e5;
var DEFAULT_OUTPUT_TOKEN_LIMIT = 32e3;
var ESCALATED_MAX_TOKENS = 64e3;
var OUTPUT_TOKEN_CEILING = ESCALATED_MAX_TOKENS;
var MIN_CLAMPED_OUTPUT_TOKENS = 4e3;
function outputClampMargin(contextWindowSize) {
  return Math.max(1e4, Math.round(0.05 * contextWindowSize));
}
__name(outputClampMargin, "outputClampMargin");
function clampOutputTokensToWindow(outputCeiling, contextWindowSize, promptTokens) {
  const room = contextWindowSize - promptTokens - outputClampMargin(contextWindowSize);
  return Math.min(outputCeiling, Math.max(MIN_CLAMPED_OUTPUT_TOKENS, room));
}
__name(clampOutputTokensToWindow, "clampOutputTokensToWindow");
function parsePositiveIntegerEnvValue(raw) {
  if (raw === void 0) return void 0;
  const trimmed = raw.trim();
  if (!/^\d+$/.test(trimmed)) return void 0;
  const parsed = Number(trimmed);
  if (!Number.isSafeInteger(parsed) || parsed <= 0) return void 0;
  return parsed;
}
__name(parsePositiveIntegerEnvValue, "parsePositiveIntegerEnvValue");
var LIMITS = {
  "32k": 32768,
  "64k": 65536,
  "128k": 131072,
  "192k": 196608,
  // MiniMax-M2.5 context window
  "200k": 2e5,
  // vendor-declared decimal, used by OpenAI, Anthropic, etc.
  "256k": 262144,
  "272k": 272e3,
  // vendor-declared decimal, GPT-5.x input (400K total - 128K output)
  "384k": 384e3,
  // vendor-declared decimal, DeepSeek V4 max output
  "400k": 4e5,
  // vendor-declared decimal, used by OpenAI GPT-5.x
  "512k": 524288,
  "1m": 1e6,
  // Output token limits (typically much smaller than input limits)
  "4k": 4096,
  "8k": 8192,
  "16k": 16384
};
function normalize(model) {
  let s = (model ?? "").toLowerCase().trim();
  s = s.replace(/^.*\//, "");
  s = s.split("|").pop() ?? s;
  s = s.split(":").pop() ?? s;
  s = s.replace(/\s+/g, "-");
  s = s.replace(/-preview/g, "");
  if (!s.match(/^qwen-(?:plus|flash|vl-max)-latest$/) && !s.match(/^kimi-k2-\d{4}$/)) {
    s = s.replace(
      /-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,
      ""
    );
  }
  s = s.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g, "");
  return s;
}
__name(normalize, "normalize");
var PATTERNS = [
  // -------------------
  // Google Gemini
  // -------------------
  [/^gemini-3/, LIMITS["1m"]],
  // Gemini 3.x (Pro, Flash, 3.1, etc.): 1M
  [/^gemini-/, LIMITS["1m"]],
  // Gemini fallback (1.5, 2.x): 1M
  // -------------------
  // OpenAI
  // -------------------
  [/^gpt-5/, LIMITS["272k"]],
  // GPT-5.x: 272K input (400K total - 128K output)
  [/^gpt-/, LIMITS["128k"]],
  // GPT fallback (4o, 4.1, etc.): 128K
  [/^o\d/, LIMITS["200k"]],
  // o-series (o3, o4-mini, etc.): 200K
  // -------------------
  // Anthropic Claude
  // -------------------
  [/^claude-opus-4-(?:6|7|8)/, LIMITS["1m"]],
  // Opus 4.6-4.8: 1M
  [/^claude-/, LIMITS["200k"]],
  // All Claude models: 200K
  // -------------------
  // Alibaba / Qwen
  // -------------------
  // Commercial API models (1,000,000 context)
  [/^qwen3-coder-plus/, LIMITS["1m"]],
  [/^qwen3-coder-flash/, LIMITS["1m"]],
  [/^qwen3\.\d/, LIMITS["1m"]],
  [/^qwen-plus-latest$/, LIMITS["1m"]],
  [/^qwen-flash-latest$/, LIMITS["1m"]],
  [/^coder-model$/, LIMITS["1m"]],
  // Commercial API models (256K context)
  [/^qwen3-max/, LIMITS["256k"]],
  // Open-source Qwen3 variants: 256K native
  [/^qwen3-coder-/, LIMITS["256k"]],
  // Qwen fallback (VL, turbo, plus, 2.5, etc.): 256K
  [/^qwen/, LIMITS["256k"]],
  // -------------------
  // DeepSeek
  // -------------------
  [/^deepseek-v4/, LIMITS["1m"]],
  // DeepSeek V4 (flash, pro): 1M
  [/^deepseek/, LIMITS["128k"]],
  // -------------------
  // Zhipu GLM
  // -------------------
  // 1M context is the forward default for new GLM releases (GLM-5.2+, GLM-6.x,
  // and beyond) so they need no future code change. Confirmed 200K families
  // (GLM-5 / 5.0 / 5.1, GLM-4.x and older) are pinned explicitly first.
  [/^glm-5(\.[01])?(-|$)/, 202752],
  // GLM-5 / 5.0 / 5.1: 200K
  [/^glm-(?:[5-9]|\d{2,})/, LIMITS["1m"]],
  // GLM-5.2+, 6.x..9.x, 10.x+: 1M
  [/^glm-/, 202752],
  // GLM <=4.x / non-numeric fallback: 200K
  // -------------------
  // MiniMax
  // -------------------
  [/^minimax-m3/i, LIMITS["1m"]],
  // MiniMax-M3: 1,000,000
  [/^minimax-m2\.5/i, LIMITS["192k"]],
  // MiniMax-M2.5: 196,608
  [/^minimax-/i, LIMITS["200k"]],
  // MiniMax fallback: 200K
  // -------------------
  // Moonshot / Kimi
  // -------------------
  [/^kimi-k3/, LIMITS["1m"]],
  // Kimi K3: 1M
  [/^kimi-/, LIMITS["256k"]],
  // Kimi fallback: 256K
  // -------------------
  // ByteDance Seed-OSS (512K)
  // -------------------
  [/^seed-oss/, LIMITS["512k"]]
];
var OUTPUT_PATTERNS = [
  // Google Gemini
  [/^gemini-3/, LIMITS["64k"]],
  // Gemini 3.x: 64K
  [/^gemini-/, LIMITS["8k"]],
  // Gemini fallback: 8K
  // OpenAI
  [/^gpt-5/, LIMITS["128k"]],
  // GPT-5.x: 128K
  [/^gpt-/, LIMITS["16k"]],
  // GPT fallback: 16K
  [/^o\d/, LIMITS["128k"]],
  // o-series: 128K
  // Anthropic Claude
  [/^claude-opus-4-(?:6|7|8)/, 128e3],
  // Opus 4.6-4.8: 128K
  [/^claude-sonnet-4-6/, LIMITS["64k"]],
  // Sonnet 4.6: 64K
  [/^claude-/, LIMITS["64k"]],
  // Claude fallback: 64K
  // Alibaba / Qwen
  [/^qwen3\.\d/, LIMITS["64k"]],
  [/^coder-model$/, LIMITS["64k"]],
  [/^qwen/, LIMITS["32k"]],
  // Qwen fallback (VL, turbo, plus, etc.): 32K
  // DeepSeek
  [/^deepseek-v4/, LIMITS["384k"]],
  // DeepSeek V4 (flash, pro): 384K
  [/^deepseek-reasoner/, LIMITS["64k"]],
  [/^deepseek-r1/, LIMITS["64k"]],
  [/^deepseek-chat/, LIMITS["8k"]],
  // Zhipu GLM
  [/^glm-5(?:\.\d+)?(?:-|$)/, LIMITS["128k"]],
  [/^glm-4\.7/, LIMITS["16k"]],
  // MiniMax
  [/^minimax-m2\.5/i, LIMITS["64k"]],
  // Kimi
  [/^kimi-k3/, LIMITS["128k"]],
  // Kimi K3: 128K default max output (up to 1M configurable)
  [/^kimi-k2\.5/, LIMITS["32k"]]
];
function findTokenLimit(model, type = "input") {
  const norm = normalize(model);
  const patterns = type === "output" ? OUTPUT_PATTERNS : PATTERNS;
  for (const [regex, limit] of patterns) {
    if (regex.test(norm)) {
      return limit;
    }
  }
  return void 0;
}
__name(findTokenLimit, "findTokenLimit");
function hasExplicitOutputLimit(model) {
  const norm = normalize(model);
  return OUTPUT_PATTERNS.some(([regex]) => regex.test(norm));
}
__name(hasExplicitOutputLimit, "hasExplicitOutputLimit");
function knownTokenLimit(model, type = "input") {
  return findTokenLimit(model, type);
}
__name(knownTokenLimit, "knownTokenLimit");
function tokenLimit(model, type = "input") {
  return knownTokenLimit(model, type) ?? (type === "output" ? DEFAULT_OUTPUT_TOKEN_LIMIT : DEFAULT_TOKEN_LIMIT);
}
__name(tokenLimit, "tokenLimit");
function defaultOutputCeiling(model) {
  const outputLimit = tokenLimit(model, "output");
  if (/^claude-opus-4-(?:6|7|8)/.test(normalize(model))) {
    return outputLimit;
  }
  return Math.min(outputLimit, OUTPUT_TOKEN_CEILING);
}
__name(defaultOutputCeiling, "defaultOutputCeiling");
function reconcileMaxTokens(configMaxTokens, requestMaxTokens) {
  if (typeof configMaxTokens === "number" && typeof requestMaxTokens === "number") {
    return Math.min(configMaxTokens, requestMaxTokens);
  }
  return void 0;
}
__name(reconcileMaxTokens, "reconcileMaxTokens");

// packages/core/src/utils/request-tokenizer/textTokenizer.ts
init_esbuild_shims();
var NON_ASCII_RE = /[\u0080-\uffff]/;
var TOKEN_ESTIMATE_UNITS_PER_TOKEN = 20;
function estimateTextTokens(text) {
  if (!text || text.length === 0) {
    return 0;
  }
  if (!NON_ASCII_RE.test(text)) {
    return Math.ceil(text.length / 4);
  }
  const nonAsciiChars = countNonAsciiChars(text);
  const asciiChars = text.length - nonAsciiChars;
  return Math.ceil(asciiChars / 4 + nonAsciiChars * 1.1);
}
__name(estimateTextTokens, "estimateTextTokens");
function estimateTextTokenUnits(text) {
  if (!text || text.length === 0) {
    return 0;
  }
  if (!NON_ASCII_RE.test(text)) {
    return text.length * 5;
  }
  const nonAsciiChars = countNonAsciiChars(text);
  const asciiChars = text.length - nonAsciiChars;
  return asciiChars * 5 + nonAsciiChars * 22;
}
__name(estimateTextTokenUnits, "estimateTextTokenUnits");
function countNonAsciiChars(text) {
  let count = 0;
  for (let i = 0; i < text.length; i++) {
    if (text.charCodeAt(i) >= 128) {
      count++;
    }
  }
  return count;
}
__name(countNonAsciiChars, "countNonAsciiChars");
var TextTokenizer = class {
  static {
    __name(this, "TextTokenizer");
  }
  /**
   * Calculate tokens for text content
   *
   * @param text - The text to estimate tokens for
   * @returns The estimated token count
   */
  async calculateTokens(text) {
    return this.calculateTokensSync(text);
  }
  /**
   * Calculate tokens for multiple text strings
   *
   * @param texts - Array of text strings to estimate tokens for
   * @returns Array of token counts corresponding to each input text
   */
  async calculateTokensBatch(texts) {
    return texts.map((text) => this.calculateTokensSync(text));
  }
  calculateTokensSync(text) {
    return estimateTextTokens(text);
  }
};

// packages/core/src/core/tool-call-preparation.ts
init_esbuild_shims();
var preparationsByResponse = /* @__PURE__ */ new WeakMap();
function setToolCallPreparations(response, preparations) {
  preparationsByResponse.set(response, preparations);
}
__name(setToolCallPreparations, "setToolCallPreparations");
function getToolCallPreparations(response) {
  return preparationsByResponse.get(response) ?? [];
}
__name(getToolCallPreparations, "getToolCallPreparations");

// packages/core/src/utils/runtimeDiagnostics.ts
init_esbuild_shims();
var RUNTIME_PROFILE_ENV = "QWEN_CODE_PROFILE_RUNTIME";
function isRuntimeDiagnosticsEnabled(env = process.env) {
  return env[RUNTIME_PROFILE_ENV] === "1";
}
__name(isRuntimeDiagnosticsEnabled, "isRuntimeDiagnosticsEnabled");
var RuntimeDiagnosticsCollector = class {
  static {
    __name(this, "RuntimeDiagnosticsCollector");
  }
  enabled;
  now;
  startedAt;
  requestIndex = 0;
  openAIWireRequestIndex = 0;
  anthropicWireRequestIndex = 0;
  requests = [];
  openaiWireRequests = [];
  anthropicWireRequests = [];
  tools = createInitialToolDiagnostics();
  constructor(options = {}) {
    this.enabled = options.enabled ?? isRuntimeDiagnosticsEnabled();
    this.now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
    this.startedAt = this.now();
  }
  reset(options = {}) {
    this.enabled = options.enabled ?? isRuntimeDiagnosticsEnabled();
    this.startedAt = this.now();
    this.requestIndex = 0;
    this.openAIWireRequestIndex = 0;
    this.anthropicWireRequestIndex = 0;
    this.requests = [];
    this.openaiWireRequests = [];
    this.anthropicWireRequests = [];
    this.tools = createInitialToolDiagnostics();
  }
  isEnabled() {
    return this.enabled;
  }
  recordGenerateContentRequest(request, options) {
    if (!this.enabled) {
      return;
    }
    this.requestIndex += 1;
    this.requests.push({
      index: this.requestIndex,
      timestamp: this.now(),
      source: options.source,
      model: request.model,
      stream: options.stream,
      serializedBytes: utf8Bytes(toJsonSafeRequest(request)),
      contents: summarizeContents(request.contents),
      systemInstructionBytes: summarizeContentTextBytes(
        request.config?.systemInstruction
      ),
      generationConfigBytes: utf8Bytes(toJsonSafeConfig(request.config)),
      tools: summarizeToolSchemas(request.config?.tools)
    });
  }
  recordOpenAIWireRequest(request) {
    if (!this.enabled) {
      return;
    }
    this.openAIWireRequestIndex += 1;
    this.openaiWireRequests.push({
      index: this.openAIWireRequestIndex,
      timestamp: this.now(),
      ...summarizeOpenAIWireRequest(request)
    });
  }
  recordAnthropicWireRequest(request) {
    if (!this.enabled) {
      return;
    }
    this.anthropicWireRequestIndex += 1;
    this.anthropicWireRequests.push({
      index: this.anthropicWireRequestIndex,
      timestamp: this.now(),
      ...summarizeAnthropicWireRequest(request)
    });
  }
  recordToolUse(name, args) {
    if (!this.enabled) {
      return;
    }
    const argBytes = utf8Bytes(args);
    const tool = this.getToolNameDiagnostics(name);
    tool.uses += 1;
    tool.argBytes += argBytes;
    tool.maxArgBytes = Math.max(tool.maxArgBytes, argBytes);
    this.tools.toolUseCount += 1;
    this.tools.totalToolUseArgBytes += argBytes;
    this.tools.maxToolUseArgBytes = Math.max(
      this.tools.maxToolUseArgBytes,
      argBytes
    );
  }
  recordToolResult(record) {
    if (!this.enabled) {
      return;
    }
    const tool = this.getToolNameDiagnostics(record.name);
    tool.results += 1;
    tool.resultBytes += record.resultBytes;
    tool.maxResultBytes = Math.max(tool.maxResultBytes, record.resultBytes);
    if (record.isError) {
      tool.errors += 1;
      this.tools.toolResultErrorCount += 1;
    }
    this.tools.toolResultCount += 1;
    this.tools.totalToolResultBytes += record.resultBytes;
    this.tools.maxToolResultBytes = Math.max(
      this.tools.maxToolResultBytes,
      record.resultBytes
    );
  }
  snapshot() {
    return {
      enabled: this.enabled,
      startedAt: this.startedAt,
      requests: this.requests.map((request) => ({
        ...request,
        contents: {
          ...request.contents,
          roleCounts: { ...request.contents.roleCounts }
        },
        tools: { ...request.tools }
      })),
      openaiWireRequests: this.openaiWireRequests.map((request) => ({
        ...request,
        messageBytesByRole: { ...request.messageBytesByRole },
        topLevelKeys: [...request.topLevelKeys]
      })),
      anthropicWireRequests: this.anthropicWireRequests.map((request) => ({
        ...request,
        messageBytesByRole: { ...request.messageBytesByRole },
        topLevelKeys: [...request.topLevelKeys]
      })),
      tools: {
        ...this.tools,
        byName: Object.fromEntries(
          Object.entries(this.tools.byName).map(([name, value]) => [
            name,
            { ...value }
          ])
        )
      }
    };
  }
  getToolNameDiagnostics(name) {
    const existing = this.tools.byName[name];
    if (existing) {
      return existing;
    }
    const created = createInitialToolNameDiagnostics();
    this.tools.byName[name] = created;
    return created;
  }
};
var runtimeDiagnostics = new RuntimeDiagnosticsCollector();
function summarizeOpenAIWireRequest(request) {
  const requestRecord = asRecord(request);
  const messages = Array.isArray(requestRecord["messages"]) ? requestRecord["messages"] : [];
  const tools = Array.isArray(requestRecord["tools"]) ? requestRecord["tools"] : [];
  const messageBytesByRole = {};
  for (const message of messages) {
    const messageRecord = asRecord(message);
    const role = typeof messageRecord["role"] === "string" ? messageRecord["role"] : "unknown";
    messageBytesByRole[role] = (messageBytesByRole[role] ?? 0) + utf8Bytes(messageRecord["content"]);
  }
  return {
    model: typeof requestRecord["model"] === "string" ? requestRecord["model"] : "unknown",
    stream: requestRecord["stream"] === true,
    bodyBytes: utf8Bytes(request),
    messageCount: messages.length,
    messageBytesByRole,
    toolsCount: tools.length,
    toolSchemaBytes: utf8Bytes(tools),
    topLevelKeys: Object.keys(requestRecord).sort()
  };
}
__name(summarizeOpenAIWireRequest, "summarizeOpenAIWireRequest");
function summarizeAnthropicWireRequest(request) {
  const requestRecord = asRecord(request);
  const messages = Array.isArray(requestRecord["messages"]) ? requestRecord["messages"] : [];
  const tools = Array.isArray(requestRecord["tools"]) ? requestRecord["tools"] : [];
  const messageBytesByRole = {};
  for (const message of messages) {
    const messageRecord = asRecord(message);
    const role = typeof messageRecord["role"] === "string" ? messageRecord["role"] : "unknown";
    messageBytesByRole[role] = (messageBytesByRole[role] ?? 0) + utf8Bytes(messageRecord["content"]);
  }
  return {
    model: typeof requestRecord["model"] === "string" ? requestRecord["model"] : "unknown",
    stream: requestRecord["stream"] === true,
    bodyBytes: utf8Bytes(request),
    messageCount: messages.length,
    messageBytesByRole,
    systemBytes: utf8Bytes(requestRecord["system"]),
    toolsCount: tools.length,
    toolSchemaBytes: utf8Bytes(tools),
    topLevelKeys: Object.keys(requestRecord).sort()
  };
}
__name(summarizeAnthropicWireRequest, "summarizeAnthropicWireRequest");
function createInitialToolDiagnostics() {
  return {
    toolUseCount: 0,
    toolResultCount: 0,
    toolResultErrorCount: 0,
    totalToolUseArgBytes: 0,
    maxToolUseArgBytes: 0,
    totalToolResultBytes: 0,
    maxToolResultBytes: 0,
    byName: /* @__PURE__ */ Object.create(null)
  };
}
__name(createInitialToolDiagnostics, "createInitialToolDiagnostics");
function createInitialToolNameDiagnostics() {
  return {
    uses: 0,
    argBytes: 0,
    maxArgBytes: 0,
    results: 0,
    errors: 0,
    resultBytes: 0,
    maxResultBytes: 0
  };
}
__name(createInitialToolNameDiagnostics, "createInitialToolNameDiagnostics");
function summarizeContents(contents) {
  const summary = {
    count: 0,
    roleCounts: {},
    partCount: 0,
    textBytes: 0,
    functionCallCount: 0,
    functionCallArgBytes: 0,
    functionResponseCount: 0,
    functionResponseBytes: 0,
    inlineDataCount: 0,
    inlineDataBytes: 0,
    fileDataCount: 0
  };
  const contentItems = Array.isArray(contents) ? contents : contents === void 0 || contents === null ? [] : [contents];
  for (const content of contentItems) {
    summary.count += 1;
    if (typeof content === "string") {
      summary.roleCounts["user"] = (summary.roleCounts["user"] ?? 0) + 1;
      summary.partCount += 1;
      summary.textBytes += utf8Bytes(content);
      continue;
    }
    const contentRecord = asRecord(content);
    const role = typeof contentRecord["role"] === "string" ? contentRecord["role"] : "unknown";
    summary.roleCounts[role] = (summary.roleCounts[role] ?? 0) + 1;
    const parts = Array.isArray(contentRecord["parts"]) ? contentRecord["parts"] : [];
    summarizeParts(parts, summary);
  }
  return summary;
}
__name(summarizeContents, "summarizeContents");
function summarizeContentTextBytes(content) {
  const summary = summarizeContents(content);
  return summary.textBytes;
}
__name(summarizeContentTextBytes, "summarizeContentTextBytes");
function summarizeParts(parts, summary) {
  for (const part of parts) {
    summary.partCount += 1;
    if (typeof part === "string") {
      summary.textBytes += utf8Bytes(part);
      continue;
    }
    const partRecord = asRecord(part);
    if (typeof partRecord["text"] === "string") {
      summary.textBytes += utf8Bytes(partRecord["text"]);
    }
    const functionCall = asOptionalRecord(partRecord["functionCall"]);
    if (functionCall) {
      summary.functionCallCount += 1;
      summary.functionCallArgBytes += utf8Bytes(functionCall["args"]);
    }
    const functionResponse = asOptionalRecord(partRecord["functionResponse"]);
    if (functionResponse) {
      summary.functionResponseCount += 1;
      summary.functionResponseBytes += utf8Bytes(functionResponse["response"]) + utf8Bytes(functionResponse["parts"]);
    }
    const inlineData = asOptionalRecord(partRecord["inlineData"]);
    if (inlineData) {
      summary.inlineDataCount += 1;
      summary.inlineDataBytes += utf8Bytes(inlineData["data"]);
    }
    if (partRecord["fileData"]) {
      summary.fileDataCount += 1;
    }
  }
}
__name(summarizeParts, "summarizeParts");
function summarizeToolSchemas(tools) {
  const toolList = Array.isArray(tools) ? tools : [];
  let functionDeclarationCount = 0;
  for (const tool of toolList) {
    const toolRecord = asRecord(tool);
    const declarations = Array.isArray(toolRecord["functionDeclarations"]) ? toolRecord["functionDeclarations"] : [];
    functionDeclarationCount += declarations.length;
  }
  return {
    count: toolList.length,
    functionDeclarationCount,
    schemaBytes: utf8Bytes(toolList)
  };
}
__name(summarizeToolSchemas, "summarizeToolSchemas");
function toJsonSafeRequest(request) {
  return {
    model: request.model,
    contents: request.contents,
    config: toJsonSafeConfig(request.config)
  };
}
__name(toJsonSafeRequest, "toJsonSafeRequest");
function toJsonSafeConfig(config) {
  if (!config) {
    return void 0;
  }
  const configRecord = asRecord(config);
  const safeConfig = {};
  for (const [key, value] of Object.entries(configRecord)) {
    if (key === "abortSignal") {
      continue;
    }
    safeConfig[key] = value;
  }
  return safeConfig;
}
__name(toJsonSafeConfig, "toJsonSafeConfig");
function utf8Bytes(value) {
  if (value === void 0 || value === null) {
    return 0;
  }
  if (typeof value === "string") {
    return Buffer.byteLength(value, "utf8");
  }
  return Buffer.byteLength(safeStringify(value), "utf8");
}
__name(utf8Bytes, "utf8Bytes");
function safeStringify(value) {
  try {
    return JSON.stringify(value) ?? "";
  } catch {
    return "[unserializable]";
  }
}
__name(safeStringify, "safeStringify");
function asRecord(value) {
  return typeof value === "object" && value !== null ? value : {};
}
__name(asRecord, "asRecord");
function asOptionalRecord(value) {
  return typeof value === "object" && value !== null ? value : null;
}
__name(asOptionalRecord, "asOptionalRecord");

// packages/core/src/utils/tool-name-utils.ts
init_esbuild_shims();
var MAX_TOOL_NAME_LENGTH = 63;
var PROVIDER_SAFE_TOOL_NAME = /^[A-Za-z][A-Za-z0-9_-]*$/;
function normalizeToolNameForProvider(name) {
  if (name.length <= MAX_TOOL_NAME_LENGTH && PROVIDER_SAFE_TOOL_NAME.test(name)) {
    return name;
  }
  const normalized = sanitizeToolNameForProvider(name);
  const suffix = `_${stableToolNameHash(name)}`;
  return `${normalized.slice(0, MAX_TOOL_NAME_LENGTH - suffix.length)}${suffix}`;
}
__name(normalizeToolNameForProvider, "normalizeToolNameForProvider");
function sanitizeToolNameForProvider(name) {
  const sanitized = name.replace(/[^A-Za-z0-9_-]/g, "_");
  return /^[A-Za-z]/.test(sanitized) ? sanitized : `tool_${sanitized}`;
}
__name(sanitizeToolNameForProvider, "sanitizeToolNameForProvider");
function normalizeMcpToolName(name) {
  return name.startsWith("mcp__") ? normalizeToolNameForProvider(name) : name;
}
__name(normalizeMcpToolName, "normalizeMcpToolName");
function generateLegacyMcpToolName(name) {
  let legacyName = name.replace(/[^A-Za-z0-9_.-]/g, "_");
  if (legacyName.length > MAX_TOOL_NAME_LENGTH) {
    legacyName = legacyName.slice(0, 28) + "___" + legacyName.slice(-32);
  }
  return legacyName;
}
__name(generateLegacyMcpToolName, "generateLegacyMcpToolName");
function stableToolNameHash(name) {
  let hash = 2166136261;
  for (let index = 0; index < name.length; index += 1) {
    hash = Math.imul(hash ^ name.charCodeAt(index), 16777619);
  }
  return (hash >>> 0).toString(36).padStart(7, "0");
}
__name(stableToolNameHash, "stableToolNameHash");

// packages/core/src/utils/safeJsonParse.ts
init_esbuild_shims();

// node_modules/jsonrepair/lib/esm/index.js
init_esbuild_shims();

// node_modules/jsonrepair/lib/esm/regular/jsonrepair.js
init_esbuild_shims();

// node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js
init_esbuild_shims();
var JSONRepairError = class extends Error {
  static {
    __name(this, "JSONRepairError");
  }
  constructor(message, position) {
    super(`${message} at position ${position}`);
    this.position = position;
  }
};

// node_modules/jsonrepair/lib/esm/utils/stringUtils.js
init_esbuild_shims();
var codeSpace = 32;
var codeNewline = 10;
var codeTab = 9;
var codeReturn = 13;
var codeNonBreakingSpace = 160;
var codeEnQuad = 8192;
var codeHairSpace = 8202;
var codeNarrowNoBreakSpace = 8239;
var codeMediumMathematicalSpace = 8287;
var codeIdeographicSpace = 12288;
function isHex(char) {
  return /^[0-9A-Fa-f]$/.test(char);
}
__name(isHex, "isHex");
function isDigit(char) {
  return char >= "0" && char <= "9";
}
__name(isDigit, "isDigit");
function isValidStringCharacter(char) {
  return char >= " ";
}
__name(isValidStringCharacter, "isValidStringCharacter");
function isDelimiter(char) {
  return ",:[]/{}()\n+".includes(char);
}
__name(isDelimiter, "isDelimiter");
function isFunctionNameCharStart(char) {
  return char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char === "_" || char === "$";
}
__name(isFunctionNameCharStart, "isFunctionNameCharStart");
function isFunctionNameChar(char) {
  return char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char === "_" || char === "$" || char >= "0" && char <= "9";
}
__name(isFunctionNameChar, "isFunctionNameChar");
var regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\/\/$/;
var regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;
function isUnquotedStringDelimiter(char) {
  return ",[]/{}\n+".includes(char);
}
__name(isUnquotedStringDelimiter, "isUnquotedStringDelimiter");
function isStartOfValue(char) {
  return isQuote(char) || regexStartOfValue.test(char);
}
__name(isStartOfValue, "isStartOfValue");
var regexStartOfValue = /^[[{\w-]$/;
function isControlCharacter(char) {
  return char === "\n" || char === "\r" || char === "	" || char === "\b" || char === "\f";
}
__name(isControlCharacter, "isControlCharacter");
function isWhitespace(text, index) {
  const code = text.charCodeAt(index);
  return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn;
}
__name(isWhitespace, "isWhitespace");
function isWhitespaceExceptNewline(text, index) {
  const code = text.charCodeAt(index);
  return code === codeSpace || code === codeTab || code === codeReturn;
}
__name(isWhitespaceExceptNewline, "isWhitespaceExceptNewline");
function isSpecialWhitespace(text, index) {
  const code = text.charCodeAt(index);
  return code === codeNonBreakingSpace || code >= codeEnQuad && code <= codeHairSpace || code === codeNarrowNoBreakSpace || code === codeMediumMathematicalSpace || code === codeIdeographicSpace;
}
__name(isSpecialWhitespace, "isSpecialWhitespace");
function isQuote(char) {
  return isDoubleQuoteLike(char) || isSingleQuoteLike(char);
}
__name(isQuote, "isQuote");
function isDoubleQuoteLike(char) {
  return char === '"' || char === "\u201C" || char === "\u201D";
}
__name(isDoubleQuoteLike, "isDoubleQuoteLike");
function isDoubleQuote(char) {
  return char === '"';
}
__name(isDoubleQuote, "isDoubleQuote");
function isSingleQuoteLike(char) {
  return char === "'" || char === "\u2018" || char === "\u2019" || char === "`" || char === "\xB4";
}
__name(isSingleQuoteLike, "isSingleQuoteLike");
function isSingleQuote(char) {
  return char === "'";
}
__name(isSingleQuote, "isSingleQuote");
function stripLastOccurrence(text, textToStrip) {
  let stripRemainingText = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
  const index = text.lastIndexOf(textToStrip);
  return index !== -1 ? text.substring(0, index) + (stripRemainingText ? "" : text.substring(index + 1)) : text;
}
__name(stripLastOccurrence, "stripLastOccurrence");
function insertBeforeLastWhitespace(text, textToInsert) {
  let index = text.length;
  if (!isWhitespace(text, index - 1)) {
    return text + textToInsert;
  }
  while (isWhitespace(text, index - 1)) {
    index--;
  }
  return text.substring(0, index) + textToInsert + text.substring(index);
}
__name(insertBeforeLastWhitespace, "insertBeforeLastWhitespace");
function removeAtIndex(text, start, count) {
  return text.substring(0, start) + text.substring(start + count);
}
__name(removeAtIndex, "removeAtIndex");
function endsWithCommaOrNewline(text) {
  return /[,\n][ \t\r]*$/.test(text);
}
__name(endsWithCommaOrNewline, "endsWithCommaOrNewline");

// node_modules/jsonrepair/lib/esm/regular/jsonrepair.js
var controlCharacters = {
  "\b": "\\b",
  "\f": "\\f",
  "\n": "\\n",
  "\r": "\\r",
  "	": "\\t"
};
var escapeCharacters = {
  '"': '"',
  "\\": "\\",
  "/": "/",
  b: "\b",
  f: "\f",
  n: "\n",
  r: "\r",
  t: "	"
  // note that \u is handled separately in parseString()
};
function jsonrepair(text) {
  let i = 0;
  let output = "";
  parseMarkdownCodeBlock(["```", "[```", "{```"]);
  const processed = parseValue();
  if (!processed) {
    throwUnexpectedEnd();
  }
  parseMarkdownCodeBlock(["```", "```]", "```}"]);
  const processedComma = parseCharacter(",");
  if (processedComma) {
    parseWhitespaceAndSkipComments();
  }
  if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {
    if (!processedComma) {
      output = insertBeforeLastWhitespace(output, ",");
    }
    parseNewlineDelimitedJSON();
  } else if (processedComma) {
    output = stripLastOccurrence(output, ",");
  }
  while (text[i] === "}" || text[i] === "]") {
    i++;
    parseWhitespaceAndSkipComments();
  }
  if (i >= text.length) {
    return output;
  }
  throwUnexpectedCharacter();
  function parseValue() {
    parseWhitespaceAndSkipComments();
    const processed2 = parseObject() || parseArray() || parseString() || parseNumber() || parseKeywords() || parseUnquotedString(false) || parseRegex();
    parseWhitespaceAndSkipComments();
    return processed2;
  }
  __name(parseValue, "parseValue");
  function parseWhitespaceAndSkipComments() {
    let skipNewline = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
    const start = i;
    let changed = parseWhitespace(skipNewline);
    do {
      changed = parseComment();
      if (changed) {
        changed = parseWhitespace(skipNewline);
      }
    } while (changed);
    return i > start;
  }
  __name(parseWhitespaceAndSkipComments, "parseWhitespaceAndSkipComments");
  function parseWhitespace(skipNewline) {
    const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline;
    let whitespace = "";
    while (true) {
      if (_isWhiteSpace(text, i)) {
        whitespace += text[i];
        i++;
      } else if (isSpecialWhitespace(text, i)) {
        whitespace += " ";
        i++;
      } else {
        break;
      }
    }
    if (whitespace.length > 0) {
      output += whitespace;
      return true;
    }
    return false;
  }
  __name(parseWhitespace, "parseWhitespace");
  function parseComment() {
    if (text[i] === "/" && text[i + 1] === "*") {
      while (i < text.length && !atEndOfBlockComment(text, i)) {
        i++;
      }
      i += 2;
      return true;
    }
    if (text[i] === "/" && text[i + 1] === "/") {
      while (i < text.length && text[i] !== "\n") {
        i++;
      }
      return true;
    }
    return false;
  }
  __name(parseComment, "parseComment");
  function parseMarkdownCodeBlock(blocks) {
    if (skipMarkdownCodeBlock(blocks)) {
      if (isFunctionNameCharStart(text[i])) {
        while (i < text.length && isFunctionNameChar(text[i])) {
          i++;
        }
      }
      parseWhitespaceAndSkipComments();
      return true;
    }
    return false;
  }
  __name(parseMarkdownCodeBlock, "parseMarkdownCodeBlock");
  function skipMarkdownCodeBlock(blocks) {
    parseWhitespace(true);
    for (const block of blocks) {
      const end = i + block.length;
      if (text.slice(i, end) === block) {
        i = end;
        return true;
      }
    }
    return false;
  }
  __name(skipMarkdownCodeBlock, "skipMarkdownCodeBlock");
  function parseCharacter(char) {
    if (text[i] === char) {
      output += text[i];
      i++;
      return true;
    }
    return false;
  }
  __name(parseCharacter, "parseCharacter");
  function skipCharacter(char) {
    if (text[i] === char) {
      i++;
      return true;
    }
    return false;
  }
  __name(skipCharacter, "skipCharacter");
  function skipEscapeCharacter() {
    return skipCharacter("\\");
  }
  __name(skipEscapeCharacter, "skipEscapeCharacter");
  function skipEllipsis() {
    parseWhitespaceAndSkipComments();
    if (text[i] === "." && text[i + 1] === "." && text[i + 2] === ".") {
      i += 3;
      parseWhitespaceAndSkipComments();
      skipCharacter(",");
      return true;
    }
    return false;
  }
  __name(skipEllipsis, "skipEllipsis");
  function parseObject() {
    if (text[i] === "{") {
      output += "{";
      i++;
      parseWhitespaceAndSkipComments();
      if (skipCharacter(",")) {
        parseWhitespaceAndSkipComments();
      }
      let initial = true;
      while (i < text.length && text[i] !== "}") {
        let processedComma2;
        if (!initial) {
          processedComma2 = parseCharacter(",");
          if (!processedComma2) {
            output = insertBeforeLastWhitespace(output, ",");
          }
          parseWhitespaceAndSkipComments();
        } else {
          processedComma2 = true;
          initial = false;
        }
        skipEllipsis();
        const processedKey = parseString() || parseUnquotedString(true);
        if (!processedKey) {
          if (text[i] === "}" || text[i] === "{" || text[i] === "]" || text[i] === "[" || text[i] === void 0) {
            output = stripLastOccurrence(output, ",");
          } else {
            throwObjectKeyExpected();
          }
          break;
        }
        parseWhitespaceAndSkipComments();
        const processedColon = parseCharacter(":");
        const truncatedText = i >= text.length;
        if (!processedColon) {
          if (isStartOfValue(text[i]) || truncatedText) {
            output = insertBeforeLastWhitespace(output, ":");
          } else {
            throwColonExpected();
          }
        }
        const processedValue = parseValue();
        if (!processedValue) {
          if (processedColon || truncatedText) {
            output += "null";
          } else {
            throwColonExpected();
          }
        }
      }
      if (text[i] === "}") {
        output += "}";
        i++;
      } else {
        output = insertBeforeLastWhitespace(output, "}");
      }
      return true;
    }
    return false;
  }
  __name(parseObject, "parseObject");
  function parseArray() {
    if (text[i] === "[") {
      output += "[";
      i++;
      parseWhitespaceAndSkipComments();
      if (skipCharacter(",")) {
        parseWhitespaceAndSkipComments();
      }
      let initial = true;
      while (i < text.length && text[i] !== "]") {
        if (!initial) {
          const processedComma2 = parseCharacter(",");
          if (!processedComma2) {
            output = insertBeforeLastWhitespace(output, ",");
          }
        } else {
          initial = false;
        }
        skipEllipsis();
        const processedValue = parseValue();
        if (!processedValue) {
          output = stripLastOccurrence(output, ",");
          break;
        }
      }
      if (text[i] === "]") {
        output += "]";
        i++;
      } else {
        output = insertBeforeLastWhitespace(output, "]");
      }
      return true;
    }
    return false;
  }
  __name(parseArray, "parseArray");
  function parseNewlineDelimitedJSON() {
    let initial = true;
    let processedValue = true;
    while (processedValue) {
      if (!initial) {
        const processedComma2 = parseCharacter(",");
        if (!processedComma2) {
          output = insertBeforeLastWhitespace(output, ",");
        }
      } else {
        initial = false;
      }
      processedValue = parseValue();
    }
    if (!processedValue) {
      output = stripLastOccurrence(output, ",");
    }
    output = `[
${output}
]`;
  }
  __name(parseNewlineDelimitedJSON, "parseNewlineDelimitedJSON");
  function parseString() {
    let stopAtDelimiter = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
    let stopAtIndex = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : -1;
    let skipEscapeChars = text[i] === "\\";
    if (skipEscapeChars) {
      i++;
      skipEscapeChars = true;
    }
    if (isQuote(text[i])) {
      const isEndQuote = isDoubleQuote(text[i]) ? isDoubleQuote : isSingleQuote(text[i]) ? isSingleQuote : isSingleQuoteLike(text[i]) ? isSingleQuoteLike : isDoubleQuoteLike;
      const iBefore = i;
      const oBefore = output.length;
      let str = '"';
      i++;
      while (true) {
        if (i >= text.length) {
          const iPrev = prevNonWhitespaceIndex(i - 1);
          if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {
            i = iBefore;
            output = output.substring(0, oBefore);
            return parseString(true);
          }
          str = insertBeforeLastWhitespace(str, '"');
          output += str;
          return true;
        }
        if (i === stopAtIndex) {
          str = insertBeforeLastWhitespace(str, '"');
          output += str;
          return true;
        }
        if (isEndQuote(text[i])) {
          const iQuote = i;
          const oQuote = str.length;
          str += '"';
          i++;
          output += str;
          parseWhitespaceAndSkipComments(false);
          if (stopAtDelimiter || i >= text.length || isDelimiter(text[i]) || isQuote(text[i]) || isDigit(text[i])) {
            parseConcatenatedString();
            return true;
          }
          const iPrevChar = prevNonWhitespaceIndex(iQuote - 1);
          const prevChar = text.charAt(iPrevChar);
          if (prevChar === ",") {
            i = iBefore;
            output = output.substring(0, oBefore);
            return parseString(false, iPrevChar);
          }
          if (isDelimiter(prevChar)) {
            i = iBefore;
            output = output.substring(0, oBefore);
            return parseString(true);
          }
          output = output.substring(0, oBefore);
          i = iQuote + 1;
          str = `${str.substring(0, oQuote)}\\${str.substring(oQuote)}`;
        } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {
          if (text[i - 1] === ":" && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {
            while (i < text.length && regexUrlChar.test(text[i])) {
              str += text[i];
              i++;
            }
          }
          str = insertBeforeLastWhitespace(str, '"');
          output += str;
          parseConcatenatedString();
          return true;
        } else if (text[i] === "\\") {
          const char = text.charAt(i + 1);
          const escapeChar = escapeCharacters[char];
          if (escapeChar !== void 0) {
            str += text.slice(i, i + 2);
            i += 2;
          } else if (char === "u") {
            let j = 2;
            while (j < 6 && isHex(text[i + j])) {
              j++;
            }
            if (j === 6) {
              str += text.slice(i, i + 6);
              i += 6;
            } else if (i + j >= text.length) {
              i = text.length;
            } else {
              throwInvalidUnicodeCharacter();
            }
          } else {
            str += char;
            i += 2;
          }
        } else {
          const char = text.charAt(i);
          if (char === '"' && text[i - 1] !== "\\") {
            str += `\\${char}`;
            i++;
          } else if (isControlCharacter(char)) {
            str += controlCharacters[char];
            i++;
          } else {
            if (!isValidStringCharacter(char)) {
              throwInvalidCharacter(char);
            }
            str += char;
            i++;
          }
        }
        if (skipEscapeChars) {
          skipEscapeCharacter();
        }
      }
    }
    return false;
  }
  __name(parseString, "parseString");
  function parseConcatenatedString() {
    let processed2 = false;
    parseWhitespaceAndSkipComments();
    while (text[i] === "+") {
      processed2 = true;
      i++;
      parseWhitespaceAndSkipComments();
      output = stripLastOccurrence(output, '"', true);
      const start = output.length;
      const parsedStr = parseString();
      if (parsedStr) {
        output = removeAtIndex(output, start, 1);
      } else {
        output = insertBeforeLastWhitespace(output, '"');
      }
    }
    return processed2;
  }
  __name(parseConcatenatedString, "parseConcatenatedString");
  function parseNumber() {
    const start = i;
    if (text[i] === "-") {
      i++;
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit(text[i])) {
        i = start;
        return false;
      }
    }
    while (isDigit(text[i])) {
      i++;
    }
    if (text[i] === ".") {
      i++;
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit(text[i])) {
        i = start;
        return false;
      }
      while (isDigit(text[i])) {
        i++;
      }
    }
    if (text[i] === "e" || text[i] === "E") {
      i++;
      if (text[i] === "-" || text[i] === "+") {
        i++;
      }
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start);
        return true;
      }
      if (!isDigit(text[i])) {
        i = start;
        return false;
      }
      while (isDigit(text[i])) {
        i++;
      }
    }
    if (!atEndOfNumber()) {
      i = start;
      return false;
    }
    if (i > start) {
      const num = text.slice(start, i);
      const hasInvalidLeadingZero = /^0\d/.test(num);
      output += hasInvalidLeadingZero ? `"${num}"` : num;
      return true;
    }
    return false;
  }
  __name(parseNumber, "parseNumber");
  function parseKeywords() {
    return parseKeyword("true", "true") || parseKeyword("false", "false") || parseKeyword("null", "null") || // repair Python keywords True, False, None
    parseKeyword("True", "true") || parseKeyword("False", "false") || parseKeyword("None", "null");
  }
  __name(parseKeywords, "parseKeywords");
  function parseKeyword(name, value) {
    if (text.slice(i, i + name.length) === name) {
      output += value;
      i += name.length;
      return true;
    }
    return false;
  }
  __name(parseKeyword, "parseKeyword");
  function parseUnquotedString(isKey) {
    const start = i;
    if (isFunctionNameCharStart(text[i])) {
      while (i < text.length && isFunctionNameChar(text[i])) {
        i++;
      }
      let j = i;
      while (isWhitespace(text, j)) {
        j++;
      }
      if (text[j] === "(") {
        i = j + 1;
        parseValue();
        if (text[i] === ")") {
          i++;
          if (text[i] === ";") {
            i++;
          }
        }
        return true;
      }
    }
    while (i < text.length && !isUnquotedStringDelimiter(text[i]) && !isQuote(text[i]) && (!isKey || text[i] !== ":")) {
      i++;
    }
    if (text[i - 1] === ":" && regexUrlStart.test(text.substring(start, i + 2))) {
      while (i < text.length && regexUrlChar.test(text[i])) {
        i++;
      }
    }
    if (i > start) {
      while (isWhitespace(text, i - 1) && i > 0) {
        i--;
      }
      const symbol = text.slice(start, i);
      output += symbol === "undefined" ? "null" : JSON.stringify(symbol);
      if (text[i] === '"') {
        i++;
      }
      return true;
    }
  }
  __name(parseUnquotedString, "parseUnquotedString");
  function parseRegex() {
    if (text[i] === "/") {
      const start = i;
      i++;
      while (i < text.length && (text[i] !== "/" || text[i - 1] === "\\")) {
        i++;
      }
      i++;
      output += `"${text.substring(start, i)}"`;
      return true;
    }
  }
  __name(parseRegex, "parseRegex");
  function prevNonWhitespaceIndex(start) {
    let prev = start;
    while (prev > 0 && isWhitespace(text, prev)) {
      prev--;
    }
    return prev;
  }
  __name(prevNonWhitespaceIndex, "prevNonWhitespaceIndex");
  function atEndOfNumber() {
    return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i);
  }
  __name(atEndOfNumber, "atEndOfNumber");
  function repairNumberEndingWithNumericSymbol(start) {
    output += `${text.slice(start, i)}0`;
  }
  __name(repairNumberEndingWithNumericSymbol, "repairNumberEndingWithNumericSymbol");
  function throwInvalidCharacter(char) {
    throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i);
  }
  __name(throwInvalidCharacter, "throwInvalidCharacter");
  function throwUnexpectedCharacter() {
    throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i);
  }
  __name(throwUnexpectedCharacter, "throwUnexpectedCharacter");
  function throwUnexpectedEnd() {
    throw new JSONRepairError("Unexpected end of json string", text.length);
  }
  __name(throwUnexpectedEnd, "throwUnexpectedEnd");
  function throwObjectKeyExpected() {
    throw new JSONRepairError("Object key expected", i);
  }
  __name(throwObjectKeyExpected, "throwObjectKeyExpected");
  function throwColonExpected() {
    throw new JSONRepairError("Colon expected", i);
  }
  __name(throwColonExpected, "throwColonExpected");
  function throwInvalidUnicodeCharacter() {
    const chars = text.slice(i, i + 6);
    throw new JSONRepairError(`Invalid unicode character "${chars}"`, i);
  }
  __name(throwInvalidUnicodeCharacter, "throwInvalidUnicodeCharacter");
}
__name(jsonrepair, "jsonrepair");
function atEndOfBlockComment(text, i) {
  return text[i] === "*" && text[i + 1] === "/";
}
__name(atEndOfBlockComment, "atEndOfBlockComment");

// packages/core/src/utils/safeJsonParse.ts
var debugLogger = createDebugLogger("JSON_PARSE");
function safeJsonParse(jsonString, fallbackValue = {}) {
  if (!jsonString || typeof jsonString !== "string") {
    return fallbackValue;
  }
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    try {
      const repairedJson = jsonrepair(jsonString);
      return JSON.parse(repairedJson);
    } catch (repairError) {
      debugLogger.error("Failed to parse JSON even with jsonrepair:", {
        originalError: error,
        repairError,
        jsonString
      });
      return fallbackValue;
    }
  }
}
__name(safeJsonParse, "safeJsonParse");

// packages/core/src/utils/schemaConverter.ts
init_esbuild_shims();
function convertSchema(schema, mode = "auto") {
  if (mode === "openapi_30") {
    return toOpenAPI30(schema);
  }
  return schema;
}
__name(convertSchema, "convertSchema");
function toOpenAPI30(schema) {
  const convert = /* @__PURE__ */ __name((obj) => {
    if (typeof obj !== "object" || obj === null) {
      return obj;
    }
    if (Array.isArray(obj)) {
      return obj.map(convert);
    }
    const source = obj;
    const target = {};
    if (Array.isArray(source["type"])) {
      const types = source["type"];
      if (types.length === 2 && types.includes("null")) {
        target["type"] = types.find((t) => t !== "null");
        target["nullable"] = true;
      } else {
        target["type"] = types.find((t) => t !== "null") ?? types[0];
        if (types.includes("null")) {
          target["nullable"] = true;
        }
      }
    } else if (source["type"] !== void 0) {
      target["type"] = source["type"];
    }
    if (source["const"] !== void 0) {
      target["enum"] = [source["const"]];
      delete target["const"];
    }
    if (typeof source["exclusiveMinimum"] === "number") {
      target["minimum"] = source["exclusiveMinimum"];
      target["exclusiveMinimum"] = true;
    }
    if (typeof source["exclusiveMaximum"] === "number") {
      target["maximum"] = source["exclusiveMaximum"];
      target["exclusiveMaximum"] = true;
    }
    if (Array.isArray(source["items"])) {
      delete target["items"];
    } else if (typeof source["items"] === "object" && source["items"] !== null) {
      target["items"] = convert(source["items"]);
    }
    if (Array.isArray(source["enum"])) {
      target["enum"] = source["enum"].map(String);
    }
    for (const [key, value] of Object.entries(source)) {
      if (key === "type" || key === "const" || key === "exclusiveMinimum" || key === "exclusiveMaximum" || key === "items" || key === "enum" || key === "$schema" || key === "$id" || key === "default" || // Optional: Gemini sometimes complains about defaults conflicting with types
      key === "dependencies" || key === "patternProperties") {
        continue;
      }
      target[key] = convert(value);
    }
    return target;
  }, "convert");
  return convert(schema);
}
__name(toOpenAPI30, "toOpenAPI30");
function relaxSchemaForFunctionCalling(schema) {
  const relax = /* @__PURE__ */ __name((obj) => {
    if (typeof obj !== "object" || obj === null) {
      return obj;
    }
    if (Array.isArray(obj)) {
      return obj.map(relax);
    }
    const source = obj;
    const target = {};
    const properties = source["properties"];
    const required = Array.isArray(source["required"]) ? source["required"].filter(
      (r) => typeof r === "string"
    ) : [];
    const hasOptionalProperties = typeof properties === "object" && properties !== null && !Array.isArray(properties) && Object.keys(properties).some((key) => !required.includes(key));
    for (const [key, value] of Object.entries(source)) {
      if (key === "$schema" || key === "$id") {
        continue;
      }
      if (key === "additionalProperties" && value === false && hasOptionalProperties) {
        continue;
      }
      if ((key === "properties" || key === "$defs" || key === "definitions") && typeof value === "object" && value !== null && !Array.isArray(value)) {
        const map = {};
        for (const [mapKey, mapValue] of Object.entries(
          value
        )) {
          map[mapKey] = relax(mapValue);
        }
        target[key] = map;
        continue;
      }
      target[key] = relax(value);
    }
    return target;
  }, "relax");
  return relax(schema);
}
__name(relaxSchemaForFunctionCalling, "relaxSchemaForFunctionCalling");

export {
  DEFAULT_TOKEN_LIMIT,
  DEFAULT_OUTPUT_TOKEN_LIMIT,
  ESCALATED_MAX_TOKENS,
  OUTPUT_TOKEN_CEILING,
  MIN_CLAMPED_OUTPUT_TOKENS,
  outputClampMargin,
  clampOutputTokensToWindow,
  parsePositiveIntegerEnvValue,
  normalize,
  hasExplicitOutputLimit,
  knownTokenLimit,
  tokenLimit,
  defaultOutputCeiling,
  reconcileMaxTokens,
  TOKEN_ESTIMATE_UNITS_PER_TOKEN,
  estimateTextTokens,
  estimateTextTokenUnits,
  TextTokenizer,
  normalizeToolNameForProvider,
  sanitizeToolNameForProvider,
  normalizeMcpToolName,
  generateLegacyMcpToolName,
  safeJsonParse,
  convertSchema,
  relaxSchemaForFunctionCalling,
  setToolCallPreparations,
  getToolCallPreparations,
  isRuntimeDiagnosticsEnabled,
  RuntimeDiagnosticsCollector,
  runtimeDiagnostics,
  summarizeOpenAIWireRequest,
  summarizeAnthropicWireRequest
};
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2026 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
