dsh-antigravity-auth 0.1.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 (114) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/LICENSE +21 -0
  3. package/README.md +168 -0
  4. package/README.zh.md +159 -0
  5. package/cordis.patch.yml +12 -0
  6. package/lib/capability-lifecycle--tgGKajs.js +1896 -0
  7. package/lib/client.cjs +2123 -0
  8. package/lib/client.cjs.map +1 -0
  9. package/lib/image.js +564 -0
  10. package/lib/index.js +176 -0
  11. package/lib/invariant.js +2 -0
  12. package/lib/live-gate-runner.js +542 -0
  13. package/lib/live-gates.js +97 -0
  14. package/lib/llm-adapter.js +916 -0
  15. package/lib/media-admission.js +206 -0
  16. package/lib/private-failure-B9vzUkQ7.js +23 -0
  17. package/lib/private-transport-urF138qW.js +641 -0
  18. package/lib/private-transport.js +2 -0
  19. package/lib/project-context.js +133 -0
  20. package/lib/quota.js +283 -0
  21. package/lib/replay.js +156 -0
  22. package/lib/rpc-contract-BFWfdKKs.js +491 -0
  23. package/lib/rpc-contract.js +2 -0
  24. package/lib/safe-text-AlEyN8q_.js +12 -0
  25. package/lib/search.js +259 -0
  26. package/lib/status-D0-em3Ru.js +125 -0
  27. package/lib/types/auth-service.d.ts +64 -0
  28. package/lib/types/auth-service.d.ts.map +1 -0
  29. package/lib/types/auth-store.d.ts +45 -0
  30. package/lib/types/auth-store.d.ts.map +1 -0
  31. package/lib/types/bootstrap-service.d.ts +6 -0
  32. package/lib/types/bootstrap-service.d.ts.map +1 -0
  33. package/lib/types/capability-gates.d.ts +19 -0
  34. package/lib/types/capability-gates.d.ts.map +1 -0
  35. package/lib/types/capability-lifecycle.d.ts +26 -0
  36. package/lib/types/capability-lifecycle.d.ts.map +1 -0
  37. package/lib/types/client/AntigravityAuthSettings.d.ts +19 -0
  38. package/lib/types/client/AntigravityAuthSettings.d.ts.map +1 -0
  39. package/lib/types/client/index.d.ts +18 -0
  40. package/lib/types/client/index.d.ts.map +1 -0
  41. package/lib/types/client/locales.d.ts +121 -0
  42. package/lib/types/client/locales.d.ts.map +1 -0
  43. package/lib/types/client/styles.d.ts +4 -0
  44. package/lib/types/client/styles.d.ts.map +1 -0
  45. package/lib/types/credential-coordinator.d.ts +84 -0
  46. package/lib/types/credential-coordinator.d.ts.map +1 -0
  47. package/lib/types/image.d.ts +39 -0
  48. package/lib/types/image.d.ts.map +1 -0
  49. package/lib/types/index.d.ts +21 -0
  50. package/lib/types/index.d.ts.map +1 -0
  51. package/lib/types/invariant.d.ts +3 -0
  52. package/lib/types/invariant.d.ts.map +1 -0
  53. package/lib/types/live-gate-attachments.d.ts +6 -0
  54. package/lib/types/live-gate-attachments.d.ts.map +1 -0
  55. package/lib/types/live-gate-auth.d.ts +5 -0
  56. package/lib/types/live-gate-auth.d.ts.map +1 -0
  57. package/lib/types/live-gate-image.d.ts +5 -0
  58. package/lib/types/live-gate-image.d.ts.map +1 -0
  59. package/lib/types/live-gate-llm.d.ts +10 -0
  60. package/lib/types/live-gate-llm.d.ts.map +1 -0
  61. package/lib/types/live-gate-outcome.d.ts +8 -0
  62. package/lib/types/live-gate-outcome.d.ts.map +1 -0
  63. package/lib/types/live-gate-runner.d.ts +15 -0
  64. package/lib/types/live-gate-runner.d.ts.map +1 -0
  65. package/lib/types/live-gate-search.d.ts +5 -0
  66. package/lib/types/live-gate-search.d.ts.map +1 -0
  67. package/lib/types/live-gate-video.d.ts +8 -0
  68. package/lib/types/live-gate-video.d.ts.map +1 -0
  69. package/lib/types/live-gates.d.ts +25 -0
  70. package/lib/types/live-gates.d.ts.map +1 -0
  71. package/lib/types/llm-adapter.d.ts +65 -0
  72. package/lib/types/llm-adapter.d.ts.map +1 -0
  73. package/lib/types/login-types.d.ts +36 -0
  74. package/lib/types/login-types.d.ts.map +1 -0
  75. package/lib/types/media-admission.d.ts +54 -0
  76. package/lib/types/media-admission.d.ts.map +1 -0
  77. package/lib/types/model-catalog.d.ts +19 -0
  78. package/lib/types/model-catalog.d.ts.map +1 -0
  79. package/lib/types/oauth-flow.d.ts +87 -0
  80. package/lib/types/oauth-flow.d.ts.map +1 -0
  81. package/lib/types/private-failure.d.ts +6 -0
  82. package/lib/types/private-failure.d.ts.map +1 -0
  83. package/lib/types/private-transport-error.d.ts +13 -0
  84. package/lib/types/private-transport-error.d.ts.map +1 -0
  85. package/lib/types/private-transport.d.ts +48 -0
  86. package/lib/types/private-transport.d.ts.map +1 -0
  87. package/lib/types/project-context.d.ts +30 -0
  88. package/lib/types/project-context.d.ts.map +1 -0
  89. package/lib/types/quota.d.ts +43 -0
  90. package/lib/types/quota.d.ts.map +1 -0
  91. package/lib/types/raw-http.d.ts +11 -0
  92. package/lib/types/raw-http.d.ts.map +1 -0
  93. package/lib/types/replay.d.ts +30 -0
  94. package/lib/types/replay.d.ts.map +1 -0
  95. package/lib/types/rpc-contract.d.ts +33 -0
  96. package/lib/types/rpc-contract.d.ts.map +1 -0
  97. package/lib/types/rpc-vocabulary.d.ts +7 -0
  98. package/lib/types/rpc-vocabulary.d.ts.map +1 -0
  99. package/lib/types/rpc.d.ts +11 -0
  100. package/lib/types/rpc.d.ts.map +1 -0
  101. package/lib/types/safe-text.d.ts +3 -0
  102. package/lib/types/safe-text.d.ts.map +1 -0
  103. package/lib/types/search.d.ts +42 -0
  104. package/lib/types/search.d.ts.map +1 -0
  105. package/lib/types/status.d.ts +62 -0
  106. package/lib/types/status.d.ts.map +1 -0
  107. package/lib/types/video.d.ts +42 -0
  108. package/lib/types/video.d.ts.map +1 -0
  109. package/lib/types/wire-identity.d.ts +49 -0
  110. package/lib/types/wire-identity.d.ts.map +1 -0
  111. package/lib/video.js +320 -0
  112. package/lib/wire-identity.js +162 -0
  113. package/package.json +189 -0
  114. package/scripts/live-gates.mjs +4 -0
