@benjamolina/pi-antigravity-guard 0.5.1 → 0.6.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.
@@ -0,0 +1,97 @@
1
+ import { formatPoolAccountSummary, formatPoolQuotaSummary, } from "./accounts.js";
2
+ function emitCommandReport(pi, ctx, customType, content) {
3
+ if (typeof pi.sendMessage === "function") {
4
+ pi.sendMessage({
5
+ customType,
6
+ content,
7
+ display: true,
8
+ }, { triggerTurn: false });
9
+ return;
10
+ }
11
+ ctx?.ui?.notify?.(content, "info");
12
+ }
13
+ const ACCOUNTS_USAGE = "Usage: /antigravity-accounts [enable <n>|disable <n>|remove <n>] (where <n> is a positive integer >= 1).";
14
+ const QUOTA_USAGE = "Usage: /antigravity-quota (no arguments accepted).";
15
+ const POSITIVE_INDEX_RE = /^[1-9]\d*$/;
16
+ function emitWarning(pi, ctx, customType, message) {
17
+ if (typeof ctx?.ui?.notify === "function") {
18
+ ctx.ui.notify(message, "warning");
19
+ return;
20
+ }
21
+ emitCommandReport(pi, ctx, customType, message);
22
+ }
23
+ export function registerPiGuardCommands(pi, options) {
24
+ if (typeof pi.registerCommand !== "function") {
25
+ return;
26
+ }
27
+ pi.registerCommand("antigravity-accounts", {
28
+ description: "Inspect and manage the shared Antigravity Guard multi-account pool (usage: /antigravity-accounts [enable <n>|disable <n>|remove <n>])",
29
+ handler: async (args, ctx) => {
30
+ const trimmed = (args ?? "").trim();
31
+ const tokens = trimmed ? trimmed.split(/\s+/) : [];
32
+ if (tokens.length === 0) {
33
+ const manager = await options.pool.loadOrRefresh(ctx?.cwd);
34
+ const cfg = options.getConfig();
35
+ const report = formatPoolAccountSummary(manager.getAccounts(), options.pool.getAccountsPath(), cfg.account_selection_strategy, (options.now ?? Date.now)());
36
+ emitCommandReport(pi, ctx, "antigravity-accounts", report);
37
+ return;
38
+ }
39
+ const subcommand = tokens[0]?.toLowerCase();
40
+ const rawTarget = tokens[1] ?? "";
41
+ const isValidAction = tokens.length === 2 &&
42
+ (subcommand === "enable" || subcommand === "disable" || subcommand === "remove") &&
43
+ POSITIVE_INDEX_RE.test(rawTarget);
44
+ const targetNum = isValidAction ? Number(rawTarget) : Number.NaN;
45
+ if (!isValidAction || !Number.isSafeInteger(targetNum) || targetNum < 1) {
46
+ emitWarning(pi, ctx, "antigravity-accounts", ACCOUNTS_USAGE);
47
+ return;
48
+ }
49
+ let manager;
50
+ if (subcommand === "remove") {
51
+ const outcome = await options.pool.removeAccountByIndex(targetNum - 1, ctx?.cwd);
52
+ manager = outcome.manager;
53
+ if (outcome.removed) {
54
+ ctx?.ui?.notify?.(`Removed account #${targetNum} from pool.`, "info");
55
+ }
56
+ else {
57
+ ctx?.ui?.notify?.(`Account #${targetNum} not found.`, "warning");
58
+ }
59
+ }
60
+ else {
61
+ manager = await options.pool.loadOrRefresh(ctx?.cwd);
62
+ const index = targetNum - 1;
63
+ const enable = subcommand === "enable";
64
+ if (enable) {
65
+ manager.clearAccountVerificationRequired(index, true);
66
+ }
67
+ const changed = manager.setAccountEnabled(index, enable);
68
+ if (changed) {
69
+ await manager.saveToDisk();
70
+ options.pool.syncAuthAfterAccountToggle(manager);
71
+ ctx?.ui?.notify?.(`Account #${targetNum} ${enable ? "enabled" : "disabled"}.`, "info");
72
+ }
73
+ else {
74
+ ctx?.ui?.notify?.(`Account #${targetNum} not found.`, "warning");
75
+ }
76
+ }
77
+ const cfg = options.getConfig();
78
+ const report = formatPoolAccountSummary(manager.getAccounts(), options.pool.getAccountsPath(), cfg.account_selection_strategy, (options.now ?? Date.now)());
79
+ emitCommandReport(pi, ctx, "antigravity-accounts", report);
80
+ },
81
+ });
82
+ pi.registerCommand("antigravity-quota", {
83
+ description: "Display live and cached soft-quota usage across the shared Antigravity Guard account pool",
84
+ handler: async (args, ctx) => {
85
+ if ((args ?? "").trim().length > 0) {
86
+ emitWarning(pi, ctx, "antigravity-quota", QUOTA_USAGE);
87
+ return;
88
+ }
89
+ const { manager, results } = await options.pool.refreshQuotasLive({
90
+ cwd: ctx?.cwd,
91
+ });
92
+ const cfg = options.getConfig();
93
+ const report = formatPoolQuotaSummary(manager.getAccounts(), cfg.soft_quota_threshold_percent, results, (options.now ?? Date.now)());
94
+ emitCommandReport(pi, ctx, "antigravity-quota", report);
95
+ },
96
+ });
97
+ }
package/dist/context.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Context, Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
2
+ import { type SessionSignatureCache } from "@benjamolina/antigravity-guard-core";
2
3
  import { type GenerationSelection } from "./catalog.ts";
