# unresolved_refs

from_node_id: function:556239ef8b09ca952650a99cd1dc5c3f
reference_kind: calls
file_path: open-sse/handlers/chatCore.ts
language: typescript
reference_name:
(() => {
        const role = typeof item?.role === "string" ? item.role.trim().toLowerCase() : "";
        const itemType = typeof item?.type === "string" ? item.type.trim().toLowerCase() : "";
        if (role && role !== "user") return "";
        if (itemType && itemType !== "message") return "";

        if (typeof item?.content === "string") return item.content.trim();
        if (Array.isArray(item?.content)) {
          return item.content
            .map((part: Record<string, unknown>) => {
              if (typeof part?.text === "string") return part.text.trim();
              if (part?.type === "input_text" && typeof part?.text === "string")
                return part.text.trim();
              return "";
            })
            .filter(Boolean)
            .join("\n")
            .trim();
        }
        return "";
      })


from_node_id: function:9cf718532f70470b23d397387eb78370
reference_kind: calls
file_path: open-sse/handlers/chatCore.ts
language: typescript
reference_name:
(async () => {
    const { getCombos } = await import("@/lib/localDb");
    return getCombos();
  })


from_node_id: function:62d84e2adbb065b53c06db34f58907a1
reference_kind: calls
file_path: open-sse/handlers/chatCore.ts
language: typescript
reference_name:
(async () => {
      try {
        if (pendingWrite) await pendingWrite;
        const { attachCompressionUsageReceipt } =
          await import("../../src/lib/db/compressionAnalytics.ts");
        attachCompressionUsageReceipt(skillRequestId, usage, source);
      } catch {
        // Compression analytics are best-effort and must never affect responses.
      }
    })


from_node_id: function:62d84e2adbb065b53c06db34f58907a1
reference_kind: calls
file_path: open-sse/handlers/chatCore.ts
language: typescript
reference_name:
(() => {
            const r = resolveModelAlias(modelToCall);
            return {
              ...getModelUpstreamExtraHeaders(provider || "", modelToCall || "", sourceFormat),
              ...getModelUpstreamExtraHeaders(provider || "", r || "", sourceFormat),
            };
          })


from_node_id: function:62d84e2adbb065b53c06db34f58907a1
reference_kind: calls
file_path: open-sse/handlers/chatCore.ts
language: typescript
reference_name:
(async () => {
              try {
                const { insertCompressionAnalyticsRow } =
                  await import("../../src/lib/db/compressionAnalytics.ts");
                const { calculateCost } = await import("../../src/lib/usage/costCalculator.ts");
                const tokensSaved = Math.max(
                  0,
                  result.stats.originalTokens - result.stats.compressedTokens
                );
                const rtkPointers = result.stats.rtkRawOutputPointers ?? [];
                const estimatedUsdSaved = await calculateCost(
                  provider ?? "",
                  effectiveModel ?? "",
                  {
                    input: tokensSaved,
                  },
                  { serviceTier: effectiveServiceTier }
                );
                insertCompressionAnalyticsRow({
                  timestamp: new Date().toISOString(),
                  combo_id: comboName ?? null,
                  provider: provider ?? null,
                  mode,
                  engine: result.stats.engine ?? mode,
                  compression_combo_id:
                    result.stats.compressionComboId ?? config.compressionComboId ?? null,
                  original_tokens: result.stats.originalTokens,
                  compressed_tokens: result.stats.compressedTokens,
                  tokens_saved: tokensSaved,
                  duration_ms: result.stats.durationMs ?? null,
                  request_id: skillRequestId,
                  estimated_usd_saved: estimatedUsdSaved || null,
                  validation_fallback: result.stats.fallbackApplied ? 1 : 0,
                  output_mode: cavemanOutputModeApplied ? cavemanOutputModeIntensity : null,
                  rtk_raw_output_pointer: rtkPointers[0]?.id ?? null,
                  rtk_raw_output_bytes: rtkPointers[0]?.bytes ?? null,
                  rtk_raw_output_pointers: rtkPointers.length
                    ? JSON.stringify(rtkPointers.map((pointer) => pointer.id))
                    : null,
                  rtk_raw_output_total_bytes: rtkPointers.length
                    ? rtkPointers.reduce((total, pointer) => total + pointer.bytes, 0)
                    : null,
                });
              } catch (err) {
                log?.debug?.(
                  "COMPRESSION",
                  "Compression analytics write skipped: " +
                    (err instanceof Error ? err.message : String(err))
                );
              }
            })


from_node_id: function:62d84e2adbb065b53c06db34f58907a1
reference_kind: calls
file_path: open-sse/handlers/chatCore.ts
language: typescript
reference_name:
(async () => {
              try {
                const { detectCachingContext } =
                  await import("../services/compression/cachingAware.ts");
                const { recordCacheStats } =
                  await import("../../src/lib/db/compressionCacheStats.ts");
                const cacheContext = detectCachingContext(compressionInputBody, {
                  provider,
                  targetFormat,
                  model: effectiveModel,
                });
                const tokensSavedCompression = Math.max(
                  0,
                  result.stats.originalTokens - result.stats.compressedTokens
                );
                recordCacheStats({
                  provider: cacheContext.provider ?? provider ?? "unknown",
                  model: effectiveModel ?? "",
                  compressionMode: mode,
                  cacheControlPresent: cacheContext.hasCacheControl,
                  estimatedCacheHit: cacheContext.hasCacheControl && cacheContext.isCachingProvider,
                  tokensSavedCompression,
                  tokensSavedCaching: 0,
                  netSavings: tokensSavedCompression,
                });
              } catch (err) {
                log?.debug?.(
                  "COMPRESSION",
                  "Compression cache stats write skipped: " +
                    (err instanceof Error ? err.message : String(err))
                );
              }
            })


from_node_id: function:62d84e2adbb065b53c06db34f58907a1
reference_kind: calls
file_path: open-sse/handlers/chatCore.ts
language: typescript
reference_name:
(async () => {
          try {
            const { insertCompressionAnalyticsRow } =
              await import("../../src/lib/db/compressionAnalytics.ts");
            insertCompressionAnalyticsRow({
              timestamp: new Date().toISOString(),
              combo_id: comboName ?? null,
              provider: provider ?? null,
              mode: "output-caveman",
              engine: "caveman-output",
              compression_combo_id: config.compressionComboId ?? null,
              original_tokens: estimatedTokens,
              compressed_tokens: estimatedTokens,
              tokens_saved: 0,
              request_id: skillRequestId,
              output_mode: cavemanOutputModeIntensity,
            });
          } catch (err) {
            log?.debug?.(
              "COMPRESSION",
              "Caveman output analytics write skipped: " +
                (err instanceof Error ? err.message : String(err))
            );
          }
        })


from_node_id: function:62d84e2adbb065b53c06db34f58907a1
reference_kind: calls
file_path: open-sse/handlers/chatCore.ts
language: typescript
reference_name:
(() => {
              const arr: [string, string][] = [];
              headers.forEach((v, k) => arr.push([k, v]));
              return arr;
            })


from_node_id: function:62870e994fc82db1094bc2f7cc49ab89
reference_kind: calls
file_path: open-sse/services/antigravityVersion.ts
language: typescript
reference_name:
(async () => {
    const resolved = await fetchLatestAntigravityVersion(fetchImpl);
    const version = resolved
      ? pickNewestVersion(resolved, ANTIGRAVITY_FALLBACK_VERSION)
      : pickNewestVersion(versionCache?.version, ANTIGRAVITY_FALLBACK_VERSION);

    if (resolved) {
      versionCache = {
        fetchedAt: Date.now(),
        version,
      };
    }

    return version;
  })


from_node_id: function:553d41325ad7b772a8ddc7f3c72a8808
reference_kind: calls
file_path: open-sse/services/chatgptTlsClient.ts
language: typescript
reference_name:
(async () => {
      try {
        const mod = await import("tls-client-node");
        const TLSClient = (mod as { TLSClient: new (opts?: Record<string, unknown>) => unknown })
          .TLSClient;
        // Native mode loads the shared library directly via koffi, avoiding the
        // managed sidecar's localhost HTTP calls that OmniRoute's global fetch
        // proxy patch interferes with.
        const client = new TLSClient({ runtimeMode: "native" }) as {
          start: () => Promise<void>;
          request: (url: string, opts: Record<string, unknown>) => Promise<TlsResponseLike>;
        };
        await client.start();

        installExitHook();
        return client;
      } catch (err) {
        clientPromise = null;
        const msg = err instanceof Error ? err.message : String(err);
        throw new TlsClientUnavailableError(
          `TLS impersonation client failed to start: ${msg}. ` +
            `Verify tls-client-node is installed and its native binary downloaded.`
        );
      }
    })


