antigravity-plugin-context-mode 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  All notable changes to `antigravity-plugin-context-mode` will be documented in this file.
4
4
 
5
+ ## [1.1.0] - 2026-11-14
6
+
7
+ ### Added
8
+ - **3-Way Telemetry Scope Toggle**: Added seamless switching between **Conversation** (active chat UUID), **Session** (current application run since app restart), and **Lifetime** (all-time cumulative database metrics).
9
+ - **Interactive Cutoff Dropdown**: Scoped cutoff selector (`2 KB`, `4 KB`, `8 KB`, `16 KB`, `32 KB`, `64 KB`, `none`) with persistent SQLite storage and fallback hierarchy.
10
+ - **Dynamic Line Slice Gating**: `PreToolUse` line limit scales dynamically with the cutoff setting (e.g. 2 KB: $\le$50 lines, 4 KB: $\le$100 lines, 8 KB: $\le$200 lines, 16 KB: $\le$400 lines, 32 KB: $\le$800 lines, 64 KB: $\le$1600 lines, none: unrestricted).
11
+ - **Dynamic Sandbox Preview Cap**: `ctx_execute` returned preview text automatically scales to double the active cutoff setting.
12
+ - **Default MS Office Exemptions**: Added `.docx`, `.doc`, `.xlsx`, `.xls`, `.pptx`, `.ppt` alongside `.pdf`, images, and audio/video files to default exemptions.
13
+ - **Clickable Recent Sources**: Click any indexed source in the dashboard to immediately open and view its raw chunks in the Search Inspector.
14
+ - **Exemptions Management Panel**: Live tag editor to add/remove custom file extensions with persistence note and default reset.
15
+ - **Tooltips on Dashboard Metrics**: Added rich context tooltips across all metric cards, lifecycle gates, and SQLite health indicators.
16
+ - **Automated LRU Database Pruning**: Capped stored sources (50 per session, 200 total) to prevent unbounded SQLite growth over long-term use.
17
+
18
+ ### Fixed
19
+ - Fixed sidecar token authentication and added dual `GET` & `POST` endpoint support for `/api/cutoff`, `/api/exemptions`, and `/api/purge` to prevent 401/405 errors inside aux pane webviews.
20
+ - Fixed MCP tool server defaulting to generic session instead of binding to `process.env.ANTIGRAVITY_CONVERSATION_ID`.
21
+ - Fixed dashboard metrics crashing on string formatted numbers by adding explicit numeric coercion.
22
+
23
+ ## [1.0.2] - 2026-11-14
24
+
25
+ ### Fixed
26
+ - Fixed npm publish script
27
+
28
+ ## [1.0.1] - 2026-11-14
29
+
30
+ ### Added
31
+ - Added screenshot of sidecar dashboard to README.md
32
+
5
33
  ## [1.0.0] - 2026-11-14
6
34
 
7
35
  ### Added
package/README.md CHANGED
@@ -110,8 +110,15 @@ npm install -g antigravity-plugin-context-mode
110
110
  Context Mode includes a native web dashboard that opens directly in Antigravity's **Auxiliary (Side) Pane**:
111
111
 
112
112
  * **One-Click Open Pill:** Click `[Open Context Mode Dashboard](sidecar://antigravity-plugin-context-mode/dashboard/)` in chat anytime.
113
- * **Real-Time Telemetry:** Displays your session's reduction percentage, raw bytes vs prompt bytes, and tokens preserved.
114
- * **Volume Compression Bar:** Visual progress comparing raw data against tokens in context.
113
+ * **3-Way Scope Toggle:** Seamlessly inspect telemetry at three distinct levels:
114
+ * **Conversation**: Telemetry strictly for the active conversation; clean slate on new chats.
115
+ * **Session**: Metrics aggregated across all conversations since the app restarted (Language Server boot).
116
+ * **Lifetime**: All-time cumulative database metrics and persistent totals.
117
+ * **Interactive Cutoff Dropdown:** Switch size cutoffs on the fly (`2 KB`, `4 KB`, `8 KB`, `16 KB`, `32 KB`, `64 KB`, or `none`). Line slice limits scale dynamically (e.g. 2 KB: $\le$50 lines, 8 KB: $\le$200 lines, 32 KB: $\le$800 lines).
118
+ * **Clickable Recent Sources:** Click any indexed source in the recent sources list to immediately inspect all of its indexed chunks right inside the Search Inspector.
119
+ * **Exempt File Extensions Panel:** Live tag editor to add or remove custom file extensions (e.g. `.csv`, `.log`, `.json`) that bypass size limits.
120
+ * **Default Exemptions & Attachments:** All chat prompt attachments (`@` mentions and drag-and-drops), PDFs, Microsoft Office documents (`.docx`, `.xlsx`, `.pptx`), and media files automatically bypass size restrictions.
121
+ * **Dynamic Sandbox Output Cap:** Automatically scales script execution preview size to double the active cutoff.
115
122
  * **Interactive FTS5 Search Inspector:** Search your indexed logs and files directly from the UI to see what the agent has indexed.