@@ -0,0 +1,916 @@
1
+ import { a as DEFAULT_PRIVATE_RESPONSE_HEADER_TIMEOUT_MS, d as privateStatusError, i as DEFAULT_PRIVATE_RESPONSE_BYTES, l as createPrivateTransport, m as PrivateTransportError, n as DEFAULT_PRIVATE_IDLE_TIMEOUT_MS, o as DEFAULT_PRIVATE_TOTAL_TIMEOUT_MS, p as readPrivateText, t as DEFAULT_PRIVATE_FRAME_BYTES, u as iteratePrivateSse } from "./private-transport-urF138qW.js";
2
+ import { ANTIGRAVITY_WIRE_ORIGIN } from "./wire-identity.js";
3
+ import { t as classifyPrivateFailure } from "./private-failure-B9vzUkQ7.js";
4
+ import { antigravityModelFamily, buildFunctionDeclarations, compatibleReplayState, createReplayState } from "./replay.js";
5
+ import { AgyRequestSessionStore, applyClaudeTransforms, applyGeminiTransforms, buildAgyAgentRequestMetadata, fnv1a64Signed, getPublicModelDefinitions, getResolverAliasMap, resolveModelWithTier } from "@cortexkit/antigravity-auth-core";
6
+ import { Buffer } from "node:buffer";
7
+ import { CallId, LlmAdapter, LlmError, ReasoningEffortId, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
8
+ //#region src/llm-adapter.ts
9
+ /** Public DSH LLM adapter for the single Antigravity provider route. */
10
+ const ANTIGRAVITY_PROVIDER = "google-antigravity";
11
+ const ANTIGRAVITY_STREAM_ENDPOINT = `${ANTIGRAVITY_WIRE_ORIGIN}/v1internal:streamGenerateContent?alt=sse`;
12
+ const ANTIGRAVITY_GENERATE_ENDPOINT = `${ANTIGRAVITY_WIRE_ORIGIN}/v1internal:generateContent`;
13
+ const ANTIGRAVITY_AVAILABLE_MODELS_ENDPOINT = `${ANTIGRAVITY_WIRE_ORIGIN}/v1internal:fetchAvailableModels`;
14
+ const ANTIGRAVITY_LLM_ROUTE = ANTIGRAVITY_PROVIDER;
15
+ const MODEL_CATALOG_TTL_MS = 3e4;
16
+ const MAX_MODEL_CATALOG_BYTES = 262144;
17
+ const MAX_PROVIDER_PARTS = 4096;
18
+ /** Adapter that owns exactly one provider route and no fallback route. */
19
+ var AntigravityAdapter = class extends LlmAdapter {
20
+ adapterOptions;
21
+ transport;
22
+ sessions = new AgyRequestSessionStore("dsh-antigravity-auth");
23
+ options;
24
+ definitions = getPublicModelDefinitions();
25
+ catalogProjectId;
26
+ catalogExpiresAt = 0;
27
+ catalogModelIds = /* @__PURE__ */ new Set();
28
+ catalogFailureCode;
29
+ catalogView;
30
+ constructor(adapterOptions) {
31
+ super();
32
+ this.adapterOptions = adapterOptions;
33
+ this.transport = adapterOptions.transport ?? createPrivateTransport(adapterOptions.responseHeaderTimeoutMs === void 0 ? {} : { responseHeaderTimeoutMs: adapterOptions.responseHeaderTimeoutMs });
34
+ this.options = {
35
+ responseHeaderTimeoutMs: boundedTimeout(adapterOptions.responseHeaderTimeoutMs, DEFAULT_PRIVATE_RESPONSE_HEADER_TIMEOUT_MS),
36
+ idleTimeoutMs: boundedTimeout(adapterOptions.idleTimeoutMs, DEFAULT_PRIVATE_IDLE_TIMEOUT_MS),
37
+ totalTimeoutMs: boundedTimeout(adapterOptions.totalTimeoutMs, DEFAULT_PRIVATE_TOTAL_TIMEOUT_MS),
38
+ maxResponseBytes: boundedLimit(adapterOptions.maxResponseBytes, DEFAULT_PRIVATE_RESPONSE_BYTES),
39
+ maxFrameBytes: boundedLimit(adapterOptions.maxFrameBytes, DEFAULT_PRIVATE_FRAME_BYTES)
40
+ };
41
+ this.catalogView = createCatalogView(this.definitions, "snapshot");
42
+ }
43
+ providerInfo(provider) {
44
+ if (provider !== "google-antigravity") throw new LlmError("Unknown Antigravity provider route", "NO_ADAPTER");
45
+ return {
46
+ id: ANTIGRAVITY_PROVIDER,
47
+ name: "Google Antigravity"
48
+ };
49
+ }
50
+ providerRetryPolicy() {
51
+ return resolveRetryPolicy({
52
+ mode: "normal",
53
+ maxRetries: 0
54
+ }, "google-antigravity");
55
+ }
56
+ /** Forget account-bound availability when Gate 0 or the credential is replaced. */
57
+ invalidateModelCatalog() {
58
+ this.catalogProjectId = void 0;
59
+ this.catalogExpiresAt = 0;
60
+ this.catalogModelIds = /* @__PURE__ */ new Set();
61
+ this.catalogFailureCode = void 0;
62
+ this.catalogView = createCatalogView(this.definitions, "snapshot");
63
+ }
64
+ /** Return the pinned catalog without performing credential or network work. */
65
+ catalogSnapshot() {
66
+ return cloneCatalogView(createCatalogView(this.definitions, "snapshot"));
67
+ }
68
+ /** Refresh the advisory catalog and collapse failures into browser-safe state. */
69
+ async modelCatalog(signal, forceRefresh = false) {
70
+ try {
71
+ const available = await this.readLiveModelIds(signal, forceRefresh);
72
+ this.catalogView = createCatalogView(this.definitions, "live-available", available, (/* @__PURE__ */ new Date()).toISOString());
73
+ } catch (error) {
74
+ const state = error instanceof LlmError && error.code === "PROTOCOL_DRIFT" ? "protocol-drift" : "refresh-failed";
75
+ this.catalogView = createCatalogView(this.definitions, state, void 0, (/* @__PURE__ */ new Date()).toISOString());
76
+ }
77
+ return cloneCatalogView(this.catalogView);
78
+ }
79
+ async listModels(provider, signal) {
80
+ this.providerInfo(provider);
81
+ let available;
82
+ try {
83
+ available = await this.readLiveModelIds(signal);
84
+ this.catalogView = createCatalogView(this.definitions, "live-available", available, (/* @__PURE__ */ new Date()).toISOString());
85
+ } catch (error) {
86
+ const state = error instanceof LlmError && error.code === "PROTOCOL_DRIFT" ? "protocol-drift" : "refresh-failed";
87
+ this.catalogView = createCatalogView(this.definitions, state, void 0, (/* @__PURE__ */ new Date()).toISOString());
88
+ throw error;
89
+ }
90
+ return Object.values(this.definitions).filter((definition) => !definition.modalities.output.includes("image") && available.has(definition.id)).map((definition) => ({
91
+ provider: ANTIGRAVITY_PROVIDER,
92
+ id: definition.id,
93
+ name: cleanModelDisplayName(definition.name),
94
+ inputModalities: definition.modalities.input.filter((item) => item === "text" || item === "image")
95
+ }));
96
+ }
97
+ async resolveModel(provider, model, _signal) {
98
+ this.providerInfo(provider);
99
+ if (typeof model !== "string" || model.trim().length === 0 || model.length > 256) throw new LlmError("The Antigravity model id is invalid", "INVALID_MODEL");
100
+ const definition = this.definitions[model];
101
+ if (definition === void 0 || definition.modalities.output.includes("image")) throw new LlmError("The Antigravity model is not in the audited text model snapshot", "INVALID_MODEL");
102
+ const reasoning = getModelReasoningEfforts(model);
103
+ return {
104
+ provider: ANTIGRAVITY_PROVIDER,
105
+ id: definition.id,
106
+ name: cleanModelDisplayName(definition.name),
107
+ inputModalities: definition.modalities.input.filter((item) => item === "text" || item === "image"),
108
+ context: { contextWindow: definition.limit.context },
109
+ defaultMaxTokens: definition.limit.output,
110
+ ...reasoning === void 0 ? {} : { reasoning }
111
+ };
112
+ }
113
+ async *stream(options) {
114
+ if (options.provider !== "google-antigravity") throw new LlmError("The Antigravity adapter received an unknown provider route", "NO_ADAPTER");
115
+ const signal = options.signal;
116
+ const requestedDefinition = this.definitions[options.model];
117
+ if (requestedDefinition === void 0 || requestedDefinition.modalities.output.includes("image")) throw new LlmError("The Antigravity model is not in the audited text model snapshot", "INVALID_MODEL");
118
+ if (isAborted(signal)) {
119
+ yield finishChunk("aborted", "CANCELLED");
120
+ return;
121
+ }
122
+ const hasEmitted = { value: false };
123
+ let replayed = false;
124
+ for (;;) {
125
+ const credential = await this.readCredential(signal, replayed);
126
+ if (credential === void 0) throw new LlmError("Antigravity login is required before model use", "AUTH");
127
+ const sessionKey = requestSessionKey(options);
128
+ const requestScope = this.sessions.beginRequest(sessionKey);
129
+ let payload;
130
+ try {
131
+ payload = await buildAntigravityGeneratePayloadForAdapter(options, credential, requestScope.session, requestScope.timestamp, this.adapterOptions.attachments);
132
+ } catch (error) {
133
+ if (error instanceof LlmError) throw error;
134
+ throw new LlmError("The Antigravity image input could not be admitted safely", "UNSUPPORTED_MODALITY");
135
+ }
136
+ let response;
137
+ try {
138
+ response = await this.transport.request({
139
+ url: ANTIGRAVITY_STREAM_ENDPOINT,
140
+ accessToken: credential.accessToken,
141
+ body: JSON.stringify(payload),
142
+ ...signal === void 0 ? {} : { signal },
143
+ responseHeaderTimeoutMs: this.options.responseHeaderTimeoutMs
144
+ });
145
+ } catch (error) {
146
+ throw toLlmError(error);
147
+ }
148
+ const statusError = privateStatusError(response.status);
149
+ if (statusError !== void 0) {
150
+ if (statusError.code === "authentication" && !replayed && !hasEmitted.value && !isAborted(signal)) {
151
+ await cancelResponse(response);
152
+ replayed = true;
153
+ continue;
154
+ }
155
+ throw toLlmError(statusError);
156
+ }
157
+ try {
158
+ yield* this.streamResponse(response, options, hasEmitted);
159
+ this.sessions.completeExecution(sessionKey);
160
+ return;
161
+ } catch (error) {
162
+ if ((error instanceof PrivateTransportError ? error : void 0)?.code === "authentication" && !replayed && !hasEmitted.value && !isAborted(signal)) {
163
+ replayed = true;
164
+ continue;
165
+ }
166
+ throw toLlmError(error);
167
+ }
168
+ }
169
+ }
170
+ async *streamResponse(response, options, hasEmitted) {
171
+ const states = [];
172
+ let current;
173
+ let usage;
174
+ let finish;
175
+ let eventError;
176
+ for await (const sse of iteratePrivateSse(response, {
177
+ ...options.signal === void 0 ? {} : { signal: options.signal },
178
+ idleTimeoutMs: this.options.idleTimeoutMs,
179
+ totalTimeoutMs: this.options.totalTimeoutMs,
180
+ maxBytes: this.options.maxResponseBytes,
181
+ maxFrameBytes: this.options.maxFrameBytes
182
+ })) {
183
+ if (sse.data.trim() === "[DONE]") continue;
184
+ const event = parseProviderEvent(sse.data);
185
+ if (event.error !== void 0) {
186
+ eventError = event.error;
187
+ if (event.error.status === 401 || isAuthenticationCode(event.error.code)) throw new PrivateTransportError("authentication", "The private endpoint requires authentication", { status: event.error.status ?? 401 });
188
+ break;
189
+ }
190
+ if (event.usage !== void 0) usage = event.usage;
191
+ if (event.finish !== void 0) finish = event.finish;
192
+ for (const part of event.parts) {
193
+ if (current === void 0 || !sameBlock(current, part)) {
194
+ if (current !== void 0) yield endBlock(current);
195
+ current = beginBlock(states, part);
196
+ yield {
197
+ type: "block-start",
198
+ index: current.index,
199
+ blockType: current.kind
200
+ };
201
+ }
202
+ if (part.kind === "tool-call") {
203
+ if (part.name !== void 0) current.name = assembleFunctionName(current.name, part.name);
204
+ current.text += part.arguments;
205
+ hasEmitted.value ||= part.arguments.length > 0 || part.name !== void 0;
206
+ yield {
207
+ type: "tool-call-delta",
208
+ index: current.index,
209
+ id: current.id,
210
+ ...part.name === void 0 ? {} : { name: part.name },
211
+ argumentsDelta: part.arguments
212
+ };
213
+ if (part.signature !== void 0) current.signature = part.signature;
214
+ } else if (part.kind === "reasoning") {
215
+ current.text += part.text;
216
+ hasEmitted.value ||= part.text.length > 0;
217
+ if (part.text.length > 0) yield {
218
+ type: "reasoning-delta",
219
+ index: current.index,
220
+ text: part.text
221
+ };
222
+ } else {
223
+ current.text += part.text;
224
+ hasEmitted.value ||= part.text.length > 0;
225
+ if (part.text.length > 0) yield {
226
+ type: "text-delta",
227
+ index: current.index,
228
+ text: part.text
229
+ };
230
+ }
231
+ }
232
+ if (finish !== void 0) break;
233
+ }
234
+ if (current !== void 0) yield endBlock(current);
235
+ if (usage !== void 0) yield {
236
+ type: "usage",
237
+ usage
238
+ };
239
+ if (eventError !== void 0) {
240
+ yield finishChunk("error", safeProviderErrorCode(eventError.code), safeProviderStatus(eventError.status));
241
+ return;
242
+ }
243
+ if (isAborted(options.signal)) {
244
+ yield finishChunk("aborted", "CANCELLED");
245
+ return;
246
+ }
247
+ if (states.length === 0) {
248
+ yield finishChunk("error", "EMPTY_RESPONSE");
249
+ return;
250
+ }
251
+ const replayBlocks = states.map((state) => ({
252
+ kind: state.kind,
253
+ ...state.signature === void 0 ? {} : { signature: state.signature }
254
+ }));
255
+ const replayState = createReplayState(options.model, antigravityModelFamily(options.model), finish, replayBlocks);
256
+ yield finishChunk(mapFinishReason(finish), finish ?? "STOP", void 0, replayState);
257
+ }
258
+ async readLiveModelIds(signal, bypassCache = false, forceCredentialRefresh = false) {
259
+ const credential = await this.readCredential(signal, forceCredentialRefresh);
260
+ if (credential === void 0) throw new LlmError("Antigravity login is required before model discovery", "AUTH");
261
+ if (!bypassCache && this.catalogProjectId === credential.projectId && Date.now() < this.catalogExpiresAt) {
262
+ if (this.catalogFailureCode !== void 0) throw new LlmError("The Antigravity live model catalog refresh remains unavailable", this.catalogFailureCode);
263
+ return this.catalogModelIds;
264
+ }
265
+ let response;
266
+ const body = credential.projectId ? { project: credential.projectId } : {};
267
+ try {
268
+ response = await this.transport.request({
269
+ url: ANTIGRAVITY_AVAILABLE_MODELS_ENDPOINT,
270
+ accessToken: credential.accessToken,
271
+ body: JSON.stringify(body),
272
+ ...signal === void 0 ? {} : { signal },
273
+ responseHeaderTimeoutMs: this.options.responseHeaderTimeoutMs
274
+ });
275
+ } catch (error) {
276
+ const failure = toLlmError(error);
277
+ this.rememberCatalogFailure(credential.projectId, failure);
278
+ throw failure;
279
+ }
280
+ if (response.status === 403 && credential.projectId) try {
281
+ const retryResponse = await this.transport.request({
282
+ url: ANTIGRAVITY_AVAILABLE_MODELS_ENDPOINT,
283
+ accessToken: credential.accessToken,
284
+ body: JSON.stringify({}),
285
+ ...signal === void 0 ? {} : { signal },
286
+ responseHeaderTimeoutMs: this.options.responseHeaderTimeoutMs
287
+ });
288
+ if (retryResponse.ok) response = retryResponse;
289
+ } catch {}
290
+ const statusError = privateStatusError(response.status);
291
+ if (statusError !== void 0) {
292
+ await cancelResponse(response);
293
+ if (statusError.code === "authentication" && !forceCredentialRefresh && !isAborted(signal)) {
294
+ this.catalogExpiresAt = 0;
295
+ return this.readLiveModelIds(signal, true, true);
296
+ }
297
+ const failure = toLlmError(statusError);
298
+ this.rememberCatalogFailure(credential.projectId, failure);
299
+ throw failure;
300
+ }
301
+ let value;
302
+ try {
303
+ value = JSON.parse(await readPrivateText(response, {
304
+ ...signal === void 0 ? {} : { signal },
305
+ idleTimeoutMs: this.options.idleTimeoutMs,
306
+ totalTimeoutMs: this.options.totalTimeoutMs,
307
+ maxBytes: Math.min(this.options.maxResponseBytes, MAX_MODEL_CATALOG_BYTES)
308
+ }));
309
+ } catch (error) {
310
+ const failure = error instanceof LlmError ? error : new LlmError("The Antigravity live model catalog did not match the audited schema", "PROTOCOL_DRIFT");
311
+ this.rememberCatalogFailure(credential.projectId, failure);
312
+ throw failure;
313
+ }
314
+ let ids;
315
+ try {
316
+ ids = parseLiveModelIds(value, this.definitions);
317
+ } catch (error) {
318
+ const failure = error instanceof LlmError ? error : new LlmError("The Antigravity live model catalog did not match the audited schema", "PROTOCOL_DRIFT");
319
+ this.rememberCatalogFailure(credential.projectId, failure);
320
+ throw failure;
321
+ }
322
+ this.catalogProjectId = credential.projectId;
323
+ this.catalogModelIds = ids;
324
+ this.catalogFailureCode = void 0;
325
+ this.catalogExpiresAt = Date.now() + MODEL_CATALOG_TTL_MS;
326
+ return ids;
327
+ }
328
+ rememberCatalogFailure(projectId, failure) {
329
+ if (failure.code === "AUTH" || failure.code === "CANCELLED") return;
330
+ this.catalogProjectId = projectId;
331
+ this.catalogModelIds = /* @__PURE__ */ new Set();
332
+ this.catalogFailureCode = failure.code;
333
+ this.catalogExpiresAt = Date.now() + MODEL_CATALOG_TTL_MS;
334
+ }
335
+ async readCredential(signal, forceRefresh) {
336
+ try {
337
+ return await this.adapterOptions.auth.credential(signal, forceRefresh ? { forceRefresh: true } : void 0);
338
+ } catch (error) {
339
+ throw toLlmError(error);
340
+ }
341
+ }
342
+ };
343
+ function cleanModelDisplayName(name) {
344
+ return name.replace(/\s*\([^)]*\)\s*$/u, "").trim();
345
+ }
346
+ function getModelReasoningEfforts(modelId) {
347
+ const lower = modelId.toLowerCase();
348
+ if (lower.includes("flash") && !lower.includes("image")) return {
349
+ efforts: [
350
+ {
351
+ id: ReasoningEffortId("low"),
352
+ name: "Low"
353
+ },
354
+ {
355
+ id: ReasoningEffortId("medium"),
356
+ name: "Medium"
357
+ },
358
+ {
359
+ id: ReasoningEffortId("high"),
360
+ name: "High"
361
+ }
362
+ ],
363
+ defaultEffort: ReasoningEffortId("high")
364
+ };
365
+ if (lower.includes("pro")) return {
366
+ efforts: [{
367
+ id: ReasoningEffortId("low"),
368
+ name: "Low"
369
+ }, {
370
+ id: ReasoningEffortId("high"),
371
+ name: "High"
372
+ }],
373
+ defaultEffort: ReasoningEffortId("high")
374
+ };
375
+ }
376
+ function createCatalogView(definitions, state, available, checkedAt) {
377
+ return {
378
+ state,
379
+ models: Object.values(definitions).filter((definition) => !definition.modalities.output.includes("image")).map((definition) => ({
380
+ id: definition.id,
381
+ name: cleanModelDisplayName(definition.name),
382
+ state: state === "live-available" ? available?.has(definition.id) === true ? "live-available" : "unavailable" : "snapshot"
383
+ })),
384
+ ...checkedAt === void 0 ? {} : { checkedAt }
385
+ };
386
+ }
387
+ function cloneCatalogView(value) {
388
+ return {
389
+ state: value.state,
390
+ models: value.models.map((model) => ({ ...model })),
391
+ ...value.checkedAt === void 0 ? {} : { checkedAt: value.checkedAt }
392
+ };
393
+ }
394
+ function parseLiveModelIds(value, definitions) {
395
+ const root = isRecord(value) && isRecord(value.response) ? value.response : value;
396
+ if (!isRecord(root) || !isRecord(root.models)) throw new LlmError("The Antigravity live model catalog did not match the audited schema", "PROTOCOL_DRIFT");
397
+ const entries = Object.entries(root.models);
398
+ if (entries.length > 512) throw new LlmError("The Antigravity live model catalog exceeded the model limit", "PROTOCOL_DRIFT");
399
+ const aliases = getResolverAliasMap();
400
+ const live = /* @__PURE__ */ new Set();
401
+ for (const [id, rawEntry] of entries) {
402
+ if (!safeModelId(id) || !isRecord(rawEntry)) throw new LlmError("The Antigravity live model catalog did not match the audited schema", "PROTOCOL_DRIFT");
403
+ const cleanId = cleanModelId(id);
404
+ live.add(canonicalWireModel(cleanId, aliases));
405
+ live.add(cleanId);
406
+ live.add(id);
407
+ if (cleanId === "gemini-3-flash" || cleanId === "gemini-3-flash-agent" || cleanId === "gemini-3.7-flash-tiered" || cleanId.startsWith("gemini-3-flash") || cleanId.startsWith("gemini-3.7-flash")) {
408
+ live.add("gemini-3.7-flash");
409
+ live.add("gemini-3.7-flash-medium");
410
+ live.add("gemini-3.7-flash-low");
411
+ live.add("gemini-3.7-flash-high");
412
+ }
413
+ if (rawEntry.modelName !== void 0 && typeof rawEntry.modelName === "string") {
414
+ if (!safeModelId(rawEntry.modelName)) throw new LlmError("The Antigravity live model catalog did not match the audited schema", "PROTOCOL_DRIFT");
415
+ const cleanName = cleanModelId(rawEntry.modelName);
416
+ live.add(canonicalWireModel(cleanName, aliases));
417
+ live.add(cleanName);
418
+ }
419
+ if (rawEntry.displayName !== void 0 && (typeof rawEntry.displayName !== "string" || rawEntry.displayName.length > 512 || containsControl(rawEntry.displayName))) throw new LlmError("The Antigravity live model catalog did not match the audited schema", "PROTOCOL_DRIFT");
420
+ }
421
+ const available = /* @__PURE__ */ new Set();
422
+ for (const definition of Object.values(definitions)) {
423
+ const resolved = resolveModelWithTier(definition.id).actualModel;
424
+ const cleanResolved = cleanModelId(resolved);
425
+ const canonical = canonicalWireModel(cleanResolved, aliases);
426
+ if (live.has(canonical) || live.has(cleanResolved) || live.has(resolved) || live.has(definition.id) || definition.id === "antigravity-gemini-3.7-flash" && (live.has("gemini-3-flash") || live.has("gemini-3-flash-agent") || live.has("gemini-3.7-flash-tiered") || live.has("gemini-3.7-flash") || live.has("gemini-3.7-flash-medium"))) available.add(definition.id);
427
+ }
428
+ return available;
429
+ }
430
+ function cleanModelId(value) {
431
+ return value.replace(/^(?:publishers\/[^/]+\/)?models\//, "");
432
+ }
433
+ function canonicalWireModel(value, aliases) {
434
+ return aliases[value] ?? value;
435
+ }
436
+ function safeModelId(value) {
437
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && !containsControl(value);
438
+ }
439
+ function containsControl(value) {
440
+ for (let index = 0; index < value.length; index += 1) {
441
+ const code = value.charCodeAt(index);
442
+ if (code < 32 || code === 127) return true;
443
+ }
444
+ return false;
445
+ }
446
+ function beginBlock(states, part) {
447
+ const index = states.length;
448
+ const block = part.kind === "tool-call" ? {
449
+ index,
450
+ kind: "tool-call",
451
+ id: CallId(part.id ?? `antigravity-call-${String(index)}`),
452
+ ...part.name === void 0 ? {} : { name: part.name },
453
+ text: "",
454
+ ...part.signature === void 0 ? {} : { signature: part.signature }
455
+ } : {
456
+ index,
457
+ kind: part.kind,
458
+ id: CallId(`antigravity-block-${String(index)}`),
459
+ text: "",
460
+ ...part.signature === void 0 ? {} : { signature: part.signature }
461
+ };
462
+ states.push(block);
463
+ return block;
464
+ }
465
+ function sameBlock(state, part) {
466
+ if (state.kind !== part.kind) return false;
467
+ return part.kind !== "tool-call" || part.id === void 0 || part.id === String(state.id);
468
+ }
469
+ function assembleFunctionName(current, fragment) {
470
+ if (fragment.length === 0 || fragment.length > 256 || containsControl(fragment)) throw new PrivateTransportError("protocol-drift", "The private tool-call name was invalid");
471
+ if (current === void 0 || current.length === 0) return fragment;
472
+ if (fragment === current) return current;
473
+ if (fragment.startsWith(current)) return fragment;
474
+ const combined = `${current}${fragment}`;
475
+ if (combined.length > 256) throw new PrivateTransportError("protocol-drift", "The private tool-call name exceeded the byte limit");
476
+ return combined;
477
+ }
478
+ function endBlock(state) {
479
+ if (state.kind === "text") return {
480
+ type: "block-end",
481
+ index: state.index,
482
+ block: {
483
+ type: "text",
484
+ text: state.text
485
+ }
486
+ };
487
+ if (state.kind === "reasoning") return {
488
+ type: "block-end",
489
+ index: state.index,
490
+ block: {
491
+ type: "reasoning",
492
+ text: state.text
493
+ }
494
+ };
495
+ let parsed;
496
+ try {
497
+ parsed = JSON.parse(state.text);
498
+ } catch {
499
+ throw new PrivateTransportError("protocol-drift", "The private tool-call arguments were incomplete JSON");
500
+ }
501
+ if (!isRecord(parsed)) throw new PrivateTransportError("protocol-drift", "The private tool-call arguments were not an object");
502
+ const args = state.text;
503
+ if (state.name === void 0 || !/^[A-Za-z_][A-Za-z0-9_.:-]{0,255}$/u.test(state.name)) throw new PrivateTransportError("protocol-drift", "The private tool-call name was missing or invalid");
504
+ return {
505
+ type: "block-end",
506
+ index: state.index,
507
+ block: {
508
+ type: "tool-call",
509
+ id: state.id,
510
+ name: state.name,
511
+ arguments: args
512
+ }
513
+ };
514
+ }
515
+ function buildAntigravityGeneratePayload(options, credential) {
516
+ const toolNames = /* @__PURE__ */ new Map();
517
+ return buildPayloadFromContents(options, credential, options.messages.filter((message) => message.role !== "system").map((message) => mapMessage(message, options.model, toolNames)));
518
+ }
519
+ async function buildAntigravityGeneratePayloadForAdapter(options, credential, session, timestamp, attachments) {
520
+ const contents = [];
521
+ const toolNames = /* @__PURE__ */ new Map();
522
+ for (const message of options.messages) {
523
+ if (message.role === "system") continue;
524
+ contents.push(await mapMessageWithAttachments(message, options.model, toolNames, attachments, options.signal));
525
+ }
526
+ const payload = buildPayloadFromContents(options, credential, contents);
527
+ const metadata = buildAgyAgentRequestMetadata(session, payload.request, resolveWireModel(options.model), timestamp);
528
+ const request = payload.request;
529
+ request.labels = metadata.labels;
530
+ request.sessionId = metadata.sessionId;
531
+ return {
532
+ ...payload,
533
+ requestId: metadata.requestId,
534
+ requestType: "agent"
535
+ };
536
+ }
537
+ function buildPayloadFromContents(options, credential, contents) {
538
+ const wireModel = resolveWireModel(options.model);
539
+ const request = { contents };
540
+ if (options.system !== void 0 && options.system.trim().length > 0) request.systemInstruction = { parts: [{ text: options.system.slice(0, 65536) }] };
541
+ const generationConfig = {};
542
+ if (options.maxTokens !== void 0) generationConfig.maxOutputTokens = boundedInteger(options.maxTokens, 1, 1e6, "maxTokens");
543
+ if (options.temperature !== void 0) generationConfig.temperature = boundedNumber(options.temperature, -100, 100, "temperature");
544
+ if (options.stop !== void 0) generationConfig.stopSequences = options.stop.slice(0, 16).map((item) => item.slice(0, 256));
545
+ if (options.reasoningEffort !== void 0) generationConfig.thinkingConfig = { thinkingLevel: String(options.reasoningEffort) };
546
+ if (Object.keys(generationConfig).length > 0) request.generationConfig = generationConfig;
547
+ if (options.tools !== void 0 && options.tools.length > 0) {
548
+ const declarations = buildFunctionDeclarations(options.tools);
549
+ if (declarations.length > 0) request.tools = [{ functionDeclarations: declarations }];
550
+ }
551
+ const resolved = resolveModelWithTier(options.model, { cli_first: false });
552
+ const thinkingLevel = normalizeReasoningEffort(options.reasoningEffort) ?? resolved.thinkingLevel;
553
+ if (wireModel.toLowerCase().includes("claude")) applyClaudeTransforms(request, {
554
+ model: wireModel,
555
+ ...resolved.thinkingBudget === void 0 ? {} : { tierThinkingBudget: resolved.thinkingBudget },
556
+ ...options.reasoningEffort === void 0 && resolved.thinkingBudget === void 0 ? {} : { normalizedThinking: {
557
+ includeThoughts: true,
558
+ ...resolved.thinkingBudget === void 0 ? {} : { thinkingBudget: resolved.thinkingBudget }
559
+ } },
560
+ cleanJSONSchema: (value) => isRecord(value) ? value : {
561
+ type: "object",
562
+ properties: {}
563
+ }
564
+ });
565
+ else applyGeminiTransforms(request, {
566
+ model: wireModel,
567
+ ...thinkingLevel === void 0 ? {} : { tierThinkingLevel: thinkingLevel },
568
+ ...resolved.thinkingBudget === void 0 ? {} : { tierThinkingBudget: resolved.thinkingBudget },
569
+ ...options.reasoningEffort === void 0 && resolved.thinkingBudget === void 0 ? {} : { normalizedThinking: {
570
+ includeThoughts: true,
571
+ ...resolved.thinkingBudget === void 0 ? {} : { thinkingBudget: resolved.thinkingBudget }
572
+ } }
573
+ });
574
+ const project = credential.projectId === "inductive-dreamer-qrkws" || !credential.projectId ? void 0 : credential.projectId;
575
+ return {
576
+ ...project === void 0 ? {} : { project },
577
+ model: wireModel,
578
+ request
579
+ };
580
+ }
581
+ function mapMessage(message, model, toolNames) {
582
+ const parts = [];
583
+ const replayBlocks = compatibleReplayState(message, "google-antigravity", model, contentKinds(message))?.blocks ?? [];
584
+ for (const block of message.content) {
585
+ const replayBlock = replayBlocks.find((r) => r.kind === block.type);
586
+ const blockSignature = block.signature ?? block.thoughtSignature ?? replayBlock?.signature;
587
+ if (block.type === "text") {
588
+ if (block.text.length === 0 && message.content.length > 1) continue;
589
+ parts.push({
590
+ text: block.text,
591
+ ...blockSignature === void 0 ? {} : { thoughtSignature: blockSignature }
592
+ });
593
+ } else if (block.type === "reasoning") parts.push({
594
+ text: block.text,
595
+ thought: true,
596
+ ...blockSignature === void 0 ? {} : { thoughtSignature: blockSignature }
597
+ });
598
+ else if (block.type === "tool-call") {
599
+ rememberToolName(toolNames, block.id, block.name);
600
+ parts.push({
601
+ functionCall: {
602
+ name: block.name,
603
+ args: parseJsonObject(block.arguments)
604
+ },
605
+ ...blockSignature === void 0 ? {} : { thoughtSignature: blockSignature }
606
+ });
607
+ } else if (block.type === "tool-result") parts.push({ functionResponse: {
608
+ name: requireToolName(toolNames, block.toolCallId),
609
+ response: { content: blocksToText(block.content) }
610
+ } });
611
+ else if (block.type === "image") throw new LlmError("Antigravity text requests do not accept unresolved image blocks", "UNSUPPORTED_MODALITY");
612
+ }
613
+ return {
614
+ role: message.role === "assistant" ? "model" : "user",
615
+ parts
616
+ };
617
+ }
618
+ async function mapMessageWithAttachments(message, model, toolNames, attachments, signal) {
619
+ if (!message.content.some((block) => block.type === "image")) return mapMessage(message, model, toolNames);
620
+ if (attachments === void 0) throw new LlmError("Antigravity image input requires the Host AttachmentStore", "UNSUPPORTED_MODALITY");
621
+ const replayBlocks = compatibleReplayState(message, "google-antigravity", model, contentKinds(message))?.blocks ?? [];
622
+ const parts = [];
623
+ for (const block of message.content) {
624
+ const replayBlock = replayBlocks.find((r) => r.kind === block.type);
625
+ const blockSignature = block.signature ?? block.thoughtSignature ?? replayBlock?.signature;
626
+ if (block.type === "image") {
627
+ const stored = await attachments.readImage(block.attachment, signal);
628
+ parts.push({ inlineData: {
629
+ mimeType: stored.ref.mediaType,
630
+ data: Buffer.from(stored.data).toString("base64")
631
+ } });
632
+ } else if (block.type === "text") {
633
+ if (block.text.length === 0 && message.content.length > 1) continue;
634
+ parts.push({
635
+ text: block.text,
636
+ ...blockSignature === void 0 ? {} : { thoughtSignature: blockSignature }
637
+ });
638
+ } else if (block.type === "reasoning") parts.push({
639
+ text: block.text,
640
+ thought: true,
641
+ ...blockSignature === void 0 ? {} : { thoughtSignature: blockSignature }
642
+ });
643
+ else if (block.type === "tool-call") {
644
+ rememberToolName(toolNames, block.id, block.name);
645
+ parts.push({
646
+ functionCall: {
647
+ name: block.name,
648
+ args: parseJsonObject(block.arguments)
649
+ },
650
+ ...blockSignature === void 0 ? {} : { thoughtSignature: blockSignature }
651
+ });
652
+ } else if (block.type === "tool-result") parts.push({ functionResponse: {
653
+ name: requireToolName(toolNames, block.toolCallId),
654
+ response: { content: blocksToText(block.content) }
655
+ } });
656
+ }
657
+ return {
658
+ role: message.role === "assistant" ? "model" : "user",
659
+ parts
660
+ };
661
+ }
662
+ function rememberToolName(toolNames, callId, name) {
663
+ if (name.length === 0 || name.length > 256 || containsControl(name)) throw new LlmError("The tool call name is invalid", "INVALID_ARGS");
664
+ const id = String(callId);
665
+ const existing = toolNames.get(id);
666
+ if (existing !== void 0 && existing !== name) throw new LlmError("A tool call id was reused with a different name", "INVALID_ARGS");
667
+ toolNames.set(id, name);
668
+ }
669
+ function requireToolName(toolNames, callId) {
670
+ const name = toolNames.get(String(callId));
671
+ if (name === void 0) throw new LlmError("A tool result did not match a prior tool call", "INVALID_ARGS");
672
+ return name;
673
+ }
674
+ function normalizeReasoningEffort(value) {
675
+ if (value === void 0) return void 0;
676
+ const normalized = String(value).toLowerCase();
677
+ return [
678
+ "minimal",
679
+ "low",
680
+ "medium",
681
+ "high"
682
+ ].includes(normalized) ? normalized : void 0;
683
+ }
684
+ function resolveWireModel(model) {
685
+ if (model === "antigravity-gemini-3.7-flash" || model === "gemini-3.7-flash") return "gemini-3-flash";
686
+ const resolved = resolveModelWithTier(model, { cli_first: false });
687
+ if (resolved.actualModel.startsWith("gemini-3.7-flash")) return "gemini-3-flash";
688
+ return resolved.actualModel;
689
+ }
690
+ function requestSessionKey(options) {
691
+ return options.sessionId === void 0 ? "default" : `session:${fnv1a64Signed(String(options.sessionId))}`;
692
+ }
693
+ function contentKinds(message) {
694
+ return message.content.flatMap((block) => block.type === "text" || block.type === "reasoning" || block.type === "tool-call" ? [block.type] : []);
695
+ }
696
+ function parseProviderEvent(data) {
697
+ const normalized = data.trim().replace(/^\)\]\}'(?:\r?\n)?/u, "");
698
+ let value;
699
+ try {
700
+ value = JSON.parse(normalized);
701
+ } catch {
702
+ throw new PrivateTransportError("invalid-response", "The private response contained invalid JSON");
703
+ }
704
+ if (!isRecord(value)) throw new PrivateTransportError("protocol-drift", "The private response event was not an object");
705
+ if (isRecord(value.error)) return {
706
+ parts: [],
707
+ error: errorDetails(value.error)
708
+ };
709
+ const root = isRecord(value.response) ? value.response : value;
710
+ if (isRecord(root.error)) return {
711
+ parts: [],
712
+ error: errorDetails(root.error)
713
+ };
714
+ const partsValue = findParts(root);
715
+ const parts = [];
716
+ for (const part of partsValue) {
717
+ const parsed = parsePart(part);
718
+ if (parsed !== void 0) parts.push(parsed);
719
+ }
720
+ const usage = parseUsage(root.usageMetadata ?? value.usageMetadata);
721
+ const finish = findFinish(root);
722
+ return {
723
+ parts,
724
+ ...usage === void 0 ? {} : { usage },
725
+ ...finish === void 0 ? {} : { finish }
726
+ };
727
+ }
728
+ function findParts(value) {
729
+ if (Array.isArray(value.parts)) return boundedParts(value.parts);
730
+ if (isRecord(value.content) && Array.isArray(value.content.parts)) return boundedParts(value.content.parts);
731
+ if (isRecord(value.modelTurn) && Array.isArray(value.modelTurn.parts)) return boundedParts(value.modelTurn.parts);
732
+ if (Array.isArray(value.candidates)) {
733
+ const output = [];
734
+ for (const candidate of value.candidates) {
735
+ if (!isRecord(candidate)) continue;
736
+ const content = isRecord(candidate.content) ? candidate.content : candidate;
737
+ if (Array.isArray(content.parts)) {
738
+ if (output.length + content.parts.length > MAX_PROVIDER_PARTS) throw new PrivateTransportError("protocol-drift", "The private response contained too many parts");
739
+ output.push(...content.parts);
740
+ }
741
+ }
742
+ return output;
743
+ }
744
+ if (isRecord(value.serverContent) && isRecord(value.serverContent.modelTurn) && Array.isArray(value.serverContent.modelTurn.parts)) return boundedParts(value.serverContent.modelTurn.parts);
745
+ return [];
746
+ }
747
+ function boundedParts(value) {
748
+ if (value.length > MAX_PROVIDER_PARTS) throw new PrivateTransportError("protocol-drift", "The private response contained too many parts");
749
+ return value;
750
+ }
751
+ function parsePart(value) {
752
+ if (!isRecord(value)) throw new PrivateTransportError("protocol-drift", "The private response part was malformed");
753
+ const functionCall = isRecord(value.functionCall) ? value.functionCall : isRecord(value.function_call) ? value.function_call : void 0;
754
+ if (functionCall !== void 0) {
755
+ const name = stringValue(functionCall.name);
756
+ const id = stringValue(functionCall.id);
757
+ const signature = signatureOf(value) ?? signatureOf(functionCall);
758
+ const args = typeof functionCall.args === "string" ? functionCall.args : JSON.stringify(functionCall.args ?? {});
759
+ return {
760
+ kind: "tool-call",
761
+ ...name === void 0 ? {} : { name },
762
+ ...id === void 0 ? {} : { id },
763
+ arguments: args,
764
+ ...signature === void 0 ? {} : { signature }
765
+ };
766
+ }
767
+ if (typeof value.text === "string" || signatureOf(value) !== void 0) {
768
+ const kind = value.thought === true || value.reasoning === true || value.thinking === true ? "reasoning" : "text";
769
+ const signature = signatureOf(value);
770
+ return {
771
+ kind,
772
+ text: typeof value.text === "string" ? value.text : "",
773
+ ...signature === void 0 ? {} : { signature }
774
+ };
775
+ }
776
+ if (value.inlineData !== void 0 || value.inline_data !== void 0) throw new PrivateTransportError("protocol-drift", "The text model returned unsupported media output");
777
+ throw new PrivateTransportError("protocol-drift", "The private response contained an unknown part type");
778
+ }
779
+ function errorDetails(value) {
780
+ const status = numberValue(value.status);
781
+ const code = stringValue(value.code);
782
+ return {
783
+ ...status === void 0 ? {} : { status },
784
+ ...code === void 0 ? {} : { code }
785
+ };
786
+ }
787
+ function parseUsage(value) {
788
+ if (!isRecord(value)) return void 0;
789
+ const input = numberValue(value.promptTokenCount ?? value.inputTokenCount);
790
+ const output = numberValue(value.candidatesTokenCount ?? value.outputTokenCount);
791
+ const reasoning = numberValue(value.thoughtsTokenCount ?? value.reasoningTokenCount);
792
+ const cached = numberValue(value.cachedContentTokenCount ?? value.cacheReadTokens);
793
+ if (input === void 0 && output === void 0 && reasoning === void 0 && cached === void 0) return void 0;
794
+ return {
795
+ inputTokens: input ?? 0,
796
+ outputTokens: output ?? 0,
797
+ ...cached === void 0 ? {} : { cacheReadTokens: cached },
798
+ ...reasoning === void 0 ? {} : { reasoningTokens: reasoning }
799
+ };
800
+ }
801
+ function findFinish(value) {
802
+ const candidate = value.finishReason ?? value.finish_reason;
803
+ if (typeof candidate === "string") return candidate;
804
+ if (isRecord(value.serverContent) && typeof value.serverContent.finishReason === "string") return value.serverContent.finishReason;
805
+ if (Array.isArray(value.candidates)) {
806
+ for (const item of value.candidates) if (isRecord(item) && typeof item.finishReason === "string") return item.finishReason;
807
+ }
808
+ }
809
+ function signatureOf(value) {
810
+ return stringValue(value.thoughtSignature ?? value.thought_signature ?? value.signature);
811
+ }
812
+ function parseJsonObject(value) {
813
+ try {
814
+ const parsed = JSON.parse(value);
815
+ if (isRecord(parsed)) return parsed;
816
+ } catch {}
817
+ throw new LlmError("The Antigravity tool-call history is malformed", "PROTOCOL_DRIFT");
818
+ }
819
+ function blocksToText(blocks) {
820
+ return blocks.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").slice(0, 65536);
821
+ }
822
+ function isAuthenticationCode(value) {
823
+ const normalized = value?.toUpperCase();
824
+ return normalized === "UNAUTHENTICATED" || normalized === "AUTHENTICATION" || normalized === "INVALID_GRANT" || normalized === "UNAUTHENTICATED_REQUEST";
825
+ }
826
+ function mapFinishReason(value) {
827
+ const normalized = value?.toUpperCase();
828
+ if (normalized === "MAX_TOKENS" || normalized === "LENGTH") return "max-tokens";
829
+ if (normalized === "SAFETY" || normalized === "BLOCKLIST" || normalized === "ERROR") return "error";
830
+ if (normalized === "TOOL_CALLS" || normalized === "FUNCTION_CALL") return "tool-calls";
831
+ return "stop";
832
+ }
833
+ function finishChunk(kind, code, status, replayState) {
834
+ return {
835
+ type: "finish",
836
+ reason: kind === "aborted" ? {
837
+ kind: "aborted",
838
+ failure: {
839
+ code,
840
+ message: "The Antigravity request was cancelled"
841
+ }
842
+ } : kind === "error" ? {
843
+ kind: "error",
844
+ failure: {
845
+ code,
846
+ message: "The Antigravity provider request failed",
847
+ ...status === void 0 ? {} : { status }
848
+ }
849
+ } : kind === "max-tokens" ? { kind: "max-tokens" } : kind === "tool-calls" ? { kind: "tool-calls" } : { kind: "stop" },
850
+ ...replayState === void 0 ? {} : { replayState }
851
+ };
852
+ }
853
+ const LLM_FAILURE_CODES = {
854
+ authentication: "AUTH",
855
+ forbidden: "FORBIDDEN",
856
+ "rate-limited": "RATE_LIMIT",
857
+ cancelled: "CANCELLED",
858
+ timeout: "TIMEOUT",
859
+ "attribution-rejected": "GATE_0_ATTRIBUTION",
860
+ "protocol-drift": "PROTOCOL_DRIFT",
861
+ "response-limit": "RESPONSE_LIMIT",
862
+ "request-limit": "REQUEST_LIMIT",
863
+ upstream: "UPSTREAM",
864
+ network: "NETWORK",
865
+ failed: "PROVIDER_ERROR"
866
+ };
867
+ function toLlmError(error) {
868
+ if (error instanceof LlmError) return error;
869
+ if (error instanceof PrivateTransportError) {
870
+ const kind = classifyPrivateFailure(error);
871
+ const code = LLM_FAILURE_CODES[kind];
872
+ const message = kind === "rate-limited" ? "Antigravity rate limit reached (Google returned 429 Resource Exhausted); please wait for your quota window to refresh" : "The Antigravity private request failed safely";
873
+ return error.status === void 0 ? new LlmError(message, code) : new LlmError(message, code, { status: error.status });
874
+ }
875
+ return new LlmError("The Antigravity provider request failed safely", "PROVIDER_ERROR");
876
+ }
877
+ function boundedTimeout(value, fallback) {
878
+ return value === void 0 || !Number.isFinite(value) || value <= 0 ? fallback : Math.min(Math.floor(value), 6e5);
879
+ }
880
+ function boundedLimit(value, fallback) {
881
+ return value === void 0 || !Number.isFinite(value) || value <= 0 ? fallback : Math.min(Math.floor(value), fallback);
882
+ }
883
+ function boundedInteger(value, min, max, field) {
884
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw new LlmError(`The Antigravity ${field} option is invalid`, "INVALID_OPTIONS");
885
+ return value;
886
+ }
887
+ function boundedNumber(value, min, max, field) {
888
+ if (!Number.isFinite(value) || value < min || value > max) throw new LlmError(`The Antigravity ${field} option is invalid`, "INVALID_OPTIONS");
889
+ return value;
890
+ }
891
+ function numberValue(value) {
892
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER ? value : void 0;
893
+ }
894
+ function stringValue(value) {
895
+ return typeof value === "string" && value.length > 0 && value.length <= 16384 && !containsControl(value) ? value : void 0;
896
+ }
897
+ function safeProviderErrorCode(value) {
898
+ const normalized = value?.toUpperCase();
899
+ return normalized === "SAFETY" || normalized === "BLOCKED" || normalized === "RESOURCE_EXHAUSTED" || normalized === "INVALID_ARGUMENT" ? normalized : "UPSTREAM_ERROR";
900
+ }
901
+ function safeProviderStatus(value) {
902
+ return value !== void 0 && Number.isInteger(value) && value >= 400 && value <= 599 ? value : void 0;
903
+ }
904
+ async function cancelResponse(response) {
905
+ try {
906
+ await response.body?.cancel();
907
+ } catch {}
908
+ }
909
+ function isAborted(signal) {
910
+ return signal !== void 0 && signal.aborted;
911
+ }
912
+ function isRecord(value) {
913
+ return typeof value === "object" && value !== null && !Array.isArray(value);
914
+ }
915
+ //#endregion
916
+ export { ANTIGRAVITY_AVAILABLE_MODELS_ENDPOINT, ANTIGRAVITY_GENERATE_ENDPOINT, ANTIGRAVITY_LLM_ROUTE, ANTIGRAVITY_PROVIDER, ANTIGRAVITY_STREAM_ENDPOINT, AntigravityAdapter, buildAntigravityGeneratePayload };