@xiaoso/dsh-tool-plus 0.1.16 → 0.1.17-beta.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.
Files changed (109) hide show
  1. package/lib/{abort-DZ54CaKU.mjs → abort-BTblp0Rt.mjs} +2 -2
  2. package/lib/{alibaba-coding-plan-DODpkcqi.mjs → alibaba-coding-plan-t3R4YKCB.mjs} +3 -3
  3. package/lib/{alibaba-token-plan-C6lpKCda.mjs → alibaba-token-plan-CO4djG1y.mjs} +4 -4
  4. package/lib/{alibaba-token-plan-CHGyWOfX.mjs → alibaba-token-plan-CUjYJX0-.mjs} +1 -1
  5. package/lib/{anthropic-Dv_GGX6g.mjs → anthropic-nf7w6so1.mjs} +48 -21
  6. package/lib/{api-key-validation-MnMf_ihX.mjs → api-key-validation-C_tZ7Y9a.mjs} +2 -2
  7. package/lib/behavior-BwvTUtag.mjs +111 -0
  8. package/lib/{browser-render-BZXt548F.mjs → browser-render-BQaEVK_n.mjs} +4 -4
  9. package/lib/{reference-CtvM4zLU.mjs → bundled-references-CrQ4dQcT.mjs} +57 -4
  10. package/lib/cascade-BWjRTD1q.mjs +30265 -0
  11. package/lib/{cline-pass-BT9CBEOj.mjs → cline-pass-Bjm-O8GG.mjs} +2 -2
  12. package/lib/cloudflare-CKXRJ0l9.mjs +37 -0
  13. package/lib/{cloudflare-ai-gateway-DReN6ohJ.mjs → cloudflare-ai-gateway-BpnBSjwV.mjs} +8 -4
  14. package/lib/cloudflare-workers-ai-odj9XswL.mjs +32 -0
  15. package/lib/collapse-_nkb2dn7.mjs +1945 -0
  16. package/lib/{coreweave-C82HrLpb.mjs → coreweave-CGDZOD8-.mjs} +1 -1
  17. package/lib/{coreweave-C68UgRQO.mjs → coreweave-DwffcgW5.mjs} +4 -4
  18. package/lib/cursor-BgOuV7Qf.mjs +794 -0
  19. package/lib/{cursor-_gHHq-Dq.mjs → cursor-CF1iHHbv.mjs} +68 -19
  20. package/lib/{cursor-proto-Cr_WEMuv.mjs → cursor-proto-BuNTjX3L.mjs} +823 -23
  21. package/lib/{devin-QpfTSl9H.mjs → devin-7OEeEb80.mjs} +112 -31
  22. package/lib/{devin-proto-DYhp4Ty6.mjs → devin-proto-C-QreeAv.mjs} +71 -5
  23. package/lib/{dom-DG3sPESc.mjs → dom-BmbZv4v9.mjs} +598 -182
  24. package/lib/{error-O63pC8zg.mjs → error-8LVo7tug.mjs} +725 -104
  25. package/lib/factory-droid-ChhmsGWb.mjs +71 -0
  26. package/lib/{fs-promises-shim-B2YFWkcd.mjs → fs-promises-shim-CANAxFWh.mjs} +10 -1
  27. package/lib/{github-copilot-BMEcw8N1.mjs → github-copilot-QwevdT30.mjs} +4 -4
  28. package/lib/{github-copilot-headers-DnjGEbko.mjs → github-copilot-headers-CAUZ0rUD.mjs} +138 -26
  29. package/lib/{gitlab-duo-DnHqJjFY.mjs → gitlab-duo-DigV7k_o.mjs} +2 -2
  30. package/lib/{google-antigravity-B1mSckrK.mjs → google-antigravity-D-oe0r8A.mjs} +6 -7
  31. package/lib/{google-gemini-cli-DJwThCCn.mjs → google-gemini-cli-CQBHgGJT.mjs} +5 -6
  32. package/lib/{google-oauth-shared-BctLpVUN.mjs → google-oauth-shared-CvgVIUwJ.mjs} +2 -2
  33. package/lib/google-validation-CdvRj4ec.mjs +126 -0
  34. package/lib/id-EJwVLDHE.mjs +2548 -0
  35. package/lib/index.mjs +248 -258
  36. package/lib/{kilo-BEgEwMJQ.mjs → kilo-5r6OffCa.mjs} +2 -2
  37. package/lib/{kimi-T9NldEIJ.mjs → kimi-DOOtbXmm.mjs} +9 -10
  38. package/lib/{launch-BIWNyrBB.mjs → launch-DkAjib7h.mjs} +1 -1
  39. package/lib/{markit-Dvp2JPdT.mjs → markit-CCcyeAds.mjs} +359 -140
  40. package/lib/{models-DnXMYGcJ.mjs → models-DCpDT_im.mjs} +199203 -112275
  41. package/lib/{muse-code-CNvqqAp6.mjs → muse-code-CYf8zj_B.mjs} +5 -5
  42. package/lib/{openai-codex-D5-CyTxa.mjs → openai-codex-Cj-TvSFh.mjs} +13 -10
  43. package/lib/{perplexity-A2PEoGaC.mjs → perplexity-Dh_Qgsmx.mjs} +68 -25
  44. package/lib/{pkce-BYjmugmw.mjs → pkce-DO-jBJLV.mjs} +1 -1
  45. package/lib/pricing-DusBEhwm.mjs +593 -0
  46. package/lib/{readability-uGhqb4GC.mjs → readability-XHK0o3bv.mjs} +287 -27
  47. package/lib/{scrapers-C1ujjV8k.mjs → scrapers-B6PADOVm.mjs} +13 -13
  48. package/lib/slugify-ynYWBIA5.mjs +11 -0
  49. package/lib/snowflake-B_jap6lz.mjs +666 -0
  50. package/lib/snowflake-Cu1ZyOp6.mjs +151 -0
  51. package/lib/{src-AELUUb5U.mjs → src-BhinCSpi.mjs} +1172 -458
  52. package/lib/{stream-AVOoe5Hj.mjs → stream-D2ivg3GH.mjs} +3740 -5311
  53. package/lib/{turndown-D6fof1OX.mjs → turndown-Vya8SavL.mjs} +82 -30
  54. package/lib/types/tools/hashline/native/index.d.ts +2 -2
  55. package/lib/types/tools/hashline/native/policy.d.ts +19 -21
  56. package/lib/types/tools/omp/session/agent-storage.d.ts +3 -3
  57. package/lib/types/tools/shared/bun-named-shim.d.ts +5 -0
  58. package/lib/{types-BLrLohwK.mjs → types-tH1v9uRm.mjs} +2 -2
  59. package/lib/{utils-cZX3f_Ls.mjs → utils-C_Ncya1r.mjs} +1737 -509
  60. package/lib/utils-D2tK38xq.mjs +34006 -0
  61. package/lib/{utils-I4I8azHN.mjs → utils-DrDwmNtu.mjs} +8 -3
  62. package/lib/{xai-oauth-CbeldUSV.mjs → xai-oauth-DLLzX6my.mjs} +4 -4
  63. package/lib/{xiaomi-Dl3VSs04.mjs → xiaomi-CqK-KivK.mjs} +2 -2
  64. package/lib/{zai-FyjGSypr.mjs → zai-DoJ2xPIH.mjs} +2 -2
  65. package/lib/{zip-DRrycScC.mjs → zip-DG1mUV6X.mjs} +1 -1
  66. package/package.json +8 -8
  67. package/lib/amazon-bedrock-Dx0rr9dY.mjs +0 -996
  68. package/lib/anthropic-ClCw0PV_.mjs +0 -3624
  69. package/lib/anthropic-wire-lbGAFzYb.mjs +0 -927
  70. package/lib/azure-openai-responses-WE_bgFWp.mjs +0 -285
  71. package/lib/bundled-references-DY3EJxZV.mjs +0 -56
  72. package/lib/cloudflare-ai-gateway-CrMa97Ap.mjs +0 -44
  73. package/lib/collapse-CkMNRNr7.mjs +0 -2304
  74. package/lib/cursor-C6jaIJDg.mjs +0 -283
  75. package/lib/cursor-D-XZYDf_.mjs +0 -4544
  76. package/lib/deterministic-id-CUEIMSqR.mjs +0 -17
  77. package/lib/devin-ExGIghmx.mjs +0 -69
  78. package/lib/devin-u0ljw5P6.mjs +0 -628
  79. package/lib/effort-BdtQMN-_.mjs +0 -23
  80. package/lib/event-stream-BKEtb45Y.mjs +0 -167
  81. package/lib/gemini-headers-Co9cVvex.mjs +0 -54
  82. package/lib/google-auth-qAN-6DMW.mjs +0 -232
  83. package/lib/google-gemini-cli-B2Aw1S5w.mjs +0 -844
  84. package/lib/google-lTxuq28n.mjs +0 -38
  85. package/lib/google-shared-Y01j9xOr.mjs +0 -856
  86. package/lib/google-validation-BEkNs-Bx.mjs +0 -18
  87. package/lib/google-vertex-DcM-FRC5.mjs +0 -99
  88. package/lib/hosts-00rjRzUD.mjs +0 -203
  89. package/lib/id-AL5obQzR.mjs +0 -71
  90. package/lib/idle-iterator-D0ZXEcUq.mjs +0 -366
  91. package/lib/ollama-6R0oXZks.mjs +0 -574
  92. package/lib/openai-codex-responses-C8bnBWOe.mjs +0 -3232
  93. package/lib/openai-completions-DNr3mUsn.mjs +0 -1430
  94. package/lib/openai-configuration-update-xMYUjaK_.mjs +0 -150
  95. package/lib/openai-reasoning-fallback-Ju-5pSR8.mjs +0 -380
  96. package/lib/openai-responses-CjpafAEr.mjs +0 -861
  97. package/lib/protobuf-BMgDYu_U.mjs +0 -717
  98. package/lib/provider-response-SqKSkkUc.mjs +0 -22
  99. package/lib/proxy-DxvCQOCA.mjs +0 -230
  100. package/lib/request-debug-BwPOqN_j.mjs +0 -183
  101. package/lib/sanitize-text-BCf5KmCf.mjs +0 -33
  102. package/lib/sse-debug-B-tkLCPW.mjs +0 -11
  103. package/lib/stream-markup-healing-CN3RsqG9.mjs +0 -267
  104. package/lib/strict-tool-validation-CBTz1dAA.mjs +0 -105
  105. package/lib/taxonomy-DSIM99rS.mjs +0 -15392
  106. package/lib/thinking-ngMwf_1Y.mjs +0 -336
  107. package/lib/type-guards-CttAANEx.mjs +0 -11
  108. package/lib/utils-CE3DSebh.mjs +0 -11763
  109. package/lib/vision-guard-BCpXWUj3.mjs +0 -77