116
123
  * **1-Click Session Purge:** Wipe session indexes and reset counters whenever you start a fresh task.
117
124
 
@@ -136,7 +143,14 @@ Once installed, the following 8 tools are registered in your Antigravity App:
136
143
 
137
144
  ## ⚙️ Configuration & Environment Variables
138
145
 
139
- You can customize Context Mode's cutoffs at any time using environment variables:
146
+ You can customize Context Mode's cutoffs at any time using the dashboard dropdown or environment variables:
147
+
148
+ | Variable | Default | Description |
149
+ | :--- | :---: | :--- |
150
+ | `CONTEXT_MODE_MAX_READ_BYTES` | `8192` (8 KB) | Size threshold beyond which un-paged file reads are rejected. Set `0` to disable. |
151
+ | `CONTEXT_MODE_MAX_LINE_RANGE` | *Dynamic* (or `200`) | Maximum allowable line slice range before pagination rejection (scales with cutoff). |
152
+ | `CONTEXT_MODE_MAX_OUTPUT_BYTES` | *Dynamic* (or `16384`) | Maximum raw preview bytes returned by `ctx_execute` (defaults to 2x cutoff). |
153
+ | `CONTEXT_MODE_TIMEOUT_MS` | `30000` (30s) | Execution timeout for sandboxed code snippets. |
140
154
 
141
155
  | Variable | Default | Description |
142
156
  | :--- | :---: | :--- |
@@ -1,26 +1,42 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
+ import { ContextModeStore } from "../lib/store.js";
4
5
 
5
6
  export const DEFAULT_MAX_READ_BYTES = 8192; // 8 KB default cutoff
6
7
  export const DEFAULT_MAX_LINE_RANGE = 200; // 200 lines max un-indexed slice
7
8
 
