@kenkaiiii/gg-ai 5.87.1 → 5.87.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -286,6 +286,10 @@ interface StreamOptions {
286
286
  * stalls — broken SSE connections (transient CDN / proxy issues) often
287
287
  * recover when the same request is issued over a plain HTTP request/response. */
288
288
  streaming?: boolean;
289
+ /** Called whenever response body bytes arrive, including SSE pings the SDK
290
+ * swallows. Lets the agent loop's watchdog see a live connection while the
291
+ * model thinks silently (Anthropic sends only a ping every 30s then). */
292
+ onTransportActivity?: () => void;
289
293
  /** Cache prewarm (Anthropic only; other providers ignore it). Sends the exact
290
294
  * same request prefix (system, tools, messages, thinking, betas) with
291
295
  * `max_tokens: 1` over a non-streaming request so the prompt cache is written
@@ -1014,6 +1018,19 @@ declare function prewarmAnthropicCache(options: {
1014
1018
  signal?: AbortSignal;
1015
1019
  }): Promise<void>;
1016
1020
 
1021
+ declare const CLAUDE_CODE_FALLBACK_VERSION = "2.1.316";
1022
+ /** Test hook: the pending background refresh, if any. */
1023
+ declare function pendingClaudeCodeVersionRefresh(): Promise<void> | null;
1024
+ /**
1025
+ * Resolve the current Claude Code release version for spoofing the claude-cli
1026
+ * User-Agent on OAuth and inference requests. Cached in-memory for the process
1027
+ * lifetime and on disk for 24h. Falls back to a hardcoded constant if the npm
1028
+ * registry is unreachable and no cache exists.
1029
+ */
1030
+ declare function getClaudeCodeVersion(): Promise<string>;
1031
+ /** Build the User-Agent string Anthropic's OAuth + inference edges expect. */
1032
+ declare function getClaudeCliUserAgent(): Promise<string>;
1033
+
1017
1034
  interface PalsuProviderState {
1018
1035
  /** `stream()` calls served. */
1019
1036
  callCount: number;
@@ -1100,4 +1117,4 @@ declare function palsuEmbedding(text: string, dimensions?: number): number[];
1100
1117
  /** Deterministic fake relevance: the share of distinct query words found in the document (0–1). */
1101
1118
  declare function palsuRerankScore(query: string, document: string): number;
1102
1119
 
1103
- export { type AssistantMessage, CODEX_CLIENT_VERSION, type CacheRetention, type ChatErrorReason, type ContentPart, type DoneEvent, type EmbedInputType, type EmbedOptions, type EmbedResult, type EmbedUsage, type ErrorEvent, type ErrorSource, EventStream, FAST_MODE_SUFFIX, type FastModeRejection, type FastModeResolution, type FormattedChatError, type FormattedError, GGAIError, type ImageContent, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type OpenRouterProviderPreferences, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type PreparedContext, type Provider, type ProviderCapability, type ProviderDiagnosticFn, type ProviderEmbedFn, type ProviderEmbedRequest, type ProviderEmbedResponse, type ProviderEntry, ProviderError, type ProviderOptions, type ProviderRerankFn, type ProviderRerankRequest, type ProviderRerankResponse, type ProviderStreamFn, REDACTED as REDACTION_MARKER, type RawContent, type RedactionOptions, type RerankOptions, type RerankResponse, type RerankResult, type RerankUsage, ResponseStalledError, type ServerToolCall, type ServerToolCallEvent, type ServerToolDefinition, type ServerToolResult, type ServerToolResultEvent, type StopReason, type StreamEvent, type StreamOptions, type StreamResponse, StreamResult, type SystemMessage, TOOL_CALL_NAME_RULES, type TextContent, type TextDeltaEvent, type ThinkingContent, type ThinkingDeltaEvent, type ThinkingLevel, type Tool, type ToolCall, type ToolCallDeltaEvent, type ToolCallDoneEvent, type ToolCallNameRule, type ToolChoice, type ToolResult, type ToolResultContent, type ToolResultMessage, type Usage, type UserMessage, type VideoContent, clampProviderContextImages, classifyProviderError, continuesTurn, describeFastModeRejection, dropInvalidToolCalls, embed, environmentSecrets, formatChatError, formatError, formatErrorForDisplay, hasLoneSurrogate, isHardBillingMessage, isUsageLimitError, isValidToolCallName, localWireModelId, opensTurn, palsuAssistantMessage, palsuEmbedding, palsuRerankScore, palsuText, palsuThinking, palsuToolCall, parseFastModeRejection, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, rerank, resolveFastModeModel, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText, toolCallNameRuleFor, usesResponsesLite };
1120
+ export { type AssistantMessage, CLAUDE_CODE_FALLBACK_VERSION, CODEX_CLIENT_VERSION, type CacheRetention, type ChatErrorReason, type ContentPart, type DoneEvent, type EmbedInputType, type EmbedOptions, type EmbedResult, type EmbedUsage, type ErrorEvent, type ErrorSource, EventStream, FAST_MODE_SUFFIX, type FastModeRejection, type FastModeResolution, type FormattedChatError, type FormattedError, GGAIError, type ImageContent, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type OpenRouterProviderPreferences, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type PreparedContext, type Provider, type ProviderCapability, type ProviderDiagnosticFn, type ProviderEmbedFn, type ProviderEmbedRequest, type ProviderEmbedResponse, type ProviderEntry, ProviderError, type ProviderOptions, type ProviderRerankFn, type ProviderRerankRequest, type ProviderRerankResponse, type ProviderStreamFn, REDACTED as REDACTION_MARKER, type RawContent, type RedactionOptions, type RerankOptions, type RerankResponse, type RerankResult, type RerankUsage, ResponseStalledError, type ServerToolCall, type ServerToolCallEvent, type ServerToolDefinition, type ServerToolResult, type ServerToolResultEvent, type StopReason, type StreamEvent, type StreamOptions, type StreamResponse, StreamResult, type SystemMessage, TOOL_CALL_NAME_RULES, type TextContent, type TextDeltaEvent, type ThinkingContent, type ThinkingDeltaEvent, type ThinkingLevel, type Tool, type ToolCall, type ToolCallDeltaEvent, type ToolCallDoneEvent, type ToolCallNameRule, type ToolChoice, type ToolResult, type ToolResultContent, type ToolResultMessage, type Usage, type UserMessage, type VideoContent, clampProviderContextImages, classifyProviderError, continuesTurn, describeFastModeRejection, dropInvalidToolCalls, embed, environmentSecrets, formatChatError, formatError, formatErrorForDisplay, getClaudeCliUserAgent, getClaudeCodeVersion, hasLoneSurrogate, isHardBillingMessage, isUsageLimitError, isValidToolCallName, localWireModelId, opensTurn, palsuAssistantMessage, palsuEmbedding, palsuRerankScore, palsuText, palsuThinking, palsuToolCall, parseFastModeRejection, pendingClaudeCodeVersionRefresh, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, rerank, resolveFastModeModel, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText, toolCallNameRuleFor, usesResponsesLite };
package/dist/index.d.ts CHANGED
@@ -286,6 +286,10 @@ interface StreamOptions {
286
286
  * stalls — broken SSE connections (transient CDN / proxy issues) often
287
287
  * recover when the same request is issued over a plain HTTP request/response. */
288
288
  streaming?: boolean;
289
+ /** Called whenever response body bytes arrive, including SSE pings the SDK
290
+ * swallows. Lets the agent loop's watchdog see a live connection while the
291
+ * model thinks silently (Anthropic sends only a ping every 30s then). */
292
+ onTransportActivity?: () => void;
289
293
  /** Cache prewarm (Anthropic only; other providers ignore it). Sends the exact
290
294
  * same request prefix (system, tools, messages, thinking, betas) with
291
295
  * `max_tokens: 1` over a non-streaming request so the prompt cache is written
@@ -1014,6 +1018,19 @@ declare function prewarmAnthropicCache(options: {
1014
1018
  signal?: AbortSignal;
1015
1019
  }): Promise<void>;
1016
1020
 
1021
+ declare const CLAUDE_CODE_FALLBACK_VERSION = "2.1.316";
1022
+ /** Test hook: the pending background refresh, if any. */
1023
+ declare function pendingClaudeCodeVersionRefresh(): Promise<void> | null;
1024
+ /**
1025
+ * Resolve the current Claude Code release version for spoofing the claude-cli
1026
+ * User-Agent on OAuth and inference requests. Cached in-memory for the process
1027
+ * lifetime and on disk for 24h. Falls back to a hardcoded constant if the npm
1028
+ * registry is unreachable and no cache exists.
1029
+ */
1030
+ declare function getClaudeCodeVersion(): Promise<string>;
1031
+ /** Build the User-Agent string Anthropic's OAuth + inference edges expect. */
1032
+ declare function getClaudeCliUserAgent(): Promise<string>;
1033
+
1017
1034
  interface PalsuProviderState {
1018
1035
  /** `stream()` calls served. */
1019
1036
  callCount: number;
@@ -1100,4 +1117,4 @@ declare function palsuEmbedding(text: string, dimensions?: number): number[];
1100
1117
  /** Deterministic fake relevance: the share of distinct query words found in the document (0–1). */
1101
1118
  declare function palsuRerankScore(query: string, document: string): number;
1102
1119
 
1103
- export { type AssistantMessage, CODEX_CLIENT_VERSION, type CacheRetention, type ChatErrorReason, type ContentPart, type DoneEvent, type EmbedInputType, type EmbedOptions, type EmbedResult, type EmbedUsage, type ErrorEvent, type ErrorSource, EventStream, FAST_MODE_SUFFIX, type FastModeRejection, type FastModeResolution, type FormattedChatError, type FormattedError, GGAIError, type ImageContent, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type OpenRouterProviderPreferences, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type PreparedContext, type Provider, type ProviderCapability, type ProviderDiagnosticFn, type ProviderEmbedFn, type ProviderEmbedRequest, type ProviderEmbedResponse, type ProviderEntry, ProviderError, type ProviderOptions, type ProviderRerankFn, type ProviderRerankRequest, type ProviderRerankResponse, type ProviderStreamFn, REDACTED as REDACTION_MARKER, type RawContent, type RedactionOptions, type RerankOptions, type RerankResponse, type RerankResult, type RerankUsage, ResponseStalledError, type ServerToolCall, type ServerToolCallEvent, type ServerToolDefinition, type ServerToolResult, type ServerToolResultEvent, type StopReason, type StreamEvent, type StreamOptions, type StreamResponse, StreamResult, type SystemMessage, TOOL_CALL_NAME_RULES, type TextContent, type TextDeltaEvent, type ThinkingContent, type ThinkingDeltaEvent, type ThinkingLevel, type Tool, type ToolCall, type ToolCallDeltaEvent, type ToolCallDoneEvent, type ToolCallNameRule, type ToolChoice, type ToolResult, type ToolResultContent, type ToolResultMessage, type Usage, type UserMessage, type VideoContent, clampProviderContextImages, classifyProviderError, continuesTurn, describeFastModeRejection, dropInvalidToolCalls, embed, environmentSecrets, formatChatError, formatError, formatErrorForDisplay, hasLoneSurrogate, isHardBillingMessage, isUsageLimitError, isValidToolCallName, localWireModelId, opensTurn, palsuAssistantMessage, palsuEmbedding, palsuRerankScore, palsuText, palsuThinking, palsuToolCall, parseFastModeRejection, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, rerank, resolveFastModeModel, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText, toolCallNameRuleFor, usesResponsesLite };
1120
+ export { type AssistantMessage, CLAUDE_CODE_FALLBACK_VERSION, CODEX_CLIENT_VERSION, type CacheRetention, type ChatErrorReason, type ContentPart, type DoneEvent, type EmbedInputType, type EmbedOptions, type EmbedResult, type EmbedUsage, type ErrorEvent, type ErrorSource, EventStream, FAST_MODE_SUFFIX, type FastModeRejection, type FastModeResolution, type FormattedChatError, type FormattedError, GGAIError, type ImageContent, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type OpenRouterProviderPreferences, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type PreparedContext, type Provider, type ProviderCapability, type ProviderDiagnosticFn, type ProviderEmbedFn, type ProviderEmbedRequest, type ProviderEmbedResponse, type ProviderEntry, ProviderError, type ProviderOptions, type ProviderRerankFn, type ProviderRerankRequest, type ProviderRerankResponse, type ProviderStreamFn, REDACTED as REDACTION_MARKER, type RawContent, type RedactionOptions, type RerankOptions, type RerankResponse, type RerankResult, type RerankUsage, ResponseStalledError, type ServerToolCall, type ServerToolCallEvent, type ServerToolDefinition, type ServerToolResult, type ServerToolResultEvent, type StopReason, type StreamEvent, type StreamOptions, type StreamResponse, StreamResult, type SystemMessage, TOOL_CALL_NAME_RULES, type TextContent, type TextDeltaEvent, type ThinkingContent, type ThinkingDeltaEvent, type ThinkingLevel, type Tool, type ToolCall, type ToolCallDeltaEvent, type ToolCallDoneEvent, type ToolCallNameRule, type ToolChoice, type ToolResult, type ToolResultContent, type ToolResultMessage, type Usage, type UserMessage, type VideoContent, clampProviderContextImages, classifyProviderError, continuesTurn, describeFastModeRejection, dropInvalidToolCalls, embed, environmentSecrets, formatChatError, formatError, formatErrorForDisplay, getClaudeCliUserAgent, getClaudeCodeVersion, hasLoneSurrogate, isHardBillingMessage, isUsageLimitError, isValidToolCallName, localWireModelId, opensTurn, palsuAssistantMessage, palsuEmbedding, palsuRerankScore, palsuText, palsuThinking, palsuToolCall, parseFastModeRejection, pendingClaudeCodeVersionRefresh, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, rerank, resolveFastModeModel, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText, toolCallNameRuleFor, usesResponsesLite };
package/dist/index.js CHANGED
@@ -554,6 +554,145 @@ var StreamResult = class _StreamResult {
554
554
  }
555
555
  };
556
556
 
557
+ // src/claude-code-version.ts
558
+ import fs from "fs/promises";
559
+ import os from "os";
560
+ import path from "path";
561
+
562
+ // src/utils/diag.ts
563
+ var _diagFn = null;
564
+ function setProviderDiagnostic(fn) {
565
+ _diagFn = fn;
566
+ }
567
+ function providerDiag(phase, data) {
568
+ _diagFn?.(phase, data);
569
+ }
570
+
571
+ // src/claude-code-version.ts
572
+ var NPM_LATEST_URL = "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";
573
+ var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
574
+ var FETCH_TIMEOUT_MS = 3e3;
575
+ var CLAUDE_CODE_FALLBACK_VERSION = "2.1.316";
576
+ function isOlder(a, b) {
577
+ const pa = a.split(".").map((n) => Number.parseInt(n, 10) || 0);
578
+ const pb = b.split(".").map((n) => Number.parseInt(n, 10) || 0);
579
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
580
+ const x = pa[i] ?? 0;
581
+ const y = pb[i] ?? 0;
582
+ if (x !== y) return x < y;
583
+ }
584
+ return false;
585
+ }
586
+ function atLeastFallback(version) {
587
+ return isOlder(version, CLAUDE_CODE_FALLBACK_VERSION) ? CLAUDE_CODE_FALLBACK_VERSION : version;
588
+ }
589
+ var memoryCache = null;
590
+ var inflight = null;
591
+ function agentDir() {
592
+ return path.join(os.homedir(), ".gg");
593
+ }
594
+ function cachePath() {
595
+ return path.join(agentDir(), "claude-code-version.json");
596
+ }
597
+ async function readDiskCache() {
598
+ try {
599
+ const raw = await fs.readFile(cachePath(), "utf-8");
600
+ const parsed = JSON.parse(raw);
601
+ if (typeof parsed.version === "string" && typeof parsed.fetchedAt === "number") {
602
+ return parsed;
603
+ }
604
+ return null;
605
+ } catch {
606
+ return null;
607
+ }
608
+ }
609
+ async function writeDiskCache(data) {
610
+ try {
611
+ await fs.mkdir(agentDir(), { recursive: true, mode: 448 });
612
+ await fs.writeFile(cachePath(), JSON.stringify(data), { mode: 384 });
613
+ } catch (err) {
614
+ providerDiag("claude_code_version_cache_write_failed", {
615
+ error: err instanceof Error ? err.message : String(err)
616
+ });
617
+ }
618
+ }
619
+ async function fetchLatest() {
620
+ const controller = new AbortController();
621
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
622
+ try {
623
+ const response = await fetch(NPM_LATEST_URL, { signal: controller.signal });
624
+ if (!response.ok) return null;
625
+ const data = await response.json();
626
+ if (typeof data.version === "string" && /^\d/.test(data.version)) {
627
+ return data.version;
628
+ }
629
+ return null;
630
+ } catch {
631
+ return null;
632
+ } finally {
633
+ clearTimeout(timer);
634
+ }
635
+ }
636
+ var refreshing = null;
637
+ function refreshInBackground() {
638
+ refreshing ??= (async () => {
639
+ try {
640
+ const fetched = await fetchLatest();
641
+ if (!fetched) return;
642
+ await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
643
+ memoryCache = { version: fetched, expiresAt: Date.now() + CACHE_TTL_MS };
644
+ } finally {
645
+ refreshing = null;
646
+ }
647
+ })();
648
+ return refreshing;
649
+ }
650
+ function pendingClaudeCodeVersionRefresh() {
651
+ return refreshing;
652
+ }
653
+ async function getClaudeCodeVersion() {
654
+ if (memoryCache && Date.now() < memoryCache.expiresAt) {
655
+ return memoryCache.version;
656
+ }
657
+ if (inflight) return inflight;
658
+ inflight = (async () => {
659
+ const disk = await readDiskCache();
660
+ const diskFresh = disk && Date.now() - disk.fetchedAt < CACHE_TTL_MS;
661
+ if (disk && diskFresh) {
662
+ const version = atLeastFallback(disk.version);
663
+ memoryCache = { version, expiresAt: Date.now() + CACHE_TTL_MS };
664
+ return version;
665
+ }
666
+ if (disk) {
667
+ const version = atLeastFallback(disk.version);
668
+ memoryCache = { version, expiresAt: Date.now() + 5 * 60 * 1e3 };
669
+ void refreshInBackground();
670
+ return version;
671
+ }
672
+ const fetched = await fetchLatest();
673
+ if (fetched) {
674
+ await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
675
+ memoryCache = { version: fetched, expiresAt: Date.now() + CACHE_TTL_MS };
676
+ return fetched;
677
+ }
678
+ const resolved = CLAUDE_CODE_FALLBACK_VERSION;
679
+ memoryCache = { version: resolved, expiresAt: Date.now() + 5 * 60 * 1e3 };
680
+ providerDiag("claude_code_version_fallback", { version: resolved });
681
+ return resolved;
682
+ })();
683
+ try {
684
+ return await inflight;
685
+ } finally {
686
+ inflight = null;
687
+ }
688
+ }
689
+ function claudeCliUserAgent(version) {
690
+ return `claude-cli/${version} (external, cli)`;
691
+ }
692
+ async function getClaudeCliUserAgent() {
693
+ return claudeCliUserAgent(await getClaudeCodeVersion());
694
+ }
695
+
557
696
  // src/utils/provider-options.ts
558
697
  var RESERVED_BODY_FIELDS = /* @__PURE__ */ new Set([
559
698
  "contents",
@@ -1721,7 +1860,7 @@ function parseToolArguments(argsJson) {
1721
1860
 
1722
1861
  // src/utils/provider-fetch.ts
1723
1862
  import { Agent, EnvHttpProxyAgent, fetch as undiciFetch } from "undici";
1724
- var PROVIDER_TRANSPORT_TIMEOUT_MS = 30 * 6e4;
1863
+ var PROVIDER_TRANSPORT_TIMEOUT_MS = 45 * 6e4;
1725
1864
  function nodeUsesEnvProxy({
1726
1865
  env = process.env,
1727
1866
  execArgv = process.execArgv,
@@ -1749,6 +1888,25 @@ function createProviderFetch(timeoutMs, { useEnvProxy = nodeUsesEnvProxy() } = {
1749
1888
  };
1750
1889
  return Object.assign(providerFetch2, { Response: globalThis.Response });
1751
1890
  }
1891
+ function withBodyActivity(fetchImpl, onActivity) {
1892
+ return async (input, init2) => {
1893
+ const response = await fetchImpl(input, init2);
1894
+ if (!response.body || !response.headers.get("content-type")?.includes("text/event-stream")) {
1895
+ return response;
1896
+ }
1897
+ const tap = new TransformStream({
1898
+ transform(chunk, controller) {
1899
+ onActivity();
1900
+ controller.enqueue(chunk);
1901
+ }
1902
+ });
1903
+ return new Response(response.body.pipeThrough(tap), {
1904
+ status: response.status,
1905
+ statusText: response.statusText,
1906
+ headers: response.headers
1907
+ });
1908
+ };
1909
+ }
1752
1910
  var providerFetch = createProviderFetch(
1753
1911
  PROVIDER_TRANSPORT_TIMEOUT_MS
1754
1912
  );
@@ -1805,9 +1963,13 @@ function sumUsageIterations(usage) {
1805
1963
  }
1806
1964
  return totals;
1807
1965
  }
1966
+ async function withClaudeUserAgent(options) {
1967
+ if (options.userAgent || !options.apiKey?.startsWith("sk-ant-oat")) return options;
1968
+ return { ...options, userAgent: await getClaudeCliUserAgent() };
1969
+ }
1808
1970
  function createClient(options) {
1809
1971
  const isOAuth = options.apiKey?.startsWith("sk-ant-oat");
1810
- const userAgent = isOAuth ? options.userAgent ?? "claude-cli/2.1.75 (external, cli)" : "";
1972
+ const userAgent = isOAuth ? options.userAgent ?? claudeCliUserAgent(CLAUDE_CODE_FALLBACK_VERSION) : "";
1811
1973
  const cacheKey = `${options.apiKey ?? ""}|${options.baseUrl ?? ""}|${userAgent}`;
1812
1974
  if (!options.fetch) {
1813
1975
  const cached = anthropicClientCache.get(cacheKey);
@@ -1837,11 +1999,13 @@ function createClient(options) {
1837
1999
  }
1838
2000
  async function prewarmAnthropicCache(options) {
1839
2001
  try {
1840
- const client = createClient({
1841
- apiKey: options.apiKey,
1842
- baseUrl: options.baseUrl,
1843
- userAgent: options.userAgent
1844
- });
2002
+ const client = createClient(
2003
+ await withClaudeUserAgent({
2004
+ apiKey: options.apiKey,
2005
+ baseUrl: options.baseUrl,
2006
+ userAgent: options.userAgent
2007
+ })
2008
+ );
1845
2009
  const cacheControl = toAnthropicCacheControl(options.cacheRetention ?? "long", options.baseUrl);
1846
2010
  const { system, messages } = toAnthropicMessages(
1847
2011
  [
@@ -1895,7 +2059,7 @@ function streamAnthropic(options) {
1895
2059
  return new StreamResult(runStream(options), options.signal);
1896
2060
  }
1897
2061
  async function* runStream(options) {
1898
- const client = createClient(options);
2062
+ const client = createClient(await withClaudeUserAgent(options));
1899
2063
  const isOAuth = options.apiKey?.startsWith("sk-ant-oat");
1900
2064
  const useStreaming = options.streaming !== false && !options.prewarm;
1901
2065
  const cacheControl = toAnthropicCacheControl(options.cacheRetention, options.baseUrl);
@@ -2049,8 +2213,10 @@ async function* runStream(options) {
2049
2213
  const keepalive = { type: "keepalive" };
2050
2214
  let receivedAnyEvent = false;
2051
2215
  try {
2216
+ const onActivity = options.onTransportActivity;
2217
+ const streamClient = onActivity ? client.withOptions({ fetch: withBodyActivity(options.fetch ?? providerFetch, onActivity) }) : client;
2052
2218
  const stream2 = await send(
2053
- (p, o) => client.messages.create(p, o)
2219
+ (p, o) => streamClient.messages.create(p, o)
2054
2220
  );
2055
2221
  for await (const event of stream2) {
2056
2222
  receivedAnyEvent = true;
@@ -2474,15 +2640,6 @@ function fnv1aHash(value) {
2474
2640
  return (hash >>> 0).toString(16).padStart(8, "0");
2475
2641
  }
2476
2642
 
2477
- // src/utils/diag.ts
2478
- var _diagFn = null;
2479
- function setProviderDiagnostic(fn) {
2480
- _diagFn = fn;
2481
- }
2482
- function providerDiag(phase, data) {
2483
- _diagFn?.(phase, data);
2484
- }
2485
-
2486
2643
  // src/providers/moonshot-video.ts
2487
2644
  async function uploadMoonshotVideos(client, messages, signal) {
2488
2645
  for (const msg of messages) {
@@ -2708,11 +2865,11 @@ async function* runStream2(options) {
2708
2865
  }
2709
2866
  const requestParams = mergeProviderOptions(params, options.providerOptions);
2710
2867
  if (getEnvironment()?.GGAI_DUMP_REQUEST) {
2711
- const fs = await import("fs");
2868
+ const fs2 = await import("fs");
2712
2869
  const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
2713
2870
  const dumpPath = `/tmp/ggai-request-${ts}.json`;
2714
- fs.writeFileSync(dumpPath, JSON.stringify(requestParams, null, 2));
2715
- fs.appendFileSync(
2871
+ fs2.writeFileSync(dumpPath, JSON.stringify(requestParams, null, 2));
2872
+ fs2.appendFileSync(
2716
2873
  "/tmp/ggai-requests.log",
2717
2874
  `[${ts}] ${dumpPath} messages=${requestParams.messages.length}
2718
2875
  `
@@ -3042,7 +3199,7 @@ function toError2(err, provider = "openai") {
3042
3199
  }
3043
3200
 
3044
3201
  // src/providers/openai-codex.ts
3045
- import os from "os";
3202
+ import os2 from "os";
3046
3203
  import * as zstd from "@bokuweb/zstd-wasm";
3047
3204
 
3048
3205
  // src/utils/sse.ts
@@ -3644,7 +3801,7 @@ async function* runStream3(options, retriedWithoutReasoning = false) {
3644
3801
  Authorization: `Bearer ${options.apiKey}`,
3645
3802
  "OpenAI-Beta": "responses=experimental",
3646
3803
  originator: responsesLite ? "codex_cli_rs" : "ggcoder",
3647
- "User-Agent": responsesLite ? `codex_cli_rs/${CODEX_CLIENT_VERSION}` : `ggcoder (${os.platform()} ${os.release()}; ${os.arch()})`,
3804
+ "User-Agent": responsesLite ? `codex_cli_rs/${CODEX_CLIENT_VERSION}` : `ggcoder (${os2.platform()} ${os2.release()}; ${os2.arch()})`,
3648
3805
  ...responsesLite ? { version: CODEX_CLIENT_VERSION } : {},
3649
3806
  ...liteShape ? { "X-OpenAI-Internal-Codex-Responses-Lite": "true" } : {}
3650
3807
  };
@@ -4768,8 +4925,8 @@ function bound(text) {
4768
4925
  const trimmed = text.trim();
4769
4926
  return trimmed.length > MAX_ERROR_MESSAGE_CHARS ? `${trimmed.slice(0, MAX_ERROR_MESSAGE_CHARS)}\u2026` : trimmed;
4770
4927
  }
4771
- function joinUrl(baseUrl, path) {
4772
- return `${baseUrl.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
4928
+ function joinUrl(baseUrl, path2) {
4929
+ return `${baseUrl.replace(/\/+$/, "")}/${path2.replace(/^\/+/, "")}`;
4773
4930
  }
4774
4931
 
4775
4932
  // src/providers/gemini-embeddings.ts
@@ -5979,6 +6136,7 @@ function palsuRerankScore(query, document) {
5979
6136
  return hits / queryTokens.size;
5980
6137
  }
5981
6138
  export {
6139
+ CLAUDE_CODE_FALLBACK_VERSION,
5982
6140
  CODEX_CLIENT_VERSION,
5983
6141
  EventStream,
5984
6142
  FAST_MODE_SUFFIX,
@@ -5998,6 +6156,8 @@ export {
5998
6156
  formatChatError,
5999
6157
  formatError,
6000
6158
  formatErrorForDisplay,
6159
+ getClaudeCliUserAgent,
6160
+ getClaudeCodeVersion,
6001
6161
  hasLoneSurrogate,
6002
6162
  isHardBillingMessage,
6003
6163
  isUsageLimitError,
@@ -6011,6 +6171,7 @@ export {
6011
6171
  palsuThinking,
6012
6172
  palsuToolCall,
6013
6173
  parseFastModeRejection,
6174
+ pendingClaudeCodeVersionRefresh,
6014
6175
  prewarmAnthropicCache,
6015
6176
  providerRegistry,
6016
6177
  redactText,