from_node_id: function:73602960351c57d7a8a2aa15c946510c
reference_kind: calls
file_path: open-sse/services/combo.ts
language: typescript
reference_name:
(async () => {
          try {
            const connections = await getProviderConnections({ provider, isActive: true });
            const activeConnections = Array.isArray(connections)
              ? (connections as Array<Record<string, unknown>>)
              : [];
            resetAwareConnectionCache.set(provider, {
              connections: activeConnections,
              fetchedAt: Date.now(),
            });
            return activeConnections;
          } catch (error) {
            log.warn?.("COMBO", "Reset-aware failed to load quota-aware connections.", {
              comboName,
              err: error,
              operation: "getProviderConnections",
              provider,
            });
            return [];
          }
        })


from_node_id: function:7f645006fb6bfeb1bf78e8af5d6a8cbd
reference_kind: calls
file_path: open-sse/services/combo.ts
language: typescript
reference_name:
(async () => {
              try {
                const { setLKGP } = await import("../../src/lib/localDb");
                await Promise.all([
                  setLKGP(combo.name, target.executionKey, provider, connId),
                  setLKGP(combo.name, combo.id || combo.name, provider, connId),
                ]);
              } catch (err) {
                log.warn("COMBO", "Failed to record Last Known Good Provider. This is non-fatal.", {
                  err,
                });
              }
            })


from_node_id: function:e2fd86246ef1ad7a22b7a142aa0994ae
reference_kind: calls
file_path: open-sse/services/combo.ts
language: typescript
reference_name:
(async () => {
              try {
                const { setLKGP } = await import("../../src/lib/localDb");
                await Promise.all([
                  setLKGP(combo.name, target.executionKey, provider, connId),
                  setLKGP(combo.name, combo.id || combo.name, provider, connId),
                ]);
              } catch (err) {
                log.warn(
                  "COMBO-RR",
                  "Failed to record Last Known Good Provider. This is non-fatal.",
                  {
                    err,
                  }
                );
              }
            })


from_node_id: function:eb1d1b3fd78149c03d56fec23ee6a658
reference_kind: calls
file_path: open-sse/services/gigachatAuth.ts
language: typescript
reference_name:
(async () => {
    const response = await fetch(authUrl, {
      method: "POST",
      headers: {
        Authorization: `Basic ${credentials}`,
        RqUID: randomUUID(),
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams({ scope }).toString(),
      signal: options.signal,
    });

    if (!response.ok) {
      const bodyText = await response.text();
      throw new Error(`GigaChat token request failed: ${response.status} ${bodyText}`.trim());
    }

    const data = (await response.json()) as Record<string, unknown>;
    const accessToken =
      typeof data.tok === "string"
        ? data.tok
        : typeof data.access_token === "string"
          ? data.access_token
          : "";
    if (!accessToken) {
      throw new Error("GigaChat token response missing access token");
    }

    const token = {
      accessToken,
      expiresAt: normalizeExpiry(data.exp ?? data.expires_at),
    };
    tokenCache.set(cacheKey, token);
    return token;
  })


from_node_id: function:9328a1b95dd0bc7abf439e982f3b8c8f
reference_kind: calls
file_path: open-sse/services/payloadRules.ts
language: typescript
reference_name:
(async () => {
    lastFileCheckAt = now;
    cachedFilePath = filePath;

    try {
      const stat = await fs.stat(filePath);
      if (!force && cachedFileMtimeMs === stat.mtimeMs) {
        return;
      }

      const content = await fs.readFile(filePath, "utf-8");
      const parsed = JSON.parse(content);
      cachedFileConfig = normalizePayloadRulesConfig(parsed);
      cachedFileMtimeMs = stat.mtimeMs;
      lastFileErrorSignature = "";
    } catch (error) {
      if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
        clearCachedFileConfig();
        lastFileErrorSignature = "";
        return;
      }

      const message = error instanceof Error ? error.message : String(error);
      const errorSignature = `${filePath}:${message}`;
      if (errorSignature !== lastFileErrorSignature) {
        console.warn(`[PAYLOAD_RULES] Failed to load ${filePath}: ${message}`);
        lastFileErrorSignature = errorSignature;
      }
    }
  })


from_node_id: function:7282b239ff70cd185097e27fad1787cf
reference_kind: calls
file_path: open-sse/services/usage.ts
language: typescript
reference_name:
(() => {
    const raw = toRecord(providerSpecificData).userId;
    return typeof raw === "string" && raw.length > 0 ? raw : null;
  })


from_node_id: function:1aea99059f7e0f282d1d408dfeedb028
reference_kind: calls
file_path: open-sse/services/usage.ts
language: typescript
reference_name:
(async () => {
    let response: Response | null = null;
    let lastError: Error | null = null;

    for (const quotaApiUrl of ANTIGRAVITY_CONFIG.quotaApiUrls) {
      try {
        response = await fetch(quotaApiUrl, {
          method: "POST",
          headers: getAntigravityHeaders("fetchAvailableModels", accessToken),
          body: JSON.stringify(projectId ? { project: projectId } : {}),
          signal: AbortSignal.timeout(10000),
        });

        if (response.ok || response.status === 401 || response.status === 403) {
          break;
        }
      } catch (error) {
        lastError = error as Error;
      }
    }

    if (!response) {
      throw lastError || new Error("Antigravity API unavailable");
    }

    if (response.status === 403) {
      return { __antigravityForbidden: true };
    }

    if (!response.ok) {
      throw new Error(`Antigravity API error: ${response.status}`);
    }

    const data = await response.json();
    _antigravityAvailableModelsCache.set(cacheKey, { data, fetchedAt: Date.now() });
    return data;
  })


from_node_id: function:2f9d06a9c620f43b11387e4b827ae7aa
reference_kind: calls
file_path: open-sse/translator/helpers/geminiToolsSanitizer.ts
language: typescript
reference_name:
(() => {
        const namespaceIndex = trimmed.indexOf(":");
        return namespaceIndex >= 0 ? trimmed.slice(namespaceIndex + 1) : trimmed;
      })


from_node_id: function:42c120659f4e02d601fbed446273779c
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/cli-tools/components/AntigravityToolCard.tsx
language: tsx
reference_name:
(() => {
              // Dynamic MITM instructions per tool (#505)
              const mitmDomains: Record<string, string> = {
                antigravity: "daily-cloudcode-pa.googleapis.com",
                kiro: "api.anthropic.com",
              };
              const toolName = tool.name || tool.id;
              const domain = mitmDomains[tool.id] || mitmDomains.antigravity;
              return (
                <div className="flex flex-col gap-1.5 px-1">
                  <p className="text-xs text-text-muted">
                    <span className="font-medium text-text-main">{t("howItWorks")}</span>{" "}
                    {t("mitmHowWorksDesc", { toolName })}
                  </p>
                  <div className="flex flex-col gap-0.5 text-[11px] text-text-muted">
                    <span>{t("mitmStep1")}</span>
                    <span>
                      {t("mitmStep2Prefix")}{" "}
                      <code className="text-[10px] bg-surface px-1 rounded">{domain}</code>{" "}
                      {t("mitmStep2Suffix")}
                    </span>
                    <span>{t("mitmStep3", { toolName })}</span>
                  </div>
                </div>
              );
            })


from_node_id: function:5343bcb4479586742268e18cbc9471c2
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/cli-tools/components/CodexToolCard.tsx
language: tsx
reference_name:
(() => {
                    const parsed = codexStatus.config.match(/base_url\s*=\s*"([^"]+)"/);
                    const currentBaseUrl = parsed ? parsed[1] : null;
                    return currentBaseUrl ? (
                      <div className="flex items-center gap-2">
                        <span className="w-32 shrink-0 text-sm font-semibold text-text-main text-right">
                          {t("current")}
                        </span>
                        <span className="material-symbols-outlined text-text-muted text-[14px]">
                          arrow_forward
                        </span>
                        <span className="flex-1 px-2 py-1.5 text-xs text-text-muted truncate">
                          {currentBaseUrl}
                        </span>
                      </div>
                    ) : null;
                  })


from_node_id: function:02b7a69e1d68259aada110b94b0fff80
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/cli-tools/components/DefaultToolCard.tsx
language: tsx
reference_name:
(() => {
                // Use runtime status if available (after expanding), otherwise use batch status
                const rs = runtimeStatus;
                const bs = batchStatus;
                const isGuide = rs?.reason === "not_required" || tool.configType === "guide";
                const isDetected = rs ? rs.installed && rs.runnable : bs?.installed && bs?.runnable;
                const isInstalled = rs ? rs.installed : bs?.installed;

                if (isGuide) {
                  return (
                    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 text-[11px] font-medium rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400">
                      <span className="size-1.5 rounded-full bg-blue-500" />
                      {t("guide")}
                    </span>
                  );
                }
                if (isDetected) {
                  return (
                    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 text-[11px] font-medium rounded-full bg-green-500/10 text-green-600 dark:text-green-400">
                      <span className="size-1.5 rounded-full bg-green-500" />
                      {t("detected")}
                    </span>
                  );
                }
                if (isInstalled === false && (rs || bs)) {
                  return (
                    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 text-[11px] font-medium rounded-full bg-zinc-500/10 text-zinc-500 dark:text-zinc-400">
                      <span className="size-1.5 rounded-full bg-zinc-400 dark:bg-zinc-500" />
                      {t("notInstalled")}
                    </span>
                  );
                }
                if (isInstalled && !isDetected && (rs || bs)) {
                  return (
                    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 text-[11px] font-medium rounded-full bg-yellow-500/10 text-yellow-600 dark:text-yellow-400">
                      <span className="size-1.5 rounded-full bg-yellow-500" />
                      {t("notReady")}
                    </span>
                  );
                }
                return null;
              })