8
- function getMaxReadBytes() {
9
- const envVal = process.env.CONTEXT_MODE_MAX_READ_BYTES;
10
- if (envVal) {
11
- const parsed = parseInt(envVal, 10);
12
- if (!Number.isNaN(parsed) && parsed > 0) return parsed;
9
+ function getMaxReadBytes(sessionId = null) {
10
+ try {
11
+ const store = new ContextModeStore();
12
+ return store.getCutoff(sessionId);
13
+ } catch {
14
+ const envVal = process.env.CONTEXT_MODE_MAX_READ_BYTES;
15
+ if (envVal) {
16
+ const parsed = parseInt(envVal, 10);
17
+ if (!Number.isNaN(parsed)) return parsed;
18
+ }
19
+ return DEFAULT_MAX_READ_BYTES;
13
20
  }
14
- return DEFAULT_MAX_READ_BYTES;
15
21
  }
16
22
 
17
- function getMaxLineRange() {
23
+ function getExemptExtensions(sessionId = null) {
24
+ try {
25
+ const store = new ContextModeStore();
26
+ return store.getExemptExtensions(sessionId);
27
+ } catch {
28
+ return Array.from(BINARY_EXTENSIONS);
29
+ }
30
+ }
31
+
32
+ function getMaxLineRange(maxReadBytes = DEFAULT_MAX_READ_BYTES) {
18
33
  const envVal = process.env.CONTEXT_MODE_MAX_LINE_RANGE;
19
34
  if (envVal) {
20
35
  const parsed = parseInt(envVal, 10);
21
36
  if (!Number.isNaN(parsed) && parsed > 0) return parsed;
22
37
  }
23
- return DEFAULT_MAX_LINE_RANGE;
38
+ if (maxReadBytes === 0) return 0;
39
+ return Math.max(50, Math.round(maxReadBytes / 40));
24
40
  }
25
41
 
26
42
  function formatBytes(bytes) {
@@ -33,6 +49,54 @@ function formatBytes(bytes) {
33
49
  return `${Number.isInteger(mb) ? mb : mb.toFixed(2)} MB`;
34
50
  }
35
51
 
52
+ const BINARY_EXTENSIONS = new Set([
53
+ // Documents & Office
54
+ ".pdf", ".docx", ".doc", ".xlsx", ".xls", ".pptx", ".ppt",
55
+ // Images
56
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".ico", ".tiff", ".tif",
57
+ // Audio & Video
58
+ ".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac", ".mp4", ".webm", ".mkv", ".avi", ".mov",
59
+ // Archives & Executables
60
+ ".zip", ".tar", ".gz", ".7z", ".rar", ".exe", ".dll", ".so", ".dylib", ".bin",
61
+ // 3D & Models
62
+ ".blend", ".fbx", ".obj", ".gltf", ".glb", ".wasm"
63
+ ]);
64
+
65
+ function isUserAttachedFile(filePath, absPath) {
66
+ const normalized = (absPath || filePath || "").replace(/\\/g, "/");
67
+ return (
68
+ normalized.includes("/.user_uploaded/") ||
69
+ normalized.includes("/user_uploaded/") ||
70
+ normalized.includes("/.system_generated/uploads/")
71
+ );
72
+ }
73
+
74
+ function isBinaryFile(absPath, ext) {
75
+ if (BINARY_EXTENSIONS.has((ext || "").toLowerCase())) {
76
+ return true;
77
+ }
78
+ try {
79
+ const fd = fs.openSync(absPath, "r");
80
+ const buf = Buffer.alloc(512);
81
+ const bytesRead = fs.readSync(fd, buf, 0, 512, 0);
82
+ fs.closeSync(fd);
83
+ if (bytesRead === 0) return false;
84
+
85
+ // Check for PDF magic header (%PDF)
86
+ if (bytesRead >= 4 && buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46) {
87
+ return true;
88
+ }
89
+
90
+ // Check for null bytes indicating binary content
91
+ for (let i = 0; i < bytesRead; i++) {
92
+ if (buf[i] === 0) return true;
93
+ }
94
+ } catch {
95
+ // ignore inspection error
96
+ }
97
+ return false;
98
+ }
99
+
36
100
  function readStdin() {
37
101
  return new Promise((resolve) => {
38
102
  let data = "";
@@ -72,29 +136,47 @@ async function main() {
72
136
  const toolName = toolCall.name || "";
73
137
  const args = toolCall.args || {};
74
138
  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;
75
145
 
76
146
  // 1. Guard read_file
77
147
  if (toolName === "read_file") {
78
148
  const filePath = args.Path || args.path || args.filePath || "";
79
149
  const startLine = args.StartLine ?? args.startLine ?? 1;
80
150
  const endLine = args.EndLine ?? args.endLine ?? null;
81
- const maxReadBytes = getMaxReadBytes();
82
- const maxLineRange = getMaxLineRange();
151
+ const maxReadBytes = getMaxReadBytes(sessionId);
152
+ const maxLineRange = getMaxLineRange(maxReadBytes);
83
153
 
84
154
  if (filePath) {
85
155
  const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
86
156
  try {
87
157
  if (fs.existsSync(absPath)) {
158
+ const ext = path.extname(absPath).toLowerCase();
159
+ const isUserAttachment = isUserAttachedFile(filePath, absPath);
160
+ const exemptExtensions = getExemptExtensions(sessionId);
161
+ const isExemptExt = exemptExtensions.includes(ext);
162
+ const isBinary = isBinaryFile(absPath, ext);
163
+
164
+ // Prompt attachments (drag-and-drop / user-uploaded), exempt extensions, or binary files bypass cutoff
165
+ if (isUserAttachment || isExemptExt || isBinary) {
166
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
167
+ return;
168
+ }
169
+
88
170
  const stat = fs.statSync(absPath);
89
- const isLargeFile = stat.size > maxReadBytes;
90
- const isWideRange = endLine === null || endLine - startLine > maxLineRange;
171
+ const isLargeFile = maxReadBytes > 0 && stat.size > maxReadBytes;
172
+ const isWideRange = maxLineRange > 0 && (endLine === null || endLine - startLine > maxLineRange);
91
173
 
92
174
  if (isLargeFile && isWideRange) {
175
+ const lineInstruction = maxLineRange > 0 ? ` or provide a tight StartLine/EndLine range (<= ${maxLineRange} lines).` : "";
93
176
  const reason =
94
177
  `[context-mode protection] File is ${formatBytes(stat.size)} (~${Math.round(stat.size / 4).toLocaleString()} tokens), exceeding the ${formatBytes(maxReadBytes)} context limit. ` +
95
178
  `Reading the entire file risks severe context bloat. ` +
96
- `Please use 'mcp_context-mode_ctx_index(path: "${filePath}")' followed by 'mcp_context-mode_ctx_search', ` +
97
- `or provide a tight StartLine/EndLine range (<= ${maxLineRange} lines).`;
179
+ `Please use 'mcp_context-mode_ctx_index(path: "${filePath}")' followed by 'mcp_context-mode_ctx_search'${lineInstruction}`;
98
180
 
99
181
  process.stdout.write(
100
182
  JSON.stringify({
package/lib/store.js CHANGED
@@ -8,6 +8,39 @@ export const SNIPPET_MAX_BYTES = 800;
8
8
  export const RRF_K = 60;
9
9
  export const STATE_BUDGET = 2048;
10
10
 
11
+ export const DEFAULT_EXEMPT_EXTENSIONS = [
12
+ // Documents & Office
13
+ ".pdf",
14
+ ".docx",
15
+ ".doc",
16
+ ".xlsx",
17
+ ".xls",
18
+ ".pptx",
19
+ ".ppt",
20
+ // Images
21
+ ".png",
22
+ ".jpg",
23
+ ".jpeg",
24
+ ".gif",
25
+ ".webp",
26
+ ".svg",
27
+ ".bmp",
28
+ ".ico",
29
+ // Audio & Video
30
+ ".mp3",
31
+ ".wav",
32
+ ".mp4",
33
+ ".mov",
34
+ // Archives & 3D
35
+ ".zip",
36
+ ".tar",
37
+ ".gz",
38
+ ".blend",
39
+ ".fbx",
40
+ ".glb",
41
+ ".wasm"
42
+ ];
43
+
11
44
  /** Default path to context database (~/.context-mode/context.db) */
12
45
  export function getDefaultDbPath() {
13
46
  const dir = path.join(os.homedir(), ".context-mode");
@@ -220,6 +253,8 @@ export class ContextModeStore {
220
253
  insertChunkTri.run(id, sid, ord, chunkText);
221
254
  }
222
255
 
256
+ this.pruneStaleSources();
257
+
223
258
  return {
224
259
  sourceId: id,
225
260
  bytesTotal: totalBytes,
@@ -416,33 +451,71 @@ export class ContextModeStore {
416
451
  }
417
452
 
418
453
  /** Retrieve compaction / state resume block */
419
- getResumeState(sessionId, limit = 5) {
454
+ getResumeState(sessionId, limit = 5, options = {}) {
420
455
  this.open();
421
456
  const sid = sessionId || "default";
422
-
423
- const sources = this.db
424
- .prepare(
425
- `
426
- SELECT id, label, kind, bytes_total, chunk_count, created_at
427
- FROM sources
428
- WHERE session_id = ?
429
- ORDER BY created_ts DESC
430
- LIMIT ?
431
- `
432
- )
433
- .all(sid, limit);
434
-
435
- const events = this.db
436
- .prepare(
437
- `
438
- SELECT seq, tool, kind, ok, sandbox_bytes, returned_bytes, created_at
439
- FROM events
440
- WHERE session_id = ?
441
- ORDER BY seq DESC
442
- LIMIT ?
443
- `
444
- )
445
- .all(sid, limit);
457
+ const sinceTs = options.sinceTs || null;
458
+ const sinceIso = sinceTs ? new Date(sinceTs).toISOString() : null;
459
+
460
+ let sources;
461
+ let events;
462
+
463
+ if (sid === "all" || sid === "lifetime") {
464
+ sources = this.db
465
+ .prepare(`
466
+ SELECT id, label, kind, bytes_total, chunk_count, created_at
467
+ FROM sources
468
+ ORDER BY created_ts DESC
469
+ LIMIT ?
470
+ `)
471
+ .all(limit);
472
+ events = this.db
473
+ .prepare(`
474
+ SELECT seq, tool, kind, ok, sandbox_bytes, returned_bytes, created_at
475
+ FROM events
476
+ ORDER BY seq DESC
477
+ LIMIT ?
478
+ `)
479
+ .all(limit);
480
+ } else if (sid === "app" && sinceIso) {
481
+ sources = this.db
482
+ .prepare(`
483
+ SELECT id, label, kind, bytes_total, chunk_count, created_at
484
+ FROM sources
485
+ WHERE created_at >= ? OR created_ts >= ?
486
+ ORDER BY created_ts DESC
487
+ LIMIT ?
488
+ `)
489
+ .all(sinceIso, sinceTs, limit);
490
+ events = this.db
491
+ .prepare(`
492
+ SELECT seq, tool, kind, ok, sandbox_bytes, returned_bytes, created_at
493
+ FROM events
494
+ WHERE created_at >= ?
495
+ ORDER BY seq DESC
496
+ LIMIT ?
497
+ `)
498
+ .all(sinceIso, limit);
499
+ } else {
500
+ sources = this.db
501
+ .prepare(`
502
+ SELECT id, label, kind, bytes_total, chunk_count, created_at
503
+ FROM sources
504
+ WHERE session_id = ?
505
+ ORDER BY created_ts DESC
506
+ LIMIT ?
507
+ `)
508
+ .all(sid, limit);
509
+ events = this.db
510
+ .prepare(`
511
+ SELECT seq, tool, kind, ok, sandbox_bytes, returned_bytes, created_at
512
+ FROM events
513
+ WHERE session_id = ?
514
+ ORDER BY seq DESC
515
+ LIMIT ?
516
+ `)
517
+ .all(sid, limit);
518
+ }
446
519
 
447
520
  return {
448
521
  sessionId: sid,
@@ -458,41 +531,83 @@ export class ContextModeStore {
458
531
  return row || null;
459
532
  }
460
533
 
534
+ /** Retrieve all chunks for a specific source */
535
+ getSourceChunks(sourceId) {
536
+ this.open();
537
+ if (!sourceId) return [];
538
+ return this.db
539
+ .prepare("SELECT ord, body, title FROM chunks WHERE source_id = ? ORDER BY ord ASC")
540
+ .all(sourceId);
541
+ }
542
+
461
543
  /** Calculate token savings & statistics */
462
- getStats(sessionId) {
544
+ getStats(sessionId, options = {}) {
463
545
  this.open();
464
546
  const sid = sessionId || "default";
465
-
466
- const eventStats = this.db
467
- .prepare(
468
- `
469
- SELECT
470
- COUNT(*) AS total_calls,
471
- SUM(sandbox_bytes) AS total_sandbox_bytes,
472
- SUM(returned_bytes) AS total_returned_bytes
473
- FROM events
474
- WHERE session_id = ?
475
- `
476
- )
477
- .get(sid);
478
-
479
- const sourceStats = this.db
480
- .prepare(
481
- `
482
- SELECT
483
- COUNT(*) AS total_sources,
484
- SUM(bytes_total) AS total_source_bytes,
485
- SUM(chunk_count) AS total_chunks
486
- FROM sources
487
- WHERE session_id = ?
488
- `
489
- )
490
- .get(sid);
547
+ const sinceTs = options.sinceTs || null;
548
+ const sinceIso = sinceTs ? new Date(sinceTs).toISOString() : null;
549
+
550
+ let eventStats;
551
+ let sourceStats;
552
+
553
+ if (sid === "all" || sid === "lifetime") {
554
+ eventStats = this.db.prepare(`
555
+ SELECT
556
+ COUNT(*) AS total_calls,
557
+ SUM(sandbox_bytes) AS total_sandbox_bytes,
558
+ SUM(returned_bytes) AS total_returned_bytes
559
+ FROM events
560
+ `).get();
561
+
562
+ sourceStats = this.db.prepare(`
563
+ SELECT
564
+ COUNT(*) AS total_sources,
565
+ SUM(bytes_total) AS total_source_bytes,
566
+ SUM(chunk_count) AS total_chunks
567
+ FROM sources
568
+ `).get();
569
+ } else if (sid === "app" && sinceIso) {
570
+ eventStats = this.db.prepare(`
571
+ SELECT
572
+ COUNT(*) AS total_calls,
573
+ SUM(sandbox_bytes) AS total_sandbox_bytes,
574
+ SUM(returned_bytes) AS total_returned_bytes
575
+ FROM events
576
+ WHERE created_at >= ?
577
+ `).get(sinceIso);
578
+
579
+ sourceStats = this.db.prepare(`
580
+ SELECT
581
+ COUNT(*) AS total_sources,
582
+ SUM(bytes_total) AS total_source_bytes,
583
+ SUM(chunk_count) AS total_chunks
584
+ FROM sources
585
+ WHERE created_at >= ? OR created_ts >= ?
586
+ `).get(sinceIso, sinceTs);
587
+ } else {
588
+ eventStats = this.db.prepare(`
589
+ SELECT
590
+ COUNT(*) AS total_calls,
591
+ SUM(sandbox_bytes) AS total_sandbox_bytes,
592
+ SUM(returned_bytes) AS total_returned_bytes
593
+ FROM events
594
+ WHERE session_id = ?
595
+ `).get(sid);
596
+
597
+ sourceStats = this.db.prepare(`
598
+ SELECT
599
+ COUNT(*) AS total_sources,
600
+ SUM(bytes_total) AS total_source_bytes,
601
+ SUM(chunk_count) AS total_chunks
602
+ FROM sources
603
+ WHERE session_id = ?
604
+ `).get(sid);
605
+ }
491
606
 
492
607
  const totalRawBytes = (eventStats?.total_sandbox_bytes || 0) + (sourceStats?.total_source_bytes || 0);
493
608
  const totalReturnedBytes = eventStats?.total_returned_bytes || 0;
494
609
  const keptOutBytes = Math.max(0, totalRawBytes - totalReturnedBytes);
495
- const savingsPercent = totalRawBytes > 0 ? ((keptOutBytes / totalRawBytes) * 100).toFixed(1) : "0.0";
610
+ const savingsPercent = totalRawBytes > 0 ? Number(((keptOutBytes / totalRawBytes) * 100).toFixed(1)) : 0;
496
611
  const tokensKeptOut = Math.round(keptOutBytes / 4);
497
612
 
498
613
  return {
@@ -501,7 +616,7 @@ export class ContextModeStore {
501
616
  totalRawBytes,
502
617
  totalReturnedBytes,
503
618
  keptOutBytes,
504
- savingsPercent: parseFloat(savingsPercent),
619
+ savingsPercent,
505
620
  tokensKeptOut,
506
621
  sourcesCount: sourceStats?.total_sources || 0,
507
622
  chunksCount: sourceStats?.total_chunks || 0
@@ -509,9 +624,9 @@ export class ContextModeStore {
509
624
  }
510
625
 
511
626
  /** Purge stored data */
512
- purge({ scope = "session", sessionId, worktree }) {
627
+ purge({ scope = "session", sessionId, worktree, sinceTs }) {
513
628
  this.open();
514
- if (scope === "all") {
629
+ if (scope === "all" || scope === "lifetime") {
515
630
  this.db.exec(`
516
631
  DELETE FROM chunks;
517
632
  DELETE FROM chunks_tri;
@@ -522,6 +637,18 @@ export class ContextModeStore {
522
637
  return { ok: true, purged: "all" };
523
638
  }
524
639
 
640
+ if (scope === "app" && sinceTs) {
641
+ const sinceIso = new Date(sinceTs).toISOString();
642
+ const sourceIds = this.db.prepare("SELECT id FROM sources WHERE created_at >= ? OR created_ts >= ?").all(sinceIso, sinceTs).map((r) => r.id);
643
+ for (const sId of sourceIds) {
644
+ this.db.prepare("DELETE FROM chunks WHERE source_id = ?").run(sId);
645
+ this.db.prepare("DELETE FROM chunks_tri WHERE source_id = ?").run(sId);
646
+ }
647
+ this.db.prepare("DELETE FROM sources WHERE created_at >= ? OR created_ts >= ?").run(sinceIso, sinceTs);
648
+ this.db.prepare("DELETE FROM events WHERE created_at >= ?").run(sinceIso);
649
+ return { ok: true, purged: "app", count: sourceIds.length };
650
+ }
651
+
525
652
  if (scope === "worktree" && worktree) {
526
653
  this.db.prepare("DELETE FROM chunks WHERE worktree = ?").run(worktree);
527
654
  this.db.prepare("DELETE FROM sources WHERE worktree = ?").run(worktree);
@@ -562,4 +689,194 @@ export class ContextModeStore {
562
689
  };
563
690
  }
564
691
  }
692
+
693
+ /** Read a key from meta table */
694
+ getMeta(key, defaultValue = null) {
695
+ this.open();
696
+ const row = this.db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
697
+ return row ? row.value : defaultValue;
698
+ }
699
+
700
+ /** Write a key-value pair to meta table */
701
+ setMeta(key, value) {
702
+ this.open();
703
+ this.db
704
+ .prepare(
705
+ "INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
706
+ )
707
+ .run(key, String(value));
708
+ }
709
+
710
+ /** Get active cutoff in bytes (0 = none/disabled) */
711
+ getCutoff(sessionId = null) {
712
+ this.open();
713
+ // 1. Session/Conversation override
714
+ if (sessionId && sessionId !== "all") {
715
+ const sessionCutoff = this.getMeta(`cutoff:session:${sessionId}`);
716
+ if (sessionCutoff !== null) {
717
+ return parseInt(sessionCutoff, 10);
718
+ }
719
+ // If checking a conversation, fall back to the app session cutoff if set
720
+ if (sessionId !== "app") {
721
+ const appCutoff = this.getMeta("cutoff:session:app");
722
+ if (appCutoff !== null) {
723
+ return parseInt(appCutoff, 10);
724
+ }
725
+ }
726
+ }
727
+
728
+ // 2. Environment variable if explicitly set
729
+ const envVal = process.env.CONTEXT_MODE_MAX_READ_BYTES;
730
+ if (envVal) {
731
+ const parsed = parseInt(envVal, 10);
732
+ if (!Number.isNaN(parsed)) return parsed;
733
+ }
734
+
735
+ // 3. Saved global setting in SQLite
736
+ const globalCutoff = this.getMeta("cutoff:global");
737
+ if (globalCutoff !== null) {
738
+ return parseInt(globalCutoff, 10);
739
+ }
740
+
741
+ // 4. Default 8 KB
742
+ return 8192;
743
+ }
744
+
745
+ /** Set cutoff in bytes (0 = none/disabled) */
746
+ setCutoff(bytes, sessionId = null) {
747
+ this.open();
748
+ const val = parseInt(bytes, 10);
749
+ const numVal = Number.isNaN(val) ? 8192 : Math.max(0, val);
750
+ if (sessionId && sessionId !== "all") {
751
+ this.setMeta(`cutoff:session:${sessionId}`, numVal);
752
+ } else {
753
+ this.setMeta("cutoff:global", numVal);
754
+ }
755
+ return numVal;
756
+ }
757
+
758
+ /** Get list of file extensions exempt from the size cutoff */
759
+ getExemptExtensions(sessionId = null) {
760
+ this.open();
761
+ // 1. Session/Conversation override
762
+ if (sessionId && sessionId !== "all") {
763
+ const raw = this.getMeta(`exempt_ext:session:${sessionId}`);
764
+ if (raw) {
765
+ try {
766
+ const parsed = JSON.parse(raw);
767
+ if (Array.isArray(parsed)) return parsed;
768
+ } catch {}
769
+ }
770
+ // If checking a conversation, fall back to the app session exemptions if set
771
+ if (sessionId !== "app") {
772
+ const appRaw = this.getMeta("exempt_ext:session:app");
773
+ if (appRaw) {
774
+ try {
775
+ const parsed = JSON.parse(appRaw);
776
+ if (Array.isArray(parsed)) return parsed;
777
+ } catch {}
778
+ }
779
+ }
780
+ }
781
+ const globalRaw = this.getMeta("exempt_ext:global");
782
+ if (globalRaw) {
783
+ try {
784
+ const parsed = JSON.parse(globalRaw);
785
+ if (Array.isArray(parsed)) return parsed;
786
+ } catch {}
787
+ }
788
+ return [...DEFAULT_EXEMPT_EXTENSIONS];
789
+ }
790
+
791
+ /** Set list of file extensions exempt from the size cutoff */
792
+ setExemptExtensions(extensions, sessionId = null) {
793
+ this.open();
794
+ const cleanList = Array.from(
795
+ new Set(
796
+ (Array.isArray(extensions) ? extensions : [])
797
+ .map((ext) => String(ext || "").trim().toLowerCase())
798
+ .filter(Boolean)
799
+ .map((ext) => (ext.startsWith(".") ? ext : `.${ext}`))
800
+ )
801
+ );
802
+ const serialized = JSON.stringify(cleanList);
803
+ if (sessionId && sessionId !== "all") {
804
+ this.setMeta(`exempt_ext:session:${sessionId}`, serialized);
805
+ } else {
806
+ this.setMeta("exempt_ext:global", serialized);
807
+ }
808
+ return cleanList;
809
+ }
810
+
811
+ /** Add an exempt file extension */
812
+ addExemptExtension(ext, sessionId = null) {
813
+ const list = this.getExemptExtensions(sessionId);
814
+ const cleanExt = String(ext || "").trim().toLowerCase();
815
+ if (!cleanExt) return list;
816
+ const formatted = cleanExt.startsWith(".") ? cleanExt : `.${cleanExt}`;
817
+ if (!list.includes(formatted)) {
818
+ list.push(formatted);
819
+ this.setExemptExtensions(list, sessionId);
820
+ }
821
+ return list;
822
+ }
823
+
824
+ /** Remove an exempt file extension */
825
+ removeExemptExtension(ext, sessionId = null) {
826
+ const list = this.getExemptExtensions(sessionId);
827
+ const cleanExt = String(ext || "").trim().toLowerCase();
828
+ const formatted = cleanExt.startsWith(".") ? cleanExt : `.${cleanExt}`;
829
+ const filtered = list.filter((e) => e !== formatted);
830
+ this.setExemptExtensions(filtered, sessionId);
831
+ return filtered;
832
+ }
833
+
834
+ /**
835
+ * Automatic LRU pruning: limits the number of indexed sources and chunks
836
+ * to avoid unbounded database expansion.
837
+ */
838
+ pruneStaleSources({ maxSourcesPerSession = 50, maxTotalSources = 200 } = {}) {
839
+ this.open();
840
+ try {
841
+ // 1. Prune sources exceeding per-session cap
842
+ const excessSessionSources = this.db
843
+ .prepare(`
844
+ SELECT id FROM sources
845
+ WHERE id NOT IN (
846
+ SELECT id FROM sources s2
847
+ WHERE s2.session_id = sources.session_id
848
+ ORDER BY s2.created_ts DESC
849
+ LIMIT ?
850
+ )
851
+ `)
852
+ .all(maxSourcesPerSession);
853
+
854
+ if (excessSessionSources.length > 0) {
855
+ const ids = excessSessionSources.map((r) => r.id);
856
+ const placeholders = ids.map(() => "?").join(",");
857
+ this.db.prepare(`DELETE FROM chunks WHERE source_id IN (${placeholders})`).run(...ids);
858
+ this.db.prepare(`DELETE FROM chunks_tri WHERE source_id IN (${placeholders})`).run(...ids);
859
+ this.db.prepare(`DELETE FROM sources WHERE id IN (${placeholders})`).run(...ids);
860
+ }
861
+
862
+ // 2. Prune global total sources if over cap
863
+ const totalCountRow = this.db.prepare("SELECT count(*) as count FROM sources").get();
864
+ if (totalCountRow && totalCountRow.count > maxTotalSources) {
865
+ const deleteCount = totalCountRow.count - maxTotalSources;
866
+ const oldest = this.db
867
+ .prepare("SELECT id FROM sources ORDER BY created_ts ASC LIMIT ?")
868
+ .all(deleteCount);
869
+
870
+ if (oldest.length > 0) {
871
+ const ids = oldest.map((r) => r.id);
872
+ const placeholders = ids.map(() => "?").join(",");
873
+ this.db.prepare(`DELETE FROM chunks WHERE source_id IN (${placeholders})`).run(...ids);
874
+ this.db.prepare(`DELETE FROM chunks_tri WHERE source_id IN (${placeholders})`).run(...ids);
875
+ this.db.prepare(`DELETE FROM sources WHERE id IN (${placeholders})`).run(...ids);
876
+ }
877
+ }
878
+ } catch {
879
+ // Best-effort auto-prune
880
+ }
881
+ }
565
882
  }
package/lib/tools.js CHANGED
@@ -89,10 +89,14 @@ export function createTools({ store, getCwd = () => process.cwd(), getSessionId
89
89
  sourceId = indexed.sourceId;
90
90
  }
91
91
 
92
+ const cutoffBytes = store.getCutoff(sessionId);
93
+ // Sandbox cap is dynamically double the current cutoff setting
94
+ const previewCapBytes = cutoffBytes > 0 ? cutoffBytes * 2 : EXEC_PREVIEW_BYTES * 8;
95
+
92
96
  let returnedText = fullOutput;
93
97
  let truncated = false;
94
- if (fullBytes > EXEC_PREVIEW_BYTES) {
95
- returnedText = fullOutput.slice(0, EXEC_PREVIEW_BYTES);
98
+ if (fullBytes > previewCapBytes) {
99
+ returnedText = fullOutput.slice(0, previewCapBytes);
96
100
  truncated = true;
97
101
  }
98
102
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "antigravity-plugin-context-mode",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Native Antigravity plugin for context-mode: SQLite FTS5 indexing, sandboxed execution, and lifecycle hook protection against context window bloat",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -54,4 +54,4 @@
54
54
  "publishConfig": {
55
55
  "access": "public"
56
56
  }
57
- }
57
+ }
package/plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "antigravity-plugin-context-mode",
3
3
  "displayName": "Context Mode",
4
4
  "description": "Context window protection for Antigravity: local SQLite FTS5 search, sandboxed execution, and lifecycle hook gating against token bloat.",
5
- "version": "1.0.0",
5
+ "version": "1.1.0",
6
6
  "author": "Phillip Webber <github@webbsense.com>",
7
7
  "repository": {
8
8
  "type": "git",
package/server.js CHANGED
@@ -5,12 +5,19 @@ import { createTools } from "./lib/tools.js";
5
5
 
6
6
  const store = new ContextModeStore();
7
7
  let currentCwd = process.cwd();
8
- let currentSessionId = "default";
8
+ let currentSessionId =
9
+ process.env.ANTIGRAVITY_CONVERSATION_ID ||
10
+ process.env.CONVERSATION_ID ||
11
+ "default";
9
12
 
10
13
  const tools = createTools({
11
14
  store,
12
15
  getCwd: () => currentCwd,
13
- getSessionId: () => currentSessionId
16
+ getSessionId: () =>
17
+ process.env.ANTIGRAVITY_CONVERSATION_ID ||
18
+ process.env.CONVERSATION_ID ||
19
+ currentSessionId ||
20
+ "default"
14
21
  });
15
22
 
16
23
  const TOOL_DEFINITIONS = [
@@ -210,6 +217,14 @@ rl.on("line", async (line) => {
210
217
  case "tools/call": {
211
218
  const toolName = params?.name;
212
219
  const toolArgs = params?.arguments || {};
220
+ const callSessionId =
221
+ toolArgs.sessionId ||
222
+ params?._meta?.conversationId ||
223
+ params?._meta?.sessionId ||
224
+ params?.sessionId;
225
+ if (callSessionId) {
226
+ currentSessionId = callSessionId;
227
+ }
213
228
 
214
229
  if (!tools[toolName]) {
215
230
  sendError(id, -32601, `Unknown tool: ${toolName}`);