@kenkaiiii/gg-ai 5.93.0 → 5.94.0
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/README.md +1 -1
- package/dist/index.cjs +31 -205
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -21
- package/dist/index.d.ts +1 -21
- package/dist/index.js +31 -201
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -315,12 +315,6 @@ interface StreamOptions {
|
|
|
315
315
|
* budget_tokens < max_tokens), no request is sent and the response has
|
|
316
316
|
* zero usage with stopReason "end_turn". */
|
|
317
317
|
prewarm?: boolean;
|
|
318
|
-
/** Override the User-Agent sent with OAuth-authenticated Anthropic requests.
|
|
319
|
-
* Anthropic's OAuth edge rejects requests whose claude-cli version lags too
|
|
320
|
-
* far behind the real Claude Code release; callers that track the live
|
|
321
|
-
* version should pass it here. Ignored for non-Anthropic providers and for
|
|
322
|
-
* Anthropic requests using a regular API key. */
|
|
323
|
-
userAgent?: string;
|
|
324
318
|
/** Extra HTTP headers attached to every model request. Used by providers
|
|
325
319
|
* whose endpoint gates on client identity (e.g. Kimi For Coding requires a
|
|
326
320
|
* `User-Agent: kimi-code-cli/...` and `X-Msh-*` device headers). Merged
|
|
@@ -1067,24 +1061,10 @@ declare function prewarmAnthropicCache(options: {
|
|
|
1067
1061
|
tools?: StreamOptions["tools"];
|
|
1068
1062
|
serverTools?: StreamOptions["serverTools"];
|
|
1069
1063
|
baseUrl?: string;
|
|
1070
|
-
userAgent?: string;
|
|
1071
1064
|
cacheRetention?: StreamOptions["cacheRetention"];
|
|
1072
1065
|
signal?: AbortSignal;
|
|
1073
1066
|
}): Promise<void>;
|
|
1074
1067
|
|
|
1075
|
-
declare const CLAUDE_CODE_FALLBACK_VERSION = "2.1.316";
|
|
1076
|
-
/** Test hook: the pending background refresh, if any. */
|
|
1077
|
-
declare function pendingClaudeCodeVersionRefresh(): Promise<void> | null;
|
|
1078
|
-
/**
|
|
1079
|
-
* Resolve the current Claude Code release version for spoofing the claude-cli
|
|
1080
|
-
* User-Agent on OAuth and inference requests. Cached in-memory for the process
|
|
1081
|
-
* lifetime and on disk for 24h. Falls back to a hardcoded constant if the npm
|
|
1082
|
-
* registry is unreachable and no cache exists.
|
|
1083
|
-
*/
|
|
1084
|
-
declare function getClaudeCodeVersion(): Promise<string>;
|
|
1085
|
-
/** Build the User-Agent string Anthropic's OAuth + inference edges expect. */
|
|
1086
|
-
declare function getClaudeCliUserAgent(): Promise<string>;
|
|
1087
|
-
|
|
1088
1068
|
interface PalsuProviderState {
|
|
1089
1069
|
/** `stream()` calls served. */
|
|
1090
1070
|
callCount: number;
|
|
@@ -1171,4 +1151,4 @@ declare function palsuEmbedding(text: string, dimensions?: number): number[];
|
|
|
1171
1151
|
/** Deterministic fake relevance: the share of distinct query words found in the document (0–1). */
|
|
1172
1152
|
declare function palsuRerankScore(query: string, document: string): number;
|
|
1173
1153
|
|
|
1174
|
-
export { type AssistantMessage,
|
|
1154
|
+
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, LOCAL_NO_API_KEY, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type OpenRouterProviderPreferences, PRECONNECT_INTERVAL_MS, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type PreconnectOptions, 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, localBearerKey, localWireModelId, opensTurn, palsuAssistantMessage, palsuEmbedding, palsuRerankScore, palsuText, palsuThinking, palsuToolCall, parseFastModeRejection, preconnectOrigin, preconnectProvider, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, rerank, resolveFastModeModel, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText, toolCallNameRuleFor, usesResponsesLite };
|
package/dist/index.d.ts
CHANGED
|
@@ -315,12 +315,6 @@ interface StreamOptions {
|
|
|
315
315
|
* budget_tokens < max_tokens), no request is sent and the response has
|
|
316
316
|
* zero usage with stopReason "end_turn". */
|
|
317
317
|
prewarm?: boolean;
|
|
318
|
-
/** Override the User-Agent sent with OAuth-authenticated Anthropic requests.
|
|
319
|
-
* Anthropic's OAuth edge rejects requests whose claude-cli version lags too
|
|
320
|
-
* far behind the real Claude Code release; callers that track the live
|
|
321
|
-
* version should pass it here. Ignored for non-Anthropic providers and for
|
|
322
|
-
* Anthropic requests using a regular API key. */
|
|
323
|
-
userAgent?: string;
|
|
324
318
|
/** Extra HTTP headers attached to every model request. Used by providers
|
|
325
319
|
* whose endpoint gates on client identity (e.g. Kimi For Coding requires a
|
|
326
320
|
* `User-Agent: kimi-code-cli/...` and `X-Msh-*` device headers). Merged
|
|
@@ -1067,24 +1061,10 @@ declare function prewarmAnthropicCache(options: {
|
|
|
1067
1061
|
tools?: StreamOptions["tools"];
|
|
1068
1062
|
serverTools?: StreamOptions["serverTools"];
|
|
1069
1063
|
baseUrl?: string;
|
|
1070
|
-
userAgent?: string;
|
|
1071
1064
|
cacheRetention?: StreamOptions["cacheRetention"];
|
|
1072
1065
|
signal?: AbortSignal;
|
|
1073
1066
|
}): Promise<void>;
|
|
1074
1067
|
|
|
1075
|
-
declare const CLAUDE_CODE_FALLBACK_VERSION = "2.1.316";
|
|
1076
|
-
/** Test hook: the pending background refresh, if any. */
|
|
1077
|
-
declare function pendingClaudeCodeVersionRefresh(): Promise<void> | null;
|
|
1078
|
-
/**
|
|
1079
|
-
* Resolve the current Claude Code release version for spoofing the claude-cli
|
|
1080
|
-
* User-Agent on OAuth and inference requests. Cached in-memory for the process
|
|
1081
|
-
* lifetime and on disk for 24h. Falls back to a hardcoded constant if the npm
|
|
1082
|
-
* registry is unreachable and no cache exists.
|
|
1083
|
-
*/
|
|
1084
|
-
declare function getClaudeCodeVersion(): Promise<string>;
|
|
1085
|
-
/** Build the User-Agent string Anthropic's OAuth + inference edges expect. */
|
|
1086
|
-
declare function getClaudeCliUserAgent(): Promise<string>;
|
|
1087
|
-
|
|
1088
1068
|
interface PalsuProviderState {
|
|
1089
1069
|
/** `stream()` calls served. */
|
|
1090
1070
|
callCount: number;
|
|
@@ -1171,4 +1151,4 @@ declare function palsuEmbedding(text: string, dimensions?: number): number[];
|
|
|
1171
1151
|
/** Deterministic fake relevance: the share of distinct query words found in the document (0–1). */
|
|
1172
1152
|
declare function palsuRerankScore(query: string, document: string): number;
|
|
1173
1153
|
|
|
1174
|
-
export { type AssistantMessage,
|
|
1154
|
+
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, LOCAL_NO_API_KEY, type Message, type MessageProvenance, type MessageProvenanceKind, type MessageProvenanceSource, type MessageProvenanceVisibility, type OpenRouterProviderPreferences, PRECONNECT_INTERVAL_MS, type PalsuModelConfig, type PalsuModelHandle, type PalsuProviderConfig, type PalsuProviderHandle, type PalsuProviderState, type PalsuResponse, type PalsuResponseFactory, type PreconnectOptions, 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, localBearerKey, localWireModelId, opensTurn, palsuAssistantMessage, palsuEmbedding, palsuRerankScore, palsuText, palsuThinking, palsuToolCall, parseFastModeRejection, preconnectOrigin, preconnectProvider, prewarmAnthropicCache, providerRegistry, redactText, redactValue, registerPalsuProvider, rerank, resolveFastModeModel, resolveToolSchema, sanitizeMessagesForWire, setProviderDiagnostic, sliceHead, sliceTail, stream, toAnthropicMessages, toOpenAIMessages, toWellFormedText, toolCallNameRuleFor, usesResponsesLite };
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
var FAST_MODE_SUFFIX = "-fast";
|
|
3
3
|
var FAST_MODE_BASE_MODELS = {
|
|
4
4
|
anthropic: ["claude-opus-5-5"],
|
|
5
|
-
openai: ["gpt-6-astra", "gpt-6.1-sol", "gpt-6-luna"]
|
|
5
|
+
openai: ["gpt-6-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-luna"]
|
|
6
6
|
};
|
|
7
7
|
function resolveFastModeModel(provider, model) {
|
|
8
8
|
if (!model.endsWith(FAST_MODE_SUFFIX)) return { model, fast: false };
|
|
@@ -608,145 +608,6 @@ var StreamResult = class _StreamResult {
|
|
|
608
608
|
}
|
|
609
609
|
};
|
|
610
610
|
|
|
611
|
-
// src/claude-code-version.ts
|
|
612
|
-
import fs from "fs/promises";
|
|
613
|
-
import os from "os";
|
|
614
|
-
import path from "path";
|
|
615
|
-
|
|
616
|
-
// src/utils/diag.ts
|
|
617
|
-
var _diagFn = null;
|
|
618
|
-
function setProviderDiagnostic(fn) {
|
|
619
|
-
_diagFn = fn;
|
|
620
|
-
}
|
|
621
|
-
function providerDiag(phase, data) {
|
|
622
|
-
_diagFn?.(phase, data);
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
// src/claude-code-version.ts
|
|
626
|
-
var NPM_LATEST_URL = "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";
|
|
627
|
-
var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
628
|
-
var FETCH_TIMEOUT_MS = 3e3;
|
|
629
|
-
var CLAUDE_CODE_FALLBACK_VERSION = "2.1.316";
|
|
630
|
-
function isOlder(a, b) {
|
|
631
|
-
const pa = a.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
632
|
-
const pb = b.split(".").map((n) => Number.parseInt(n, 10) || 0);
|
|
633
|
-
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
634
|
-
const x = pa[i] ?? 0;
|
|
635
|
-
const y = pb[i] ?? 0;
|
|
636
|
-
if (x !== y) return x < y;
|
|
637
|
-
}
|
|
638
|
-
return false;
|
|
639
|
-
}
|
|
640
|
-
function atLeastFallback(version) {
|
|
641
|
-
return isOlder(version, CLAUDE_CODE_FALLBACK_VERSION) ? CLAUDE_CODE_FALLBACK_VERSION : version;
|
|
642
|
-
}
|
|
643
|
-
var memoryCache = null;
|
|
644
|
-
var inflight = null;
|
|
645
|
-
function agentDir() {
|
|
646
|
-
return path.join(os.homedir(), ".gg");
|
|
647
|
-
}
|
|
648
|
-
function cachePath() {
|
|
649
|
-
return path.join(agentDir(), "claude-code-version.json");
|
|
650
|
-
}
|
|
651
|
-
async function readDiskCache() {
|
|
652
|
-
try {
|
|
653
|
-
const raw = await fs.readFile(cachePath(), "utf-8");
|
|
654
|
-
const parsed = JSON.parse(raw);
|
|
655
|
-
if (typeof parsed.version === "string" && typeof parsed.fetchedAt === "number") {
|
|
656
|
-
return parsed;
|
|
657
|
-
}
|
|
658
|
-
return null;
|
|
659
|
-
} catch {
|
|
660
|
-
return null;
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
async function writeDiskCache(data) {
|
|
664
|
-
try {
|
|
665
|
-
await fs.mkdir(agentDir(), { recursive: true, mode: 448 });
|
|
666
|
-
await fs.writeFile(cachePath(), JSON.stringify(data), { mode: 384 });
|
|
667
|
-
} catch (err) {
|
|
668
|
-
providerDiag("claude_code_version_cache_write_failed", {
|
|
669
|
-
error: err instanceof Error ? err.message : String(err)
|
|
670
|
-
});
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
async function fetchLatest() {
|
|
674
|
-
const controller = new AbortController();
|
|
675
|
-
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
676
|
-
try {
|
|
677
|
-
const response = await fetch(NPM_LATEST_URL, { signal: controller.signal });
|
|
678
|
-
if (!response.ok) return null;
|
|
679
|
-
const data = await response.json();
|
|
680
|
-
if (typeof data.version === "string" && /^\d/.test(data.version)) {
|
|
681
|
-
return data.version;
|
|
682
|
-
}
|
|
683
|
-
return null;
|
|
684
|
-
} catch {
|
|
685
|
-
return null;
|
|
686
|
-
} finally {
|
|
687
|
-
clearTimeout(timer);
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
var refreshing = null;
|
|
691
|
-
function refreshInBackground() {
|
|
692
|
-
refreshing ??= (async () => {
|
|
693
|
-
try {
|
|
694
|
-
const fetched = await fetchLatest();
|
|
695
|
-
if (!fetched) return;
|
|
696
|
-
await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
|
|
697
|
-
memoryCache = { version: fetched, expiresAt: Date.now() + CACHE_TTL_MS };
|
|
698
|
-
} finally {
|
|
699
|
-
refreshing = null;
|
|
700
|
-
}
|
|
701
|
-
})();
|
|
702
|
-
return refreshing;
|
|
703
|
-
}
|
|
704
|
-
function pendingClaudeCodeVersionRefresh() {
|
|
705
|
-
return refreshing;
|
|
706
|
-
}
|
|
707
|
-
async function getClaudeCodeVersion() {
|
|
708
|
-
if (memoryCache && Date.now() < memoryCache.expiresAt) {
|
|
709
|
-
return memoryCache.version;
|
|
710
|
-
}
|
|
711
|
-
if (inflight) return inflight;
|
|
712
|
-
inflight = (async () => {
|
|
713
|
-
const disk = await readDiskCache();
|
|
714
|
-
const diskFresh = disk && Date.now() - disk.fetchedAt < CACHE_TTL_MS;
|
|
715
|
-
if (disk && diskFresh) {
|
|
716
|
-
const version = atLeastFallback(disk.version);
|
|
717
|
-
memoryCache = { version, expiresAt: Date.now() + CACHE_TTL_MS };
|
|
718
|
-
return version;
|
|
719
|
-
}
|
|
720
|
-
if (disk) {
|
|
721
|
-
const version = atLeastFallback(disk.version);
|
|
722
|
-
memoryCache = { version, expiresAt: Date.now() + 5 * 60 * 1e3 };
|
|
723
|
-
void refreshInBackground();
|
|
724
|
-
return version;
|
|
725
|
-
}
|
|
726
|
-
const fetched = await fetchLatest();
|
|
727
|
-
if (fetched) {
|
|
728
|
-
await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
|
|
729
|
-
memoryCache = { version: fetched, expiresAt: Date.now() + CACHE_TTL_MS };
|
|
730
|
-
return fetched;
|
|
731
|
-
}
|
|
732
|
-
const resolved = CLAUDE_CODE_FALLBACK_VERSION;
|
|
733
|
-
memoryCache = { version: resolved, expiresAt: Date.now() + 5 * 60 * 1e3 };
|
|
734
|
-
providerDiag("claude_code_version_fallback", { version: resolved });
|
|
735
|
-
return resolved;
|
|
736
|
-
})();
|
|
737
|
-
try {
|
|
738
|
-
return await inflight;
|
|
739
|
-
} finally {
|
|
740
|
-
inflight = null;
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
function claudeCliUserAgent(version) {
|
|
744
|
-
return `claude-cli/${version} (external, cli)`;
|
|
745
|
-
}
|
|
746
|
-
async function getClaudeCliUserAgent() {
|
|
747
|
-
return claudeCliUserAgent(await getClaudeCodeVersion());
|
|
748
|
-
}
|
|
749
|
-
|
|
750
611
|
// src/utils/provider-options.ts
|
|
751
612
|
var RESERVED_BODY_FIELDS = /* @__PURE__ */ new Set([
|
|
752
613
|
"contents",
|
|
@@ -1972,7 +1833,7 @@ function toGlmReasoningEffort(level) {
|
|
|
1972
1833
|
}
|
|
1973
1834
|
function toCodexReasoningEffort(level, model) {
|
|
1974
1835
|
if (level !== "ultra") return level;
|
|
1975
|
-
return model === "gpt-6-astra" || model === "gpt-6.1-sol" ? "xhigh" : "max";
|
|
1836
|
+
return model === "gpt-6-astra" || model === "gpt-6.1-sol" || model === "gpt-6.1-terra" ? "xhigh" : "max";
|
|
1976
1837
|
}
|
|
1977
1838
|
var DECLARED_EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"];
|
|
1978
1839
|
function effortForRequest(level, model, declared) {
|
|
@@ -2109,8 +1970,7 @@ var anthropicServerFallback = {
|
|
|
2109
1970
|
}
|
|
2110
1971
|
};
|
|
2111
1972
|
function serverFallbackKey(options) {
|
|
2112
|
-
|
|
2113
|
-
return `${options.baseUrl ?? process.env.ANTHROPIC_BASE_URL ?? ""}|${auth}`;
|
|
1973
|
+
return options.baseUrl ?? process.env.ANTHROPIC_BASE_URL ?? "";
|
|
2114
1974
|
}
|
|
2115
1975
|
function isDirectAnthropicApi(baseUrl) {
|
|
2116
1976
|
const effective = baseUrl ?? process.env.ANTHROPIC_BASE_URL;
|
|
@@ -2143,30 +2003,18 @@ function sumUsageIterations(usage) {
|
|
|
2143
2003
|
}
|
|
2144
2004
|
return totals;
|
|
2145
2005
|
}
|
|
2146
|
-
async function withClaudeUserAgent(options) {
|
|
2147
|
-
if (options.userAgent || !options.apiKey?.startsWith("sk-ant-oat")) return options;
|
|
2148
|
-
return { ...options, userAgent: await getClaudeCliUserAgent() };
|
|
2149
|
-
}
|
|
2150
2006
|
function createClient(options) {
|
|
2151
|
-
const
|
|
2152
|
-
const userAgent = isOAuth ? options.userAgent ?? claudeCliUserAgent(CLAUDE_CODE_FALLBACK_VERSION) : "";
|
|
2153
|
-
const cacheKey = `${options.apiKey ?? ""}|${options.baseUrl ?? ""}|${userAgent}`;
|
|
2007
|
+
const cacheKey = `${options.apiKey ?? ""}|${options.baseUrl ?? ""}`;
|
|
2154
2008
|
if (!options.fetch) {
|
|
2155
2009
|
const cached = anthropicClientCache.get(cacheKey);
|
|
2156
2010
|
if (cached) return cached;
|
|
2157
2011
|
}
|
|
2158
2012
|
const client = new Anthropic({
|
|
2159
|
-
|
|
2013
|
+
apiKey: options.apiKey,
|
|
2160
2014
|
...options.baseUrl ? { baseURL: options.baseUrl } : {},
|
|
2161
2015
|
// Default transport lifts undici's 300s header/body caps (see provider-fetch.ts).
|
|
2162
2016
|
fetch: options.fetch ?? providerFetch,
|
|
2163
|
-
maxRetries: 0
|
|
2164
|
-
...isOAuth ? {
|
|
2165
|
-
defaultHeaders: {
|
|
2166
|
-
"user-agent": userAgent,
|
|
2167
|
-
"x-app": "cli"
|
|
2168
|
-
}
|
|
2169
|
-
} : {}
|
|
2017
|
+
maxRetries: 0
|
|
2170
2018
|
});
|
|
2171
2019
|
if (!options.fetch) {
|
|
2172
2020
|
if (anthropicClientCache.size >= 8) {
|
|
@@ -2179,13 +2027,10 @@ function createClient(options) {
|
|
|
2179
2027
|
}
|
|
2180
2028
|
async function prewarmAnthropicCache(options) {
|
|
2181
2029
|
try {
|
|
2182
|
-
const client = createClient(
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
userAgent: options.userAgent
|
|
2187
|
-
})
|
|
2188
|
-
);
|
|
2030
|
+
const client = createClient({
|
|
2031
|
+
apiKey: options.apiKey,
|
|
2032
|
+
baseUrl: options.baseUrl
|
|
2033
|
+
});
|
|
2189
2034
|
const cacheControl = toAnthropicCacheControl(options.cacheRetention ?? "long", options.baseUrl);
|
|
2190
2035
|
const { system, messages } = toAnthropicMessages(
|
|
2191
2036
|
[
|
|
@@ -2194,21 +2039,13 @@ async function prewarmAnthropicCache(options) {
|
|
|
2194
2039
|
],
|
|
2195
2040
|
cacheControl
|
|
2196
2041
|
);
|
|
2197
|
-
const isOAuth = options.apiKey.startsWith("sk-ant-oat");
|
|
2198
|
-
const fullSystem = isOAuth ? [
|
|
2199
|
-
{
|
|
2200
|
-
type: "text",
|
|
2201
|
-
text: "You are Claude Code, Anthropic's official CLI for Claude."
|
|
2202
|
-
},
|
|
2203
|
-
...system ?? []
|
|
2204
|
-
] : system;
|
|
2205
2042
|
const tools = options.tools?.length ? toAnthropicTools(options.tools, {
|
|
2206
2043
|
cacheControl,
|
|
2207
2044
|
// Keep the serialized tool bytes identical to runStream so the
|
|
2208
2045
|
// prewarmed prompt cache actually hits — both are gated by the flag.
|
|
2209
2046
|
enableFineGrainedToolStreaming: fineGrainedToolStreamingEnabled()
|
|
2210
2047
|
}) : void 0;
|
|
2211
|
-
if (estimatePrefixTokens(
|
|
2048
|
+
if (estimatePrefixTokens(system, tools) < anthropicMinCacheableTokens(options.model)) {
|
|
2212
2049
|
return;
|
|
2213
2050
|
}
|
|
2214
2051
|
await client.messages.create(
|
|
@@ -2216,7 +2053,7 @@ async function prewarmAnthropicCache(options) {
|
|
|
2216
2053
|
model: options.model,
|
|
2217
2054
|
max_tokens: 1,
|
|
2218
2055
|
messages,
|
|
2219
|
-
...
|
|
2056
|
+
...system ? { system } : {},
|
|
2220
2057
|
...tools ? {
|
|
2221
2058
|
tools: [
|
|
2222
2059
|
...tools,
|
|
@@ -2227,10 +2064,7 @@ async function prewarmAnthropicCache(options) {
|
|
|
2227
2064
|
{
|
|
2228
2065
|
signal: options.signal ?? void 0,
|
|
2229
2066
|
...(() => {
|
|
2230
|
-
const betas = [
|
|
2231
|
-
...isOAuth ? ["claude-code-20250219", "oauth-2025-04-20"] : [],
|
|
2232
|
-
...cacheControl?.ttl === "1h" ? ["extended-cache-ttl-2025-04-11"] : []
|
|
2233
|
-
];
|
|
2067
|
+
const betas = cacheControl?.ttl === "1h" ? ["extended-cache-ttl-2025-04-11"] : [];
|
|
2234
2068
|
return betas.length ? { headers: { "anthropic-beta": betas.join(",") } } : {};
|
|
2235
2069
|
})()
|
|
2236
2070
|
}
|
|
@@ -2242,8 +2076,7 @@ function streamAnthropic(options) {
|
|
|
2242
2076
|
return new StreamResult(runStream(options), options.signal);
|
|
2243
2077
|
}
|
|
2244
2078
|
async function* runStream(options) {
|
|
2245
|
-
const client = createClient(
|
|
2246
|
-
const isOAuth = options.apiKey?.startsWith("sk-ant-oat");
|
|
2079
|
+
const client = createClient(options);
|
|
2247
2080
|
const useStreaming = options.streaming !== false && !options.prewarm;
|
|
2248
2081
|
const cacheControl = toAnthropicCacheControl(options.cacheRetention, options.baseUrl);
|
|
2249
2082
|
const supportsFirstPartyToolExtras = !options.baseUrl || options.baseUrl.includes("api.anthropic.com");
|
|
@@ -2253,18 +2086,11 @@ async function* runStream(options) {
|
|
|
2253
2086
|
const useServerFallback = options.provider !== "minimax" && isDirectAnthropicApi(options.baseUrl) && !anthropicServerFallback.disabled.has(fallbackKey);
|
|
2254
2087
|
const deferredPlan = options.provider === "anthropic" && isDirectAnthropicApi(options.baseUrl) && supportsAnthropicDeferredTools(options.model) ? planDeferredTools(options.tools, options.deferredTools, downgradedMessages) : void 0;
|
|
2255
2088
|
const toolReferences = deferredPlan?.loaded;
|
|
2256
|
-
const { system
|
|
2089
|
+
const { system, messages } = toAnthropicMessages(downgradedMessages, cacheControl, {
|
|
2257
2090
|
fallbackBlocks: useServerFallback,
|
|
2258
2091
|
toolReferences
|
|
2259
2092
|
});
|
|
2260
2093
|
const useFastMode = options.speed === "fast" && options.provider === "anthropic" && isDirectAnthropicApi(options.baseUrl);
|
|
2261
|
-
const system = isOAuth ? [
|
|
2262
|
-
{
|
|
2263
|
-
type: "text",
|
|
2264
|
-
text: "You are Claude Code, Anthropic's official CLI for Claude."
|
|
2265
|
-
},
|
|
2266
|
-
...rawSystem ?? []
|
|
2267
|
-
] : rawSystem;
|
|
2268
2094
|
let maxTokens = options.maxTokens ?? 4096;
|
|
2269
2095
|
let thinking;
|
|
2270
2096
|
let outputConfig;
|
|
@@ -2340,7 +2166,6 @@ async function* runStream(options) {
|
|
|
2340
2166
|
const params = mergeProviderOptions(baseParams, options.providerOptions);
|
|
2341
2167
|
const hasAdaptiveThinking = isAdaptiveThinkingModel(options.model);
|
|
2342
2168
|
const betaHeaders = [
|
|
2343
|
-
...isOAuth ? ["claude-code-20250219", "oauth-2025-04-20"] : [],
|
|
2344
2169
|
...options.compaction ? ["compact-2026-01-12"] : [],
|
|
2345
2170
|
...options.clearToolUses ? ["context-management-2025-06-27"] : [],
|
|
2346
2171
|
// Eager tool-input streaming beta — opt-in only (see
|
|
@@ -2836,6 +2661,15 @@ function fnv1aHash(value) {
|
|
|
2836
2661
|
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
2837
2662
|
}
|
|
2838
2663
|
|
|
2664
|
+
// src/utils/diag.ts
|
|
2665
|
+
var _diagFn = null;
|
|
2666
|
+
function setProviderDiagnostic(fn) {
|
|
2667
|
+
_diagFn = fn;
|
|
2668
|
+
}
|
|
2669
|
+
function providerDiag(phase, data) {
|
|
2670
|
+
_diagFn?.(phase, data);
|
|
2671
|
+
}
|
|
2672
|
+
|
|
2839
2673
|
// src/providers/moonshot-video.ts
|
|
2840
2674
|
async function uploadMoonshotVideos(client, messages, signal) {
|
|
2841
2675
|
for (const msg of messages) {
|
|
@@ -3079,11 +2913,11 @@ async function* runStream2(options) {
|
|
|
3079
2913
|
}
|
|
3080
2914
|
const requestParams = mergeProviderOptions(params, options.providerOptions);
|
|
3081
2915
|
if (getEnvironment()?.GGAI_DUMP_REQUEST) {
|
|
3082
|
-
const
|
|
2916
|
+
const fs = await import("fs");
|
|
3083
2917
|
const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
3084
2918
|
const dumpPath = `/tmp/ggai-request-${ts}.json`;
|
|
3085
|
-
|
|
3086
|
-
|
|
2919
|
+
fs.writeFileSync(dumpPath, JSON.stringify(requestParams, null, 2));
|
|
2920
|
+
fs.appendFileSync(
|
|
3087
2921
|
"/tmp/ggai-requests.log",
|
|
3088
2922
|
`[${ts}] ${dumpPath} messages=${requestParams.messages.length}
|
|
3089
2923
|
`
|
|
@@ -3413,7 +3247,7 @@ function toError2(err, provider = "openai") {
|
|
|
3413
3247
|
}
|
|
3414
3248
|
|
|
3415
3249
|
// src/providers/openai-codex.ts
|
|
3416
|
-
import
|
|
3250
|
+
import os from "os";
|
|
3417
3251
|
import * as zstd from "@bokuweb/zstd-wasm";
|
|
3418
3252
|
|
|
3419
3253
|
// src/utils/sse.ts
|
|
@@ -4059,7 +3893,7 @@ async function* runStream3(options, retriedWithoutReasoning = false) {
|
|
|
4059
3893
|
Authorization: `Bearer ${options.apiKey}`,
|
|
4060
3894
|
"OpenAI-Beta": "responses=experimental",
|
|
4061
3895
|
originator: responsesLite ? "codex_cli_rs" : "ggcoder",
|
|
4062
|
-
"User-Agent": responsesLite ? `codex_cli_rs/${CODEX_CLIENT_VERSION}` : `ggcoder (${
|
|
3896
|
+
"User-Agent": responsesLite ? `codex_cli_rs/${CODEX_CLIENT_VERSION}` : `ggcoder (${os.platform()} ${os.release()}; ${os.arch()})`,
|
|
4063
3897
|
...responsesLite ? { version: CODEX_CLIENT_VERSION } : {},
|
|
4064
3898
|
...liteShape ? { "X-OpenAI-Internal-Codex-Responses-Lite": "true" } : {}
|
|
4065
3899
|
};
|
|
@@ -5199,8 +5033,8 @@ function bound(text) {
|
|
|
5199
5033
|
const trimmed = text.trim();
|
|
5200
5034
|
return trimmed.length > MAX_ERROR_MESSAGE_CHARS ? `${trimmed.slice(0, MAX_ERROR_MESSAGE_CHARS)}\u2026` : trimmed;
|
|
5201
5035
|
}
|
|
5202
|
-
function joinUrl(baseUrl,
|
|
5203
|
-
return `${baseUrl.replace(/\/+$/, "")}/${
|
|
5036
|
+
function joinUrl(baseUrl, path) {
|
|
5037
|
+
return `${baseUrl.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
5204
5038
|
}
|
|
5205
5039
|
|
|
5206
5040
|
// src/providers/gemini-embeddings.ts
|
|
@@ -6507,7 +6341,6 @@ function palsuRerankScore(query, document) {
|
|
|
6507
6341
|
return hits / queryTokens.size;
|
|
6508
6342
|
}
|
|
6509
6343
|
export {
|
|
6510
|
-
CLAUDE_CODE_FALLBACK_VERSION,
|
|
6511
6344
|
CODEX_CLIENT_VERSION,
|
|
6512
6345
|
EventStream,
|
|
6513
6346
|
FAST_MODE_SUFFIX,
|
|
@@ -6529,8 +6362,6 @@ export {
|
|
|
6529
6362
|
formatChatError,
|
|
6530
6363
|
formatError,
|
|
6531
6364
|
formatErrorForDisplay,
|
|
6532
|
-
getClaudeCliUserAgent,
|
|
6533
|
-
getClaudeCodeVersion,
|
|
6534
6365
|
hasLoneSurrogate,
|
|
6535
6366
|
isHardBillingMessage,
|
|
6536
6367
|
isUsageLimitError,
|
|
@@ -6545,7 +6376,6 @@ export {
|
|
|
6545
6376
|
palsuThinking,
|
|
6546
6377
|
palsuToolCall,
|
|
6547
6378
|
parseFastModeRejection,
|
|
6548
|
-
pendingClaudeCodeVersionRefresh,
|
|
6549
6379
|
preconnectOrigin,
|
|
6550
6380
|
preconnectProvider,
|
|
6551
6381
|
prewarmAnthropicCache,
|