antigravity-plugin-context-mode 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to `antigravity-plugin-context-mode` will be documented in this file.
4
+
5
+ ## [1.0.0] - 2026-11-14
6
+
7
+ ### Added
8
+ - **Native Antigravity App Plugin Bundle**: Complete manifest and customization suite (`plugin.json`, `hooks.json`, `mcp_config.json`).
9
+ - **Stdio MCP Server**: Zero-dependency JSON-RPC server implementing the 8 core context tools (`ctx_execute`, `ctx_batch`, `ctx_index`, `ctx_search`, `ctx_resume`, `ctx_stats`, `ctx_doctor`, `ctx_purge`).
10
+ - **SQLite FTS5 Storage Engine**: Native database layer using Node.js `DatabaseSync` (`node:sqlite`) with WAL mode, chunked source storage, and session journaling.
11
+ - **Hybrid Search & Ranking**: Combined Porter BM25 stemming and Trigram full-text search merged via Reciprocal Rank Fusion ($RRF_{k=60}$).
12
+ - **Antigravity Lifecycle Hooks**:
13
+ - `PreToolUse`: Automated gating that blocks unbounded log dump commands (`cat`, `Get-Content` on raw `.log`) and un-paged file reads over 8 KB.
14
+ - `SessionStart`: Injects session state continuity and active context protection advice.
15
+ - **Configurable Cutoffs via Environment Variables**:
16
+ - `CONTEXT_MODE_MAX_READ_BYTES`: Configurable ceiling for un-paged file reads (defaults to 8 KB / 8,192 bytes).
17
+ - `CONTEXT_MODE_MAX_LINE_RANGE`: Maximum allowed line range slice without pagination rejection (defaults to 200 lines).
18
+ - **Auxiliary Pane Sidecar Web UI**: Dedicated sidecar dashboard (`sidecars/dashboard/`):
19
+ - `sidecar.json` configured for `SIDECAR_UI_ENTRYPOINT_AUX_PANE`.
20
+ - `server.mjs` backend powered by `sidecar_sdk` with fallback standalone HTTP server.
21
+ - `index.html` real-time telemetry dashboard featuring reduction rate metrics, volume compression visualization, an interactive FTS5 search inspector, recent sources, and session purge controls.
22
+ - **Agent Skill & Behavioral Rules**: Bundled `skills/context-mode/SKILL.md` (Thinking in Code) and `rules/AGENTS.md` (context budgeting laws).
23
+ - **Test Suite**: Native `node:test` test harness covering storage, execution sandbox, tools, hooks, and MCP JSON-RPC protocol with 100% pass rate.
24
+ - **CI/CD Automation**: Automated `publish.yml` GitHub Actions workflow for npm and GitHub Releases.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Phillip Webber
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,185 @@
1
- # Temporary Holding Version
1
+ # Antigravity Context Mode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Stop context bloat. Save 90%+ of your prompt tokens. Keep your agent fast, focused, and responsive.**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/antigravity-plugin-context-mode.svg)](https://www.npmjs.com/package/antigravity-plugin-context-mode)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+ [![Zero Runtime Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)]()
8
+ [![Antigravity App Compatible](https://img.shields.io/badge/Antigravity%20App-Native%20Plugin-6366f1.svg)]()
9
+
10
+ **Antigravity Context Mode** is a free, local-first plugin built specifically for the **Google Antigravity App**. It prevents terminal commands, build logs, and multi-megabyte files from flooding your conversation history, saving thousands of tokens per turn and stopping "agent amnesia" in its tracks.
11
+
12
+ ---
13
+ <img width="962" height="812" alt="image" src="https://github.com/user-attachments/assets/873f818d-3bd9-4746-94a9-fc182a174efb" />
14
+
15
+ ## ⚡ The Problem: Context Window Bloat
16
+
17
+ When an AI coding agent runs tools, standard workflows dump everything directly into your conversation history:
18
+
19
+ * Running `Get-Content Logs/Editor.log` dumps **65 KB (~16,000 tokens)** into your prompt.
20
+ * Running test suites or compiler logs dumps **100+ KB** of repetitive output.
21
+ * Reading large source files or documentation dumps **thousands of lines** of irrelevant boilerplate.
22
+
23
+ ### Why this hurts:
24
+ 1. **Agent Amnesia**: Important system instructions and recent conversation steps get drowned out in a sea of raw log text ("lost in the middle").
25
+ 2. **Slow Responses**: Prompt evaluation times climb rapidly as token count grows.
26
+ 3. **Burned Quota & Limits**: You hit model context ceilings and rate limits after only a few turns.
27
+
28
+ ---
29
+
30
+ ## 🛡️ The Solution: How Context Mode Works
31
+
32
+ ```text
33
+ ┌────────────────────────────────────────────────────────────────────────┐
34
+ │ ANTIGRAVITY AGENT │
35
+ └───────────────────────────────────┬────────────────────────────────────┘
36
+ │
37
+ Tool Call (e.g. read large log)
38
+ ▼
39
+ ┌────────────────────────────────────────────────────────────────────────┐
40
+ │ PRE-TOOL-USE LIFECYCLE HOOK GATE │
41
+ │ • Blocks unbounded dumps (cat *.log, Get-Content) │
42
+ │ • Enforces 8 KB cutoff for un-paged file reads │
43
+ └───────────────────┬────────────────────────────────┬───────────────────┘
44
+ │ │
45
+ Under 8 KB (Safe) Over 8 KB (Blocked)
46
+ │ │
47
+ ▼ ▼
48
+ Executes normally Redirects to Context Mode Engine:
49
+ ┌───────────────────────────────────┐
50
+ │ 1. Sandboxed Code Execution │
51
+ │ (Thinking in Code) │
52
+ │ 2. SQLite FTS5 Indexing │
53
+ │ 3. BM25 + Trigram RRF Search │
54
+ └───────────────────────────────────┘
55
+ │
56
+ ▼
57
+ Returns only the 550 B
58
+ filtered answer to prompt!
59
+ ```
60
+
61
+ 1. **Smart Lifecycle Gating (`hooks.json`)**: Before a command or file read executes, Context Mode checks if it will cause a token flood. If it exceeds 8 KB or attempts an unbounded log dump, the hook intercepts it and guides the agent to query or sandbox the data instead.
62
+ 2. **"Thinking in Code" (`ctx_execute`)**: Instead of reading a 5,000-line log into memory, the agent executes a 5-line local script (Node, Python, PowerShell, or Bash). The script filters the log in **50 ms** and returns *only* the specific errors to the conversation.
63
+ 3. **SQLite FTS5 Storage (`ctx_search`, `ctx_index`)**: Full raw outputs are saved safely on your local disk in `~/.context-mode/context.db`. The agent uses reciprocal rank fusion search to fetch only the exact snippets it needs.
64
+ 4. **Live Sidecar Dashboard**: A native side pane right inside the Antigravity App that displays your real-time token savings and lets you search indexed logs with a click.
65
+
66
+ ---
67
+
68
+ ## 📊 Proven Results
69
+
70
+ Tested live on real Unity 6.6 build and engine logs in the Antigravity App:
71
+
72
+ | Operation | Without Context Mode | With Context Mode | Savings |
73
+ | :--- | :---: | :---: | :---: |
74
+ | **Parsing 665-line Unity Editor.log** | 65,242 B (~16,300 tokens) | **550 B (~137 tokens)** | **99.2% saved** |
75
+ | **Full File Read on 40 KB component** | 40,960 B (~10,240 tokens) | Intercepted & paged to 50 lines (**~800 tokens**) | **92.1% saved** |
76
+ | **Searching Compiler Warnings** | Entire log dumped into chat | Top 2 ranked FTS5 snippets (**~350 tokens**) | **97.8% saved** |
77
+
78
+ ---
79
+
80
+ ## 🚀 Quick Start & Installation
81
+
82
+ ### Option 1: Global User Install (Recommended)
83
+ Installs Context Mode for all your projects and conversations:
84
+
85
+ ```bash
86
+ # Clone directly into your Antigravity user plugins directory
87
+ git clone https://github.com/Domush/antigravity-plugin-context-mode.git ~/.gemini/config/plugins/antigravity-plugin-context-mode
88
+ ```
89
+
90
+ Restart the Antigravity App once. The plugin, hooks, and MCP tools will be active globally!
91
+
92
+ ### Option 2: Project-Scoped Workspace Install
93
+ If you only want Context Mode active in a specific project:
94
+
95
+ ```bash
96
+ # From your project root directory:
97
+ mkdir -p .agents/plugins
98
+ git clone https://github.com/Domush/antigravity-plugin-context-mode.git .agents/plugins/antigravity-plugin-context-mode
99
+ ```
100
+
101
+ ### Option 3: Via npm
102
+ ```bash
103
+ npm install -g antigravity-plugin-context-mode
104
+ ```
105
+
106
+ ---
107
+
108
+ ## 🖥️ Live Auxiliary Sidecar Dashboard
109
+
110
+ Context Mode includes a native web dashboard that opens directly in Antigravity's **Auxiliary (Side) Pane**:
111
+
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.
115
+ * **Interactive FTS5 Search Inspector:** Search your indexed logs and files directly from the UI to see what the agent has indexed.
116
+ * **1-Click Session Purge:** Wipe session indexes and reset counters whenever you start a fresh task.
117
+
118
+ ---
119
+
120
+ ## 🧰 Available MCP Tools
121
+
122
+ Once installed, the following 8 tools are registered in your Antigravity App:
123
+
124
+ | Tool | What It Does | Example Use Case |
125
+ | :--- | :--- | :--- |
126
+ | **`ctx_execute`** | Runs sandboxed Node.js, Python, or PowerShell scripts with token limits. | Filtering build errors, extracting JSON keys from large API responses. |
127
+ | **`ctx_search`** | Searches SQLite FTS5 using BM25 stemming and Trigram matching. | Finding error codes, method names, or stack traces in past logs. |
128
+ | **`ctx_index`** | Indexes local files, web URLs, or text into searchable chunks. | Indexing a 1,000-line documentation file or architecture spec. |
129
+ | **`ctx_batch`** | Runs multiple shell commands in batch and indexes the combined output. | Running `git status`, `git log`, and `npm test` in one compact call. |
130
+ | **`ctx_stats`** | Displays a formatted ASCII savings report and token metrics. | Checking how many tokens were saved during your session. |
131
+ | **`ctx_resume`** | Returns recent indexed sources and state pointers. | Re-orienting the agent after context compaction. |
132
+ | **`ctx_doctor`** | Checks SQLite database health, WAL mode, and active runtimes. | Verifying database integrity and platform runtimes. |
133
+ | **`ctx_purge`** | Clears stored sources and events from SQLite. | Resetting session or worktree indexes. |
134
+
135
+ ---
136
+
137
+ ## ⚙️ Configuration & Environment Variables
138
+
139
+ You can customize Context Mode's cutoffs at any time using environment variables:
140
+
141
+ | Variable | Default | Description |
142
+ | :--- | :---: | :--- |
143
+ | `CONTEXT_MODE_MAX_READ_BYTES` | `8192` (8 KB) | Maximum file size allowed for an un-paged `read_file` before gating kicks in. Set to `4096` for strict mode or `16384` for relaxed mode. |
144
+ | `CONTEXT_MODE_MAX_LINE_RANGE` | `200` lines | Maximum line slice allowed without pagination rejection. |
145
+
146
+ ### How to set on Windows (PowerShell):
147
+ ```powershell
148
+ $env:CONTEXT_MODE_MAX_READ_BYTES = "4096" # Enforce strict 4 KB cutoff
149
+ ```
150
+
151
+ ### How to set on macOS / Linux:
152
+ ```bash
153
+ export CONTEXT_MODE_MAX_READ_BYTES=4096
154
+ ```
155
+
156
+ ---
157
+
158
+ ## 🔒 Privacy & Zero Dependencies
159
+
160
+ * **100% Local**: All indexed data lives on your machine in `~/.context-mode/context.db`. Zero network calls are made.
161
+ * **Zero 3rd-Party Dependencies**: Built exclusively on native Node.js (`node:sqlite` / `DatabaseSync`, `child_process`, and `http`). No native C++ builds, no `node-gyp`, and no dependency security vulnerabilities.
162
+ * **Safe Sandboxing**: Process execution in `ctx_execute` enforces strict execution timeouts and output caps to prevent runaway processes.
163
+
164
+ ---
165
+
166
+ ## 🧪 Running Tests
167
+
168
+ Context Mode ships with a complete test suite using Node's native test runner:
169
+
170
+ ```bash
171
+ npm test
172
+ ```
173
+
174
+ Verifies:
175
+ * SQLite FTS5 schema initialization, chunking, Porter BM25, and Trigram search.
176
+ * Reciprocal Rank Fusion (RRF) ranking.
177
+ * Sandbox execution and process timeout termination.
178
+ * `PreToolUse` and `SessionStart` lifecycle hook gating.
179
+ * MCP stdio JSON-RPC protocol compliance.
180
+
181
+ ---
182
+
183
+ ## 📄 License
184
+
185
+ MIT © [Phillip Webber](https://github.com/Domush)
@@ -0,0 +1,20 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
2
+ <defs>
3
+ <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
4
+ <stop offset="0%" stop-color="#4285F4" />
5
+ <stop offset="50%" stop-color="#9B72CF" />
6
+ <stop offset="100%" stop-color="#24C1E0" />
7
+ </linearGradient>
8
+ </defs>
9
+ <rect width="128" height="128" rx="28" fill="#1e1e2e" />
10
+ <rect x="8" y="8" width="112" height="112" rx="22" fill="none" stroke="url(#grad)" stroke-width="3" stroke-opacity="0.4" />
11
+
12
+ <!-- Outer Context Bounds -->
13
+ <rect x="26" y="26" width="76" height="76" rx="14" fill="none" stroke="url(#grad)" stroke-width="4" stroke-dasharray="6 4" />
14
+
15
+ <!-- Inner Compressed Core -->
16
+ <rect x="42" y="42" width="44" height="44" rx="8" fill="url(#grad)" opacity="0.9" />
17
+
18
+ <!-- Lightning / Filter Spark -->
19
+ <path d="M66 48 L56 64 L64 64 L62 80 L74 62 L66 62 Z" fill="#ffffff" />
20
+ </svg>
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ export const DEFAULT_MAX_READ_BYTES = 8192; // 8 KB default cutoff
6
+ export const DEFAULT_MAX_LINE_RANGE = 200; // 200 lines max un-indexed slice
7
+
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;
13
+ }
14
+ return DEFAULT_MAX_READ_BYTES;
15
+ }
16
+
17
+ function getMaxLineRange() {
18
+ const envVal = process.env.CONTEXT_MODE_MAX_LINE_RANGE;
19
+ if (envVal) {
20
+ const parsed = parseInt(envVal, 10);
21
+ if (!Number.isNaN(parsed) && parsed > 0) return parsed;
22
+ }
23
+ return DEFAULT_MAX_LINE_RANGE;
24
+ }
25
+
26
+ function formatBytes(bytes) {
27
+ if (bytes < 1024) return `${bytes} B`;
28
+ if (bytes < 1024 * 1024) {
29
+ const kb = bytes / 1024;
30
+ return `${Number.isInteger(kb) ? kb : kb.toFixed(1)} KB`;
31
+ }
32
+ const mb = bytes / (1024 * 1024);
33
+ return `${Number.isInteger(mb) ? mb : mb.toFixed(2)} MB`;
34
+ }
35
+
36
+ function readStdin() {
37
+ return new Promise((resolve) => {
38
+ let data = "";
39
+ process.stdin.setEncoding("utf8");
40
+ process.stdin.on("data", (chunk) => {
41
+ data += chunk;
42
+ });
43
+ process.stdin.on("end", () => {
44
+ resolve(data);
45
+ });
46
+ });
47
+ }
48
+
49
+ const UNBOUNDED_COMMAND_PATTERNS = [
50
+ /^\s*(cat|type|Get-Content)\s+.*?\.(log|json|xml|csv|tsv|dump|sql|txt)\s*$/i,
51
+ /^\s*git\s+log\s*$/i,
52
+ /^\s*git\s+log\s+--oneline\s*$/i,
53
+ /^\s*curl(\.exe)?\s+-s?\s+https?:\/\/.*?\.(json|log|txt)\s*$/i
54
+ ];
55
+
56
+ async function main() {
57
+ const rawInput = await readStdin();
58
+ if (!rawInput.trim()) {
59
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
60
+ return;
61
+ }
62
+
63
+ let payload;
64
+ try {
65
+ payload = JSON.parse(rawInput);
66
+ } catch {
67
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
68
+ return;
69
+ }
70
+
71
+ const toolCall = payload.toolCall || {};
72
+ const toolName = toolCall.name || "";
73
+ const args = toolCall.args || {};
74
+ const cwd = payload.cwd || process.cwd();
75
+
76
+ // 1. Guard read_file
77
+ if (toolName === "read_file") {
78
+ const filePath = args.Path || args.path || args.filePath || "";
79
+ const startLine = args.StartLine ?? args.startLine ?? 1;
80
+ const endLine = args.EndLine ?? args.endLine ?? null;
81
+ const maxReadBytes = getMaxReadBytes();
82
+ const maxLineRange = getMaxLineRange();
83
+
84
+ if (filePath) {
85
+ const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
86
+ try {
87
+ if (fs.existsSync(absPath)) {
88
+ const stat = fs.statSync(absPath);
89
+ const isLargeFile = stat.size > maxReadBytes;
90
+ const isWideRange = endLine === null || endLine - startLine > maxLineRange;
91
+
92
+ if (isLargeFile && isWideRange) {
93
+ const reason =
94
+ `[context-mode protection] File is ${formatBytes(stat.size)} (~${Math.round(stat.size / 4).toLocaleString()} tokens), exceeding the ${formatBytes(maxReadBytes)} context limit. ` +
95
+ `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).`;
98
+
99
+ process.stdout.write(
100
+ JSON.stringify({
101
+ decision: "deny",
102
+ reason
103
+ }) + "\n"
104
+ );
105
+ return;
106
+ }
107
+ }
108
+ } catch {
109
+ // ignore stat error, allow tool to report error
110
+ }
111
+ }
112
+ }
113
+
114
+ // 2. Guard run_command
115
+ if (toolName === "run_command") {
116
+ const commandLine = args.CommandLine || args.commandLine || args.command || "";
117
+ for (const pattern of UNBOUNDED_COMMAND_PATTERNS) {
118
+ if (pattern.test(commandLine)) {
119
+ const reason =
120
+ `[context-mode protection] Command matches an unbounded dump pattern that could flood the context window. ` +
121
+ `Please use 'mcp_context-mode_ctx_execute' (runs in local sandbox with token bounding) or append a limiter ` +
122
+ `such as '| Select-Object -First 50' or '| head -n 50'.`;
123
+
124
+ process.stdout.write(
125
+ JSON.stringify({
126
+ decision: "deny",
127
+ reason
128
+ }) + "\n"
129
+ );
130
+ return;
131
+ }
132
+ }
133
+ }
134
+
135
+ // Default allow
136
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
137
+ }
138
+
139
+ main().catch(() => {
140
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
141
+ });
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+
3
+ function readStdin() {
4
+ return new Promise((resolve) => {
5
+ let data = "";
6
+ process.stdin.setEncoding("utf8");
7
+ process.stdin.on("data", (chunk) => {
8
+ data += chunk;
9
+ });
10
+ process.stdin.on("end", () => {
11
+ resolve(data);
12
+ });
13
+ });
14
+ }
15
+
16
+ async function main() {
17
+ await readStdin();
18
+
19
+ const response = {
20
+ injectSteps: [
21
+ {
22
+ systemMessage: {
23
+ systemMessage:
24
+ "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."
25
+ }
26
+ }
27
+ ]
28
+ };
29
+
30
+ process.stdout.write(JSON.stringify(response) + "\n");
31
+ }
32
+
33
+ main().catch(() => {
34
+ process.stdout.write(JSON.stringify({}) + "\n");
35
+ });
package/hooks.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "context-mode": {
3
+ "PreToolUse": [
4
+ {
5
+ "matcher": "run_command|read_file",
6
+ "hooks": [
7
+ {
8
+ "type": "command",
9
+ "command": "node ./hooks/pre-tool-use.js",
10
+ "timeout": 15
11
+ }
12
+ ]
13
+ }
14
+ ],
15
+ "SessionStart": [
16
+ {
17
+ "type": "command",
18
+ "command": "node ./hooks/session-start.js",
19
+ "timeout": 10
20
+ }
21
+ ]
22
+ }
23
+ }
@@ -0,0 +1,221 @@
1
+ import { spawn } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ export const OUTPUT_CAP = 16384; // 16 KB default preview cap
5
+ export const DEFAULT_TIMEOUT_MS = 30000; // 30s timeout
6
+
7
+ /** Run a process and capture stdout / stderr with time and byte bounding */
8
+ export function runProcess({
9
+ cmd,
10
+ args = [],
11
+ cwd,
12
+ timeoutMs = DEFAULT_TIMEOUT_MS,
13
+ maxBytes = 10 * 1024 * 1024,
14
+ env = process.env,
15
+ stdinData = null
16
+ }) {
17
+ return new Promise((resolve) => {
18
+ const stdoutBuffer = [];
19
+ const stderrBuffer = [];
20
+ let stdoutBytes = 0;
21
+ let stderrBytes = 0;
22
+ let timedOut = false;
23
+ let finished = false;
24
+
25
+ const child = spawn(cmd, args, {
26
+ cwd: cwd || process.cwd(),
27
+ env: { ...process.env, ...env },
28
+ windowsHide: true,
29
+ stdio: ["pipe", "pipe", "pipe"]
30
+ });
31
+
32
+ const timer = setTimeout(() => {
33
+ timedOut = true;
34
+ try {
35
+ if (process.platform === "win32") {
36
+ spawn("taskkill", ["/F", "/T", "/PID", String(child.pid)], { windowsHide: true });
37
+ } else {
38
+ child.kill("SIGKILL");
39
+ }
40
+ } catch {
41
+ // kill failed
42
+ }
43
+ }, timeoutMs);
44
+
45
+ if (stdinData && child.stdin) {
46
+ try {
47
+ child.stdin.end(stdinData);
48
+ } catch {
49
+ // ignore
50
+ }
51
+ } else if (child.stdin) {
52
+ try {
53
+ child.stdin.end();
54
+ } catch {
55
+ // ignore
56
+ }
57
+ }
58
+
59
+ child.stdout.on("data", (chunk) => {
60
+ stdoutBytes += chunk.byteLength;
61
+ if (stdoutBytes <= maxBytes) {
62
+ stdoutBuffer.push(chunk);
63
+ }
64
+ });
65
+
66
+ child.stderr.on("data", (chunk) => {
67
+ stderrBytes += chunk.byteLength;
68
+ if (stderrBytes <= maxBytes) {
69
+ stderrBuffer.push(chunk);
70
+ }
71
+ });
72
+
73
+ const onFinish = (exitCode, signal) => {
74
+ if (finished) return;
75
+ finished = true;
76
+ clearTimeout(timer);
77
+
78
+ const stdout = Buffer.concat(stdoutBuffer).toString("utf8");
79
+ const stderr = Buffer.concat(stderrBuffer).toString("utf8");
80
+ const rawBytes = stdoutBytes + stderrBytes;
81
+
82
+ resolve({
83
+ ok: exitCode === 0 && !timedOut,
84
+ exitCode: timedOut ? 124 : (exitCode ?? (signal ? 1 : 0)),
85
+ signal,
86
+ timedOut,
87
+ stdout,
88
+ stderr,
89
+ rawBytes
90
+ });
91
+ };
92
+
93
+ child.on("error", (err) => {
94
+ if (finished) return;
95
+ finished = true;
96
+ clearTimeout(timer);
97
+ resolve({
98
+ ok: false,
99
+ exitCode: 1,
100
+ signal: null,
101
+ timedOut: false,
102
+ stdout: "",
103
+ stderr: String(err && err.message ? err.message : err),
104
+ rawBytes: 0
105
+ });
106
+ });
107
+
108
+ child.on("close", (code, sig) => onFinish(code, sig));
109
+ child.on("exit", (code, sig) => onFinish(code, sig));
110
+ });
111
+ }
112
+
113
+ /** Execute code in specified runtime (nodejs, python, shell, pwsh, cmd) */
114
+ export async function executeCode({
115
+ language = "shell",
116
+ code = "",
117
+ file = "",
118
+ args = [],
119
+ cwd,
120
+ timeoutMs = DEFAULT_TIMEOUT_MS,
121
+ env = {}
122
+ }) {
123
+ const normLang = String(language || "shell").toLowerCase().trim();
124
+ const workdir = cwd || process.cwd();
125
+
126
+ // 1. Node.js
127
+ if (normLang === "nodejs" || normLang === "node" || normLang === "javascript" || normLang === "js") {
128
+ if (file) {
129
+ const scriptPath = path.isAbsolute(file) ? file : path.resolve(workdir, file);
130
+ return runProcess({
131
+ cmd: process.execPath,
132
+ args: [scriptPath, ...args],
133
+ cwd: workdir,
134
+ timeoutMs,
135
+ env
136
+ });
137
+ }
138
+ return runProcess({
139
+ cmd: process.execPath,
140
+ args: ["-e", code, "--", ...args],
141
+ cwd: workdir,
142
+ timeoutMs,
143
+ env
144
+ });
145
+ }
146
+
147
+ // 2. Python
148
+ if (normLang === "python" || normLang === "python3" || normLang === "py") {
149
+ const pythonBin = process.platform === "win32" ? "python" : "python3";
150
+ if (file) {
151
+ const scriptPath = path.isAbsolute(file) ? file : path.resolve(workdir, file);
152
+ return runProcess({
153
+ cmd: pythonBin,
154
+ args: [scriptPath, ...args],
155
+ cwd: workdir,
156
+ timeoutMs,
157
+ env
158
+ });
159
+ }
160
+ return runProcess({
161
+ cmd: pythonBin,
162
+ args: ["-c", code, ...args],
163
+ cwd: workdir,
164
+ timeoutMs,
165
+ env
166
+ });
167
+ }
168
+
169
+ // 3. PowerShell
170
+ if (normLang === "pwsh" || normLang === "powershell") {
171
+ const bin = "powershell.exe";
172
+ if (file) {
173
+ const scriptPath = path.isAbsolute(file) ? file : path.resolve(workdir, file);
174
+ return runProcess({
175
+ cmd: bin,
176
+ args: ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", scriptPath, ...args],
177
+ cwd: workdir,
178
+ timeoutMs,
179
+ env
180
+ });
181
+ }
182
+ return runProcess({
183
+ cmd: bin,
184
+ args: ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", code],
185
+ cwd: workdir,
186
+ timeoutMs,
187
+ env
188
+ });
189
+ }
190
+
191
+ // 4. Windows CMD
192
+ if (normLang === "cmd" || normLang === "bat") {
193
+ return runProcess({
194
+ cmd: "cmd.exe",
195
+ args: ["/d", "/s", "/c", code || (file ? `call "${file}"` : "")],
196
+ cwd: workdir,
197
+ timeoutMs,
198
+ env
199
+ });
200
+ }
201
+
202
+ // 5. Default Shell
203
+ if (process.platform === "win32") {
204
+ return runProcess({
205
+ cmd: "powershell.exe",
206
+ args: ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", code || (file ? `& "${file}"` : "")],
207
+ cwd: workdir,
208
+ timeoutMs,
209
+ env
210
+ });
211
+ } else {
212
+ const shell = process.env.SHELL || "/bin/sh";
213
+ return runProcess({
214
+ cmd: shell,
215
+ args: ["-c", code || (file ? `sh "${file}"` : "")],
216
+ cwd: workdir,
217
+ timeoutMs,
218
+ env
219
+ });
220
+ }
221
+ }