@benjamolina/pi-antigravity-guard 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/context.js CHANGED
@@ -9,7 +9,7 @@ const THINKING_LEVELS = ["minimal", "low", "medium", "high", "xhigh"];
9
9
  const PI_HARNESS_MARKER = "operating inside pi, a coding agent harness";
10
10
  export class ContextSerializationError extends Error {
11
11
  }
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;
12
+ 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
13
  export function sanitizeAntigravitySystemPrompt(systemPrompt) {
14
14
  if (!systemPrompt.includes(PI_HARNESS_MARKER))
15
15
  return systemPrompt;
@@ -40,10 +40,19 @@ export function serializeContext(input, injectedSelection, onDiagnostics) {
40
40
  fail("Invalid tool capability selection.");
41
41
  if (selection.tools.state !== "enabled")
42
42
  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;
43
+ const normalized = normalizeContextRecord(context);
44
+ const prepared = prepareToolContext(normalized.tools ?? [], isRecord(options) ? field(options, "toolChoice") : undefined, selection.tools.schemaProfile);
45
+ const { tools: _tools, messages: _messages, systemPrompt: _systemPrompt, ...textContext } = context;
45
46
  const { toolChoice: _choice, ...textOptions } = isRecord(options) ? options : {};
46
- const text = serializeTextContext({ ...input, context: { ...textContext, messages: [{ role: "user", content: "placeholder", timestamp: 0 }] }, options: textOptions });
47
+ const text = serializeTextContext({
48
+ ...input,
49
+ context: {
50
+ ...textContext,
51
+ ...(normalized.systemPrompt !== undefined ? { systemPrompt: normalized.systemPrompt } : {}),
52
+ messages: [{ role: "user", content: "placeholder", timestamp: 0 }],
53
+ },
54
+ options: textOptions,
55
+ });
47
56
  const sameModel = (message) => field(message, "role") === "assistant" && entry.replay.kind === "same-public-model" && isSameProviderAndModel(message, entry.publicId);
48
57
  const requireSigned = geminiRequiresSignedToolReplay(selection.route.wireModel);
49
58
  const includeToolCallId = entry.response.family === "claude" || entry.response.family === "gpt-oss";
@@ -53,13 +62,13 @@ export function serializeContext(input, injectedSelection, onDiagnostics) {
53
62
  toolCallSignature: (part, message) => sameModel(message) ? validThoughtSignature(field(part, "thoughtSignature")) : undefined,
54
63
  includeToolCallId,
55
64
  } : undefined;
56
- const contents = replayToolHistory(isDenseArray(messages), (part, message) => messagePart(part, field(message, "role") === "assistant", sameModel(message)), onDiagnostics, toolReplayPolicy, prepared?.declarations.length ?? 0);
65
+ const contents = replayToolHistory(normalized.messages, (part, message) => messagePart(part, field(message, "role") === "assistant", sameModel(message)), onDiagnostics, toolReplayPolicy, prepared?.declarations.length ?? 0);
57
66
  const { systemInstruction, generationConfig } = text.request;
58
67
  const envelope = buildAntigravityEnvelope({
59
68
  wireModelId: selection.route.wireModel,
60
69
  family: entry.response.family,
61
70
  contentsCount: contents.length,
62
- messages: isDenseArray(messages),
71
+ messages: normalized.messages,
63
72
  injectedRequestId: input.requestId,
64
73
  });
65
74
  return { ...text, request: {
@@ -98,10 +107,11 @@ export function serializeTextContext(input) {
98
107
  fail("Invalid text context.");
99
108
  const selection = resolveGenerationSelection(entry, option(options, "reasoning"));
100
109
  const route = selection.route;
101
- if (isToolBearingContext(context) && selection.tools.state !== "enabled")
110
+ const normalized = normalizeContextRecord(context);
111
+ if (isToolBearingNormalizedContext(normalized) && selection.tools.state !== "enabled")
102
112
  fail(capabilityError(entry.publicId, selection.level, selection.tools));
103
- const rawSystemPrompt = field(context, "systemPrompt");
104
- const tools = field(context, "tools");
113
+ const rawSystemPrompt = normalized.systemPrompt;
114
+ const tools = normalized.tools;
105
115
  if (rawSystemPrompt !== undefined && typeof rawSystemPrompt !== "string")
106
116
  fail("Text-only context is required.");
107
117
  if (tools !== undefined && isDenseArray(tools).length)
@@ -110,7 +120,7 @@ export function serializeTextContext(input) {
110
120
  const systemPrompt = rawSystemPrompt === undefined ? undefined : sanitizeAntigravitySystemPrompt(rawSystemPrompt);
111
121
  let textBytes = byteLength(systemPrompt ?? "");
112
122
  const contents = [];
113
- for (const message of isDenseArray(field(context, "messages", true))) {
123
+ for (const message of normalized.messages) {
114
124
  if (!isRecord(message))
115
125
  fail("Invalid text context.");
116
126
  const role = field(message, "role", true);
@@ -134,7 +144,7 @@ export function serializeTextContext(input) {
134
144
  wireModelId: route.wireModel,
135
145
  family: entry.response.family,
136
146
  contentsCount: contents.length,
137
- messages: isDenseArray(field(context, "messages", true)),
147
+ messages: normalized.messages,
138
148
  injectedRequestId: requestId,
139
149
  });
140
150
  return { project, model: route.wireModel, request: { contents, ...(systemInstruction ? { systemInstruction } : {}), generationConfig: {
@@ -152,16 +162,102 @@ export function serializeTextContext(input) {
152
162
  fail("Invalid text context.");
153
163
  }
154
164
  }
165
+ function normalizeContextRecord(context) {
166
+ const rawSystemPrompt = field(context, "systemPrompt");
167
+ const rawTools = field(context, "tools");
168
+ const rawMessages = isDenseArray(field(context, "messages", true));
169
+ const hasSystemMessage = rawMessages.some((message) => isRecord(message) && field(message, "role") === "system");
170
+ if (!hasSystemMessage) {
171
+ return { systemPrompt: rawSystemPrompt, tools: rawTools, messages: rawMessages };
172
+ }
173
+ if (rawSystemPrompt !== undefined && typeof rawSystemPrompt !== "string")
174
+ fail("Text-only context is required.");
175
+ const systemContentParts = [];
176
+ const sectionMap = new Map();
177
+ const toolMap = new Map();
178
+ if (rawTools !== undefined) {
179
+ for (const tool of isDenseArray(rawTools)) {
180
+ const name = isRecord(tool) ? field(tool, "name") : undefined;
181
+ toolMap.set(typeof name === "string" && name ? name : Symbol("tool"), tool);
182
+ }
183
+ }
184
+ const conversationMessages = [];
185
+ for (const message of rawMessages) {
186
+ if (!isRecord(message))
187
+ fail("Invalid text context.");
188
+ const role = field(message, "role", true);
189
+ if (role !== "system") {
190
+ conversationMessages.push(message);
191
+ continue;
192
+ }
193
+ const contentText = extractSystemMessageContent(field(message, "content", true));
194
+ if (contentText.length > 0)
195
+ systemContentParts.push(contentText);
196
+ const rawSections = field(message, "sections");
197
+ if (rawSections !== undefined) {
198
+ if (!isRecord(rawSections))
199
+ fail("Invalid text context.");
200
+ for (const sectionName of Object.keys(rawSections)) {
201
+ const sectionValue = field(rawSections, sectionName);
202
+ if (sectionValue === null)
203
+ sectionMap.delete(sectionName);
204
+ else if (typeof sectionValue === "string")
205
+ sectionMap.set(sectionName, sectionValue);
206
+ else
207
+ fail("Invalid text context.");
208
+ }
209
+ }
210
+ const rawRemoved = field(message, "toolsRemoved");
211
+ if (rawRemoved !== undefined) {
212
+ for (const ref of isDenseArray(rawRemoved)) {
213
+ if (!isRecord(ref))
214
+ fail("Invalid text context.");
215
+ const removedName = field(ref, "name", true);
216
+ if (typeof removedName !== "string" || !removedName)
217
+ fail("Invalid text context.");
218
+ toolMap.delete(removedName);
219
+ }
220
+ }
221
+ const rawAdded = field(message, "toolsAdded");
222
+ if (rawAdded !== undefined) {
223
+ for (const tool of isDenseArray(rawAdded)) {
224
+ const addedName = isRecord(tool) ? field(tool, "name") : undefined;
225
+ toolMap.set(typeof addedName === "string" && addedName ? addedName : Symbol("tool"), tool);
226
+ }
227
+ }
228
+ }
229
+ const basePrompt = systemContentParts.join("\n\n");
230
+ const transcriptPrompt = [basePrompt, ...sectionMap.values()].filter((part) => part.length > 0).join("\n\n");
231
+ const effectiveSystemPrompt = typeof rawSystemPrompt === "string"
232
+ ? [rawSystemPrompt, transcriptPrompt].filter((part) => part.length > 0).join("\n\n")
233
+ : (transcriptPrompt.length > 0 ? transcriptPrompt : undefined);
234
+ const effectiveTools = toolMap.size > 0 ? [...toolMap.values()] : (rawTools !== undefined ? [] : undefined);
235
+ return { systemPrompt: effectiveSystemPrompt, tools: effectiveTools, messages: conversationMessages };
236
+ }
237
+ function extractSystemMessageContent(content) {
238
+ if (typeof content === "string")
239
+ return content;
240
+ const parts = isDenseArray(content);
241
+ const texts = [];
242
+ for (const item of parts) {
243
+ if (!isRecord(item) || field(item, "type", true) !== "text")
244
+ fail("Only text context is supported by this provider.");
245
+ const text = field(item, "text", true);
246
+ if (typeof text !== "string")
247
+ fail("Only text context is supported by this provider.");
248
+ texts.push(text);
249
+ }
250
+ return texts.join("\n");
251
+ }
155
252
  function capabilityError(publicId, reasoning, capability) {
156
253
  const reason = capability.state === "disabled" ? capability.reason : capability.state;
157
254
  return `PI_TOOL_CAPABILITY_NOT_ENABLED: ${publicId}/${reasoning} is ${capability.state} (${reason}).`;
158
255
  }
159
- function isToolBearingContext(context) {
160
- const tools = field(context, "tools");
256
+ function isToolBearingNormalizedContext(context) {
257
+ const tools = context.tools;
161
258
  if (tools !== undefined && isDenseArray(tools).length > 0)
162
259
  return true;
163
- const messages = isDenseArray(field(context, "messages", true));
164
- for (const message of messages) {
260
+ for (const message of context.messages) {
165
261
  if (!isRecord(message))
166
262
  continue;
167
263
  if (field(message, "role") === "toolResult")
@@ -8,14 +8,48 @@ export function hasToolContext(context) {
8
8
  if (Array.isArray(tools) && tools.length > 0)
9
9
  return true;
10
10
  const messages = value(context, "messages");
11
- return Array.isArray(messages) && messages.some((message) => {
11
+ if (!Array.isArray(messages))
12
+ return false;
13
+ const activeTools = new Map();
14
+ for (let index = 0; index < messages.length; index++) {
15
+ const descriptor = Object.getOwnPropertyDescriptor(messages, String(index));
16
+ if (!descriptor || !("value" in descriptor))
17
+ continue;
18
+ const message = descriptor.value;
12
19
  if (!isRecord(message))
13
- return false;
14
- if (value(message, "role") === "toolResult")
20
+ continue;
21
+ const role = value(message, "role");
22
+ if (role === "toolResult")
15
23
  return true;
24
+ if (role === "system") {
25
+ const removed = value(message, "toolsRemoved");
26
+ if (Array.isArray(removed)) {
27
+ for (let r = 0; r < removed.length; r++) {
28
+ const rd = Object.getOwnPropertyDescriptor(removed, String(r));
29
+ const item = rd && "value" in rd ? rd.value : undefined;
30
+ const name = isRecord(item) ? value(item, "name") : undefined;
31
+ if (typeof name === "string" && name)
32
+ activeTools.delete(name);
33
+ }
34
+ }
35
+ const added = value(message, "toolsAdded");
36
+ if (Array.isArray(added)) {
37
+ for (let a = 0; a < added.length; a++) {
38
+ const ad = Object.getOwnPropertyDescriptor(added, String(a));
39
+ if (!ad || !("value" in ad))
40
+ continue;
41
+ const item = ad.value;
42
+ const name = isRecord(item) ? value(item, "name") : undefined;
43
+ activeTools.set(typeof name === "string" && name ? name : Symbol("tool"), item);
44
+ }
45
+ }
46
+ continue;
47
+ }
16
48
  const content = value(message, "content");
17
- return Array.isArray(content) && content.some((part) => isRecord(part) && value(part, "type") === "toolCall");
18
- });
49
+ if (Array.isArray(content) && content.some((part) => isRecord(part) && value(part, "type") === "toolCall"))
50
+ return true;
51
+ }
52
+ return activeTools.size > 0;
19
53
  }
20
54
  export function prepareToolContext(tools, choice, schemaProfile) {
21
55
  if (schemaProfile !== GEMINI_PARAMETERS_JSON_SCHEMA_PROFILE && schemaProfile !== CLAUDE_CUSTOM_PARAMETERS_PROFILE)
@@ -32,7 +32,7 @@ function normalizeDeclaration(value, index, names) {
32
32
  if (typeof description !== "string" || !description.trim())
33
33
  fail("PI_TOOL_DECLARATION_INVALID", name, `${path}.description`);
34
34
  const constrainedSampling = ownData(tool, "constrainedSampling", name, path);
35
- if (constrainedSampling !== undefined && constrainedSampling !== false)
35
+ if (!isAdmittedConstrainedSampling(constrainedSampling, name, `${path}.constrainedSampling`))
36
36
  fail("PI_TOOL_CONSTRAINED_SAMPLING_UNSUPPORTED", name, `${path}.constrainedSampling`);
37
37
  const root = plainObject(ownData(tool, "parameters", name, path), name, "$");
38
38
  if (ownData(root, "type", name, "$") !== "object")
@@ -47,6 +47,14 @@ function normalizeDeclaration(value, index, names) {
47
47
  fail("PI_TOOL_SCHEMA_LIMIT", name, "$");
48
48
  return freeze({ name, description, parameters });
49
49
  }
50
+ function isAdmittedConstrainedSampling(value, declaration, path) {
51
+ if (value === undefined || value === false)
52
+ return true;
53
+ if (typeof value !== "object" || value === null || Array.isArray(value))
54
+ return false;
55
+ const config = plainObject(value, declaration, path);
56
+ return ownData(config, "type", declaration, path) === "json_schema" && ownData(config, "strict", declaration, path) === "prefer";
57
+ }
50
58
  function snapshotJson(value, declaration, path, state, depth = 0) {
51
59
  if (depth > MAX_SCHEMA_DEPTH || ++state.nodes > MAX_SCHEMA_NODES)
52
60
  fail("PI_TOOL_SCHEMA_LIMIT", declaration, path);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@benjamolina/pi-antigravity-guard",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Pi adapter for Antigravity Guard",
5
5
  "type": "module",
6
6
  "license": "MIT",