antigravity-plugin-context-mode 1.1.0 → 1.3.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.
@@ -6,10 +6,23 @@ import { ContextModeStore } from "../lib/store.js";
6
6
  export const DEFAULT_MAX_READ_BYTES = 8192; // 8 KB default cutoff
7
7
  export const DEFAULT_MAX_LINE_RANGE = 200; // 200 lines max un-indexed slice
8
8
 
9
+ function isProtectionPaused(sessionId = null) {
10
+ try {
11
+ const store = new ContextModeStore();
12
+ const paused = store.isPaused(sessionId);
13
+ store.close();
14
+ return paused;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
9
20
  function getMaxReadBytes(sessionId = null) {
10
21
  try {
11
22
  const store = new ContextModeStore();
12
- return store.getCutoff(sessionId);
23
+ const cutoff = store.getCutoff(sessionId);
24
+ store.close();
25
+ return cutoff;
13
26
  } catch {
14
27
  const envVal = process.env.CONTEXT_MODE_MAX_READ_BYTES;
15
28
  if (envVal) {
@@ -23,7 +36,9 @@ function getMaxReadBytes(sessionId = null) {
23
36
  function getExemptExtensions(sessionId = null) {
24
37
  try {
25
38
  const store = new ContextModeStore();
26
- return store.getExemptExtensions(sessionId);
39
+ const exts = store.getExemptExtensions(sessionId);
40
+ store.close();
41
+ return exts;
27
42
  } catch {
28
43
  return Array.from(BINARY_EXTENSIONS);
29
44
  }
@@ -49,6 +64,66 @@ function formatBytes(bytes) {
49
64
  return `${Number.isInteger(mb) ? mb : mb.toFixed(2)} MB`;
50
65
  }
51
66
 
67
+ export function cleanStringArg(val) {
68
+ if (val === undefined || val === null) return "";
69
+ let str = String(val).trim();
70
+ while (
71
+ (str.startsWith('"') && str.endsWith('"') && str.length >= 2) ||
72
+ (str.startsWith("'") && str.endsWith("'") && str.length >= 2)
73
+ ) {
74
+ str = str.slice(1, -1).trim();
75
+ }
76
+ return str;
77
+ }
78
+
79
+ export function cleanFilePath(val) {
80
+ let p = cleanStringArg(val);
81
+ if (!p) return "";
82
+ // Strip file URI prefix
83
+ if (p.startsWith("file:///")) {
84
+ p = p.slice(8);
85
+ } else if (p.startsWith("file://")) {
86
+ p = p.slice(7);
87
+ }
88
+ try {
89
+ p = decodeURIComponent(p);
90
+ } catch {}
91
+ // Strip trailing line anchor (e.g. #L1-L20)
92
+ p = p.replace(/#L\d+(-L\d+)?$/i, "");
93
+ // Normalize Windows slashes
94
+ return path.normalize(p.trim());
95
+ }
96
+
97
+ export function parseLineArg(val) {
98
+ if (val === undefined || val === null) return null;
99
+ const str = cleanStringArg(val);
100
+ if (!str || str.toLowerCase() === "null" || str.toLowerCase() === "undefined") {
101
+ return null;
102
+ }
103
+ const parsed = parseInt(str, 10);
104
+ return Number.isNaN(parsed) ? null : parsed;
105
+ }
106
+
107
+ const KNOWN_TEXT_EXTENSIONS = new Set([
108
+ // Markdown & Documentation
109
+ ".md", ".markdown", ".mdown", ".mkd", ".rst", ".adoc",
110
+ // Code
111
+ ".cs", ".csx",
112
+ ".js", ".jsx", ".mjs", ".cjs",
113
+ ".ts", ".tsx", ".mts", ".cts",
114
+ ".py", ".pyw",
115
+ ".c", ".h", ".cpp", ".hpp", ".cc", ".cxx", ".hh",
116
+ ".rs", ".go", ".java", ".kt", ".kts", ".scala",
117
+ ".rb", ".php", ".sh", ".bash", ".ps1", ".psm1", ".psd1",
118
+ ".bat", ".cmd",
119
+ // Web & Config
120
+ ".html", ".htm", ".xhtml", ".css", ".scss", ".sass", ".less",
121
+ ".json", ".jsonc", ".json5",
122
+ ".xml", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf",
123
+ ".sql", ".graphql", ".gql",
124
+ ".diff", ".patch", ".txt", ".text", ".log", ".csv", ".tsv"
125
+ ]);
126
+
52
127
  const BINARY_EXTENSIONS = new Set([
53
128
  // Documents & Office
54
129
  ".pdf", ".docx", ".doc", ".xlsx", ".xls", ".pptx", ".ppt",
@@ -72,7 +147,11 @@ function isUserAttachedFile(filePath, absPath) {
72
147
  }
73
148
 
74
149
  function isBinaryFile(absPath, ext) {
75
- if (BINARY_EXTENSIONS.has((ext || "").toLowerCase())) {
150
+ const lowerExt = (ext || "").toLowerCase();
151
+ if (KNOWN_TEXT_EXTENSIONS.has(lowerExt)) {
152
+ return false;
153
+ }
154
+ if (BINARY_EXTENSIONS.has(lowerExt)) {
76
155
  return true;
77
156
  }
78
157
  try {
@@ -82,6 +161,15 @@ function isBinaryFile(absPath, ext) {
82
161
  fs.closeSync(fd);
83
162
  if (bytesRead === 0) return false;
84
163
 
164
+ // Check for UTF-16 LE BOM (FF FE) or BE BOM (FE FF)
165
+ if (bytesRead >= 2 && ((buf[0] === 0xff && buf[1] === 0xfe) || (buf[0] === 0xfe && buf[1] === 0xff))) {
166
+ return false; // Text file with UTF-16 BOM
167
+ }
168
+ // Check for UTF-8 BOM (EF BB BF)
169
+ if (bytesRead >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf) {
170
+ return false;
171
+ }
172
+
85
173
  // Check for PDF magic header (%PDF)
86
174
  if (bytesRead >= 4 && buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46) {
87
175
  return true;
@@ -97,6 +185,59 @@ function isBinaryFile(absPath, ext) {
97
185
  return false;
98
186
  }
99
187
 
188
+ export function resolveSharedSessionId(payload = {}) {
189
+ return (
190
+ payload.rootConversationId ||
191
+ payload.root_conversation_id ||
192
+ payload.parentConversationId ||
193
+ payload.parent_conversation_id ||
194
+ process.env.ANTIGRAVITY_ROOT_CONVERSATION_ID ||
195
+ process.env.ANTIGRAVITY_PARENT_CONVERSATION_ID ||
196
+ process.env.ANTIGRAVITY_CONVERSATION_ID ||
197
+ payload.conversationId ||
198
+ payload.conversation_id ||
199
+ payload.sessionId ||
200
+ payload.session_id ||
201
+ "default"
202
+ );
203
+ }
204
+
205
+ export function resolveAgentName(payload = {}) {
206
+ return (
207
+ payload.agent ||
208
+ payload.agentName ||
209
+ payload.agent_name ||
210
+ payload.agentType ||
211
+ payload.agent_type ||
212
+ payload.role ||
213
+ (payload.subagent ? "subagent" : "antigravity")
214
+ );
215
+ }
216
+
217
+ function recordInterception({ sessionId, agent, cwd, toolName, path: targetPath, size, reason }) {
218
+ try {
219
+ const store = new ContextModeStore();
220
+ store.recordEvent({
221
+ sessionId: sessionId || "default",
222
+ worktree: cwd || process.cwd(),
223
+ agent: agent || "antigravity",
224
+ kind: "interception",
225
+ tool: toolName,
226
+ key: "blocked",
227
+ path: targetPath || null,
228
+ ok: 0,
229
+ exitCode: 1,
230
+ bytes: size || 0,
231
+ body: reason,
232
+ sandboxBytes: size || 0,
233
+ returnedBytes: 0
234
+ });
235
+ store.close();
236
+ } catch {
237
+ // Non-blocking: database recording failure must never crash the hook
238
+ }
239
+ }
240
+
100
241
  function readStdin() {
101
242
  return new Promise((resolve) => {
102
243
  let data = "";
@@ -110,13 +251,144 @@ function readStdin() {
110
251
  });
111
252
  }
112
253
 
113
- const UNBOUNDED_COMMAND_PATTERNS = [
114
- /^\s*(cat|type|Get-Content)\s+.*?\.(log|json|xml|csv|tsv|dump|sql|txt)\s*$/i,
115
- /^\s*git\s+log\s*$/i,
116
- /^\s*git\s+log\s+--oneline\s*$/i,
117
- /^\s*curl(\.exe)?\s+-s?\s+https?:\/\/.*?\.(json|log|txt)\s*$/i
254
+ // Kept for backward compatibility
255
+ export const UNBOUNDED_COMMAND_PATTERNS = [
256
+ /^\s*(cat|type|Get-Content|gc)\b/i,
257
+ /^\s*git\s+log\b/i,
258
+ /^\s*(curl|wget)\b/i
118
259
  ];
119
260
 
261
+ /**
262
+ * Dynamically inspects shell commands against active SQLite cutoff and user exemptions
263
+ * without relying on a static hardcoded file extension whitelist.
264
+ */
265
+ export function inspectCommand({ commandLine, cwd, sessionId }) {
266
+ if (!commandLine || typeof commandLine !== "string") {
267
+ return { shouldDeny: false };
268
+ }
269
+
270
+ const cleanCmd = cleanStringArg(commandLine);
271
+ const maxReadBytes = getMaxReadBytes(sessionId);
272
+ const exemptExtensions = getExemptExtensions(sessionId);
273
+
274
+ // 1. Git log without count limiter
275
+ if (/^\s*git\s+log\b/i.test(cleanCmd)) {
276
+ const isLimited = /(-n\s+\d+|-\d+|--max-count|\s*\|\s*(head|Select-Object|select|more))/i.test(cleanCmd);
277
+ if (!isLimited) {
278
+ return {
279
+ shouldDeny: true,
280
+ reason:
281
+ `[context-mode protection] 'git log' without a count limiter risks dumping thousands of commits into context. ` +
282
+ `Please specify a count (e.g. 'git log -n 10') or run inside 'mcp_context-mode_ctx_execute'.`,
283
+ size: 32768,
284
+ targetPath: "git log"
285
+ };
286
+ }
287
+ }
288
+
289
+ // 2. Direct curl / wget to stdout without file destination or limiter
290
+ if (/^\s*(curl(\.exe)?|wget(\.exe)?)\b/i.test(cleanCmd)) {
291
+ const writesToFile = /(-o\s+|-O\s+|--output\s+|>)/i.test(cleanCmd);
292
+ const hasLimiter = /\|\s*(head|Select-Object|select|more)/i.test(cleanCmd);
293
+ if (!writesToFile && !hasLimiter) {
294
+ // Allow if downloading a file with an exempt extension (e.g. images, media, office docs)
295
+ const urlMatch = cleanCmd.match(/https?:\/\/[^\s"']+/i);
296
+ if (urlMatch) {
297
+ try {
298
+ const parsedUrl = new URL(urlMatch[0]);
299
+ const ext = path.extname(parsedUrl.pathname).toLowerCase();
300
+ if (ext && exemptExtensions.includes(ext)) {
301
+ return { shouldDeny: false };
302
+ }
303
+ } catch {}
304
+ }
305
+
306
+ return {
307
+ shouldDeny: true,
308
+ reason:
309
+ `[context-mode protection] Direct curl/wget download to stdout risks flooding the context window. ` +
310
+ `Please use 'mcp_context-mode_ctx_execute', save to disk ('-o <file>'), or append '| head -n 50'.`,
311
+ size: 32768,
312
+ targetPath: urlMatch ? urlMatch[0] : cleanCmd
313
+ };
314
+ }
315
+ }
316
+
317
+ // 3. Raw file dump utilities (cat, type, Get-Content, gc)
318
+ const printMatch = cleanCmd.match(/^\s*(cat|type|Get-Content|gc)(\.exe)?\b/i);
319
+ if (printMatch) {
320
+ // Allow if command includes pagination flags or piping to limiters / file sinks
321
+ const hasLimiter =
322
+ /(-Head|-TotalCount|-First|-Tail)\s+\d+/i.test(cleanCmd) ||
323
+ /\|\s*(head|Select-Object|select\s+(-[a-zA-Z]+\s+)*-First|more|Out-Null|Set-Content|Out-File)/i.test(cleanCmd) ||
324
+ />\s*[^>]/i.test(cleanCmd);
325
+
326
+ if (hasLimiter) {
327
+ return { shouldDeny: false };
328
+ }
329
+
330
+ // Extract target argument
331
+ const argMatch = cleanCmd.match(/(?:cat|type|Get-Content|gc)(?:\.exe)?(?:\s+(?:-Path|-LiteralPath))?\s+["']?([^"'\r\n;|]+)["']?/i);
332
+ const rawTarget = argMatch && argMatch[1] ? argMatch[1].trim() : "";
333
+
334
+ // Wildcard dump (e.g. cat *.log, Get-Content *)
335
+ if (rawTarget.includes("*") || rawTarget.includes("?")) {
336
+ return {
337
+ shouldDeny: true,
338
+ reason:
339
+ `[context-mode protection] Wildcard file dump ('${rawTarget}') risks flooding the context window. ` +
340
+ `Please use 'mcp_context-mode_ctx_execute' or append a limiter such as '| Select-Object -First 50'.`,
341
+ size: 32768,
342
+ targetPath: rawTarget
343
+ };
344
+ }
345
+
346
+ if (rawTarget) {
347
+ const cleanTarget = cleanFilePath(rawTarget);
348
+ const absPath = path.isAbsolute(cleanTarget) ? cleanTarget : path.resolve(cwd, cleanTarget);
349
+
350
+ try {
351
+ if (fs.existsSync(absPath)) {
352
+ const ext = path.extname(absPath).toLowerCase();
353
+ // Dynamic exemption check from SQLite/Dashboard configuration
354
+ if (ext && exemptExtensions.includes(ext)) {
355
+ return { shouldDeny: false };
356
+ }
357
+
358
+ const stat = fs.statSync(absPath);
359
+ // Dynamic cutoff check against active setting
360
+ if (maxReadBytes > 0 && stat.size > maxReadBytes) {
361
+ return {
362
+ shouldDeny: true,
363
+ reason:
364
+ `[context-mode protection] Command attempts an un-paged dump of '${cleanTarget}' (${formatBytes(stat.size)}), ` +
365
+ `exceeding the ${formatBytes(maxReadBytes)} context limit. ` +
366
+ `Please use 'mcp_context-mode_ctx_execute' or append '| Select-Object -First 50' or '-Head 50'.`,
367
+ size: stat.size,
368
+ targetPath: cleanTarget
369
+ };
370
+ }
371
+
372
+ // File is small and within cutoff
373
+ return { shouldDeny: false };
374
+ }
375
+ } catch {}
376
+
377
+ // If file doesn't exist on disk or path cannot be resolved, block unpaged dump defensively
378
+ return {
379
+ shouldDeny: true,
380
+ reason:
381
+ `[context-mode protection] Command matches an un-paged file dump ('${rawTarget}') that could flood the context window. ` +
382
+ `Please use 'mcp_context-mode_ctx_execute' or append a limiter such as '| Select-Object -First 50' or '| head -n 50'.`,
383
+ size: 32768,
384
+ targetPath: cleanTarget || rawTarget
385
+ };
386
+ }
387
+ }
388
+
389
+ return { shouldDeny: false };
390
+ }
391
+
120
392
  async function main() {
121
393
  const rawInput = await readStdin();
122
394
  if (!rawInput.trim()) {
@@ -136,18 +408,21 @@ async function main() {
136
408
  const toolName = toolCall.name || "";
137
409
  const args = toolCall.args || {};
138
410
  const cwd = payload.cwd || process.cwd();
139
- const sessionId =
140
- payload.sessionId ||
141
- payload.session_id ||
142
- payload.conversationId ||
143
- process.env.ANTIGRAVITY_CONVERSATION_ID ||
144
- null;
411
+ const sessionId = resolveSharedSessionId(payload);
412
+ const agentName = resolveAgentName(payload);
413
+
414
+ // If Context Mode protection is paused, allow all tool calls through without interception
415
+ if (isProtectionPaused(sessionId)) {
416
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
417
+ process.exit(0);
418
+ }
145
419
 
146
- // 1. Guard read_file
147
- if (toolName === "read_file") {
148
- const filePath = args.Path || args.path || args.filePath || "";
149
- const startLine = args.StartLine ?? args.startLine ?? 1;
150
- const endLine = args.EndLine ?? args.endLine ?? null;
420
+ // 1. Guard read_file / view_file
421
+ if (toolName === "read_file" || toolName === "view_file") {
422
+ const rawFilePath = args.Path || args.path || args.filePath || "";
423
+ const filePath = cleanFilePath(rawFilePath);
424
+ const startLine = parseLineArg(args.StartLine ?? args.startLine) ?? 1;
425
+ const endLine = parseLineArg(args.EndLine ?? args.endLine);
151
426
  const maxReadBytes = getMaxReadBytes(sessionId);
152
427
  const maxLineRange = getMaxLineRange(maxReadBytes);
153
428
 
@@ -156,7 +431,7 @@ async function main() {
156
431
  try {
157
432
  if (fs.existsSync(absPath)) {
158
433
  const ext = path.extname(absPath).toLowerCase();
159
- const isUserAttachment = isUserAttachedFile(filePath, absPath);
434
+ const isUserAttachment = isUserAttachedFile(rawFilePath, absPath);
160
435
  const exemptExtensions = getExemptExtensions(sessionId);
161
436
  const isExemptExt = exemptExtensions.includes(ext);
162
437
  const isBinary = isBinaryFile(absPath, ext);
@@ -169,7 +444,7 @@ async function main() {
169
444
 
170
445
  const stat = fs.statSync(absPath);
171
446
  const isLargeFile = maxReadBytes > 0 && stat.size > maxReadBytes;
172
- const isWideRange = maxLineRange > 0 && (endLine === null || endLine - startLine > maxLineRange);
447
+ const isWideRange = maxLineRange > 0 && (endLine === null || (endLine - startLine) > maxLineRange);
173
448
 
174
449
  if (isLargeFile && isWideRange) {
175
450
  const lineInstruction = maxLineRange > 0 ? ` or provide a tight StartLine/EndLine range (<= ${maxLineRange} lines).` : "";
@@ -178,13 +453,24 @@ async function main() {
178
453
  `Reading the entire file risks severe context bloat. ` +
179
454
  `Please use 'mcp_context-mode_ctx_index(path: "${filePath}")' followed by 'mcp_context-mode_ctx_search'${lineInstruction}`;
180
455
 
456
+ // Record interception event in SQLite store so dashboard telemetry updates immediately
457
+ recordInterception({
458
+ sessionId,
459
+ agent: agentName,
460
+ cwd,
461
+ toolName,
462
+ path: filePath,
463
+ size: stat.size,
464
+ reason
465
+ });
466
+
181
467
  process.stdout.write(
182
468
  JSON.stringify({
183
469
  decision: "deny",
184
470
  reason
185
471
  }) + "\n"
186
472
  );
187
- return;
473
+ process.exit(0);
188
474
  }
189
475
  }
190
476
  } catch {
@@ -195,29 +481,40 @@ async function main() {
195
481
 
196
482
  // 2. Guard run_command
197
483
  if (toolName === "run_command") {
198
- const commandLine = args.CommandLine || args.commandLine || args.command || "";
199
- for (const pattern of UNBOUNDED_COMMAND_PATTERNS) {
200
- if (pattern.test(commandLine)) {
201
- const reason =
202
- `[context-mode protection] Command matches an unbounded dump pattern that could flood the context window. ` +
203
- `Please use 'mcp_context-mode_ctx_execute' (runs in local sandbox with token bounding) or append a limiter ` +
204
- `such as '| Select-Object -First 50' or '| head -n 50'.`;
205
-
206
- process.stdout.write(
207
- JSON.stringify({
208
- decision: "deny",
209
- reason
210
- }) + "\n"
211
- );
212
- return;
213
- }
484
+ const rawCommandLine = args.CommandLine || args.commandLine || args.command || "";
485
+ const inspection = inspectCommand({
486
+ commandLine: rawCommandLine,
487
+ cwd,
488
+ sessionId
489
+ });
490
+
491
+ if (inspection.shouldDeny) {
492
+ recordInterception({
493
+ sessionId,
494
+ agent: agentName,
495
+ cwd,
496
+ toolName,
497
+ path: inspection.targetPath || cleanStringArg(rawCommandLine),
498
+ size: inspection.size || 32768,
499
+ reason: inspection.reason
500
+ });
501
+
502
+ process.stdout.write(
503
+ JSON.stringify({
504
+ decision: "deny",
505
+ reason: inspection.reason
506
+ }) + "\n"
507
+ );
508
+ process.exit(0);
214
509
  }
215
510
  }
216
511
 
217
512
  // Default allow
218
513
  process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
514
+ process.exit(0);
219
515
  }
220
516
 
221
517
  main().catch(() => {
222
518
  process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
519
+ process.exit(0);
223
520
  });
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { ContextModeStore } from "../lib/store.js";
2
3
 
3
4
  function readStdin() {
4
5
  return new Promise((resolve) => {
@@ -16,6 +17,12 @@ function readStdin() {
16
17
  async function main() {
17
18
  await readStdin();
18
19
 
20
+ try {
21
+ const store = new ContextModeStore();
22
+ store.clearSessionOverrides();
23
+ store.close();
24
+ } catch {}
25
+
19
26
  const response = {
20
27
  injectSteps: [
21
28
  {
package/hooks.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "context-mode": {
3
3
  "PreToolUse": [
4
4
  {
5
- "matcher": "run_command|read_file",
5
+ "matcher": "run_command|read_file|view_file",
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",