from_node_id: function:5e059490fb74e9460051c11352553c76
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/health/page.tsx
language: tsx
reference_name:
(() => {
            const unhealthy = cbEntries.filter(([, cb]: [string, any]) => cb.state !== "CLOSED");
            const healthy = cbEntries.filter(([, cb]: [string, any]) => cb.state === "CLOSED");
            return (
              <div className="space-y-4">
                {/* Unhealthy providers first */}
                {unhealthy.length > 0 && (
                  <div className="space-y-2">
                    <p className="text-xs font-medium text-red-400 uppercase tracking-wide">
                      {t("issuesLabel")}
                    </p>
                    {unhealthy.map(([provider, cb]: [string, any]) => {
                      const style = CB_STYLES[cb.state] || CB_STYLES.OPEN;
                      const providerInfo = AI_PROVIDERS[provider];
                      const displayName = getProviderDisplayName(provider, providerInfo);
                      return (
                        <div
                          key={provider}
                          className={`rounded-lg p-3 ${style.bg} border border-white/5 flex items-center gap-3`}
                        >
                          <div
                            className="size-8 rounded-lg flex items-center justify-center shrink-0 text-xs font-bold"
                            style={{
                              backgroundColor: `${providerInfo?.color || "#888"}15`,
                              color: providerInfo?.color || "#888",
                            }}
                          >
                            {providerInfo?.textIcon || provider.slice(0, 2).toUpperCase()}
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2">
                              <span className="text-sm font-medium text-text-main truncate">
                                {displayName}
                              </span>
                              <span
                                className={`text-xs font-semibold px-1.5 py-0.5 rounded ${style.bg} ${style.text}`}
                              >
                                {t(style.labelKey)}
                              </span>
                            </div>
                            <div className="text-xs text-text-muted mt-0.5">
                              {cb.failures === 1
                                ? t("failures", { count: cb.failures })
                                : t("failuresPlural", { count: cb.failures })}
                              {Number(cb.retryAfterMs) > 0 && (
                                <span className="ml-2">· retry in {fmtMs(cb.retryAfterMs)}</span>
                              )}
                              {cb.lastFailure && (
                                <span className="ml-2">
                                  · {t("lastFailure")}:{" "}
                                  {new Date(cb.lastFailure).toLocaleTimeString()}
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}

                {/* Healthy providers in compact grid */}
                {healthy.length > 0 && (
                  <div>
                    {unhealthy.length > 0 && (
                      <p className="text-xs font-medium text-green-400 uppercase tracking-wide mb-2">
                        {t("operational")}
                      </p>
                    )}
                    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2">
                      {healthy.map(([provider]) => {
                        const providerInfo = AI_PROVIDERS[provider];
                        const displayName = getProviderDisplayName(provider, providerInfo);
                        return (
                          <div
                            key={provider}
                            className="rounded-lg p-2.5 bg-green-500/5 border border-white/5 flex items-center gap-2"
                          >
                            <span className="size-2 rounded-full bg-green-500 shrink-0" />
                            <span
                              className="text-xs font-medium text-text-main truncate"
                              title={displayName}
                            >
                              {displayName}
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}
              </div>
            );
          })


from_node_id: function:5e059490fb74e9460051c11352553c76
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/health/page.tsx
language: tsx
reference_name:
(() => {
          // Parse rate limit keys ("provider:connectionId" or "provider:connectionId:model")
          const parseKey = (key) => {
            const parts = key.split(":");
            const providerId = parts[0];
            const connectionId = parts[1] || "";
            const model = parts.slice(2).join(":") || null;

            // Resolve friendly name
            let displayName;
            let providerInfo = AI_PROVIDERS[providerId];

            if (providerId.startsWith("openai-compatible-")) {
              const customName = providerId.replace("openai-compatible-", "");
              displayName = tp("openaiCompatibleName");
              providerInfo = { color: "#10A37F", textIcon: "OC" };
              if (customName.length > 12) displayName += ` (${customName.slice(0, 8)}…)`;
              else if (customName) displayName += ` (${customName})`;
            } else if (providerId.startsWith("anthropic-compatible-")) {
              const customName = providerId.replace("anthropic-compatible-", "");
              displayName = tp("anthropicCompatibleName");
              providerInfo = { color: "#D97757", textIcon: "AC" };
              if (customName.length > 12) displayName += ` (${customName.slice(0, 8)}…)`;
              else if (customName) displayName += ` (${customName})`;
            } else {
              displayName = getProviderDisplayName(providerId, providerInfo);
            }

            return { providerId, displayName, providerInfo, connectionId, model };
          };

          // Group entries by provider for a cleaner display
          const entries = Object.entries(rateLimitStatus).map(([key, status]: [string, any]) => ({
            key,
            ...parseKey(key),
            status,
          }));

          // Sort: active (queued/running > 0) first, then alphabetically
          entries.sort((a, b) => {
            const aActive = (a.status.queued || 0) + (a.status.running || 0);
            const bActive = (b.status.queued || 0) + (b.status.running || 0);
            if (aActive !== bActive) return bActive - aActive;
            return a.displayName.localeCompare(b.displayName);
          });

          return (
            <Card className="p-5">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-lg font-semibold text-text-main flex items-center gap-2">
                  <span className="material-symbols-outlined text-[20px] text-amber-500">
                    speed
                  </span>
                  {t("rateLimitStatus")}
                </h2>
                <span className="text-xs text-text-muted">
                  {entries.length === 1
                    ? t("activeLimiters", { count: entries.length })
                    : t("activeLimitersPlural", { count: entries.length })}
                </span>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                {entries.map(
                  ({ key, displayName, providerInfo, connectionId, model, status }: any) => {
                    const learned = learnedLimits?.[key] || null;
                    const isActive = (status.queued || 0) + (status.running || 0) > 0;
                    const isQueued = (status.queued || 0) > 0;
                    const learnedLimit =
                      typeof learned?.limit === "number" && learned.limit > 0
                        ? learned.limit
                        : null;
                    const learnedRemaining =
                      typeof learned?.remaining === "number" ? learned.remaining : null;
                    const learnedMinTime =
                      typeof learned?.minTime === "number" && learned.minTime > 0
                        ? learned.minTime
                        : null;
                    const learnedLastUpdated =
                      typeof learned?.lastUpdated === "number" ? learned.lastUpdated : null;
                    const lowRemaining =
                      learnedLimit != null &&
                      learnedRemaining != null &&
                      learnedRemaining / learnedLimit <= 0.1;
                    const exhausted = learnedRemaining != null && learnedRemaining <= 0;
                    const quotaProgress =
                      learnedLimit != null && learnedRemaining != null
                        ? Math.max(0, Math.min(100, (learnedRemaining / learnedLimit) * 100))
                        : null;
                    return (
                      <div
                        key={key}
                        className={`rounded-lg p-3 border transition-colors ${
                          exhausted
                            ? "bg-red-500/5 border-red-500/20"
                            : isQueued || lowRemaining
                              ? "bg-amber-500/5 border-amber-500/20"
                              : isActive
                                ? "bg-blue-500/5 border-blue-500/15"
                                : "bg-surface/30 border-white/5"
                        }`}
                        title={key}
                      >
                        <div className="flex items-center gap-2.5 mb-2">
                          <div
                            className="size-7 rounded-md flex items-center justify-center shrink-0 text-[10px] font-bold"
                            style={{
                              backgroundColor: `${providerInfo?.color || "#888"}15`,
                              color: providerInfo?.color || "#888",
                            }}
                          >
                            {providerInfo?.textIcon || displayName.slice(0, 2).toUpperCase()}
                          </div>
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-text-main truncate">
                              {displayName}
                            </p>
                            {connectionId && (
                              <p className="text-[10px] text-text-muted font-mono truncate">
                                {connectionId.length > 12
                                  ? connectionId.slice(0, 8) + "…"
                                  : connectionId}
                                {model && (
                                  <span className="ml-1 text-text-muted/60">· {model}</span>
                                )}
                              </p>
                            )}
                          </div>
                          <span
                            className={`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold ${
                              exhausted
                                ? "bg-red-500/15 text-red-400"
                                : isQueued || lowRemaining
                                  ? "bg-amber-500/15 text-amber-400"
                                  : isActive
                                    ? "bg-blue-500/15 text-blue-400"
                                    : "bg-green-500/10 text-green-400"
                            }`}
                          >
                            {exhausted
                              ? t("limitExhausted")
                              : isQueued || lowRemaining
                                ? t("queued")
                                : isActive
                                  ? tc("active")
                                  : t("ok")}
                          </span>
                        </div>
                        {quotaProgress != null && (
                          <div className="mb-3">
                            <div className="mb-1 flex items-center justify-between text-[11px] text-text-muted">
                              <span>{t("learnedFromHeaders")}</span>
                              <span>
                                {t("remainingOfLimit", {
                                  remaining: learnedRemaining,
                                  limit: learnedLimit,
                                })}
                              </span>
                            </div>
                            <div className="h-2 overflow-hidden rounded-full bg-surface/70">
                              <div
                                className={`h-full rounded-full ${
                                  exhausted
                                    ? "bg-red-500"
                                    : lowRemaining
                                      ? "bg-amber-500"
                                      : "bg-emerald-500"
                                }`}
                                style={{ width: `${quotaProgress}%` }}
                              />
                            </div>
                          </div>
                        )}
                        <div className="flex items-center gap-3 text-[11px] text-text-muted">
                          <span className="flex items-center gap-1">
                            <span className="material-symbols-outlined text-[12px]">schedule</span>
                            {t("queuedCount", { count: status.queued || 0 })}
                          </span>
                          <span className="flex items-center gap-1">
                            <span className="material-symbols-outlined text-[12px]">
                              play_arrow
                            </span>
                            {t("runningCount", { count: status.running || 0 })}
                          </span>
                        </div>
                        {(learnedMinTime != null || learnedLastUpdated != null) && (
                          <div className="mt-3 space-y-1 text-[11px] text-text-muted">
                            {learnedMinTime != null && (
                              <p>{t("throttleStatus", { value: `${learnedMinTime}ms/req` })}</p>
                            )}
                            {learnedLastUpdated != null && (
                              <p>
                                {t("lastHeaderUpdate", {
                                  age: formatRelativeTime(learnedLastUpdated) || t("notAvailable"),
                                })}
                              </p>
                            )}
                          </div>
                        )}
                      </div>
                    );
                  }
                )}
              </div>
            </Card>
          );
        })


from_node_id: function:8a9f80192da15203f67135769e715b1f
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/playground/ChatPlayground.tsx
language: tsx
reference_name:
(() => {
    const seen = new Set<string>();
    const out: Array<{ value: string; label: string }> = [];
    for (const m of models) {
      if (typeof m?.id !== "string") continue;
      if (selectedProvider && !m.id.startsWith(selectedProvider + "/")) continue;
      if (seen.has(m.id)) continue;
      seen.add(m.id);
      out.push({ value: m.id, label: m.id });
    }
    return out;
  })


from_node_id: function:b402db171a1a1a2d0886e69cf1eeaca8
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/providers/[id]/page.tsx
language: tsx
reference_name:
(() => {
              const sorted = [...connections].sort((a, b) => (a.priority || 0) - (b.priority || 0));
              const hasAnyTag = sorted.some(
                (c) => c.providerSpecificData?.tag as string | undefined
              );
              const allSelected = selectedIds.size === connections.length && connections.length > 0;
              const someSelected = selectedIds.size > 0 && selectedIds.size < connections.length;

              if (!hasAnyTag) {
                return (
                  <>
                    <div className="flex items-center justify-between px-3 py-2 bg-muted/50 rounded-t-lg border border-b-0 border-border">
                      <label className="flex items-center gap-2 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          checked={allSelected}
                          ref={(el) => {
                            if (el) el.indeterminate = someSelected;
                          }}
                          onChange={handleToggleSelectAll}
                          className="w-4 h-4 rounded border-border text-primary focus:ring-primary/30 cursor-pointer"
                        />
                        <span className="text-sm font-medium text-text-muted">
                          {selectedIds.size > 0
                            ? `${selectedIds.size} selected`
                            : `${connections.length} accounts`}
                        </span>
                      </label>

                      {selectedIds.size > 0 && (
                        <Button
                          variant="danger"
                          size="sm"
                          icon="delete"
                          loading={batchDeleting}
                          onClick={handleBatchDelete}
                        >
                          {t("batchDeleteSelected", { count: selectedIds.size })}
                        </Button>
                      )}
                    </div>
                    <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03] border border-t-0 border-border rounded-b-lg overflow-hidden">
                      {sorted.map((conn, index) => (
                        <ConnectionRow
                          key={conn.id}
                          connection={conn}
                          isOAuth={conn.authType === "oauth"}
                          isClaude={providerId === "claude"}
                          codexFastGlobalEnabled={codexGlobalFastServiceTier}
                          isFirst={index === 0}
                          isLast={index === sorted.length - 1}
                          isSelected={selectedIds.has(conn.id)}
                          onToggleSelect={() => handleToggleSelectOne(conn.id)}
                          onMoveUp={() => handleSwapPriority(conn, sorted[index - 1])}
                          onMoveDown={() => handleSwapPriority(conn, sorted[index + 1])}
                          onToggleActive={(isActive) =>
                            handleUpdateConnectionStatus(conn.id, isActive)
                          }
                          onToggleRateLimit={(enabled) => handleToggleRateLimit(conn.id, enabled)}
                          onToggleClaudeExtraUsage={(enabled) =>
                            handleToggleClaudeExtraUsage(conn.id, enabled)
                          }
                          isCodex={providerId === "codex"}
                          isGeminiCli={providerId === "gemini-cli"}
                          isCcCompatible={isCcCompatible}
                          cliproxyapiEnabled={cpaProviderEnabled}
                          onToggleCliproxyapiMode={(enabled) =>
                            handleToggleCliproxyapiMode(conn.id, enabled)
                          }
                          onToggleCodex5h={(enabled) =>
                            handleToggleCodexLimit(conn.id, "use5h", enabled)
                          }
                          onToggleCodexWeekly={(enabled) =>
                            handleToggleCodexLimit(conn.id, "useWeekly", enabled)
                          }
                          onRetest={() => handleRetestConnection(conn.id)}
                          isRetesting={retestingId === conn.id}
                          onEdit={() => {
                            setSelectedConnection(conn);
                            setShowEditModal(true);
                          }}
                          onDelete={() => handleDelete(conn.id)}
                          onReauth={
                            conn.authType === "oauth"
                              ? () => setShowOAuthModal(true, conn)
                              : undefined
                          }
                          onRefreshToken={
                            conn.authType === "oauth"
                              ? () => handleRefreshToken(conn.id)
                              : undefined
                          }
                          isRefreshing={refreshingId === conn.id}
                          onApplyCodexAuthLocal={
                            providerId === "codex"
                              ? () => setApplyCodexModalConnectionId(conn.id)
                              : undefined
                          }
                          isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
                          onExportCodexAuthFile={
                            providerId === "codex"
                              ? () => handleExportCodexAuthFile(conn.id)
                              : undefined
                          }
                          isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
                          onApplyClaudeAuthLocal={
                            providerId === "claude"
                              ? () => setApplyClaudeModalConnectionId(conn.id)
                              : undefined
                          }
                          isApplyingClaudeAuthLocal={applyingClaudeAuthId === conn.id}
                          onExportClaudeAuthFile={
                            providerId === "claude"
                              ? () => handleExportClaudeAuthFile(conn.id)
                              : undefined
                          }
                          isExportingClaudeAuthFile={exportingClaudeAuthId === conn.id}
                          onApplyGeminiAuthLocal={
                            providerId === "gemini-cli"
                              ? () => setApplyGeminiModalConnectionId(conn.id)
                              : undefined
                          }
                          isApplyingGeminiAuthLocal={applyingGeminiAuthId === conn.id}
                          onExportGeminiAuthFile={
                            providerId === "gemini-cli"
                              ? () => handleExportGeminiAuthFile(conn.id)
                              : undefined
                          }
                          isExportingGeminiAuthFile={exportingGeminiAuthId === conn.id}
                          onProxy={() =>
                            setProxyTarget({
                              level: "key",
                              id: conn.id,
                              label: pickDisplayValue(
                                [conn.name, conn.email],
                                emailsVisible,
                                conn.id
                              ),
                            })
                          }
                          hasProxy={!!connProxyMap[conn.id]?.proxy}
                          proxySource={connProxyMap[conn.id]?.level || null}
                          proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
                        />
                      ))}
                    </div>
                  </>
                );
              }

              // Build ordered tag groups: untagged first, then alphabetically
              const groupMap = new Map<string, ConnectionRowConnection[]>();
              for (const conn of sorted) {
                const tag = (conn.providerSpecificData?.tag as string | undefined)?.trim() || "";
                if (!groupMap.has(tag)) groupMap.set(tag, []);
                groupMap.get(tag)!.push(conn);
              }
              const groupKeys = Array.from(groupMap.keys()).sort((a, b) => {
                if (a === "") return -1;
                if (b === "") return 1;
                return a.localeCompare(b);
              });

              return (
                <>
                  {selectedIds.size > 0 || connections.length > 0 ? (
                    <div className="flex items-center justify-between px-3 py-2 bg-muted/50 rounded-t-lg border border-b-0 border-border">
                      <label className="flex items-center gap-2 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          checked={allSelected}
                          ref={(el) => {
                            if (el) el.indeterminate = someSelected;
                          }}
                          onChange={handleToggleSelectAll}
                          className="w-4 h-4 rounded border-border text-primary focus:ring-primary/30 cursor-pointer"
                        />
                        <span className="text-sm font-medium text-text-muted">
                          {selectedIds.size > 0
                            ? `${selectedIds.size} selected`
                            : `${connections.length} accounts`}
                        </span>
                      </label>

                      {selectedIds.size > 0 && (
                        <Button
                          variant="danger"
                          size="sm"
                          icon="delete"
                          loading={batchDeleting}
                          onClick={handleBatchDelete}
                        >
                          {t("batchDeleteSelected", { count: selectedIds.size })}
                        </Button>
                      )}
                    </div>
                  ) : null}
                  <div className="flex flex-col gap-0 border border-t-0 border-border rounded-b-lg overflow-hidden">
                    {groupKeys.map((tag, gi) => {
                      const groupConns = groupMap.get(tag)!;
                      return (
                        <div
                          key={tag || "__untagged__"}
                          className={
                            gi > 0
                              ? "border-t border-black/[0.06] dark:border-white/[0.06] mt-1 pt-1"
                              : ""
                          }
                        >
                          {tag && (
                            <div className="flex items-center gap-2 px-3 pt-2 pb-1">
                              <span className="material-symbols-outlined text-[13px] text-text-muted/50">
                                label
                              </span>
                              <span className="text-[11px] font-semibold uppercase tracking-widest text-text-muted/60 select-none">
                                {tag}
                              </span>
                              <div className="flex-1 h-px bg-black/[0.04] dark:bg-white/[0.04]" />
                              <span className="text-[10px] text-text-muted/40">
                                {groupConns.length}
                              </span>
                            </div>
                          )}
                          <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]">
                            {groupConns.map((conn, index) => (
                              <ConnectionRow
                                key={conn.id}
                                connection={conn}
                                isOAuth={conn.authType === "oauth"}
                                isClaude={providerId === "claude"}
                                codexFastGlobalEnabled={codexGlobalFastServiceTier}
                                isFirst={gi === 0 && index === 0}
                                isLast={
                                  gi === groupKeys.length - 1 && index === groupConns.length - 1
                                }
                                isSelected={selectedIds.has(conn.id)}
                                onToggleSelect={() => handleToggleSelectOne(conn.id)}
                                onMoveUp={() =>
                                  handleSwapPriority(conn, sorted[sorted.indexOf(conn) - 1])
                                }
                                onMoveDown={() =>
                                  handleSwapPriority(conn, sorted[sorted.indexOf(conn) + 1])
                                }
                                onToggleActive={(isActive) =>
                                  handleUpdateConnectionStatus(conn.id, isActive)
                                }
                                onToggleRateLimit={(enabled) =>
                                  handleToggleRateLimit(conn.id, enabled)
                                }
                                onToggleClaudeExtraUsage={(enabled) =>
                                  handleToggleClaudeExtraUsage(conn.id, enabled)
                                }
                                isCodex={providerId === "codex"}
                                isGeminiCli={providerId === "gemini-cli"}
                                isCcCompatible={isCcCompatible}
                                cliproxyapiEnabled={cpaProviderEnabled}
                                onToggleCodex5h={(enabled) =>
                                  handleToggleCodexLimit(conn.id, "use5h", enabled)
                                }
                                onToggleCodexWeekly={(enabled) =>
                                  handleToggleCodexLimit(conn.id, "useWeekly", enabled)
                                }
                                onRetest={() => handleRetestConnection(conn.id)}
                                isRetesting={retestingId === conn.id}
                                onEdit={() => {
                                  setSelectedConnection(conn);
                                  setShowEditModal(true);
                                }}
                                onDelete={() => handleDelete(conn.id)}
                                onReauth={
                                  conn.authType === "oauth"
                                    ? () => setShowOAuthModal(true, conn)
                                    : undefined
                                }
                                onRefreshToken={
                                  conn.authType === "oauth"
                                    ? () => handleRefreshToken(conn.id)
                                    : undefined
                                }
                                isRefreshing={refreshingId === conn.id}
                                onApplyCodexAuthLocal={
                                  providerId === "codex"
                                    ? () => setApplyCodexModalConnectionId(conn.id)
                                    : undefined
                                }
                                isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
                                onExportCodexAuthFile={
                                  providerId === "codex"
                                    ? () => handleExportCodexAuthFile(conn.id)
                                    : undefined
                                }
                                isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
                                onApplyClaudeAuthLocal={
                                  providerId === "claude"
                                    ? () => setApplyClaudeModalConnectionId(conn.id)
                                    : undefined
                                }
                                isApplyingClaudeAuthLocal={applyingClaudeAuthId === conn.id}
                                onExportClaudeAuthFile={
                                  providerId === "claude"
                                    ? () => handleExportClaudeAuthFile(conn.id)
                                    : undefined
                                }
                                isExportingClaudeAuthFile={exportingClaudeAuthId === conn.id}
                                onApplyGeminiAuthLocal={
                                  providerId === "gemini-cli"
                                    ? () => setApplyGeminiModalConnectionId(conn.id)
                                    : undefined
                                }
                                isApplyingGeminiAuthLocal={applyingGeminiAuthId === conn.id}
                                onExportGeminiAuthFile={
                                  providerId === "gemini-cli"
                                    ? () => handleExportGeminiAuthFile(conn.id)
                                    : undefined
                                }
                                isExportingGeminiAuthFile={exportingGeminiAuthId === conn.id}
                                onProxy={() =>
                                  setProxyTarget({
                                    level: "key",
                                    id: conn.id,
                                    label: pickDisplayValue(
                                      [conn.name, conn.email],
                                      emailsVisible,
                                      conn.id
                                    ),
                                  })
                                }
                                hasProxy={!!connProxyMap[conn.id]?.proxy}
                                proxySource={connProxyMap[conn.id]?.level || null}
                                proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
                              />
                            ))}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </>
              );
            })


from_node_id: function:12daac7e75a62a3d9e51b506ceae5b91
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/providers/[id]/page.tsx
language: tsx
reference_name:
(() => {
                const colorClass =
                  proxySource === "global"
                    ? "bg-emerald-500/15 text-emerald-500"
                    : proxySource === "provider"
                      ? "bg-amber-500/15 text-amber-500"
                      : "bg-blue-500/15 text-blue-500";
                const label =
                  proxySource === "global"
                    ? t("proxySourceGlobal")
                    : proxySource === "provider"
                      ? t("proxySourceProvider")
                      : t("proxySourceKey");
                return (
                  <>
                    <span className="text-text-muted/30 select-none">|</span>
                    <span
                      className={`inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-xs font-medium ${colorClass}`}
                      title={t("proxyConfiguredBySource", {
                        source: label,
                        host: proxyHost || t("configured"),
                      })}
                    >
                      <span className="material-symbols-outlined text-[13px]">vpn_lock</span>
                      {proxyHost || t("proxy")}
                    </span>
                  </>
                );
              })


from_node_id: function:ee170fa621fd3530fa8e7705d1b80cf4
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/providers/[id]/page.tsx
language: tsx
reference_name:
(() => {
                const keyId = "primary";
                const health = apiKeyHealth[keyId];
                const statusColor =
                  health?.status === "invalid"
                    ? "text-red-400"
                    : health?.status === "warning"
                      ? "text-yellow-400"
                      : "text-text-muted";
                const statusIcon =
                  health?.status === "invalid" ? "🔴" : health?.status === "warning" ? "🟡" : "🟢";
                const statusLabel =
                  health?.status === "invalid"
                    ? t("apiKeyStatusInvalid")
                    : health?.status === "warning"
                      ? t("apiKeyStatusWarning", { count: health.failures })
                      : t("apiKeyStatusActive");

                return (
                  <div className="flex items-center gap-2">
                    <span
                      className={`flex-1 font-mono text-xs bg-sidebar/50 px-3 py-2 rounded border border-border truncate ${statusColor}`}
                    >
                      {statusIcon} {t("primaryKey")}: {connection.apiKey.slice(0, 6)}...
                      {connection.apiKey.slice(-4)}
                    </span>
                    {health && (
                      <span
                        className="text-[10px] text-text-muted whitespace-nowrap"
                        title={statusLabel}
                      >
                        {health.failures}x
                        {health.lastFailure ? ` · ${formatTimeAgo(health.lastFailure)}` : ""}
                        {health.totalRequests != null
                          ? ` · (${health.totalRequests} req${health.totalFailures != null ? `, ${health.totalFailures} fail` : ""})`
                          : ""}
                      </span>
                    )}
                  </div>
                );
              })


from_node_id: function:d99ebca1e95625e61c10ec6d641bcae7
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/providers/components/ProviderCard.tsx
language: tsx
reference_name:
(() => {
    if (isCompatible) {
      return provider.apiType === "responses" ? "/providers/oai-r.png" : "/providers/oai-cc.png";
    }
    if (isAnthropicCompatible || isCcCompatible) return "/providers/anthropic-m.png";
    return null;
  })


from_node_id: function:239f165ed8fb51fd89e11019457ce53f
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/runtime/RuntimePageClient.tsx
language: tsx
reference_name:
(() => {
            const monitors = health?.quotaMonitor?.monitors ?? [];
            const exhausted = monitors.filter((m) => m.status === "exhausted");
            const alerting = monitors.filter((m) => m.status === "alerting");
            const errors = monitors.filter((m) => m.status === "error");
            const total = exhausted.length + alerting.length + errors.length;
            if (total === 0) {
              return (
                <div className="text-center py-8 text-text-muted">
                  <span className="material-symbols-outlined text-[40px] opacity-30 block mb-2">
                    radar
                  </span>
                  <p className="text-sm">{t("allQuotasHealthy")}</p>
                </div>
              );
            }
            return (
              <div className="mt-2 flex flex-col gap-3">
                {exhausted.length > 0 && (
                  <QuotaGroup tone="red" label={t("statusExhausted")} items={exhausted} />
                )}
                {alerting.length > 0 && (
                  <QuotaGroup tone="amber" label={t("statusAlerting")} items={alerting} />
                )}
                {errors.length > 0 && (
                  <QuotaGroup tone="orange" label={t("statusError")} items={errors} />
                )}
              </div>
            );
          })


from_node_id: function:2f322d51d632a3da4f16b15eb2b9d671
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/settings/components/PricingTab.tsx
language: tsx
reference_name:
(() => {
            const pct =
              provider.modelCount > 0 ? Math.round((pricedCount / provider.modelCount) * 100) : 0;
            const barColor =
              pct >= 100 ? "bg-emerald-500" : pct >= 50 ? "bg-amber-500" : "bg-red-500";
            const textColor =
              pct >= 100 ? "text-emerald-400" : pct >= 50 ? "text-amber-400" : "text-red-400";
            const icon = pct >= 100 ? "✓" : pct >= 50 ? "◐" : "⚠";
            return (
              <>
                <div className="w-20 h-1.5 bg-bg-subtle rounded-full overflow-hidden">
                  <div
                    className={`h-full ${barColor} rounded-full transition-all`}
                    style={{ width: `${pct}%` }}
                  />
                </div>
                <span
                  className={`text-[11px] font-bold tabular-nums w-10 text-right ${textColor}`}
                  title={`${pricedCount}/${provider.modelCount} ${t("withPricing")}`}
                >
                  {pct}% {icon}
                </span>
              </>
            );
          })


from_node_id: function:64b6cd41243043bbebc8af3d4b9cbbd8
reference_kind: calls
file_path: src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx
language: tsx
reference_name:
(() => {
                const tier = TIER_FILTERS.find((tier) => tier.key === tierFilter);
                return tier?.label || t(tier?.labelKey || "tierUnknown");
              })


from_node_id: function:26663d724908f0e26528cfdba4c2e705
reference_kind: calls
file_path: src/app/api/providers/[id]/models/route.ts
language: typescript
reference_name:
(async () => {
    await resolveAntigravityVersion();
    await ensureAntigravityProjectAssigned(
      accessToken,
      fetch,
      normalizeAntigravityClientProfile(asRecord(providerSpecificData).clientProfile)
    );

    for (const discoveryUrl of [
      ...getAntigravityFetchAvailableModelsUrls(),
      ...getAntigravityModelsDiscoveryUrls(),
    ]) {
      try {
        const response = await safeOutboundFetch(discoveryUrl, {
          ...SAFE_OUTBOUND_FETCH_PRESETS.modelsDiscovery,
          guard: getProviderOutboundGuard(),
          proxyConfig: proxy,
          method: "POST",
          headers: getAntigravityHeaders("models", accessToken),
          body: JSON.stringify({}),
        });

        if (!response.ok) {
          const errorText = await response.text();
          console.warn(
            `[models] antigravity discovery failed at ${discoveryUrl} (${response.status}): ${errorText}`
          );
          continue;
        }

        const models = filterUserCallableAntigravityModels(
          normalizeAntigravityModelsResponse(await response.json())
        ).map(mapAntigravityModelForClient);
        if (models.length > 0) {
          return models;
        }
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.warn(`[models] antigravity discovery threw for ${discoveryUrl}: ${message}`);
      }
    }

    return [];
  })


from_node_id: function:8ba38c4c4566e21d6cfc4836f781f19f
reference_kind: calls
file_path: src/app/api/providers/[id]/sync-models/route.ts
language: typescript
reference_name:
(async () => {
    const f = opts.fetch ?? fetch;
    const maxWaitMs = opts.maxWaitMs ?? 30_000;
    const pollMs = opts.pollMs ?? 250;
    const deadline = Date.now() + maxWaitMs;
    let lastErr: unknown;
    while (Date.now() < deadline) {
      try {
        // Hit a stable endpoint; any HTTP status (200/404/etc) confirms
        // readiness — we only care that the dispatcher succeeds (no
        // ECONNREFUSED). Using a synthetic connection id so no real DB lookup
        // is needed; the 404 is sufficient proof the server is dispatching.
        const probePort = process.env.OMNIROUTE_PORT || process.env.PORT || "20128";
        const res = await f(
          `http://127.0.0.1:${probePort}/api/providers/__readiness_probe__/models`,
          {
            signal: AbortSignal.timeout(2_000),
          }
        );
        if (res.status >= 200 && res.status < 600) return;
      } catch (err) {
        lastErr = err;
      }
      await new Promise((r) => setTimeout(r, pollMs));
    }
    throw new Error(`loopback server not ready within ${maxWaitMs}ms: ${String(lastErr)}`);
  })


from_node_id: function:aeee1b6c25503cdc6b01dee51d3d4822
reference_kind: calls
file_path: src/app/api/tunnels/tailscale/install/route.ts
language: typescript
reference_name:
(async () => {
        try {
          await installTailscale({
            sudoPassword: parsed.data.sudoPassword,
            onProgress: (message) => pushEvent("progress", { message }),
          });

          pushEvent("done", {
            success: true,
            status: await getTailscaleTunnelStatus(),
          });
        } catch (error) {
          pushEvent("error", {
            error: error instanceof Error ? error.message : "Failed to install Tailscale",
          });
        } finally {
          controller.close();
        }
      })


from_node_id: function:caf3ee1bbfafc0ae733cdcb1cd402c4c
reference_kind: calls
file_path: src/lib/cloudflaredTunnel.ts
language: typescript
reference_name:
(async () => {
    const spec = getCloudflaredAssetSpec();
    if (!spec) {
      throw new Error(
        `Unsupported platform for managed cloudflared install: ${process.platform}/${process.arch}`
      );
    }

    await ensureTunnelDir();
    const managedBinaryPath = getManagedBinaryPath();
    const tempDownloadPath = path.join(getTunnelDir(), `${spec.assetName}.download`);

    await updateStateFile({
      status: "starting",
      lastError: null,
    });

    try {
      const downloadSpec = await resolveCloudflaredDownloadSpec(spec);
      await downloadToFile(
        downloadSpec.downloadUrl,
        tempDownloadPath,
        downloadSpec.expectedSha256,
        downloadSpec.assetName
      );

      if (spec.archive === "tgz") {
        await extractArchive(tempDownloadPath, path.dirname(managedBinaryPath));
      } else {
        await fs.rename(tempDownloadPath, managedBinaryPath);
      }

      await ensureExecutable(managedBinaryPath);
      await updateStateFile({
        binaryPath: managedBinaryPath,
        installSource: "managed",
        installedAt: new Date().toISOString(),
        lastError: null,
      });

      return managedBinaryPath;
    } finally {
      try {
        await fs.unlink(tempDownloadPath);
      } catch {
        // Ignore temp cleanup issues.
      }
      installPromise = null;
    }
  })


from_node_id: function:4190fffcb9a7a135c7c4e363ec99d2f0
reference_kind: calls
file_path: src/lib/cloudflaredTunnel.ts
language: typescript
reference_name:
(async () => {
    const spec = getCloudflaredAssetSpec();
    if (!spec && !(await resolveBinary()).binaryPath) {
      throw new Error(
        `Unsupported platform for cloudflared tunnel: ${process.platform}/${process.arch}`
      );
    }

    const binary = await ensureBinary();
    const targetUrl = getLocalTargetUrl();

    await stopExistingTunnel();
    await ensureTunnelDir();
    await ensureTunnelRuntimeDirs();
    await fs.writeFile(getLogFilePath(), "", "utf8");

    await writeStateFile({
      binaryPath: binary.binaryPath,
      installSource: binary.source,
      ownerPid: process.pid,
      pid: null,
      publicUrl: null,
      apiUrl: null,
      targetUrl,
      status: "starting",
      lastError: null,
      startedAt: new Date().toISOString(),
    });

    const child = spawn(binary.binaryPath as string, getCloudflaredStartArgs(targetUrl), {
      stdio: ["ignore", "pipe", "pipe"],
      env: buildCloudflaredChildEnv(),
    });

    tunnelProcess = child;
    tunnelPid = child.pid ?? null;

    if (!child.pid) {
      throw new Error("cloudflared failed to start");
    }

    await writePidFile(child.pid);
    await updateStateFile({ pid: child.pid, status: "starting" });

    const ready = await new Promise<CloudflaredTunnelStatus>((resolve, reject) => {
      let settled = false;
      let timeout: ReturnType<typeof setTimeout> | null = null;

      const settle = (handler: () => void) => {
        if (settled) return;
        settled = true;
        if (timeout) clearTimeout(timeout);
        handler();
      };

      const handleOutput = async (source: "stdout" | "stderr", chunk: Buffer) => {
        const text = chunk.toString("utf8").trim();
        if (!text) return;

        await appendTunnelLog(source, text);
        const errorMessage = source === "stderr" ? extractCloudflaredErrorMessage(text) : null;
        if (errorMessage) {
          await updateStateFile({
            ownerPid: process.pid,
            pid: child.pid,
            status: "error",
            lastError: errorMessage,
          });
        }
        const url = extractTryCloudflareUrl(text);
        if (!url) return;

        const apiUrl = getTunnelApiUrl(url);
        await updateStateFile({
          ownerPid: process.pid,
          pid: child.pid,
          publicUrl: url,
          apiUrl,
          status: "running",
          lastError: null,
        });

        const status = await getCloudflaredTunnelStatus();
        settle(() => resolve(status));
      };

      child.stdout.on("data", (chunk: Buffer) => {
        void handleOutput("stdout", chunk);
      });
      child.stderr.on("data", (chunk: Buffer) => {
        void handleOutput("stderr", chunk);
      });

      child.once("exit", (code, signal) => {
        void finalizeProcessExit(code, signal);
        settle(() =>
          reject(
            new Error(
              `cloudflared exited before tunnel URL was ready (${code ?? "signal"}${signal ? `/${signal}` : ""})`
            )
          )
        );
      });

      timeout = setTimeout(async () => {
        await stopExistingTunnel();
        settle(() => reject(new Error("Timed out while waiting for Cloudflare tunnel URL")));
      }, START_TIMEOUT_MS);
    });

    return ready;
  })


from_node_id: function:20556524c7580f3c14d205b74515a358
reference_kind: calls
file_path: src/lib/db/commandCodeAuth.ts
language: typescript
reference_name:
database.transaction(() => {
    const now = nowIso();
    database
      .prepare(
        `UPDATE command_code_auth_sessions
         SET status = 'expired', updated_at = ?
         WHERE state_hash = ? AND status IN ('pending', 'received') AND expires_at <= ?`
      )
      .run(now, stateHash, now);

    const row = database
      .prepare<AuthSessionRow>(
        `SELECT * FROM command_code_auth_sessions
         WHERE state_hash = ? AND status = 'received' AND expires_at > ? AND encrypted_api_key IS NOT NULL`
      )
      .get(stateHash, now);
    if (!row?.encrypted_api_key) return null;

    const apiKey = decrypt(row.encrypted_api_key);
    if (!apiKey) return null;

    const result = database
      .prepare(
        `UPDATE command_code_auth_sessions
         SET status = 'applied', encrypted_api_key = NULL, applied_at = ?, updated_at = ?
         WHERE id = ? AND status = 'received'`
      )
      .run(now, now, row.id);
    if (!result.changes) return null;

    return {
      ...toSafeStatus({
        ...row,
        status: "applied",
        encrypted_api_key: null,
        applied_at: now,
        updated_at: now,
      }),
      apiKey,
    };
  })


from_node_id: function:aa7ddab4c4d7955f07e0207550d29361
reference_kind: calls
file_path: src/lib/db/compressionCombos.ts
language: typescript
reference_name:
db.transaction(() => {
    db.prepare("UPDATE compression_combos SET is_default = 0").run();
    db.prepare("UPDATE compression_combos SET is_default = 1, updated_at = ? WHERE id = ?").run(
      now,
      id
    );
  })


from_node_id: function:1bafe5af27d39371b0419e32f5a91c15
reference_kind: calls
file_path: src/lib/db/compressionCombos.ts
language: typescript
reference_name:
db.transaction(() => {
    db.prepare("DELETE FROM compression_combo_assignments WHERE compression_combo_id = ?").run(
      compressionComboId
    );
    if (cleanedIds.length > 0) {
      const deleteExisting = db.prepare(
        "DELETE FROM compression_combo_assignments WHERE routing_combo_id = ?"
      );
      const insert = db.prepare(
        `
        INSERT INTO compression_combo_assignments (
          id, compression_combo_id, routing_combo_id, created_at
        )
        VALUES (?, ?, ?, ?)
      `
      );
      for (const routingComboId of cleanedIds) {
        deleteExisting.run(routingComboId);
        insert.run(uuidv4(), compressionComboId, routingComboId, new Date().toISOString());
      }
    }
  })


from_node_id: function:6811bb4fe3e48b32f8db26a1cfa71bb0
reference_kind: calls
file_path: src/lib/db/providers.ts
language: typescript
reference_name:
db.transaction(() => {
    const placeholders = ids.map(() => "?").join(",");
    db.prepare(`DELETE FROM quota_snapshots WHERE connection_id IN (${placeholders})`).run(...ids);
    const result = db
      .prepare(`DELETE FROM provider_connections WHERE id IN (${placeholders})`)
      .run(...ids);
    return result.changes ?? 0;
  })


from_node_id: function:58c7e7058be20168cde4263d55b42c4c
reference_kind: calls
file_path: src/lib/modelMetadataRegistry.ts
language: typescript
reference_name:
(() => {
      const id = asNonEmptyString(entry.id);
      if (!id) return null;
      if (id.includes("/")) return id.slice(id.indexOf("/") + 1);
      return id;
    })


from_node_id: function:e777ede8c270873c54126941f9d6b2e4
reference_kind: calls
file_path: src/lib/ngrokTunnel.ts
language: typescript
reference_name:
(async () => {
    try {
      const authToken =
        inputAuthToken && inputAuthToken.trim() !== ""
          ? inputAuthToken.trim()
          : process.env.NGROK_AUTHTOKEN;

      if (!authToken) {
        return {
          ...(await getNgrokTunnelStatus()),
          phase: "needs_auth",
          lastError: "An ngrok authtoken is required.",
        };
      }

      // Dynamically import ngrok so it doesn't break environments where native build fails if not used
      const ngrok = await import("@ngrok/ngrok");

      const targetUrl = getLocalTargetUrl();
      const listenerOptions: any = { addr: targetUrl };

      if (!inputAuthToken && process.env.NGROK_AUTHTOKEN) {
        listenerOptions.authtoken_from_env = true;
      } else {
        listenerOptions.authtoken = authToken;
      }

      const listener = await ngrok.forward(listenerOptions);
      globalForNgrok.__ngrokListener = listener;

      let url = null;
      try {
        url = typeof listener.url === "function" ? listener.url() : listener.url;
      } catch {
        // Ignored
      }

      if (!url) {
        await stopNgrokTunnel();
        throw new Error("ngrok did not return a public URL.");
      }

      return await getNgrokTunnelStatus();
    } catch (error) {
      return {
        ...(await getNgrokTunnelStatus()),
        phase: "error",
        lastError: error instanceof Error ? error.message : String(error),
      };
    } finally {
      startPromise = null;
    }
  })


from_node_id: method:9af6d83e66ffd54f8fec95b7524997a9
reference_kind: calls
file_path: src/lib/skills/registry.ts
language: typescript
reference_name:
(async () => {
      try {
        log.debug("skills.registry.loadFromDatabase", { cached: false });
        const db = getDbInstance();
        const rows = apiKeyId
          ? db.prepare("SELECT * FROM skills WHERE api_key_id = ?").all(apiKeyId)
          : db.prepare("SELECT * FROM skills").all();

        for (const row of rows as any[]) {
          const tags = (() => {
            try {
              if (typeof row.tags !== "string") return [];
              const parsed = JSON.parse(row.tags);
              return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
            } catch {
              return [];
            }
          })();

          const skill: Skill = {
            id: row.id,
            apiKeyId: row.api_key_id,
            name: row.name,
            version: row.version,
            description: row.description || "",
            schema: JSON.parse(row.schema),
            handler: row.handler,
            enabled: row.enabled === 1,
            mode: row.mode === "off" || row.mode === "auto" ? row.mode : "on",
            sourceProvider:
              row.source_provider === "skillsmp" || row.source_provider === "skillssh"
                ? row.source_provider
                : row.source_provider
                  ? "local"
                  : undefined,
            tags,
            installCount: typeof row.install_count === "number" ? row.install_count : 0,
            createdAt: new Date(row.created_at),
            updatedAt: new Date(row.updated_at),
          };
          this.registeredSkills.set(`${skill.name}@${skill.version}`, skill);
          this.updateVersionCache(skill);
        }
        this.lastLoaded = Date.now();
      } catch (err: any) {
        log.error("loadFromDatabase error:", err);
        throw err;
      } finally {
        this.pendingLoad = null;
      }
    })


from_node_id: method:9af6d83e66ffd54f8fec95b7524997a9
reference_kind: calls
file_path: src/lib/skills/registry.ts
language: typescript
reference_name:
(() => {
            try {
              if (typeof row.tags !== "string") return [];
              const parsed = JSON.parse(row.tags);
              return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
            } catch {
              return [];
            }
          })


from_node_id: method:54652db05c30336a38dc1009d7ac1b7f
reference_kind: calls
file_path: src/lib/spend/batchWriter.ts
language: typescript
reference_name:
(async () => {
      const entriesToPersist = entriesToFlush.filter(
        (entry) => !this.discardedApiKeyIds.has(entry.apiKeyId)
      );
      const uniqueKeys = new Set(entriesToPersist.map((entry) => entry.apiKeyId)).size;

      try {
        if (entriesToPersist.length > 0) {
          await this.persistEntries(entriesToPersist);
        }
        this.logger.log(
          `[SpendWriter] Flushed ${entriesToPersist.length} cost entr${
            entriesToPersist.length === 1 ? "y" : "ies"
          } across ${uniqueKeys} key(s)`
        );
        return {
          flushedEntries: entriesToPersist.length,
          uniqueKeys,
          requeued: false,
        };
      } catch (error) {
        this.buffer = [...entriesToPersist, ...this.buffer];
        const message = error instanceof Error ? error.message : String(error);
        this.logger.error(`[SpendWriter] Flush error: ${message}`);
        return {
          flushedEntries: 0,
          uniqueKeys,
          requeued: true,
        };
      } finally {
        this.inFlightEntries = [];
        this.flushPromise = null;
      }
    })


from_node_id: function:41836edb3c92acf9e4d6b0529858739f
reference_kind: calls
file_path: src/lib/tokenHealthCheck.ts
language: typescript
reference_name:
(async () => {
    try {
      const settings = await getSettings();
      cachedHideLogs = settings.hideHealthCheckLogs === true;
      cacheTimestamp = now;
      return cachedHideLogs;
    } catch {
      return false;
    } finally {
      pendingHideLogs = null;
    }
  })


from_node_id: function:1828196d40df081748b06edd7b756603
reference_kind: calls
file_path: src/shared/components/RequestLoggerDetail.tsx
language: tsx
reference_name:
(() => {
    if (!debugEnabled || !detail?.pipelinePayloads?.streamChunks) return null;
    let chunks: StreamChunks = detail.pipelinePayloads.streamChunks;

    // If stored as a JSON string, try to parse it so we can render joined raw chunks
    if (typeof chunks === "string") {
      try {
        const parsed = JSON.parse(chunks);
        chunks = parsed;
      } catch {
        // Keep as string and return raw text (don't JSON-stringify)
        return chunks;
      }
    }

    if (chunks && typeof chunks === "object") {
      try {
        return Object.entries(chunks)
          .map(([stage, arr]) => {
            const joined = Array.isArray(arr) ? arr.join("") : String(arr);
            return `--- ${stage} ---\n${joined}`;
          })
          .join("\n\n");
      } catch {
        return toPrettyJson(chunks);
      }
    }

    return null;
  })


from_node_id: function:1828196d40df081748b06edd7b756603
reference_kind: calls
file_path: src/shared/components/RequestLoggerDetail.tsx
language: tsx
reference_name:
(() => {
                  const fromTokens = tokenStats.totalIn + tokenStats.compressed;
                  const pct = Math.round((tokenStats.compressed / fromTokens) * 100);
                  return (
                    <span className="px-2 py-0.5 rounded bg-purple-500/20 text-purple-700 dark:text-purple-300 text-xs font-bold">
                      Compressed: {fromTokens.toLocaleString()} → {tokenStats.totalIn.toLocaleString()} (-{pct}%)
                    </span>
                  );
                })


from_node_id: function:30591733b1edbd5d796bbf966faf38cf
reference_kind: calls
file_path: src/shared/components/RequestLoggerV2.tsx
language: tsx
reference_name:
(() => {
                            const tps = getLogTps(log);
                            const color =
                              tps <= 0
                                ? "text-text-muted"
                                : tps >= 80
                                  ? "text-emerald-600 dark:text-emerald-400"
                                  : tps >= 30
                                    ? "text-sky-600 dark:text-sky-400"
                                    : "text-amber-600 dark:text-amber-400";
                            return (
                              <span className={color} title={`${tps.toFixed(2)} tokens/sec`}>
                                {formatTps(tps)}
                              </span>
                            );
                          })


from_node_id: function:fabe3d8fb9ea001059ff023cebb7b8a4
reference_kind: calls
file_path: src/shared/components/Sidebar.tsx
language: tsx
reference_name:
(() => {
      try {
        return localStorage.getItem(PINNED_SECTIONS_KEY);
      } catch {
        return null;
      }
    })


from_node_id: function:49dcf1c590ae40980423b647a8762b26
reference_kind: calls
file_path: src/shared/components/Tooltip.tsx
language: tsx
reference_name:
(() => {
      const child = children as ReactElement<AriaDescribedElement>;
      const existingDescribedBy = child.props["aria-describedby"];
      const mergedDescribedBy = [existingDescribedBy, describedById].filter(Boolean).join(" ");
      return cloneElement(child, {
        "aria-describedby": mergedDescribedBy || undefined,
      });
    })


from_node_id: function:8f1eb6ed683439b62037e024592a8cb6
reference_kind: calls
file_path: src/shared/services/providerLimitsSyncScheduler.ts
language: typescript
reference_name:
(async () => {
    let initialDelayMs = STARTUP_DELAY_MS;
    const lastAutoSyncAt = await getLastProviderLimitsAutoSyncTime();

    if (lastAutoSyncAt) {
      const lastRunMs = Date.parse(lastAutoSyncAt);
      if (Number.isFinite(lastRunMs)) {
        const elapsedMs = Date.now() - lastRunMs;
        if (elapsedMs < intervalMs) {
          initialDelayMs = Math.max(intervalMs - elapsedMs, STARTUP_DELAY_MS);
        }
      }
    }

    startupTimer = setTimeout(() => {
      startupTimer = null;
      void runProviderLimitsSyncCycle();

      schedulerTimer = setInterval(() => {
        void runProviderLimitsSyncCycle();
      }, intervalMs);
      schedulerTimer.unref?.();
    }, initialDelayMs);

    startupTimer.unref?.();
  })


from_node_id: file:tests/translator/testFromFile.ts
reference_kind: calls
file_path: tests/translator/testFromFile.ts
language: typescript
reference_name:
(async () => {
  try {
    console.log("\n🚀 Sending request...");

    const response = await fetch(url, {
      method: "POST",
      headers,
      body: JSON.stringify(body),
    });

    console.log(`\n📥 Response: ${response.status} ${response.statusText}`);

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`\n❌ Error response:\n${errorText}`);
      process.exit(1);
    }

    const isStreaming =
      body.stream || response.headers.get("content-type")?.includes("text/event-stream");

    if (isStreaming) {
      console.log("\n📡 Streaming response...\n");

      const reader = response.body?.getReader();
      if (!reader) throw new Error("No response body");
      const decoder = new TextDecoder();
      let chunkCount = 0;
      let buffer = "";

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() || ""; // Keep incomplete line in buffer

        for (const line of lines) {
          if (line.trim()) {
            process.stdout.write(line + "\n");
            chunkCount++;
          }
        }
      }

      // Process any remaining data
      if (buffer.trim()) {
        process.stdout.write(buffer + "\n");
      }

      console.log(`\n\n✅ Received ${chunkCount} chunks`);
    } else {
      const responseData = (await response.json()) as any;
      console.log("\n📦 Response:");
      console.log(JSON.stringify(responseData, null, 2));
    }
  } catch (err: any) {
    console.error("\n❌ Request failed:", err.message);
    if (process.env.DEBUG) {
      console.error(err.stack);
    }
    process.exit(1);
  }
})


from_node_id: function:113f88fb20ce4b10b49aaea07e1b4ef0
reference_kind: calls
file_path: tests/unit/cursor-agent-session.test.ts
language: typescript
reference_name:
{
      write: (data: Buffer) => {
        calls.push({ kind: "write", data });
        return true;
      },
      close: () => {
        calls.push({ kind: "close" });
      },
    } as unknown as import


from_node_id: function:4367c35a685aee069a5dcb0cbdc11bde
reference_kind: calls
file_path: tests/unit/responses-transformer.test.ts
language: typescript
reference_name:
(async () => {
    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      output.push(decoder.decode(value));
    }
  })