3
4
  import { type ToolReplayDiagnostics } from "./tool-context.ts";
4
5
  declare const THINKING_LEVELS: readonly ["minimal", "low", "medium", "high", "xhigh"];
@@ -31,9 +32,10 @@ export interface GenerationRequest {
31
32
  role?: "user";
32
33
  parts: Part[];
33
34
  };
34
- tools?: {
35
+ tools?: Array<{
35
36
  functionDeclarations: readonly GeminiFunctionDeclaration[];
36
- }[];
37
+ googleSearch?: Record<string, never>;
38
+ }>;
37
39
  toolConfig?: {
38
40
  functionCallingConfig: {
39
41
  mode: "AUTO" | "NONE";
@@ -57,13 +59,21 @@ export interface GenerationRequest {
57
59
  userAgent: "antigravity";
58
60
  requestId: string;
59
61
  }
62
+ export type SignatureRestoreSource = Pick<SessionSignatureCache, "getCachedSignature">;
60
63
  export interface SerializeTextContextInput {
61
64
  context: Context;
62
65
  model: Model<string>;
63
66
  options?: SimpleStreamOptions;
64
67
  project: string;
65
68
  requestId: string;
69
+ signatureCache?: SignatureRestoreSource;
70
+ allowSentinelFallback?: boolean;
66
71
  }
72
+ export declare function resolvePiSignatureSessionKey(options: {
73
+ context: unknown;
74
+ wireModel: string;
75
+ projectId: string;
76
+ }): string;
67
77
  export declare class ContextSerializationError extends Error {
68
78
  }
69
79
  export declare function sanitizeAntigravitySystemPrompt(systemPrompt: string): string;
package/dist/context.js CHANGED
@@ -1,12 +1,46 @@
1
+ import { MIN_THOUGHT_SIGNATURE_LENGTH, SKIP_THOUGHT_SIGNATURE, buildSignatureSessionKey, signatureCacheProjectKey, stripThinkingTierSuffixForCacheKey, } from "@benjamolina/antigravity-guard-core";
1
2
  import { CLAUDE_CUSTOM_PARAMETERS_PROFILE, getCatalogEntry, resolveGenerationSelection } from "./catalog.js";
2
3
  import { normalizeCustomToolSchema } from "./tool-schema.js";
3
- import { buildAntigravityEnvelope } from "./envelope.js";
4
+ import { buildAntigravityEnvelope, resolveSessionTrajectory } from "./envelope.js";
4
5
  import { hasToolContext, prepareToolContext, replayToolHistory } from "./tool-context.js";
5
6
  const MAX_TEXT_BYTES = 8 * 1024 * 1024;
6
7
  const PROVIDER = "antigravity-guard";
7
8
  const RESERVED_HEADERS = new Set(["authorization", "host", "content-type", "content-length"]);
8
9
  const THINKING_LEVELS = ["minimal", "low", "medium", "high", "xhigh"];
9
10
  const PI_HARNESS_MARKER = "operating inside pi, a coding agent harness";
11
+ export function resolvePiSignatureSessionKey(options) {
12
+ const rawMessagesField = isRecord(options.context) ? field(options.context, "messages") : undefined;
13
+ const rawMessages = Array.isArray(rawMessagesField) ? rawMessagesField : [];
14
+ const conversationMessages = rawMessages.filter((msg) => !(isRecord(msg) && field(msg, "role") === "system"));
15
+ const trajectoryId = resolveSessionTrajectory(conversationMessages).trajectoryId;
16
+ const modelForCacheKey = stripThinkingTierSuffixForCacheKey(options.wireModel);
17
+ return buildSignatureSessionKey("pi", modelForCacheKey, trajectoryId, signatureCacheProjectKey(modelForCacheKey, options.projectId));
18
+ }
19
+ function buildSignatureRestoreState(options) {
20
+ const hasCache = Boolean(options.signatureCache);
21
+ const allowSentinelFallback = hasCache
22
+ ? options.allowSentinelFallback !== false
23
+ : options.allowSentinelFallback === true;
24
+ if (!hasCache && !allowSentinelFallback)
25
+ return undefined;
26
+ if (!hasCache) {
27
+ return {
28
+ family: options.family,
29
+ hasCache: false,
30
+ allowSentinelFallback,
31
+ getSignature: () => undefined,
32
+ };
33
+ }
34
+ const trajectoryId = resolveSessionTrajectory(options.messages).trajectoryId;
35
+ const modelForCacheKey = stripThinkingTierSuffixForCacheKey(options.wireModel);
36
+ const sessionKey = buildSignatureSessionKey("pi", modelForCacheKey, trajectoryId, signatureCacheProjectKey(modelForCacheKey, options.projectId));
37
+ return {
38
+ family: options.family,
39
+ hasCache: true,
40
+ allowSentinelFallback,
41
+ getSignature: (thinkingText) => options.signatureCache.getCachedSignature(sessionKey, thinkingText),
42
+ };
43
+ }
10
44
  export class ContextSerializationError extends Error {
11
45
  }
12
46
  const PI_DOCS_BLOCK_REGEX = /(?:<docs>\r?\n)?Pi documentation \(read only when the user asks about pi[^)]*\):\r?\n- Main documentation: ([^\r\n]+)\r?\n- Additional docs: ([^\r\n]+)\r?\n- Examples: ([^\r\n]+)[^\r\n]*\r?\n(?:- When reading pi docs or examples[^\r\n]+\r?\n)?- When asked about:[^\r\n]+\r?\n(?:- When working on pi topics[^\r\n]+\r?\n)?- Always read pi \.md files completely[^\r\n]+(?:\r?\n<\/docs>)?/g;
@@ -46,6 +80,8 @@ export function serializeContext(input, injectedSelection, onDiagnostics) {
46
80
  const { toolChoice: _choice, ...textOptions } = isRecord(options) ? options : {};
47
81
  const text = serializeTextContext({
48
82
  ...input,
83
+ signatureCache: undefined,
84
+ allowSentinelFallback: undefined,
49
85
  context: {
50
86
  ...textContext,
51
87
  ...(normalized.systemPrompt !== undefined ? { systemPrompt: normalized.systemPrompt } : {}),
@@ -53,17 +89,41 @@ export function serializeContext(input, injectedSelection, onDiagnostics) {
53
89
  },
54
90
  options: textOptions,
55
91
  });
92
+ const restore = buildSignatureRestoreState({
93
+ signatureCache: input.signatureCache,
94
+ allowSentinelFallback: input.allowSentinelFallback,
95
+ messages: normalized.messages,
96
+ wireModel: selection.route.wireModel,
97
+ projectId: input.project,
98
+ family: entry.response.family,
99
+ });
56
100
  const sameModel = (message) => field(message, "role") === "assistant" && entry.replay.kind === "same-public-model" && isSameProviderAndModel(message, entry.publicId);
57
101
  const requireSigned = geminiRequiresSignedToolReplay(selection.route.wireModel);
58
102
  const includeToolCallId = entry.response.family === "claude" || entry.response.family === "gpt-oss";
59
- const toolReplayPolicy = (requireSigned || includeToolCallId) ? {
103
+ const allowMultimodal = entry.response.family === "gemini" || entry.response.family === "claude";
104
+ const toolReplayPolicy = (requireSigned || includeToolCallId || !allowMultimodal) ? {
60
105
  requireSignedToolCalls: requireSigned,
61
106
  isSameModel: sameModel,
62
- toolCallSignature: (part, message) => sameModel(message) ? validThoughtSignature(field(part, "thoughtSignature")) : undefined,
107
+ toolCallSignature: (part, message, callIndex, contentIndex) => {
108
+ if (!sameModel(message))
109
+ return undefined;
110
+ const rawSignature = field(part, "thoughtSignature");
111
+ if (rawSignature !== undefined) {
112
+ return validThoughtSignature(rawSignature, restore?.allowSentinelFallback === true);
113
+ }
114
+ if (!restore || callIndex > 0 || !requireSigned)
115
+ return undefined;
116
+ const turnSignature = resolveTurnThinkingSignature(message, restore, contentIndex);
117
+ if (turnSignature)
118
+ return turnSignature;
119
+ return restore.allowSentinelFallback ? SKIP_THOUGHT_SIGNATURE : undefined;
120
+ },
63
121
  includeToolCallId,
122
+ allowMultimodal,
64
123
  } : undefined;
65
- const contents = replayToolHistory(normalized.messages, (part, message) => messagePart(part, field(message, "role") === "assistant", sameModel(message)), onDiagnostics, toolReplayPolicy, prepared?.declarations.length ?? 0);
124
+ const contents = replayToolHistory(normalized.messages, (part, message) => messagePart(part, field(message, "role") === "assistant", sameModel(message), restore, allowMultimodal), onDiagnostics, toolReplayPolicy, prepared?.declarations.length ?? 0);
66
125
  const { systemInstruction, generationConfig } = text.request;
126
+ const sonarGrounding = !prepared && shouldInjectSonarGoogleSearch(selection.route.wireModel, options);
67
127
  const envelope = buildAntigravityEnvelope({
68
128
  wireModelId: selection.route.wireModel,
69
129
  family: entry.response.family,
@@ -87,6 +147,8 @@ export function serializeContext(input, injectedSelection, onDiagnostics) {
87
147
  : (entry.response.family === "claude" || entry.response.family === "gpt-oss"
88
148
  ? { toolConfig: { functionCallingConfig: { mode: "AUTO" } } }
89
149
  : {})),
150
+ } : sonarGrounding ? {
151
+ tools: [{ googleSearch: {} }],
90
152
  } : {}),
91
153
  generationConfig,
92
154
  sessionId: envelope.sessionId,
@@ -118,7 +180,16 @@ export function serializeTextContext(input) {
118
180
  fail("Tools are not supported by this text-only provider.");
119
181
  validateOptions(options, entry.descriptor.maxTokens);
120
182
  const systemPrompt = rawSystemPrompt === undefined ? undefined : sanitizeAntigravitySystemPrompt(rawSystemPrompt);
183
+ const restore = buildSignatureRestoreState({
184
+ signatureCache: field(input, "signatureCache"),
185
+ allowSentinelFallback: field(input, "allowSentinelFallback"),
186
+ messages: normalized.messages,
187
+ wireModel: route.wireModel,
188
+ projectId: project,
189
+ family: entry.response.family,
190
+ });
121
191
  let textBytes = byteLength(systemPrompt ?? "");
192
+ const allowMultimodal = entry.response.family === "gemini" || entry.response.family === "claude";
122
193
  const contents = [];
123
194
  for (const message of normalized.messages) {
124
195
  if (!isRecord(message))
@@ -129,7 +200,7 @@ export function serializeTextContext(input) {
129
200
  if (role !== "user" && role !== "assistant")
130
201
  fail("Unsupported context role for this text-only provider.");
131
202
  const assistant = role === "assistant";
132
- const parts = messageParts(field(message, "content", true), assistant, assistant && entry.replay.kind === "same-public-model" && isSameProviderAndModel(message, entry.publicId));
203
+ const parts = messageParts(field(message, "content", true), assistant, assistant && entry.replay.kind === "same-public-model" && isSameProviderAndModel(message, entry.publicId), restore, allowMultimodal);
133
204
  textBytes += parts.reduce((total, part) => total + (part.text ? byteLength(part.text) : (part.inlineData ? byteLength(part.inlineData.data) : 0)), 0);
134
205
  if (textBytes > MAX_TEXT_BYTES)
135
206
  fail("Text context is too large.");
@@ -140,6 +211,7 @@ export function serializeTextContext(input) {
140
211
  const systemInstruction = systemPrompt === undefined ? undefined : { role: "user", parts: [{ text: systemPrompt }] };
141
212
  const temperature = option(options, "temperature");
142
213
  const maxTokens = option(options, "maxTokens");
214
+ const sonarGrounding = shouldInjectSonarGoogleSearch(route.wireModel, options);
143
215
  const envelope = buildAntigravityEnvelope({
144
216
  wireModelId: route.wireModel,
145
217
  family: entry.response.family,
@@ -147,7 +219,7 @@ export function serializeTextContext(input) {
147
219
  messages: normalized.messages,
148
220
  injectedRequestId: requestId,
149
221
  });
150
- return { project, model: route.wireModel, request: { contents, ...(systemInstruction ? { systemInstruction } : {}), generationConfig: {
222
+ return { project, model: route.wireModel, request: { contents, ...(systemInstruction ? { systemInstruction } : {}), ...(sonarGrounding ? { tools: [{ googleSearch: {} }] } : {}), generationConfig: {
151
223
  temperature: typeof temperature === "number" ? temperature : 1,
152
224
  maxOutputTokens: resolveOutputTokens(maxTokens, entry.descriptor.maxTokens, route.thinking),
153
225
  ...(() => {
@@ -271,21 +343,46 @@ function isToolBearingNormalizedContext(context) {
271
343
  }
272
344
  return false;
273
345
  }
274
- function messageParts(content, assistant, sameProviderAndModel) {
346
+ function messageParts(content, assistant, sameProviderAndModel, restore, allowMultimodal = true) {
275
347
  if (typeof content === "string")
276
348
  return content ? [{ text: content }] : fail("A text conversation is required.");
277
349
  const parts = isDenseArray(content);
278
350
  if (!parts.length)
279
351
  fail("A text conversation is required.");
280
- return parts.map((part) => messagePart(isRecord(part) ? part : fail("Only text context is supported by this provider."), assistant, sameProviderAndModel));
352
+ return parts.map((part) => messagePart(isRecord(part) ? part : fail("Only text context is supported by this provider."), assistant, sameProviderAndModel, restore, allowMultimodal));
353
+ }
354
+ function isSupportedInlineMimeType(mimeType) {
355
+ const lower = mimeType.trim().toLowerCase();
356
+ return lower === "application/pdf" || lower.startsWith("image/");
357
+ }
358
+ function extractInlineMediaPart(part, type, allowMultimodal) {
359
+ if (!allowMultimodal)
360
+ fail("Only text context is supported by this provider.");
361
+ const source = isRecord(field(part, "source")) ? field(part, "source") : undefined;
362
+ const rawData = field(part, "data") ?? (source ? field(source, "data") : undefined);
363
+ if (typeof rawData !== "string" || !rawData)
364
+ fail(type === "image" ? "Invalid image data." : "Invalid document data.");
365
+ const dataUriMatch = /^data:([^;,]+);base64,/is.exec(rawData);
366
+ const rawMime = field(part, "mimeType") ?? (source ? field(source, "media_type") ?? field(source, "mimeType") : undefined) ?? dataUriMatch?.[1];
367
+ const defaultMime = type === "image" ? "image/jpeg" : "application/pdf";
368
+ const mimeType = typeof rawMime === "string" && rawMime.trim() ? rawMime.trim() : defaultMime;
369
+ if (!isSupportedInlineMimeType(mimeType))
370
+ fail("Unsupported media type.");
371
+ if ((type === "document" || type === "file") && mimeType.toLowerCase() !== "application/pdf")
372
+ fail("Unsupported document media type.");
373
+ const cleanedData = rawData.replace(/^data:[^;]+;base64,/is, "").replace(/\s+/g, "");
374
+ if (!cleanedData || cleanedData.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(cleanedData)) {
375
+ fail(type === "image" ? "Invalid image data." : "Invalid document data.");
376
+ }
377
+ return { inlineData: { mimeType, data: cleanedData } };
281
378
  }
282
- function messagePart(part, assistant, sameProviderAndModel) {
379
+ function messagePart(part, assistant, sameProviderAndModel, restore, allowMultimodal = true) {
283
380
  const type = field(part, "type", true);
284
381
  if (type === "text") {
285
382
  const text = field(part, "text", true);
286
383
  if (typeof text !== "string")
287
384
  fail("Only text context is supported by this provider.");
288
- const thoughtSignature = sameProviderAndModel ? validThoughtSignature(field(part, "textSignature")) : undefined;
385
+ const thoughtSignature = sameProviderAndModel ? validThoughtSignature(field(part, "textSignature"), restore?.allowSentinelFallback === true) : undefined;
289
386
  if (!text && !thoughtSignature)
290
387
  fail("Only text context is supported by this provider.");
291
388
  return { text, ...(thoughtSignature ? { thoughtSignature } : {}) };
@@ -294,7 +391,38 @@ function messagePart(part, assistant, sameProviderAndModel) {
294
391
  const text = field(part, "thinking", true);
295
392
  if (typeof text !== "string")
296
393
  fail("Only text context is supported by this provider.");
297
- const thoughtSignature = validThoughtSignature(field(part, "thinkingSignature"));
394
+ const rawThinkingSig = field(part, "thinkingSignature");
395
+ const explicitSig = validThoughtSignature(rawThinkingSig, restore?.allowSentinelFallback === true);
396
+ let thoughtSignature;
397
+ if (restore && restore.family === "claude") {
398
+ const cachedSig = text.length > 0 && restore.hasCache
399
+ ? restoreCachedSignature(restore.getSignature(text))
400
+ : undefined;
401
+ if (explicitSig === SKIP_THOUGHT_SIGNATURE) {
402
+ thoughtSignature = SKIP_THOUGHT_SIGNATURE;
403
+ }
404
+ else if (rawThinkingSig !== undefined && !explicitSig) {
405
+ thoughtSignature = undefined;
406
+ }
407
+ else if (explicitSig && !restore.hasCache) {
408
+ thoughtSignature = explicitSig;
409
+ }
410
+ else if (explicitSig && cachedSig && explicitSig === cachedSig) {
411
+ thoughtSignature = explicitSig;
412
+ }
413
+ else if (!explicitSig && cachedSig) {
414
+ thoughtSignature = cachedSig;
415
+ }
416
+ else if (restore.allowSentinelFallback) {
417
+ thoughtSignature = SKIP_THOUGHT_SIGNATURE;
418
+ }
419
+ }
420
+ else {
421
+ const cachedSig = rawThinkingSig === undefined && text.length > 0 && restore?.hasCache
422
+ ? restoreCachedSignature(restore.getSignature(text))
423
+ : undefined;
424
+ thoughtSignature = explicitSig ?? cachedSig;
425
+ }
298
426
  if (!text && !thoughtSignature)
299
427
  fail("Only text context is supported by this provider.");
300
428
  return { thought: true, text, ...(thoughtSignature ? { thoughtSignature } : {}) };
@@ -305,17 +433,20 @@ function messagePart(part, assistant, sameProviderAndModel) {
305
433
  fail("Only text context is supported by this provider.");
306
434
  return { text };
307
435
  }
308
- if (type === "image") {
309
- const rawData = field(part, "data") ?? (isRecord(field(part, "source")) ? field(field(part, "source"), "data") : undefined);
310
- if (typeof rawData !== "string" || !rawData)
311
- fail("Invalid image data.");
312
- const rawMime = field(part, "mimeType") ?? (isRecord(field(part, "source")) ? field(field(part, "source"), "media_type") : undefined);
313
- const mimeType = typeof rawMime === "string" && rawMime ? rawMime : "image/jpeg";
314
- const cleanedData = rawData.replace(/^data:[^;]+;base64,/s, "").trim();
315
- return { inlineData: { mimeType, data: cleanedData } };
436
+ if (type === "image" || type === "document" || type === "file") {
437
+ if (assistant)
438
+ fail("Only text context is supported by this provider.");
439
+ return extractInlineMediaPart(part, type, allowMultimodal);
316
440
  }
317
441
  fail("Only text context is supported by this provider.");
318
442
  }
443
+ function shouldInjectSonarGoogleSearch(wireModel, options) {
444
+ if (!wireModel.toLowerCase().endsWith("-sonar"))
445
+ return false;
446
+ if (isRecord(options) && option(options, "toolChoice") === "none")
447
+ return false;
448
+ return true;
449
+ }
319
450
  function isSameProviderAndModel(message, publicId) {
320
451
  return field(message, "provider") === PROVIDER && field(message, "model") === publicId;
321
452
  }
@@ -344,11 +475,41 @@ function geminiRequiresSignedToolReplay(wireModel) {
344
475
  return Number(match[1]) >= 3;
345
476
  return true;
346
477
  }
347
- function validThoughtSignature(value) {
478
+ function validThoughtSignature(value, allowSentinel = false) {
479
+ if (allowSentinel && value === SKIP_THOUGHT_SIGNATURE)
480
+ return SKIP_THOUGHT_SIGNATURE;
348
481
  if (typeof value !== "string" || !value || value.length % 4 !== 0)
349
482
  return undefined;
350
483
  return /^[A-Za-z0-9+/]+={0,2}$/.test(value) ? value : undefined;
351
484
  }
485
+ function restoreCachedSignature(value) {
486
+ if (typeof value !== "string" || !value)
487
+ return undefined;
488
+ if (value === SKIP_THOUGHT_SIGNATURE)
489
+ return undefined;
490
+ return validThoughtSignature(value, false) ?? (value.length >= MIN_THOUGHT_SIGNATURE_LENGTH ? value : undefined);
491
+ }
492
+ function resolveTurnThinkingSignature(message, restore, beforeContentIndex) {
493
+ const content = field(message, "content");
494
+ if (!Array.isArray(content))
495
+ return undefined;
496
+ const upperBound = Math.min(beforeContentIndex, content.length);
497
+ for (let index = upperBound - 1; index >= 0; index--) {
498
+ const item = content[index];
499
+ if (!isRecord(item) || field(item, "type") !== "thinking")
500
+ continue;
501
+ const rawThinkingSig = field(item, "thinkingSignature");
502
+ if (rawThinkingSig !== undefined) {
503
+ return validThoughtSignature(rawThinkingSig, false);
504
+ }
505
+ const thinkingText = field(item, "thinking");
506
+ if (typeof thinkingText === "string" && thinkingText.length > 0 && restore.hasCache) {
507
+ return restoreCachedSignature(restore.getSignature(thinkingText));
508
+ }
509
+ return undefined;
510
+ }
511
+ return undefined;
512
+ }
352
513
  function validateOptions(options, maxAllowedTokens) {
353
514
  if (options === undefined)
354
515
  return;
@@ -1,2 +1,2 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- export default function extension(pi: Pick<ExtensionAPI, "registerProvider">): void;
1
+ import { type PiGuardRuntimeOptions, type ProviderRegistrationHost } from "./provider.ts";
2
+ export default function extension(pi: ProviderRegistrationHost, options?: PiGuardRuntimeOptions): void;
package/dist/extension.js CHANGED
@@ -1,4 +1,4 @@
1
- import { registerAntigravityProvider } from "./provider.js";
2
- export default function extension(pi) {
3
- registerAntigravityProvider(pi);
1
+ import { registerAntigravityProvider, } from "./provider.js";
2
+ export default function extension(pi, options) {
3
+ registerAntigravityProvider(pi, options);
4
4
  }
package/dist/project.d.ts CHANGED
@@ -5,6 +5,7 @@ export interface LoginProjectOptions {
5
5
  platform: string;
6
6
  signal?: AbortSignal;
7
7
  deadlineMs?: number;
8
+ userAgent?: string;
8
9
  }
9
10
  export interface LoginProject {
10
11
  email?: string;
package/dist/project.js CHANGED
@@ -36,7 +36,7 @@ async function discoveredProject(options) {
36
36
  headers: {
37
37
  Authorization: `Bearer ${options.accessToken}`,
38
38
  "Content-Type": "application/json",
39
- "User-Agent": ANTIGRAVITY_USER_AGENT,
39
+ "User-Agent": options.userAgent ?? ANTIGRAVITY_USER_AGENT,
40
40
  },
41
41
  body: JSON.stringify({ metadata: { ideType: "ANTIGRAVITY" } }),
42
42
  };
@@ -1,5 +1,30 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- export declare function registerAntigravityProvider(pi: Pick<ExtensionAPI, "registerProvider">): void;
2
+ import { type ResolveSharedGuardPathsOptions, type SessionSignatureCache, type SharedGuardConfig } from "@benjamolina/antigravity-guard-core";
3
+ import { type PiAccountPool } from "./accounts.ts";
4
+ export interface PiGuardRuntimeOptions extends ResolveSharedGuardPathsOptions {
5
+ fetch?: typeof globalThis.fetch;
6
+ now?: () => number;
7
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
8
+ }
9
+ export interface PiGuardRuntime {
10
+ getVersion(): string;
11
+ getUserAgent(): string;
12
+ getConfig(): SharedGuardConfig;
13
+ getAccountPool(): PiAccountPool;
14
+ getSignatureCache(): SessionSignatureCache;
15
+ refreshSession(cwd?: string): Promise<void>;
16
+ shutdown(): void;
17
+ }
18
+ export declare function createPiGuardRuntime(options?: PiGuardRuntimeOptions): PiGuardRuntime;
19
+ export type ProviderRegistrationHost = Pick<ExtensionAPI, "registerProvider"> & {
20
+ registerCommand?: ExtensionAPI["registerCommand"];
21
+ registerTool?: ExtensionAPI["registerTool"];
22
+ sendMessage?: ExtensionAPI["sendMessage"];
23
+ on?: (event: "session_start" | "session_shutdown", handler: (event: unknown, ctx?: {
24
+ cwd?: string;
25
+ }) => Promise<void> | void) => void;
26
+ };
27
+ export declare function registerAntigravityProvider(pi: ProviderRegistrationHost, options?: PiGuardRuntimeOptions): PiGuardRuntime;
3
28
  export declare function parseProviderApiKey(value: string): {
4
29
  token: string;
5
30
  projectId: string;