antigravity-plugin-context-mode 1.3.2 → 1.5.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 +29 -0
- package/README.md +4 -4
- package/hooks/pre-invocation.js +84 -0
- package/hooks/pre-tool-use.js +129 -24
- package/hooks/session-start.js +75 -7
- package/hooks.json +7 -0
- package/lib/store.js +415 -66
- package/lib/tools.js +83 -68
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +18 -5
- package/server.js +11 -17
- package/skills/context-mode/SKILL.md +27 -18
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,35 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `antigravity-plugin-context-mode` will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.5.0] - 2026-11-21
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- **SQLite Schema v3 (`path` as Primary Key Everywhere)**: Migrated database schema to v3, promoting `path` to the primary key on `sources(path TEXT PRIMARY KEY)` and foreign reference on `chunks(path UNINDEXED)` / `chunks_tri(path UNINDEXED)`. Seamless automatic migration from existing v2 databases preserves database integrity while eliminating all legacy surrogate ID generators.
|
|
9
|
+
- **Just-In-Time On-Demand Indexing (`ctx_search`)**: Refactored `ctx_search` to support `path` for individual files, directory paths, and remote URLs. Unindexed or modified files are automatically checked against file modification timestamps (`mtime`) and indexed Just-In-Time before searching, returning instant, fresh hits in a single call.
|
|
10
|
+
- **Reverse Search for Log Files (`reverse: true`)**: Added optional `reverse` parameter to `ctx_search` to sort search hits by chunk order in reverse (`b.ord - a.ord`). Prioritizes the latest events, errors, and fatal crashes at the end of large log files first.
|
|
11
|
+
- **Snippet Centering on Search Hits**: Window search snippets around the matched query term position rather than slicing from offset 0, ensuring matching context is visible even in large chunks.
|
|
12
|
+
- **Intra-File Search Priority in Agent Standards (`rules/AGENTS.md`)**: Instructs agents to always prioritize `ctx_search(queries: [...], path: "path/to/target")` for all intra-file and directory searches without manual indexing or pre-reading into context.
|
|
13
|
+
- **Live Active Cutoff & Exemption Injections (`SessionStart` & `PreInvocation`)**: Injected system messages dynamically report the active single-operation read cutoff and enumerate all active exempt file categories and custom extensions. Explicitly clarifies to LLM agents that the cutoff is a single-read tool threshold, not the model's context window.
|
|
14
|
+
- **Mid-Session Dynamic Configuration Tracking (`PreInvocation`)**: Added `hooks/pre-invocation.js` registered under `PreInvocation` in `hooks.json`. Automatically detects when cutoff limits or file exemptions are modified mid-session (via dashboard or API) and immediately informs the agent on the subsequent turn while remaining completely quiet when unchanged.
|
|
15
|
+
- **Automatic Indexing Redirection on Interception (`PreToolUse`)**: Instead of simply rejecting large `read_file` operations or un-paged file dump commands (`cat`, `Get-Content`, `type`), `PreToolUse` now automatically reads and indexes the target file into SQLite FTS5 (up to a configurable 50 MB ceiling) and returns `[context-mode protection: auto-indexed]` with the intuitive workspace-relative path and immediate search instructions (`ctx_search(queries: [...], path: "...")`).
|
|
16
|
+
- **Auto-Index Limit Dashboard Control & API**: Added a Max Auto-Index dropdown selector (`1 MB`, `5 MB`, `10 MB`, `50 MB`, `100 MB`, `Off`) directly adjacent to the Cutoff dropdown in the sidecar dashboard. Added `/api/auto-index-limit` (`GET` and `POST`) endpoint in `server.mjs`.
|
|
17
|
+
- **Configurable Auto-Index Limits Cascade**: Configurable via `CONTEXT_MODE_MAX_AUTO_INDEX_BYTES` env variable, session overrides, or SQLite global setting (`store.getMaxAutoIndexBytes()` and `store.setMaxAutoIndexBytes()`).
|
|
18
|
+
- **Idempotent File Re-indexing**: Re-indexing an existing file path cleans up prior chunk entries before writing new ones, preventing chunk duplication when files are edited and re-indexed.
|
|
19
|
+
- **Active Limit & Exemption Diagnostics in MCP Tools**: Enhanced `ctx_stats` and `ctx_doctor` to return active cutoff bytes, formatted cutoff strings, and active exempt categories/extensions.
|
|
20
|
+
|
|
21
|
+
### Removed
|
|
22
|
+
- **Retired `ctx_index` Tool**: Removed `ctx_index` from MCP tool definitions, server schemas, rules, and skills. Because `ctx_search` automatically indexes files, directories, and URLs on-demand, manual indexing is completely obsolete.
|
|
23
|
+
- **Eliminated `sourceId` Parameter**: Replaced internal database identifier `sourceId` across all tool schemas, denial messages, and agent instructions with standard `path`.
|
|
24
|
+
- **Stripped `mcp_context-mode_` Prefix from Denial Messages**: Simplified all guidance messages so tool calls are referred to cleanly as `ctx_search` and `ctx_execute`.
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
- **Dynamic Maximum Line Ranges**: Replaced arbitrary hardcoded line numbers (`-First 50`, `head -n 50`) in denial messages and rules with dynamic maximum limits (`getMaxLineRange(maxReadBytes)`) and explicit instructions to read only the lines needed.
|
|
28
|
+
- **Zero Redundant Instructions**: Stripped repetitive tutorial text, hardcoded exemption catalogs, and false guarantees from rules, session-start notices, and tool denial reasons.
|
|
29
|
+
- **Debunked 8 KB Context Window Hallucination in Agent Rules (`rules/AGENTS.md`)**: Updated behavioral guidelines to explicitly distinguish between the tool-level read cutoff and the model's actual context window, and instructed agents that exempt files bypass cutoff protection.
|
|
30
|
+
- **Dynamic PreToolUse Denial Messages**: Refactored denial messages in `hooks/pre-tool-use.js` to dynamically generate the live active exempt categories and custom extensions from SQLite rather than displaying a static hardcoded note.
|
|
31
|
+
- **Double-Counting Prevention in Statistics**: Updated `getStats()` in `lib/store.js` to ensure auto-indexed files logged through `read_file` or `run_command` interceptions are not double-counted between `events` and `sources`.
|
|
32
|
+
- **Safe ES Module Hook Imports**: Added `isMain` execution guards to `hooks/pre-tool-use.js` and `hooks/session-start.js` to prevent unintended top-level execution when importing helper utilities across hooks and test suites.
|
|
33
|
+
|
|
5
34
|
## [1.3.2] - 2026-11-17
|
|
6
35
|
|
|
7
36
|
### Documentation
|
package/README.md
CHANGED
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
|
|
13
13
|
> 🌐 **Interactive Live Simulator & Documentation:** [domush.github.io/antigravity-plugin-context-mode](https://domush.github.io/antigravity-plugin-context-mode/)
|
|
14
14
|
|
|
15
|
-
<img width="
|
|
15
|
+
<img width="715" height="632" alt="image" src="https://github.com/user-attachments/assets/952b84a0-3e71-4bd6-99ae-e604532c1c7f" />
|
|
16
|
+
|
|
16
17
|
---
|
|
17
18
|
|
|
18
19
|
## Quick Install (10 Seconds)
|
|
@@ -98,13 +99,12 @@ Tested live on real-world build logs and source files in the Antigravity App:
|
|
|
98
99
|
|
|
99
100
|
## Available MCP Tools
|
|
100
101
|
|
|
101
|
-
Once installed, Context Mode provides
|
|
102
|
+
Once installed, Context Mode provides 7 specialized tools for your agent:
|
|
102
103
|
|
|
103
104
|
| Tool | What It Does |
|
|
104
105
|
| :--- | :--- |
|
|
105
106
|
| **`ctx_execute`** | Runs sandboxed Node.js, Python, or PowerShell scripts to inspect files and extract answers without context dumps. |
|
|
106
|
-
| **`ctx_search`** | Searches
|
|
107
|
-
| **`ctx_index`** | Indexes local files or documentation into searchable chunks for the agent. |
|
|
107
|
+
| **`ctx_search`** | Searches files, directories, or URLs with Just-In-Time auto-indexing using local SQLite FTS5 BM25 + Trigram RRF. |
|
|
108
108
|
| **`ctx_batch`** | Runs multiple terminal commands in batch and indexes the combined output. |
|
|
109
109
|
| **`ctx_stats`** | Displays a formatted context savings report and token metrics. |
|
|
110
110
|
| **`ctx_resume`** | Returns recent indexed sources and state pointers after context compactions. |
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { ContextModeStore } from "../lib/store.js";
|
|
5
|
+
import { resolveSharedSessionId } from "./pre-tool-use.js";
|
|
6
|
+
import { buildStatusMessage } from "./session-start.js";
|
|
7
|
+
|
|
8
|
+
function readStdin() {
|
|
9
|
+
return new Promise((resolve) => {
|
|
10
|
+
let data = "";
|
|
11
|
+
process.stdin.setEncoding("utf8");
|
|
12
|
+
process.stdin.on("data", (chunk) => {
|
|
13
|
+
data += chunk;
|
|
14
|
+
});
|
|
15
|
+
process.stdin.on("end", () => {
|
|
16
|
+
resolve(data);
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function main() {
|
|
22
|
+
const rawInput = await readStdin();
|
|
23
|
+
let payload = {};
|
|
24
|
+
try {
|
|
25
|
+
if (rawInput && rawInput.trim()) {
|
|
26
|
+
payload = JSON.parse(rawInput);
|
|
27
|
+
}
|
|
28
|
+
} catch {}
|
|
29
|
+
|
|
30
|
+
const sessionId = resolveSharedSessionId(payload);
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
const store = new ContextModeStore();
|
|
34
|
+
const cutoff = store.getCutoff(sessionId);
|
|
35
|
+
const exemptCats = store.getExemptCategories(sessionId);
|
|
36
|
+
const exemptExts = store.getExemptExtensions(sessionId);
|
|
37
|
+
const customExts = store.getCustomExemptExtensions(sessionId);
|
|
38
|
+
|
|
39
|
+
const sig = `${cutoff}:${exemptExts.slice().sort().join(",")}`;
|
|
40
|
+
const lastInformed = store.getMeta(`informed_config:session:${sessionId}`);
|
|
41
|
+
|
|
42
|
+
if (lastInformed !== sig) {
|
|
43
|
+
store.setMeta(`informed_config:session:${sessionId}`, sig);
|
|
44
|
+
store.close();
|
|
45
|
+
|
|
46
|
+
const message = buildStatusMessage({
|
|
47
|
+
cutoff,
|
|
48
|
+
exemptCategories: exemptCats,
|
|
49
|
+
exemptExtensions: exemptExts,
|
|
50
|
+
customExtensions: customExts,
|
|
51
|
+
isUpdate: Boolean(lastInformed)
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const response = {
|
|
55
|
+
injectSteps: [
|
|
56
|
+
{
|
|
57
|
+
systemMessage: {
|
|
58
|
+
systemMessage: message
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
]
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
process.stdout.write(JSON.stringify(response) + "\n");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
store.close();
|
|
69
|
+
} catch {}
|
|
70
|
+
|
|
71
|
+
process.stdout.write(JSON.stringify({}) + "\n");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const isMain = Boolean(
|
|
75
|
+
process.argv[1] &&
|
|
76
|
+
path.resolve(fileURLToPath(import.meta.url)).toLowerCase() ===
|
|
77
|
+
path.resolve(process.argv[1]).toLowerCase()
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
if (isMain) {
|
|
81
|
+
main().catch(() => {
|
|
82
|
+
process.stdout.write(JSON.stringify({}) + "\n");
|
|
83
|
+
});
|
|
84
|
+
}
|
package/hooks/pre-tool-use.js
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { ContextModeStore, DEFAULT_MAX_AUTO_INDEX_BYTES, resolveFilePath } from "../lib/store.js";
|
|
5
6
|
|
|
6
7
|
export const DEFAULT_MAX_READ_BYTES = 8192; // 8 KB default cutoff
|
|
7
8
|
export const DEFAULT_MAX_LINE_RANGE = 200; // 200 lines max un-indexed slice
|
|
8
9
|
|
|
10
|
+
export function getMaxAutoIndexBytes(sessionId = null) {
|
|
11
|
+
try {
|
|
12
|
+
const store = new ContextModeStore();
|
|
13
|
+
const limit = store.getMaxAutoIndexBytes(sessionId);
|
|
14
|
+
store.close();
|
|
15
|
+
return limit;
|
|
16
|
+
} catch {
|
|
17
|
+
const envVal = process.env.CONTEXT_MODE_MAX_AUTO_INDEX_BYTES;
|
|
18
|
+
if (envVal) {
|
|
19
|
+
const parsed = parseInt(envVal, 10);
|
|
20
|
+
if (!Number.isNaN(parsed)) return parsed;
|
|
21
|
+
}
|
|
22
|
+
return DEFAULT_MAX_AUTO_INDEX_BYTES;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
9
26
|
function isProtectionPaused(sessionId = null) {
|
|
10
27
|
try {
|
|
11
28
|
const store = new ContextModeStore();
|
|
@@ -17,7 +34,7 @@ function isProtectionPaused(sessionId = null) {
|
|
|
17
34
|
}
|
|
18
35
|
}
|
|
19
36
|
|
|
20
|
-
function getMaxReadBytes(sessionId = null) {
|
|
37
|
+
export function getMaxReadBytes(sessionId = null) {
|
|
21
38
|
try {
|
|
22
39
|
const store = new ContextModeStore();
|
|
23
40
|
const cutoff = store.getCutoff(sessionId);
|
|
@@ -33,7 +50,7 @@ function getMaxReadBytes(sessionId = null) {
|
|
|
33
50
|
}
|
|
34
51
|
}
|
|
35
52
|
|
|
36
|
-
function getExemptExtensions(sessionId = null) {
|
|
53
|
+
export function getExemptExtensions(sessionId = null) {
|
|
37
54
|
try {
|
|
38
55
|
const store = new ContextModeStore();
|
|
39
56
|
const exts = store.getExemptExtensions(sessionId);
|
|
@@ -44,7 +61,18 @@ function getExemptExtensions(sessionId = null) {
|
|
|
44
61
|
}
|
|
45
62
|
}
|
|
46
63
|
|
|
47
|
-
function
|
|
64
|
+
export function getActiveExemptSummary(sessionId = null) {
|
|
65
|
+
try {
|
|
66
|
+
const store = new ContextModeStore();
|
|
67
|
+
const summary = store.getExemptSummary(sessionId);
|
|
68
|
+
store.close();
|
|
69
|
+
return summary;
|
|
70
|
+
} catch {
|
|
71
|
+
return "prompt attachments in .user_uploaded/";
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function getMaxLineRange(maxReadBytes = DEFAULT_MAX_READ_BYTES) {
|
|
48
76
|
const envVal = process.env.CONTEXT_MODE_MAX_LINE_RANGE;
|
|
49
77
|
if (envVal) {
|
|
50
78
|
const parsed = parseInt(envVal, 10);
|
|
@@ -54,7 +82,7 @@ function getMaxLineRange(maxReadBytes = DEFAULT_MAX_READ_BYTES) {
|
|
|
54
82
|
return Math.max(50, Math.round(maxReadBytes / 40));
|
|
55
83
|
}
|
|
56
84
|
|
|
57
|
-
function formatBytes(bytes) {
|
|
85
|
+
export function formatBytes(bytes) {
|
|
58
86
|
if (bytes < 1024) return `${bytes} B`;
|
|
59
87
|
if (bytes < 1024 * 1024) {
|
|
60
88
|
const kb = bytes / 1024;
|
|
@@ -269,6 +297,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
269
297
|
|
|
270
298
|
const cleanCmd = cleanStringArg(commandLine);
|
|
271
299
|
const maxReadBytes = getMaxReadBytes(sessionId);
|
|
300
|
+
const maxLineRange = getMaxLineRange(maxReadBytes);
|
|
272
301
|
const exemptExtensions = getExemptExtensions(sessionId);
|
|
273
302
|
|
|
274
303
|
// 1. Git log without count limiter
|
|
@@ -279,7 +308,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
279
308
|
shouldDeny: true,
|
|
280
309
|
reason:
|
|
281
310
|
`[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 '
|
|
311
|
+
`Please specify a count (e.g. 'git log -n 10') or run inside 'ctx_execute'.`,
|
|
283
312
|
size: 32768,
|
|
284
313
|
targetPath: "git log"
|
|
285
314
|
};
|
|
@@ -307,7 +336,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
307
336
|
shouldDeny: true,
|
|
308
337
|
reason:
|
|
309
338
|
`[context-mode protection] Direct curl/wget download to stdout risks flooding the context window. ` +
|
|
310
|
-
`Please use '
|
|
339
|
+
`Please use 'ctx_execute', save to disk ('-o <file>'), or limit output (e.g. '| head -n <lines>').`,
|
|
311
340
|
size: 32768,
|
|
312
341
|
targetPath: urlMatch ? urlMatch[0] : cleanCmd
|
|
313
342
|
};
|
|
@@ -337,7 +366,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
337
366
|
shouldDeny: true,
|
|
338
367
|
reason:
|
|
339
368
|
`[context-mode protection] Wildcard file dump ('${rawTarget}') risks flooding the context window. ` +
|
|
340
|
-
`Please use '
|
|
369
|
+
`Please use 'ctx_execute' or limit output to only the needed lines (<= ${maxLineRange} lines, e.g. '| Select-Object -First <lines>').`,
|
|
341
370
|
size: 32768,
|
|
342
371
|
targetPath: rawTarget
|
|
343
372
|
};
|
|
@@ -358,14 +387,48 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
358
387
|
const stat = fs.statSync(absPath);
|
|
359
388
|
// Dynamic cutoff check against active setting
|
|
360
389
|
if (maxReadBytes > 0 && stat.size > maxReadBytes) {
|
|
390
|
+
const maxAutoIndexBytes = getMaxAutoIndexBytes(sessionId);
|
|
391
|
+
const targetPath = resolveFilePath(absPath, cwd) || cleanTarget;
|
|
392
|
+
|
|
393
|
+
let isAutoIndexed = false;
|
|
394
|
+
if (maxAutoIndexBytes > 0 && stat.size <= maxAutoIndexBytes) {
|
|
395
|
+
try {
|
|
396
|
+
const store = new ContextModeStore();
|
|
397
|
+
const content = fs.readFileSync(absPath, "utf8");
|
|
398
|
+
store.indexContent({
|
|
399
|
+
sessionId,
|
|
400
|
+
worktree: cwd,
|
|
401
|
+
agent: "antigravity",
|
|
402
|
+
kind: "file",
|
|
403
|
+
label: targetPath,
|
|
404
|
+
path: targetPath,
|
|
405
|
+
content,
|
|
406
|
+
mtime: Math.round(stat.mtimeMs)
|
|
407
|
+
});
|
|
408
|
+
store.close();
|
|
409
|
+
isAutoIndexed = true;
|
|
410
|
+
} catch {}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
let reason = "";
|
|
414
|
+
if (isAutoIndexed) {
|
|
415
|
+
reason =
|
|
416
|
+
`[context-mode protection: auto-indexed] Command attempts an un-paged dump of '${cleanTarget}' (${formatBytes(stat.size)}), ` +
|
|
417
|
+
`exceeding the active ${formatBytes(maxReadBytes)} context limit. ` +
|
|
418
|
+
`The file has been automatically indexed into Context Mode. ` +
|
|
419
|
+
`Query it with 'ctx_search(queries: [...], path: "${targetPath}")' or limit output to only needed lines (<= ${maxLineRange} lines, e.g. -Head <lines> or '| Select-Object -First <lines>').`;
|
|
420
|
+
} else {
|
|
421
|
+
reason =
|
|
422
|
+
`[context-mode protection] Command attempts an un-paged dump of '${cleanTarget}' (${formatBytes(stat.size)}), ` +
|
|
423
|
+
`exceeding the active ${formatBytes(maxReadBytes)} context limit. ` +
|
|
424
|
+
`Please use 'ctx_execute' or limit output to only needed lines (<= ${maxLineRange} lines, e.g. -Head <lines> or '| Select-Object -First <lines>').`;
|
|
425
|
+
}
|
|
426
|
+
|
|
361
427
|
return {
|
|
362
428
|
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'.`,
|
|
429
|
+
reason,
|
|
367
430
|
size: stat.size,
|
|
368
|
-
targetPath
|
|
431
|
+
targetPath
|
|
369
432
|
};
|
|
370
433
|
}
|
|
371
434
|
|
|
@@ -379,7 +442,7 @@ export function inspectCommand({ commandLine, cwd, sessionId }) {
|
|
|
379
442
|
shouldDeny: true,
|
|
380
443
|
reason:
|
|
381
444
|
`[context-mode protection] Command matches an un-paged file dump ('${rawTarget}') that could flood the context window. ` +
|
|
382
|
-
`Please use '
|
|
445
|
+
`Please use 'ctx_execute' or limit output to only needed lines (<= ${maxLineRange} lines, e.g. '| Select-Object -First <lines>' or '| head -n <lines>').`,
|
|
383
446
|
size: 32768,
|
|
384
447
|
targetPath: cleanTarget || rawTarget
|
|
385
448
|
};
|
|
@@ -447,11 +510,45 @@ async function main() {
|
|
|
447
510
|
const isWideRange = maxLineRange > 0 && (endLine === null || (endLine - startLine) > maxLineRange);
|
|
448
511
|
|
|
449
512
|
if (isLargeFile && isWideRange) {
|
|
450
|
-
const lineInstruction = maxLineRange > 0 ? ` or
|
|
451
|
-
const
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
513
|
+
const lineInstruction = maxLineRange > 0 ? ` or read only the needed lines with StartLine/EndLine (<= ${maxLineRange} lines).` : "";
|
|
514
|
+
const maxAutoIndexBytes = getMaxAutoIndexBytes(sessionId);
|
|
515
|
+
const targetPath = resolveFilePath(absPath, cwd) || filePath;
|
|
516
|
+
|
|
517
|
+
let isAutoIndexed = false;
|
|
518
|
+
if (maxAutoIndexBytes > 0 && stat.size <= maxAutoIndexBytes) {
|
|
519
|
+
try {
|
|
520
|
+
const store = new ContextModeStore();
|
|
521
|
+
const content = fs.readFileSync(absPath, "utf8");
|
|
522
|
+
store.indexContent({
|
|
523
|
+
sessionId,
|
|
524
|
+
worktree: cwd,
|
|
525
|
+
agent: agentName,
|
|
526
|
+
kind: "file",
|
|
527
|
+
label: targetPath,
|
|
528
|
+
path: targetPath,
|
|
529
|
+
content,
|
|
530
|
+
mtime: Math.round(stat.mtimeMs)
|
|
531
|
+
});
|
|
532
|
+
store.close();
|
|
533
|
+
isAutoIndexed = true;
|
|
534
|
+
} catch {}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
let reason = "";
|
|
538
|
+
if (isAutoIndexed) {
|
|
539
|
+
reason =
|
|
540
|
+
`[context-mode protection: auto-indexed] File '${targetPath}' (${formatBytes(stat.size)}) ` +
|
|
541
|
+
`exceeded the active ${formatBytes(maxReadBytes)} context limit. ` +
|
|
542
|
+
`The file has been automatically indexed into Context Mode. ` +
|
|
543
|
+
`Query it immediately using 'ctx_search(queries: [...], path: "${targetPath}")'${lineInstruction}`;
|
|
544
|
+
} else {
|
|
545
|
+
const ceilingNote = maxAutoIndexBytes > 0 && stat.size > maxAutoIndexBytes
|
|
546
|
+
? ` and the ${formatBytes(maxAutoIndexBytes)} auto-indexing ceiling`
|
|
547
|
+
: "";
|
|
548
|
+
reason =
|
|
549
|
+
`[context-mode protection] File is ${formatBytes(stat.size)}, exceeding the active ${formatBytes(maxReadBytes)} context limit${ceilingNote}. ` +
|
|
550
|
+
`Please use 'ctx_execute'${lineInstruction}`;
|
|
551
|
+
}
|
|
455
552
|
|
|
456
553
|
// Record interception event in SQLite store so dashboard telemetry updates immediately
|
|
457
554
|
recordInterception({
|
|
@@ -459,7 +556,7 @@ async function main() {
|
|
|
459
556
|
agent: agentName,
|
|
460
557
|
cwd,
|
|
461
558
|
toolName,
|
|
462
|
-
path:
|
|
559
|
+
path: targetPath,
|
|
463
560
|
size: stat.size,
|
|
464
561
|
reason
|
|
465
562
|
});
|
|
@@ -514,7 +611,15 @@ async function main() {
|
|
|
514
611
|
process.exit(0);
|
|
515
612
|
}
|
|
516
613
|
|
|
517
|
-
|
|
518
|
-
process.
|
|
519
|
-
|
|
520
|
-
|
|
614
|
+
const isMain = Boolean(
|
|
615
|
+
process.argv[1] &&
|
|
616
|
+
path.resolve(fileURLToPath(import.meta.url)).toLowerCase() ===
|
|
617
|
+
path.resolve(process.argv[1]).toLowerCase()
|
|
618
|
+
);
|
|
619
|
+
|
|
620
|
+
if (isMain) {
|
|
621
|
+
main().catch(() => {
|
|
622
|
+
process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
|
|
623
|
+
process.exit(0);
|
|
624
|
+
});
|
|
625
|
+
}
|
package/hooks/session-start.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { ContextModeStore, formatExemptSummary } from "../lib/store.js";
|
|
5
|
+
import { resolveSharedSessionId, formatBytes, getMaxLineRange } from "./pre-tool-use.js";
|
|
3
6
|
|
|
4
7
|
function readStdin() {
|
|
5
8
|
return new Promise((resolve) => {
|
|
@@ -14,21 +17,78 @@ function readStdin() {
|
|
|
14
17
|
});
|
|
15
18
|
}
|
|
16
19
|
|
|
20
|
+
export function buildStatusMessage({
|
|
21
|
+
cutoff = 8192,
|
|
22
|
+
exemptCategories = [],
|
|
23
|
+
exemptExtensions = [],
|
|
24
|
+
customExtensions = [],
|
|
25
|
+
isUpdate = false
|
|
26
|
+
} = {}) {
|
|
27
|
+
const cutoffFormatted =
|
|
28
|
+
cutoff === 0
|
|
29
|
+
? "Disabled (unlimited)"
|
|
30
|
+
: `${formatBytes(cutoff)} (${cutoff.toLocaleString()} bytes)`;
|
|
31
|
+
|
|
32
|
+
const exemptSummary = formatExemptSummary({
|
|
33
|
+
activeCats: exemptCategories,
|
|
34
|
+
customs: customExtensions
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const header = isUpdate
|
|
38
|
+
? "[context-mode config update]"
|
|
39
|
+
: "[context-mode active]";
|
|
40
|
+
|
|
41
|
+
const lines = [
|
|
42
|
+
header,
|
|
43
|
+
`• Read cutoff: ${cutoffFormatted}`,
|
|
44
|
+
`• Exempt file types: ${exemptSummary || "None"}`
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
return lines.join("\n");
|
|
48
|
+
}
|
|
49
|
+
|
|
17
50
|
async function main() {
|
|
18
|
-
await readStdin();
|
|
51
|
+
const rawInput = await readStdin();
|
|
52
|
+
let payload = {};
|
|
53
|
+
try {
|
|
54
|
+
if (rawInput && rawInput.trim()) {
|
|
55
|
+
payload = JSON.parse(rawInput);
|
|
56
|
+
}
|
|
57
|
+
} catch {}
|
|
58
|
+
|
|
59
|
+
const sessionId = resolveSharedSessionId(payload);
|
|
60
|
+
let cutoff = 8192;
|
|
61
|
+
let exemptCats = [];
|
|
62
|
+
let exemptExts = [];
|
|
63
|
+
let customExts = [];
|
|
19
64
|
|
|
20
65
|
try {
|
|
21
66
|
const store = new ContextModeStore();
|
|
22
67
|
store.clearSessionOverrides();
|
|
68
|
+
cutoff = store.getCutoff(sessionId);
|
|
69
|
+
exemptCats = store.getExemptCategories(sessionId);
|
|
70
|
+
exemptExts = store.getExemptExtensions(sessionId);
|
|
71
|
+
customExts = store.getCustomExemptExtensions(sessionId);
|
|
72
|
+
|
|
73
|
+
// Save informed configuration signature for this session so PreInvocation stays in sync
|
|
74
|
+
const sig = `${cutoff}:${exemptExts.slice().sort().join(",")}`;
|
|
75
|
+
store.setMeta(`informed_config:session:${sessionId}`, sig);
|
|
23
76
|
store.close();
|
|
24
77
|
} catch {}
|
|
25
78
|
|
|
79
|
+
const message = buildStatusMessage({
|
|
80
|
+
cutoff,
|
|
81
|
+
exemptCategories: exemptCats,
|
|
82
|
+
exemptExtensions: exemptExts,
|
|
83
|
+
customExtensions: customExts,
|
|
84
|
+
isUpdate: false
|
|
85
|
+
});
|
|
86
|
+
|
|
26
87
|
const response = {
|
|
27
88
|
injectSteps: [
|
|
28
89
|
{
|
|
29
90
|
systemMessage: {
|
|
30
|
-
systemMessage:
|
|
31
|
-
"context-mode active: Tool executions are protected against context window bloat via SQLite FTS5 BM25 search and local sandboxed execution. For heavy logs, large files, or bulk queries, use ctx_execute or ctx_search."
|
|
91
|
+
systemMessage: message
|
|
32
92
|
}
|
|
33
93
|
}
|
|
34
94
|
]
|
|
@@ -37,6 +97,14 @@ async function main() {
|
|
|
37
97
|
process.stdout.write(JSON.stringify(response) + "\n");
|
|
38
98
|
}
|
|
39
99
|
|
|
40
|
-
|
|
41
|
-
process.
|
|
42
|
-
|
|
100
|
+
const isMain = Boolean(
|
|
101
|
+
process.argv[1] &&
|
|
102
|
+
path.resolve(fileURLToPath(import.meta.url)).toLowerCase() ===
|
|
103
|
+
path.resolve(process.argv[1]).toLowerCase()
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
if (isMain) {
|
|
107
|
+
main().catch(() => {
|
|
108
|
+
process.stdout.write(JSON.stringify({}) + "\n");
|
|
109
|
+
});
|
|
110
|
+
}
|