@@ -1,844 +0,0 @@
1
- import { installBunShim as __installBunShim } from "./bun-shim.mjs";
2
- __installBunShim();
3
- import { o as readSseJson } from "./src-AELUUb5U.mjs";
4
- import { C as classify, G as fetchWithRetry, L as GeminiCliApiError, W as extractHttpStatusFromError, _ as AbortError, a as isTransientStatus, c as finalize, f as OAuthError, j as retriable, n as StreamTimeoutError, r as ValidationError, s as ProviderResponseError, t as ConfigurationError } from "./error-O63pC8zg.mjs";
5
- import { N as normalizeSchemaForCCA, o as normalizeSystemPrompts } from "./utils-cZX3f_Ls.mjs";
6
- import { t as calculateCost } from "./models-DnXMYGcJ.mjs";
7
- import { t as AssistantMessageEventStream } from "./event-stream-BKEtb45Y.mjs";
8
- import { n as getAntigravityUserAgent, r as getGeminiCliHeaders, t as getAntigravityModelWireProfile } from "./gemini-headers-Co9cVvex.mjs";
9
- import { i as getStreamFirstEventTimeoutMs, o as iterateWithIdleTimeout, t as armPreResponseTimeout } from "./idle-iterator-D0ZXEcUq.mjs";
10
- import { t as StreamMarkupHealing } from "./stream-markup-healing-CN3RsqG9.mjs";
11
- import { n as formatGoogleValidationRequiredMessage, t as extractGoogleValidationUrl } from "./google-validation-BEkNs-Bx.mjs";
12
- import { a as isThinkingPart, c as nextToolCallId, d as retainThoughtSignature, f as startTextOrThinkingBlock, i as hasMeaningfulGoogleContent, l as pushBlockEndEvent, n as convertMessages, o as mapStopReasonString, r as convertTools, s as mapToolChoice, u as pushToolCallEvents } from "./google-shared-Y01j9xOr.mjs";
13
- import { scheduler } from "node:timers/promises";
14
- import { createHash, randomBytes, randomUUID } from "node:crypto";
15
- import { type } from "@oh-my-pi/omptype";
16
- //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/google-antigravity-forced-tool.md
17
- var google_antigravity_forced_tool_default = "TOOL-ONLY TURN. This turn accepts a tool call and nothing else; a text reply here is discarded unread and you will be re-prompted. Emit the tool call now.\n";
18
- //#endregion
19
- //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/google-gemini-cli.ts
20
- /**
21
- * Google Gemini CLI / Antigravity provider.
22
- * Shared implementation for both google-gemini-cli and google-antigravity providers.
23
- * Uses the Cloud Code Assist API endpoint to access Gemini and Claude models.
24
- */
25
- function isPlanningLeakPrefix(text) {
26
- const trimmed = text.trimStart();
27
- if (!trimmed.startsWith("{")) return false;
28
- const afterBrace = trimmed.slice(1).trimStart();
29
- if (afterBrace === "") return trimmed.length <= 100;
30
- if (afterBrace[0] !== "\"") return false;
31
- const nextQuoteIndex = afterBrace.indexOf("\"", 1);
32
- if (nextQuoteIndex === -1) {
33
- const keyPrefix = afterBrace.slice(1);
34
- return "thought".startsWith(keyPrefix) && trimmed.length <= 100;
35
- }
36
- if (afterBrace.slice(1, nextQuoteIndex) !== "thought") return false;
37
- const afterKey = afterBrace.slice(nextQuoteIndex + 1).trimStart();
38
- if (afterKey === "") return trimmed.length <= 100;
39
- if (afterKey[0] !== ":") return false;
40
- return true;
41
- }
42
- function isPlanningLeakObject(parsed, toolNames) {
43
- if (!parsed || typeof parsed !== "object") return false;
44
- const record = parsed;
45
- const hasThought = typeof record.thought === "string";
46
- const isOmpTool = typeof record.call === "string" && toolNames.has(record.call);
47
- const hasToolSignature = "_i" in record || "paths" in record || "command" in record || "path" in record && "content" in record;
48
- return hasThought || isOmpTool || hasToolSignature;
49
- }
50
- function splitLeadingJsonObject(text) {
51
- const prefixLength = text.length - text.trimStart().length;
52
- const trimmed = text.slice(prefixLength);
53
- if (!trimmed.startsWith("{")) return void 0;
54
- let depth = 0;
55
- let inString = false;
56
- let escaped = false;
57
- for (let index = 0; index < trimmed.length; index += 1) {
58
- const ch = trimmed[index];
59
- if (inString) {
60
- if (escaped) {
61
- escaped = false;
62
- continue;
63
- }
64
- if (ch === "\\") {
65
- escaped = true;
66
- continue;
67
- }
68
- if (ch === "\"") inString = false;
69
- continue;
70
- }
71
- if (ch === "\"") {
72
- inString = true;
73
- continue;
74
- }
75
- if (ch === "{") {
76
- depth += 1;
77
- continue;
78
- }
79
- if (ch !== "}") continue;
80
- depth -= 1;
81
- if (depth !== 0) continue;
82
- const jsonText = trimmed.slice(0, index + 1);
83
- return {
84
- prefixLength: prefixLength + index + 1,
85
- jsonText,
86
- rest: trimmed.slice(index + 1)
87
- };
88
- }
89
- }
90
- function splitLeadingJsonObjectIgnoringQuotes(text) {
91
- const prefixLength = text.length - text.trimStart().length;
92
- const trimmed = text.slice(prefixLength);
93
- if (!trimmed.startsWith("{")) return void 0;
94
- let depth = 0;
95
- for (let index = 0; index < trimmed.length; index += 1) {
96
- const ch = trimmed[index];
97
- if (ch === "{") depth += 1;
98
- else if (ch === "}") {
99
- depth -= 1;
100
- if (depth === 0) return {
101
- prefixLength: prefixLength + index + 1,
102
- jsonText: trimmed.slice(0, index + 1),
103
- rest: trimmed.slice(index + 1)
104
- };
105
- }
106
- }
107
- }
108
- function consumePlanningBuffer(text, toolNames, isFinal = false) {
109
- if (!isPlanningLeakPrefix(text)) return {
110
- kind: "plain",
111
- visibleText: text
112
- };
113
- let leading = splitLeadingJsonObject(text);
114
- if (!leading) leading = splitLeadingJsonObjectIgnoringQuotes(text);
115
- if (!leading) {
116
- if (isFinal) {
117
- const trimmed = text.trim();
118
- const hasThoughtKey = trimmed.includes("\"thought\"");
119
- const hasToolKey = Array.from(toolNames).some((name) => trimmed.includes(`"${name}"`));
120
- const hasToolSignature = trimmed.includes("\"_i\"") || trimmed.includes("\"paths\"") || trimmed.includes("\"command\"") || trimmed.includes("\"path\"") && trimmed.includes("\"content\"");
121
- if (hasThoughtKey || hasToolKey || hasToolSignature) return {
122
- kind: "leak",
123
- visibleText: ""
124
- };
125
- return {
126
- kind: "plain",
127
- visibleText: text
128
- };
129
- }
130
- return { kind: "incomplete" };
131
- }
132
- let parsed;
133
- try {
134
- parsed = JSON.parse(leading.jsonText);
135
- } catch {
136
- const hasThoughtKey = leading.jsonText.includes("\"thought\"");
137
- const hasToolKey = Array.from(toolNames).some((name) => leading.jsonText.includes(`"${name}"`));
138
- const hasToolSignature = leading.jsonText.includes("\"_i\"") || leading.jsonText.includes("\"paths\"") || leading.jsonText.includes("\"command\"") || leading.jsonText.includes("\"path\"") && leading.jsonText.includes("\"content\"");
139
- if (hasThoughtKey || hasToolKey || hasToolSignature) return {
140
- kind: "leak",
141
- visibleText: leading.rest
142
- };
143
- return {
144
- kind: "plain",
145
- visibleText: text
146
- };
147
- }
148
- return isPlanningLeakObject(parsed, toolNames) ? {
149
- kind: "leak",
150
- visibleText: leading.rest
151
- } : {
152
- kind: "plain",
153
- visibleText: text
154
- };
155
- }
156
- const ANTIGRAVITY_PROVIDER_SESSION_STATE_KEY = "google-antigravity-session-state";
157
- function getAntigravityProviderSessionState(providerSessionState) {
158
- if (!providerSessionState) return void 0;
159
- let existing = providerSessionState.get(ANTIGRAVITY_PROVIDER_SESSION_STATE_KEY);
160
- if (!existing) {
161
- existing = { close: () => {} };
162
- providerSessionState.set(ANTIGRAVITY_PROVIDER_SESSION_STATE_KEY, existing);
163
- }
164
- return existing;
165
- }
166
- const DEFAULT_ENDPOINT = "https://cloudcode-pa.googleapis.com";
167
- const ANTIGRAVITY_DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
168
- const ANTIGRAVITY_SANDBOX_ENDPOINT = "https://daily-cloudcode-pa.sandbox.googleapis.com";
169
- const ANTIGRAVITY_ENDPOINT_FALLBACKS = [ANTIGRAVITY_DAILY_ENDPOINT, ANTIGRAVITY_SANDBOX_ENDPOINT];
170
- const BASE_DELAY_MS = 1e3;
171
- const DEFAULT_FIRST_EVENT_TIMEOUT_MS = 3e5;
172
- const FIRST_EVENT_TIMEOUT_ERROR = "Cloud Code Assist stream timed out while waiting for the first event";
173
- const RATE_LIMIT_BUDGET_MS = 3e5;
174
- const CLAUDE_THINKING_BETA_HEADER = "interleaved-thinking-2025-05-14";
175
- const GOOGLE_GEMINI_REFRESH_SKEW_MS = 6e4;
176
- const ANTIGRAVITY_REFRESH_SKEW_MS = 6e4;
177
- const optionalCredentialString = type("unknown").pipe((raw) => {
178
- const out = type("string")(raw);
179
- return out instanceof type.errors ? void 0 : out;
180
- });
181
- const innerCredentialsSchema = type({
182
- "token?": optionalCredentialString,
183
- "projectId?": optionalCredentialString,
184
- "project_id?": optionalCredentialString,
185
- "refreshToken?": optionalCredentialString,
186
- "refresh?": optionalCredentialString,
187
- "email?": optionalCredentialString,
188
- "expiresAt?": "unknown",
189
- "expires?": "unknown"
190
- });
191
- const geminiCliCredentialsSchema = type("unknown").pipe((raw) => {
192
- const out = innerCredentialsSchema(raw);
193
- return out instanceof type.errors ? {} : out;
194
- });
195
- function normalizeExpiryMs(value) {
196
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return;
197
- return value < 1e10 ? value * 1e3 : value;
198
- }
199
- function parseGeminiCliCredentials(apiKeyRaw) {
200
- const invalidCredentialsMessage = "Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.";
201
- const missingCredentialsMessage = "Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.";
202
- let rawCredentials;
203
- try {
204
- rawCredentials = JSON.parse(apiKeyRaw);
205
- } catch {
206
- throw new ValidationError(invalidCredentialsMessage);
207
- }
208
- const parsed = geminiCliCredentialsSchema(rawCredentials);
209
- if (parsed instanceof type.errors) throw new ValidationError(invalidCredentialsMessage);
210
- const projectId = parsed.projectId ?? parsed.project_id;
211
- if (parsed.token === void 0 || projectId === void 0) throw new ValidationError(missingCredentialsMessage);
212
- const refreshToken = parsed.refreshToken ?? parsed.refresh;
213
- const expiresAt = normalizeExpiryMs(parsed.expiresAt ?? parsed.expires);
214
- const email = parsed.email && parsed.email.length > 0 ? parsed.email : void 0;
215
- return {
216
- accessToken: parsed.token,
217
- projectId,
218
- refreshToken,
219
- expiresAt,
220
- email
221
- };
222
- }
223
- function shouldRefreshGeminiCliCredentials(expiresAt, isAntigravity, nowMs = Date.now()) {
224
- if (expiresAt === void 0) return false;
225
- return nowMs + (isAntigravity ? ANTIGRAVITY_REFRESH_SKEW_MS : GOOGLE_GEMINI_REFRESH_SKEW_MS) >= expiresAt;
226
- }
227
- const streamGoogleGeminiCli = (model, context, options) => {
228
- const stream = new AssistantMessageEventStream();
229
- (async () => {
230
- const startTime = performance.now();
231
- let firstTokenTime;
232
- const output = {
233
- role: "assistant",
234
- content: [],
235
- api: "google-gemini-cli",
236
- provider: model.provider,
237
- model: model.id,
238
- usage: {
239
- input: 0,
240
- output: 0,
241
- cacheRead: 0,
242
- cacheWrite: 0,
243
- totalTokens: 0,
244
- cost: {
245
- input: 0,
246
- output: 0,
247
- cacheRead: 0,
248
- cacheWrite: 0,
249
- total: 0
250
- }
251
- },
252
- stopReason: "stop",
253
- timestamp: Date.now()
254
- };
255
- let rawRequestDump;
256
- try {
257
- const apiKeyRaw = options?.apiKey;
258
- if (!apiKeyRaw) throw new ConfigurationError("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");
259
- const isAntigravity = model.provider === "google-antigravity";
260
- const parsedCredentials = parseGeminiCliCredentials(apiKeyRaw);
261
- const { accessToken, projectId } = parsedCredentials;
262
- if (shouldRefreshGeminiCliCredentials(parsedCredentials.expiresAt, isAntigravity) && parsedCredentials.expiresAt !== void 0 && Date.now() >= parsedCredentials.expiresAt) throw new OAuthError("OAuth token expired before request — please retry; AuthStorage will refresh on the next attempt.", {
263
- kind: "token-refresh",
264
- provider: model.provider
265
- });
266
- const baseUrl = model.baseUrl?.trim();
267
- let endpoints;
268
- const providerState = isAntigravity ? getAntigravityProviderSessionState(options?.providerSessionState) : void 0;
269
- if (isAntigravity) {
270
- const mode = options?.antigravityEndpointMode ?? "auto";
271
- if (mode === "sandbox") {
272
- endpoints = [ANTIGRAVITY_SANDBOX_ENDPOINT];
273
- if (providerState) providerState.lastGoodEndpoint = void 0;
274
- } else if (mode === "production") {
275
- endpoints = [ANTIGRAVITY_DAILY_ENDPOINT];
276
- if (providerState) providerState.lastGoodEndpoint = void 0;
277
- } else if (baseUrl) {
278
- const cleanUrl = baseUrl.replace(/\/+$/, "");
279
- if (cleanUrl !== ANTIGRAVITY_DAILY_ENDPOINT && cleanUrl !== ANTIGRAVITY_SANDBOX_ENDPOINT) {
280
- endpoints = [baseUrl];
281
- if (providerState) providerState.lastGoodEndpoint = void 0;
282
- } else {
283
- const defaultFallbacks = [...ANTIGRAVITY_ENDPOINT_FALLBACKS];
284
- const lastGood = providerState?.lastGoodEndpoint;
285
- if (lastGood && defaultFallbacks.includes(lastGood)) endpoints = [lastGood, ...defaultFallbacks.filter((e) => e !== lastGood)];
286
- else endpoints = defaultFallbacks;
287
- }
288
- } else {
289
- const defaultFallbacks = [...ANTIGRAVITY_ENDPOINT_FALLBACKS];
290
- const lastGood = providerState?.lastGoodEndpoint;
291
- if (lastGood && defaultFallbacks.includes(lastGood)) endpoints = [lastGood, ...defaultFallbacks.filter((e) => e !== lastGood)];
292
- else endpoints = defaultFallbacks;
293
- }
294
- } else endpoints = baseUrl ? [baseUrl] : [DEFAULT_ENDPOINT];
295
- let requestBody = buildRequest(model, context, projectId, options, isAntigravity);
296
- const replacementPayload = await options?.onPayload?.(requestBody, model);
297
- if (replacementPayload !== void 0) requestBody = replacementPayload;
298
- const headers = isAntigravity ? { "User-Agent": getAntigravityUserAgent() } : getGeminiCliHeaders(model.id);
299
- const requestHeaders = {
300
- Authorization: `Bearer ${accessToken}`,
301
- "Content-Type": "application/json",
302
- Accept: "text/event-stream",
303
- ...headers,
304
- ...model.compat.claudeThinkingBetaHeader && model.identity.class === "anthropic" && model.reasoning ? { "anthropic-beta": CLAUDE_THINKING_BETA_HEADER } : {},
305
- ...options?.headers
306
- };
307
- const requestBodyJson = JSON.stringify(requestBody);
308
- rawRequestDump = {
309
- provider: model.provider,
310
- api: output.api,
311
- model: model.id,
312
- method: "POST",
313
- body: requestBody,
314
- headers: requestHeaders
315
- };
316
- const firstEventTimeoutMs = options?.streamFirstEventTimeoutMs ?? getStreamFirstEventTimeoutMs(void 0, model.compat.streamFirstEventTimeoutMs ?? DEFAULT_FIRST_EVENT_TIMEOUT_MS);
317
- const callerSignal = options?.signal;
318
- const toolNames = new Set(context.tools?.map((t) => t.name) ?? []);
319
- const isFlashLeakModel = model.compat.flashStreamLeakWorkaround;
320
- let started = false;
321
- let sawFinishReason = false;
322
- let lastResponseId;
323
- const ensureStarted = () => {
324
- if (!started) {
325
- if (!firstTokenTime) firstTokenTime = performance.now();
326
- stream.push({
327
- type: "start",
328
- partial: output
329
- });
330
- started = true;
331
- }
332
- };
333
- const resetOutput = () => {
334
- output.content = [];
335
- output.usage = {
336
- input: 0,
337
- output: 0,
338
- cacheRead: 0,
339
- cacheWrite: 0,
340
- totalTokens: 0,
341
- cost: {
342
- input: 0,
343
- output: 0,
344
- cacheRead: 0,
345
- cacheWrite: 0,
346
- total: 0
347
- }
348
- };
349
- output.stopReason = "stop";
350
- output.errorMessage = void 0;
351
- output.timestamp = Date.now();
352
- sawFinishReason = false;
353
- };
354
- const streamResponse = async (activeResponse) => {
355
- if (!activeResponse.body) throw new ProviderResponseError("No response body", {
356
- provider: model.provider,
357
- kind: "empty-body"
358
- });
359
- lastResponseId = void 0;
360
- let currentBlock = null;
361
- const blocks = output.content;
362
- const blockIndex = () => blocks.length - 1;
363
- const visibleTextHealing = new StreamMarkupHealing({ pattern: "thinking" });
364
- let isBuffering = false;
365
- let textBuffer = "";
366
- let bufferedTextSignature;
367
- let strippedPlanningLeak = false;
368
- const endCurrentBlock = () => {
369
- if (!currentBlock) return;
370
- pushBlockEndEvent(currentBlock, blockIndex(), output, stream);
371
- currentBlock = null;
372
- };
373
- const startTextBlock = () => {
374
- let block = currentBlock;
375
- if (block?.type !== "text") {
376
- endCurrentBlock();
377
- block = startTextOrThinkingBlock(false, output, stream, ensureStarted);
378
- currentBlock = block;
379
- }
380
- return block;
381
- };
382
- const startThinkingBlock = () => {
383
- let block = currentBlock;
384
- if (block?.type !== "thinking") {
385
- endCurrentBlock();
386
- block = startTextOrThinkingBlock(true, output, stream, ensureStarted);
387
- currentBlock = block;
388
- }
389
- return block;
390
- };
391
- const emitVisibleText = (delta, thoughtSignature) => {
392
- if (!delta) return;
393
- const block = startTextBlock();
394
- block.text += delta;
395
- block.textSignature = retainThoughtSignature(block.textSignature, thoughtSignature);
396
- stream.push({
397
- type: "text_delta",
398
- contentIndex: blockIndex(),
399
- delta,
400
- partial: output
401
- });
402
- };
403
- const emitVisibleThinking = (delta) => {
404
- if (!delta) return;
405
- const block = startThinkingBlock();
406
- block.thinking += delta;
407
- stream.push({
408
- type: "thinking_delta",
409
- contentIndex: blockIndex(),
410
- delta,
411
- partial: output
412
- });
413
- };
414
- const emitHealingEvent = (event, thoughtSignature) => {
415
- if (event.type === "text") emitVisibleText(event.text, thoughtSignature);
416
- else if (event.type === "thinking") emitVisibleThinking(event.thinking);
417
- };
418
- const feedVisibleText = (delta, thoughtSignature) => {
419
- for (const event of visibleTextHealing.feedEvents(delta)) emitHealingEvent(event, thoughtSignature);
420
- };
421
- const flushVisibleText = (thoughtSignature) => {
422
- for (const event of visibleTextHealing.flushEvents()) emitHealingEvent(event, thoughtSignature);
423
- };
424
- const retainCurrentBlockThoughtSignature = (thoughtSignature) => {
425
- const block = currentBlock;
426
- if (!block) return;
427
- if (block.type === "thinking") block.thinkingSignature = retainThoughtSignature(block.thinkingSignature, thoughtSignature);
428
- else block.textSignature = retainThoughtSignature(block.textSignature, thoughtSignature);
429
- };
430
- const responseAbortController = new AbortController();
431
- const responseSignal = options?.signal ? AbortSignal.any([options.signal, responseAbortController.signal]) : responseAbortController.signal;
432
- const chunks = iterateWithIdleTimeout(readSseJson(activeResponse.body, responseSignal, (event) => options?.onSseEvent?.({
433
- event: event.event,
434
- data: event.data,
435
- raw: [...event.raw]
436
- }, model)), {
437
- firstItemTimeoutMs: firstEventTimeoutMs,
438
- errorMessage: FIRST_EVENT_TIMEOUT_ERROR,
439
- firstItemErrorMessage: FIRST_EVENT_TIMEOUT_ERROR,
440
- onFirstItemTimeout: () => responseAbortController.abort(new StreamTimeoutError(FIRST_EVENT_TIMEOUT_ERROR)),
441
- abortSignal: options?.signal
442
- });
443
- for await (const chunk of chunks) {
444
- if (chunk.error) {
445
- const message = `Cloud Code Assist stream error: ${chunk.error.message || chunk.error.status || "unknown error"}`;
446
- throw typeof chunk.error.code === "number" && chunk.error.code >= 400 ? new GeminiCliApiError(message, chunk.error.code) : new ProviderResponseError(message, {
447
- provider: model.provider,
448
- kind: "runtime"
449
- });
450
- }
451
- const responseData = chunk.response;
452
- if (!responseData) continue;
453
- if (responseData.responseId) lastResponseId = responseData.responseId;
454
- if (!responseData.candidates?.length && responseData.promptFeedback?.blockReason) {
455
- const detail = responseData.promptFeedback.blockReasonMessage;
456
- throw new ProviderResponseError(`Request blocked by Google (${responseData.promptFeedback.blockReason})${detail ? `: ${detail}` : ""}`, {
457
- provider: model.provider,
458
- kind: "content-blocked"
459
- });
460
- }
461
- const candidate = responseData.candidates?.[0];
462
- if (candidate?.content?.parts) for (const part of candidate.content.parts) {
463
- if (part.text !== void 0 && part.text !== "") {
464
- if (isThinkingPart(part)) {
465
- flushVisibleText();
466
- const block = startThinkingBlock();
467
- block.thinking += part.text;
468
- block.thinkingSignature = retainThoughtSignature(block.thinkingSignature, part.thoughtSignature);
469
- stream.push({
470
- type: "thinking_delta",
471
- contentIndex: blockIndex(),
472
- delta: part.text,
473
- partial: output
474
- });
475
- } else {
476
- if (isBuffering) {
477
- textBuffer += part.text;
478
- bufferedTextSignature = retainThoughtSignature(bufferedTextSignature, part.thoughtSignature);
479
- } else if (isFlashLeakModel && part.text.trimStart().startsWith("{")) {
480
- isBuffering = true;
481
- textBuffer = part.text;
482
- bufferedTextSignature = part.thoughtSignature;
483
- } else feedVisibleText(part.text, part.thoughtSignature);
484
- if (isBuffering) {
485
- const buffered = consumePlanningBuffer(textBuffer, toolNames);
486
- if (buffered.kind !== "incomplete") {
487
- if (buffered.kind === "leak") strippedPlanningLeak = true;
488
- const visibleSignature = bufferedTextSignature;
489
- isBuffering = false;
490
- textBuffer = "";
491
- bufferedTextSignature = void 0;
492
- feedVisibleText(buffered.visibleText, visibleSignature);
493
- }
494
- }
495
- }
496
- } else if (part.text === "" && part.thoughtSignature && !part.functionCall) retainCurrentBlockThoughtSignature(part.thoughtSignature);
497
- if (part.functionCall) {
498
- flushVisibleText();
499
- endCurrentBlock();
500
- isBuffering = false;
501
- textBuffer = "";
502
- const providedId = part.functionCall.id;
503
- const toolCall = {
504
- type: "toolCall",
505
- id: !providedId || output.content.some((b) => b.type === "toolCall" && b.id === providedId) ? nextToolCallId(part.functionCall.name || "tool") : providedId,
506
- name: part.functionCall.name || "",
507
- arguments: part.functionCall.args ?? {},
508
- ...part.thoughtSignature && { thoughtSignature: part.thoughtSignature }
509
- };
510
- output.content.push(toolCall);
511
- ensureStarted();
512
- pushToolCallEvents(toolCall, blockIndex(), output, stream);
513
- }
514
- }
515
- if (candidate?.finishReason) {
516
- sawFinishReason = true;
517
- const mapped = mapStopReasonString(candidate.finishReason);
518
- if ((mapped === "stop" || mapped === "length") && output.content.some((b) => b.type === "toolCall")) output.stopReason = "toolUse";
519
- else {
520
- output.stopReason = mapped;
521
- if (mapped === "error") output.errorMessage = `Generation failed with finish reason: ${candidate.finishReason}`;
522
- }
523
- }
524
- if (responseData.usageMetadata) {
525
- const promptTokens = responseData.usageMetadata.promptTokenCount || 0;
526
- const cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0;
527
- const thinkingTokens = responseData.usageMetadata.thoughtsTokenCount || 0;
528
- output.usage = {
529
- input: promptTokens - cacheReadTokens,
530
- output: (responseData.usageMetadata.candidatesTokenCount || 0) + thinkingTokens,
531
- cacheRead: cacheReadTokens,
532
- cacheWrite: 0,
533
- totalTokens: responseData.usageMetadata.totalTokenCount || 0,
534
- ...thinkingTokens > 0 ? { reasoningTokens: thinkingTokens } : {},
535
- cost: {
536
- input: 0,
537
- output: 0,
538
- cacheRead: 0,
539
- cacheWrite: 0,
540
- total: 0
541
- }
542
- };
543
- calculateCost(model, output.usage, output.timestamp);
544
- }
545
- }
546
- if (isBuffering && textBuffer !== "") {
547
- const buffered = consumePlanningBuffer(textBuffer, toolNames, true);
548
- if (buffered.kind !== "incomplete") {
549
- if (buffered.kind === "leak") strippedPlanningLeak = true;
550
- feedVisibleText(buffered.visibleText, bufferedTextSignature);
551
- }
552
- bufferedTextSignature = void 0;
553
- isBuffering = false;
554
- textBuffer = "";
555
- }
556
- flushVisibleText(bufferedTextSignature);
557
- endCurrentBlock();
558
- return {
559
- meaningful: hasMeaningfulGoogleContent(output),
560
- strippedPlanningLeak
561
- };
562
- };
563
- let receivedContent = false;
564
- const hasThinkingOutput = () => output.content.some((block) => block.type === "thinking" && (block.thinking.trim().length > 0 || Boolean(block.thinkingSignature)));
565
- for (let i = 0; i < endpoints.length; i++) {
566
- const endpoint = endpoints[i];
567
- const isLastEndpoint = i === endpoints.length - 1;
568
- try {
569
- started = false;
570
- resetOutput();
571
- const watchdog = armPreResponseTimeout(callerSignal, firstEventTimeoutMs);
572
- let response;
573
- try {
574
- response = await fetchWithRetry(() => `${endpoint}/v1internal:streamGenerateContent?alt=sse`, {
575
- method: "POST",
576
- headers: requestHeaders,
577
- body: requestBodyJson,
578
- signal: watchdog.signal,
579
- maxAttempts: isLastEndpoint ? 4 : 1,
580
- defaultDelayMs: (attempt) => BASE_DELAY_MS * 2 ** attempt,
581
- maxDelayMs: options?.maxRetryDelayMs ?? RATE_LIMIT_BUDGET_MS,
582
- fetch: options?.fetch,
583
- timeout: false
584
- });
585
- } finally {
586
- watchdog.clear();
587
- }
588
- if (!response.ok) {
589
- if (isTransientStatus(response.status)) {
590
- if (!isLastEndpoint) continue;
591
- }
592
- const errorText = await response.text();
593
- const validationUrl = extractGoogleValidationUrl(errorText);
594
- const errorMessage = validationUrl ? formatGoogleValidationRequiredMessage(validationUrl, "retry your request", parsedCredentials.email) : errorText;
595
- throw new GeminiCliApiError(`Cloud Code Assist API error (${response.status}): ${errorMessage}`, response.status, { headers: response.headers });
596
- }
597
- const requestUrl = response.url;
598
- let currentResponse = response;
599
- for (let emptyAttempt = 0; emptyAttempt <= 2; emptyAttempt++) {
600
- if (options?.signal?.aborted) throw new AbortError("Request was aborted");
601
- if (emptyAttempt > 0) {
602
- const backoffMs = 500 * 2 ** (emptyAttempt - 1);
603
- try {
604
- await scheduler.wait(backoffMs, { signal: options?.signal });
605
- } catch {
606
- throw new AbortError("Request was aborted");
607
- }
608
- if (!requestUrl) throw new ConfigurationError("Missing request URL");
609
- currentResponse = await (options?.fetch ?? fetch)(requestUrl, {
610
- method: "POST",
611
- headers: requestHeaders,
612
- body: requestBodyJson,
613
- signal: options?.signal
614
- });
615
- if (!currentResponse.ok) {
616
- const retryErrorText = await currentResponse.text();
617
- throw new GeminiCliApiError(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`, currentResponse.status, { headers: currentResponse.headers });
618
- }
619
- }
620
- const streamed = await streamResponse(currentResponse);
621
- const thoughtOnly = hasThinkingOutput();
622
- const acceptedSilence = options?.acceptEmptyResponse === true && !streamed.strippedPlanningLeak && (isLastEndpoint || thoughtOnly);
623
- if (output.stopReason !== "stop" || streamed.meaningful || acceptedSilence) {
624
- receivedContent = streamed.meaningful || acceptedSilence;
625
- break;
626
- }
627
- if (thoughtOnly) break;
628
- if (emptyAttempt < 2) resetOutput();
629
- }
630
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new ProviderResponseError(output.errorMessage ?? "An unknown error occurred", {
631
- provider: model.provider,
632
- kind: "output"
633
- });
634
- if (!receivedContent) {
635
- const thoughtOnly = hasThinkingOutput();
636
- throw new ProviderResponseError(thoughtOnly ? "Cloud Code Assist API returned a thought-only response without final output" : "Cloud Code Assist API returned an empty response", {
637
- provider: model.provider,
638
- kind: thoughtOnly ? "empty-output" : "empty-body"
639
- });
640
- }
641
- if (options?.signal?.aborted) throw new AbortError("Request was aborted");
642
- if (!sawFinishReason) throw new ProviderResponseError("Cloud Code Assist stream ended without a finish reason (connection dropped or response truncated)", {
643
- provider: model.provider,
644
- kind: "incomplete-stream"
645
- });
646
- if (providerState && (options?.antigravityEndpointMode === "auto" || !options?.antigravityEndpointMode)) providerState.lastGoodEndpoint = endpoint;
647
- if (providerState) providerState.lastExecutionId = lastResponseId;
648
- break;
649
- } catch (error) {
650
- const status = extractHttpStatusFromError(error);
651
- if (!isLastEndpoint && !started && (isTransientStatus(status) || status === void 0 && !(error instanceof ProviderResponseError && error.kind === "output") && retriable(classify(error)))) continue;
652
- throw error;
653
- }
654
- }
655
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new ProviderResponseError(output.errorMessage ?? "An unknown error occurred", {
656
- provider: model.provider,
657
- kind: "output"
658
- });
659
- output.duration = performance.now() - startTime;
660
- if (firstTokenTime) output.ttft = firstTokenTime - startTime;
661
- stream.push({
662
- type: "done",
663
- reason: output.stopReason,
664
- message: output
665
- });
666
- stream.end();
667
- } catch (error) {
668
- const result = await finalize(error, {
669
- api: model.api,
670
- signal: options?.signal,
671
- rawRequestDump
672
- });
673
- output.stopReason = result.stopReason;
674
- output.errorStatus = result.status;
675
- output.errorId = result.id;
676
- output.errorMessage = result.message;
677
- output.duration = performance.now() - startTime;
678
- if (firstTokenTime) output.ttft = firstTokenTime - startTime;
679
- stream.push({
680
- type: "error",
681
- reason: output.stopReason,
682
- error: output
683
- });
684
- stream.end();
685
- }
686
- })();
687
- return stream;
688
- };
689
- const INT63_MASK = (1n << 63n) - 1n;
690
- const ANTIGRAVITY_RANDOM_BOUND = 9000000000000000000n;
691
- function formatSignedDecimalSessionId(value) {
692
- return `-${value.toString()}`;
693
- }
694
- function deriveSignedDecimalFromHash(text) {
695
- const digest = createHash("sha256").update(text).digest();
696
- let value = 0n;
697
- for (let index = 0; index < 8; index += 1) value = value << 8n | BigInt(digest[index] ?? 0);
698
- return formatSignedDecimalSessionId(value & INT63_MASK);
699
- }
700
- function randomBoundedInt63(maxExclusive) {
701
- while (true) {
702
- const bytes = randomBytes(8);
703
- let value = 0n;
704
- for (const byte of bytes) value = value << 8n | BigInt(byte);
705
- value &= INT63_MASK;
706
- if (value < maxExclusive) return value;
707
- }
708
- }
709
- function randomSignedDecimalSessionId() {
710
- return formatSignedDecimalSessionId(randomBoundedInt63(ANTIGRAVITY_RANDOM_BOUND));
711
- }
712
- function getFirstUserTextForAntigravitySession(context) {
713
- for (const message of context.messages) {
714
- if (message.role !== "user") continue;
715
- if (typeof message.content === "string") return message.content;
716
- if (Array.isArray(message.content)) return message.content.find((item) => item.type === "text")?.text;
717
- return;
718
- }
719
- }
720
- function deriveAntigravitySessionId(context) {
721
- const text = getFirstUserTextForAntigravitySession(context);
722
- if (text && text.trim().length > 0) return deriveSignedDecimalFromHash(text);
723
- return randomSignedDecimalSessionId();
724
- }
725
- function normalizeAntigravityTools(tools) {
726
- return tools?.map((tool) => ({
727
- ...tool,
728
- functionDeclarations: tool.functionDeclarations.map((declaration) => {
729
- if ("parameters" in declaration) return declaration;
730
- const { parametersJsonSchema, ...rest } = declaration;
731
- return {
732
- ...rest,
733
- parameters: normalizeSchemaForCCA(parametersJsonSchema)
734
- };
735
- })
736
- }));
737
- }
738
- /**
739
- * Build the Antigravity request envelope (sessionId, structured requestId,
740
- * labels) advancing the per-conversation session state. Mirrors the real
741
- * `antigravity/hub` client: `requestId` is `agent/<agentId>/<ts>/<trajectoryId>/<step>`
742
- * and `labels.last_step_index` trails the requestId step by one. Without session
743
- * state (direct callers/tests) it falls back to ephemeral ids.
744
- */
745
- function buildAntigravityRequestEnvelope(model, context, wireModelId, state) {
746
- if (state) {
747
- state.agentId ??= randomUUID();
748
- state.trajectoryId ??= randomUUID();
749
- state.sessionId ??= randomSignedDecimalSessionId();
750
- state.stepIndex = (state.stepIndex ?? 1) + 1;
751
- }
752
- const agentId = state?.agentId ?? randomUUID();
753
- const trajectoryId = state?.trajectoryId ?? randomUUID();
754
- const sessionId = state?.sessionId ?? deriveAntigravitySessionId(context);
755
- const step = state?.stepIndex ?? 2;
756
- const requestId = `agent/${agentId}/${Date.now()}/${trajectoryId}/${step}`;
757
- const isClaude = model.identity.class === "anthropic";
758
- const profile = getAntigravityModelWireProfile(wireModelId);
759
- const labels = {};
760
- if (state?.lastExecutionId) labels.last_execution_id = state.lastExecutionId;
761
- labels.last_step_index = String(step - 1);
762
- if (profile?.modelEnum !== void 0) labels.model_enum = profile.modelEnum;
763
- labels.trajectory_id = trajectoryId;
764
- const usageLabel = model.compat.antigravityUsageLabel ?? String(isClaude);
765
- labels.used_claude = usageLabel;
766
- labels.used_claude_conservative = usageLabel;
767
- return {
768
- sessionId,
769
- requestId,
770
- labels
771
- };
772
- }
773
- function buildRequest(model, context, projectId, options = {}, isAntigravity = false) {
774
- const systemPrompts = normalizeSystemPrompts(context.systemPrompt);
775
- const contents = convertMessages(model, context);
776
- const generationConfig = {};
777
- if (options.temperature !== void 0) generationConfig.temperature = options.temperature;
778
- if (options.maxTokens !== void 0) generationConfig.maxOutputTokens = options.maxTokens;
779
- if (options.topP !== void 0) generationConfig.topP = options.topP;
780
- if (options.topK !== void 0) generationConfig.topK = options.topK;
781
- if (options.minP !== void 0) generationConfig.minP = options.minP;
782
- if (options.presencePenalty !== void 0) generationConfig.presencePenalty = options.presencePenalty;
783
- if (options.repetitionPenalty !== void 0) generationConfig.repetitionPenalty = options.repetitionPenalty;
784
- if (options.thinking?.enabled && model.reasoning) {
785
- generationConfig.thinkingConfig = { includeThoughts: !options.hideThinkingSummary };
786
- if (options.thinking.level !== void 0) generationConfig.thinkingConfig.thinkingLevel = options.thinking.level;
787
- else if (options.thinking.budgetTokens !== void 0) generationConfig.thinkingConfig.thinkingBudget = options.thinking.budgetTokens;
788
- } else if (options.thinking?.suppress && model.reasoning) {
789
- const suppress = options.thinking.suppress;
790
- generationConfig.thinkingConfig = { includeThoughts: false };
791
- if ("level" in suppress) generationConfig.thinkingConfig.thinkingLevel = suppress.level;
792
- else generationConfig.thinkingConfig.thinkingBudget = suppress.budget;
793
- }
794
- const request = { contents };
795
- if (systemPrompts.length > 0) request.systemInstruction = {
796
- ...isAntigravity ? { role: "user" } : {},
797
- parts: systemPrompts.map((text) => ({ text }))
798
- };
799
- if (context.tools && context.tools.length > 0) {
800
- const convertedTools = convertTools(context.tools, model);
801
- request.tools = isAntigravity ? normalizeAntigravityTools(convertedTools) : convertedTools;
802
- if (options.toolChoice) {
803
- const choice = options.toolChoice;
804
- if (typeof choice === "string") {
805
- const mode = mapToolChoice(choice);
806
- if (mode !== "AUTO") request.toolConfig = { functionCallingConfig: { mode } };
807
- } else request.toolConfig = { functionCallingConfig: {
808
- mode: "ANY",
809
- allowedFunctionNames: [...choice.allowedFunctionNames]
810
- } };
811
- if (isAntigravity && model.identity.class !== "anthropic" && request.toolConfig?.functionCallingConfig.mode === "ANY") contents.push({
812
- role: "user",
813
- parts: [{ text: google_antigravity_forced_tool_default }]
814
- });
815
- }
816
- if (isAntigravity && !request.toolConfig) request.toolConfig = { functionCallingConfig: { mode: "VALIDATED" } };
817
- }
818
- if (isAntigravity && model.identity.class === "anthropic" && model.compat.antigravityClaudeToolMode) request.toolConfig = { functionCallingConfig: { mode: "VALIDATED" } };
819
- const wireModelId = options.requestModelId ?? model.requestModelId ?? model.id;
820
- if (isAntigravity) {
821
- const profile = getAntigravityModelWireProfile(wireModelId);
822
- if (profile) generationConfig.maxOutputTokens = profile.maxOutputTokens;
823
- const envelope = buildAntigravityRequestEnvelope(model, context, wireModelId, getAntigravityProviderSessionState(options.providerSessionState));
824
- request.labels = envelope.labels;
825
- if (Object.keys(generationConfig).length > 0) request.generationConfig = generationConfig;
826
- request.sessionId = envelope.sessionId;
827
- return {
828
- project: projectId,
829
- requestId: envelope.requestId,
830
- request,
831
- model: wireModelId,
832
- userAgent: "antigravity",
833
- requestType: "agent"
834
- };
835
- }
836
- if (Object.keys(generationConfig).length > 0) request.generationConfig = generationConfig;
837
- return {
838
- project: projectId,
839
- model: wireModelId,
840
- request
841
- };
842
- }
843
- //#endregion
844
- export { streamGoogleGeminiCli };