@benjamolina/pi-antigravity-guard 0.5.0 → 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,15 +1,49 @@
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
- const PI_DOCS_BLOCK_REGEX = /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 asked about:[^\r\n]+\r?\n(?:- When working on pi topics[^\r\n]+\r?\n)?- Always read pi \.md files completely[^\r\n]+/g;
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;
13
47
  export function sanitizeAntigravitySystemPrompt(systemPrompt) {
14
48
  if (!systemPrompt.includes(PI_HARNESS_MARKER))
15
49
  return systemPrompt;
@@ -40,26 +74,61 @@ export function serializeContext(input, injectedSelection, onDiagnostics) {
40
74
  fail("Invalid tool capability selection.");
41
75
  if (selection.tools.state !== "enabled")
42
76
  fail(capabilityError(entry.publicId, selection.level, selection.tools));
43
- const prepared = prepareToolContext(field(context, "tools") ?? [], isRecord(options) ? field(options, "toolChoice") : undefined, selection.tools.schemaProfile);
44
- const { tools: _tools, messages, ...textContext } = context;
77
+ const normalized = normalizeContextRecord(context);
78
+ const prepared = prepareToolContext(normalized.tools ?? [], isRecord(options) ? field(options, "toolChoice") : undefined, selection.tools.schemaProfile);
79
+ const { tools: _tools, messages: _messages, systemPrompt: _systemPrompt, ...textContext } = context;
45
80
  const { toolChoice: _choice, ...textOptions } = isRecord(options) ? options : {};
46
- const text = serializeTextContext({ ...input, context: { ...textContext, messages: [{ role: "user", content: "placeholder", timestamp: 0 }] }, options: textOptions });
81
+ const text = serializeTextContext({
82
+ ...input,
83
+ signatureCache: undefined,
84
+ allowSentinelFallback: undefined,
85
+ context: {
86
+ ...textContext,
87
+ ...(normalized.systemPrompt !== undefined ? { systemPrompt: normalized.systemPrompt } : {}),
88
+ messages: [{ role: "user", content: "placeholder", timestamp: 0 }],
89
+ },
90
+ options: textOptions,
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
+ });
47
100
  const sameModel = (message) => field(message, "role") === "assistant" && entry.replay.kind === "same-public-model" && isSameProviderAndModel(message, entry.publicId);
48
101
  const requireSigned = geminiRequiresSignedToolReplay(selection.route.wireModel);
49
102
  const includeToolCallId = entry.response.family === "claude" || entry.response.family === "gpt-oss";
50
- const toolReplayPolicy = (requireSigned || includeToolCallId) ? {
103
+ const allowMultimodal = entry.response.family === "gemini" || entry.response.family === "claude";
104
+ const toolReplayPolicy = (requireSigned || includeToolCallId || !allowMultimodal) ? {
51
105
  requireSignedToolCalls: requireSigned,
52
106
  isSameModel: sameModel,
53
- 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
+ },
54
121
  includeToolCallId,
122
+ allowMultimodal,
55
123
  } : undefined;
56
- const contents = replayToolHistory(isDenseArray(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);
57
125
  const { systemInstruction, generationConfig } = text.request;
126
+ const sonarGrounding = !prepared && shouldInjectSonarGoogleSearch(selection.route.wireModel, options);
58
127
  const envelope = buildAntigravityEnvelope({
59
128
  wireModelId: selection.route.wireModel,
60
129
  family: entry.response.family,
61
130
  contentsCount: contents.length,
62
- messages: isDenseArray(messages),
131
+ messages: normalized.messages,
63
132
  injectedRequestId: input.requestId,
64
133
  });
65
134
  return { ...text, request: {
@@ -78,6 +147,8 @@ export function serializeContext(input, injectedSelection, onDiagnostics) {
78
147
  : (entry.response.family === "claude" || entry.response.family === "gpt-oss"
79
148
  ? { toolConfig: { functionCallingConfig: { mode: "AUTO" } } }
80
149
  : {})),
150
+ } : sonarGrounding ? {
151
+ tools: [{ googleSearch: {} }],
81
152
  } : {}),
82
153
  generationConfig,
83
154
  sessionId: envelope.sessionId,
@@ -98,19 +169,29 @@ export function serializeTextContext(input) {
98
169
  fail("Invalid text context.");
99
170
  const selection = resolveGenerationSelection(entry, option(options, "reasoning"));
100
171
  const route = selection.route;
101
- if (isToolBearingContext(context) && selection.tools.state !== "enabled")
172
+ const normalized = normalizeContextRecord(context);
173
+ if (isToolBearingNormalizedContext(normalized) && selection.tools.state !== "enabled")
102
174
  fail(capabilityError(entry.publicId, selection.level, selection.tools));
103
- const rawSystemPrompt = field(context, "systemPrompt");
104
- const tools = field(context, "tools");
175
+ const rawSystemPrompt = normalized.systemPrompt;
176
+ const tools = normalized.tools;
105
177
  if (rawSystemPrompt !== undefined && typeof rawSystemPrompt !== "string")
106
178
  fail("Text-only context is required.");
107
179
  if (tools !== undefined && isDenseArray(tools).length)
108
180
  fail("Tools are not supported by this text-only provider.");
109
181
  validateOptions(options, entry.descriptor.maxTokens);
110
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
+ });
111
191
  let textBytes = byteLength(systemPrompt ?? "");
192
+ const allowMultimodal = entry.response.family === "gemini" || entry.response.family === "claude";
112
193
  const contents = [];
113
- for (const message of isDenseArray(field(context, "messages", true))) {
194
+ for (const message of normalized.messages) {
114
195
  if (!isRecord(message))
115
196
  fail("Invalid text context.");
116
197
  const role = field(message, "role", true);
@@ -119,7 +200,7 @@ export function serializeTextContext(input) {
119
200
  if (role !== "user" && role !== "assistant")
120
201
  fail("Unsupported context role for this text-only provider.");
121
202
  const assistant = role === "assistant";
122
- 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);
123
204
  textBytes += parts.reduce((total, part) => total + (part.text ? byteLength(part.text) : (part.inlineData ? byteLength(part.inlineData.data) : 0)), 0);
124
205
  if (textBytes > MAX_TEXT_BYTES)
125
206
  fail("Text context is too large.");
@@ -130,14 +211,15 @@ export function serializeTextContext(input) {
130
211
  const systemInstruction = systemPrompt === undefined ? undefined : { role: "user", parts: [{ text: systemPrompt }] };
131
212
  const temperature = option(options, "temperature");
132
213
  const maxTokens = option(options, "maxTokens");
214
+ const sonarGrounding = shouldInjectSonarGoogleSearch(route.wireModel, options);
133
215
  const envelope = buildAntigravityEnvelope({
134
216
  wireModelId: route.wireModel,
135
217
  family: entry.response.family,
136
218
  contentsCount: contents.length,
137
- messages: isDenseArray(field(context, "messages", true)),
219
+ messages: normalized.messages,
138
220
  injectedRequestId: requestId,
139
221
  });
140
- return { project, model: route.wireModel, request: { contents, ...(systemInstruction ? { systemInstruction } : {}), generationConfig: {
222
+ return { project, model: route.wireModel, request: { contents, ...(systemInstruction ? { systemInstruction } : {}), ...(sonarGrounding ? { tools: [{ googleSearch: {} }] } : {}), generationConfig: {
141
223
  temperature: typeof temperature === "number" ? temperature : 1,
142
224
  maxOutputTokens: resolveOutputTokens(maxTokens, entry.descriptor.maxTokens, route.thinking),
143
225
  ...(() => {
@@ -152,16 +234,102 @@ export function serializeTextContext(input) {
152
234
  fail("Invalid text context.");
153
235
  }
154
236
  }
237
+ function normalizeContextRecord(context) {
238
+ const rawSystemPrompt = field(context, "systemPrompt");
239
+ const rawTools = field(context, "tools");
240
+ const rawMessages = isDenseArray(field(context, "messages", true));
241
+ const hasSystemMessage = rawMessages.some((message) => isRecord(message) && field(message, "role") === "system");
242
+ if (!hasSystemMessage) {
243
+ return { systemPrompt: rawSystemPrompt, tools: rawTools, messages: rawMessages };
244
+ }
245
+ if (rawSystemPrompt !== undefined && typeof rawSystemPrompt !== "string")
246
+ fail("Text-only context is required.");
247
+ const systemContentParts = [];
248
+ const sectionMap = new Map();
249
+ const toolMap = new Map();
250
+ if (rawTools !== undefined) {
251
+ for (const tool of isDenseArray(rawTools)) {
252
+ const name = isRecord(tool) ? field(tool, "name") : undefined;
253
+ toolMap.set(typeof name === "string" && name ? name : Symbol("tool"), tool);
254
+ }
255
+ }
256
+ const conversationMessages = [];
257
+ for (const message of rawMessages) {
258
+ if (!isRecord(message))
259
+ fail("Invalid text context.");
260
+ const role = field(message, "role", true);
261
+ if (role !== "system") {
262
+ conversationMessages.push(message);
263
+ continue;
264
+ }
265
+ const contentText = extractSystemMessageContent(field(message, "content", true));
266
+ if (contentText.length > 0)
267
+ systemContentParts.push(contentText);
268
+ const rawSections = field(message, "sections");
269
+ if (rawSections !== undefined) {
270
+ if (!isRecord(rawSections))
271
+ fail("Invalid text context.");
272
+ for (const sectionName of Object.keys(rawSections)) {
273
+ const sectionValue = field(rawSections, sectionName);
274
+ if (sectionValue === null)
275
+ sectionMap.delete(sectionName);
276
+ else if (typeof sectionValue === "string")
277
+ sectionMap.set(sectionName, sectionValue);
278
+ else
279
+ fail("Invalid text context.");
280
+ }
281
+ }
282
+ const rawRemoved = field(message, "toolsRemoved");
283
+ if (rawRemoved !== undefined) {
284
+ for (const ref of isDenseArray(rawRemoved)) {
285
+ if (!isRecord(ref))
286
+ fail("Invalid text context.");
287
+ const removedName = field(ref, "name", true);
288
+ if (typeof removedName !== "string" || !removedName)
289
+ fail("Invalid text context.");
290
+ toolMap.delete(removedName);
291
+ }
292
+ }
293
+ const rawAdded = field(message, "toolsAdded");
294
+ if (rawAdded !== undefined) {
295
+ for (const tool of isDenseArray(rawAdded)) {
296
+ const addedName = isRecord(tool) ? field(tool, "name") : undefined;
297
+ toolMap.set(typeof addedName === "string" && addedName ? addedName : Symbol("tool"), tool);
298
+ }
299
+ }
300
+ }
301
+ const basePrompt = systemContentParts.join("\n\n");
302
+ const transcriptPrompt = [basePrompt, ...sectionMap.values()].filter((part) => part.length > 0).join("\n\n");
303
+ const effectiveSystemPrompt = typeof rawSystemPrompt === "string"
304
+ ? [rawSystemPrompt, transcriptPrompt].filter((part) => part.length > 0).join("\n\n")
305
+ : (transcriptPrompt.length > 0 ? transcriptPrompt : undefined);
306
+ const effectiveTools = toolMap.size > 0 ? [...toolMap.values()] : (rawTools !== undefined ? [] : undefined);
307
+ return { systemPrompt: effectiveSystemPrompt, tools: effectiveTools, messages: conversationMessages };
308
+ }
309
+ function extractSystemMessageContent(content) {
310
+ if (typeof content === "string")
311
+ return content;
312
+ const parts = isDenseArray(content);
313
+ const texts = [];
314
+ for (const item of parts) {
315
+ if (!isRecord(item) || field(item, "type", true) !== "text")
316
+ fail("Only text context is supported by this provider.");
317
+ const text = field(item, "text", true);
318
+ if (typeof text !== "string")
319
+ fail("Only text context is supported by this provider.");
320
+ texts.push(text);
321
+ }
322
+ return texts.join("\n");
323
+ }
155
324
  function capabilityError(publicId, reasoning, capability) {
156
325
  const reason = capability.state === "disabled" ? capability.reason : capability.state;
157
326
  return `PI_TOOL_CAPABILITY_NOT_ENABLED: ${publicId}/${reasoning} is ${capability.state} (${reason}).`;
158
327
  }
159
- function isToolBearingContext(context) {
160
- const tools = field(context, "tools");
328
+ function isToolBearingNormalizedContext(context) {
329
+ const tools = context.tools;
161
330
  if (tools !== undefined && isDenseArray(tools).length > 0)
162
331
  return true;
163
- const messages = isDenseArray(field(context, "messages", true));
164
- for (const message of messages) {
332
+ for (const message of context.messages) {
165
333
  if (!isRecord(message))
166
334
  continue;
167
335
  if (field(message, "role") === "toolResult")
@@ -175,21 +343,46 @@ function isToolBearingContext(context) {
175
343
  }
176
344
  return false;
177
345
  }
178
- function messageParts(content, assistant, sameProviderAndModel) {
346
+ function messageParts(content, assistant, sameProviderAndModel, restore, allowMultimodal = true) {
179
347
  if (typeof content === "string")
180
348
  return content ? [{ text: content }] : fail("A text conversation is required.");
181
349
  const parts = isDenseArray(content);
182
350
  if (!parts.length)
183
351
  fail("A text conversation is required.");
184
- 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 } };
185
378
  }
186
- function messagePart(part, assistant, sameProviderAndModel) {
379
+ function messagePart(part, assistant, sameProviderAndModel, restore, allowMultimodal = true) {
187
380
  const type = field(part, "type", true);
188
381
  if (type === "text") {
189
382
  const text = field(part, "text", true);
190
383
  if (typeof text !== "string")
191
384
  fail("Only text context is supported by this provider.");
192
- const thoughtSignature = sameProviderAndModel ? validThoughtSignature(field(part, "textSignature")) : undefined;
385
+ const thoughtSignature = sameProviderAndModel ? validThoughtSignature(field(part, "textSignature"), restore?.allowSentinelFallback === true) : undefined;
193
386
  if (!text && !thoughtSignature)
194
387
  fail("Only text context is supported by this provider.");
195
388
  return { text, ...(thoughtSignature ? { thoughtSignature } : {}) };
@@ -198,7 +391,38 @@ function messagePart(part, assistant, sameProviderAndModel) {
198
391
  const text = field(part, "thinking", true);
199
392
  if (typeof text !== "string")
200
393
  fail("Only text context is supported by this provider.");
201
- 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
+ }
202
426
  if (!text && !thoughtSignature)
203
427
  fail("Only text context is supported by this provider.");
204
428
  return { thought: true, text, ...(thoughtSignature ? { thoughtSignature } : {}) };
@@ -209,17 +433,20 @@ function messagePart(part, assistant, sameProviderAndModel) {
209
433
  fail("Only text context is supported by this provider.");
210
434
  return { text };
211
435
  }
212
- if (type === "image") {
213
- const rawData = field(part, "data") ?? (isRecord(field(part, "source")) ? field(field(part, "source"), "data") : undefined);
214
- if (typeof rawData !== "string" || !rawData)
215
- fail("Invalid image data.");
216
- const rawMime = field(part, "mimeType") ?? (isRecord(field(part, "source")) ? field(field(part, "source"), "media_type") : undefined);
217
- const mimeType = typeof rawMime === "string" && rawMime ? rawMime : "image/jpeg";
218
- const cleanedData = rawData.replace(/^data:[^;]+;base64,/s, "").trim();
219
- 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);
220
440
  }
221
441
  fail("Only text context is supported by this provider.");
222
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
+ }
223
450
  function isSameProviderAndModel(message, publicId) {
224
451
  return field(message, "provider") === PROVIDER && field(message, "model") === publicId;
225
452
  }
@@ -248,11 +475,41 @@ function geminiRequiresSignedToolReplay(wireModel) {
248
475
  return Number(match[1]) >= 3;
249
476
  return true;
250
477
  }
251
- function validThoughtSignature(value) {
478
+ function validThoughtSignature(value, allowSentinel = false) {
479
+ if (allowSentinel && value === SKIP_THOUGHT_SIGNATURE)
480
+ return SKIP_THOUGHT_SIGNATURE;
252
481
  if (typeof value !== "string" || !value || value.length % 4 !== 0)
253
482
  return undefined;
254
483
  return /^[A-Za-z0-9+/]+={0,2}$/.test(value) ? value : undefined;
255
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
+ }
256
513
  function validateOptions(options, maxAllowedTokens) {
257
514
  if (options === undefined)
258
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
  };