Deep dive into the AI Toolbox plugin's system architecture, design patterns, and internal workflows.
tests/ βββ *.test.ts β Unit tests for each module βββ __mocks__/ β Jest mocks for ESM packages β βββ archiver.ts β Mock for archiver@8.x (ESM-only) β βββ unzipper.ts β Mock for unzipper (ESM syntax) βββ fixtures/ β Test data files (if needed)
jest.config.cjs){ preset: 'ts-jest', testEnvironment: 'node', moduleNameMapper: { '^archiver ## π System Overview
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β LM Studio Host β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β Plugin Runner (Node.js) β β β β β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β AI Toolbox Plugin β β β β β β β β β β β β ββββββββββββββββ β β β β β β β index.ts βββββ Entry Point (main function) β β β β β β β (entry) β β β β β β β ββββββββ¬ββββββββ β β β β β β β β β β β β β βΌ β β β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β β β Core Services β β β β β β β β ββββββββββββ ββββββββββββ ββββββββββββββββββββ β β β β β β β β β config.tsβ βsecurity β βstateManager.ts β β β β β β β β β β(Zod+UI) β β .ts β β(persistence) β β β β β β β β β ββββββββββββ β(validators)β ββββββββββββββββββββ β β β β β β β β ββββββββββββ β β β β β β β β ββββββββββββ ββββββββββββ ββββββββββββββββββββ β β β β β β β β βworkingDirβ βperformancβ βpromptPreprocessor β β β β β β β β β β .ts β βeUtils.ts β β .ts β β β β β β β β β β(path mgmtβ β(caching) β β(Document RAG + β β β β β β β β β ββββββββββββ ββββββββββββ β ContextGuard) β β β β β β β β β ββββββββββββββββββββ β β β β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β β β β β β β β ββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β β β Tool Registration Layer β β β β β β β β βββββββββββββββββββ ββββββββββββββββββββββββ β β β β β β β β β toolsProvider.ts β β ToolRegistry β β β β β β β β β β (factory fn) β β (central map) β β β β β β β β β ββββββββββ¬βββββββββ ββββββββββββ¬ββββββββββββ β β β β β β β βββββββββββββΌβββββββββββββββββββββββΌββββββββββββββ β β β β β β β β β β β β β β βββββββββββββ΄βββββββββββββββββββββββ΄ββββββββββββββ β β β β β β β Tool Modules (14 files) β β β β β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β β β β β βfileSys β βwebRes β βbrowser β β git β β β β β β β β β β (17) β β (4) β β (5) β β (14) β β β β β β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β β β β β β datab β βbackgnd β βexec β β utilityβ β β β β β β β β β (1) β β cmd(3) β β (4) β β (7) β β β β β β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β β β β β β image β β http β β vector β β UI β β β β β β β β β β (4) β β (3) β β RAG(3) β β Gen(3) β β β β β β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β β β β β ββββββββββ β β β β β β β β β Context β β β β β β β β β β Mgmt(7) β β β β β β β β β ββββββββββ β β β β β β β βββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β External Dependencies β β β β β Puppeteer β simple-git β Tesseract.js β pdf-parse β β β β β duck-duck-scrape β node:sqlite β node-notifier β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
src/toolsProvider.ts)Central registry managing all tool instances:
Key Design Decisions:
src/stateManager.ts)Persistent state with debounced disk writes:
Key Features:
src/tools/contextManagementTools.ts) πPersistent context storage for session tracking:
Key Features:
src/security.ts)Multi-layer security pipeline:
src/workingDir.ts)Mutable base path for all file operations:
| Cache | TTL | Max Entries | Purpose |
|---|---|---|---|
| Fuzzy Search | 60s | 100 | File name similarity results |
| Web Requests | 30s | 50 | HTTP responses |
Heavy dependencies loaded on first use:
up_to_date)Visual Indicator Example:
security.ts imports from workingDir.ts (not vice versa)stateManager.ts has minimal logger (no index.ts import)The Zod schema (src/config.ts) defines all plugin settings:
Each field maps to a UI element in LM Studio's settings panel via createConfigSchematics().
| Config Key | UI Name | Type | Range | Default | Description |
|---|---|---|---|---|---|
contextGuardEnabled | π§ ContextGuard Token Management | Boolean | β | true | Master switch for all ContextGuard features |
contextGuardTokenLimit | π Token Limit Before Compression | Number | 1,000β200,000 | 80,000 | Compression triggers at 90% of this value (e.g., 72k for 80k limit) |
contextGuardSmartReading | π Smart File Reading | Boolean | β | true | Extracts keywords from queries to read only relevant file portions |
contextGuardSummaryModel | π€ Summary Model Name | String | Any model name | "" (current chat model) | Dedicated LM Studio model for summarization tasks |
contextGuardTerminalFilterEnabled | π Terminal Output Filtering | Boolean | β | true | Auto-truncates long terminal outputs to save tokens |
contextGuardTerminalFilterLength | π Max Terminal Output Length | Number | 100β20,000 | 2,000 | Characters before terminal output is truncated |
Access Path: LM Studio β Plugins β AI Toolbox β βοΈ Settings β Scroll to "π§ ContextGuard Token Management" section
: '
src/toolsProvider.ts)Central registry managing all tool instances:
Key Design Decisions:
src/stateManager.ts)Persistent state with debounced disk writes:
Key Features:
src/tools/contextManagementTools.ts) πPersistent context storage for session tracking:
Key Features:
src/security.ts)Multi-layer security pipeline:
src/workingDir.ts)Mutable base path for all file operations:
| Cache | TTL | Max Entries | Purpose |
|---|---|---|---|
| Fuzzy Search | 60s | 100 | File name similarity results |
| Web Requests | 30s | 50 | HTTP responses |
Heavy dependencies loaded on first use:
up_to_date)Visual Indicator Example:
security.ts imports from workingDir.ts (not vice versa)stateManager.ts has minimal logger (no index.ts import)The Zod schema (src/config.ts) defines all plugin settings:
Each field maps to a UI element in LM Studio's settings panel via createConfigSchematics().
| Config Key | UI Name | Type | Range | Default | Description |
|---|---|---|---|---|---|
contextGuardEnabled | π§ ContextGuard Token Management | Boolean | β | true | Master switch for all ContextGuard features |
contextGuardTokenLimit | π Token Limit Before Compression | Number | 1,000β200,000 | 80,000 | Compression triggers at 90% of this value (e.g., 72k for 80k limit) |
contextGuardSmartReading | π Smart File Reading | Boolean | β | true | Extracts keywords from queries to read only relevant file portions |
contextGuardSummaryModel | π€ Summary Model Name | String | Any model name | "" (current chat model) | Dedicated LM Studio model for summarization tasks |
contextGuardTerminalFilterEnabled | π Terminal Output Filtering | Boolean | β | true | Auto-truncates long terminal outputs to save tokens |
contextGuardTerminalFilterLength | π Max Terminal Output Length | Number | 100β20,000 | 2,000 | Characters before terminal output is truncated |
Access Path: LM Studio β Plugins β AI Toolbox β βοΈ Settings β Scroll to "π§ ContextGuard Token Management" section
: '
Test Coverage: 19 test suites, 265 tests β all passing β
src/toolsProvider.ts)Central registry managing all tool instances:
Key Design Decisions:
src/stateManager.ts)Persistent state with debounced disk writes:
Key Features:
src/tools/contextManagementTools.ts) πPersistent context storage for session tracking:
Key Features:
src/security.ts)Multi-layer security pipeline:
src/workingDir.ts)Mutable base path for all file operations:
| Cache | TTL | Max Entries | Purpose |
|---|---|---|---|
| Fuzzy Search | 60s | 100 | File name similarity results |
| Web Requests | 30s | 50 | HTTP responses |
Heavy dependencies loaded on first use:
up_to_date)Visual Indicator Example:
security.ts imports from workingDir.ts (not vice versa)stateManager.ts has minimal logger (no index.ts import)The Zod schema (src/config.ts) defines all plugin settings:
Each field maps to a UI element in LM Studio's settings panel via createConfigSchematics().
| Config Key | UI Name | Type | Range | Default | Description |
|---|---|---|---|---|---|
contextGuardEnabled | π§ ContextGuard Token Management | Boolean | β | true | Master switch for all ContextGuard features |
contextGuardTokenLimit | π Token Limit Before Compression | Number | 1,000β200,000 | 80,000 | Compression triggers at 90% of this value (e.g., 72k for 80k limit) |
contextGuardSmartReading | π Smart File Reading | Boolean | β | true | Extracts keywords from queries to read only relevant file portions |
contextGuardSummaryModel | π€ Summary Model Name | String | Any model name | "" (current chat model) | Dedicated LM Studio model for summarization tasks |
contextGuardTerminalFilterEnabled | π Terminal Output Filtering | Boolean | β | true | Auto-truncates long terminal outputs to save tokens |
contextGuardTerminalFilterLength | π Max Terminal Output Length | Number | 100β20,000 | 2,000 | Characters before terminal output is truncated |
Access Path: LM Studio β Plugins β AI Toolbox β βοΈ Settings β Scroll to "π§ ContextGuard Token Management" section
---
## π Plugin Lifecycle
### 1. Initialization
```typescript
// index.ts
export function main(context: PluginContext) {
// 1. Register config schematics (UI toggles)
context.withConfigSchematics(configSchematics);
// 2. Register prompt preprocessor (Document RAG + ContextGuard)
context.withPromptPreprocessor(preprocess);
// 3. Register tools provider (all 80+ tools)
context.withToolsProvider(toolsProvider);
// 4. Setup cleanup handlers
process.on('SIGTERM', cleanupBrowserSession);
process.on('SIGINT', cleanupBrowserSession);
}
toolsProvider() called by LM Studio SDK
β
βΌ
createToolsProvider(config)
β
βΌ
new ToolsProvider(config)
β
βββ StateManager(config) βββββββΊ Load state from disk
βββ BackgroundCommandManager βββΊ Initialize process tracker
βββ ToolRegistry.registerAll()
β
βββ registerFileSystemTools() βββΊ 17 tools
βββ registerWebResearchTools() βββΊ 4 tools
βββ registerBrowserTools() βββΊ 5 tools
βββ registerGitTools() βββΊ 14 tools
βββ registerDatabaseTools() βββΊ 1 tool
βββ registerDocumentTools() βββΊ 1 tool
βββ registerBackgroundCommandTools() ββΊ 3 tools
βββ registerExecutionTools() βββΊ 4 tools (filtered)
βββ registerUtilityTools() βββΊ 7 tools
βββ registerImageProcessingTools() ββΊ 4 tools
βββ registerHttpClientTools() βββΊ 3 tools
βββ registerRagTools() βββΊ 3 tools
βββ registerUiGenerationTools() βββΊ 3 tools (π)
βββ registerContextManagementTools() ββΊ 7 tools (π)
β
βΌ
ToolRegistry.toolMap (Map<string, TypedTool>)
β
βΌ
Return Tool[] to SDK βββΊ SDK registers with LLM
Session Activity Occurs
β
βΌ
auto_summarize_context() called
β
βββ Analyze tool usage patterns
βββ Detect configuration changes
βββ Identify important decisions
βββ Generate summary
βΌ
ContextStorageManager.addEntry(entry)
β
βββ Load existing entries from .ai_toolbox_context.json
βββ Append new entry to beginning of array
βββ Limit to 1000 entries (prevent unbounded growth)
βββ Save atomically (temp file + rename)
βΌ
Persistent Storage (.ai_toolbox_context.json)
β
βββ get_context_memory() β Retrieve recent entries
βββ search_context(query) β Text-based search
βββ context_summary() β Statistics & counts
βββ delete_context_entry(id) β Remove specific entry
class ToolRegistry {
private toolMap = new Map<string, TypedTool>();
registerAll(config, stateManager, bgCommandManager): void
getAll(): Tool[]
get(name: string): TypedTool | undefined
has(name: string): boolean
}
class StateManager {
private state: Map<string, StateEntry>;
private runningSize: number; // O(1) size tracking
set(key, value): void // Debounced save (500ms)
get<T>(key): T | undefined
delete(key): boolean
getAllKeys(): string[]
clear(): void
}
class ContextStorageManager {
private storagePath: string; // .ai_toolbox_context.json
load(): ContextEntry[]
save(entries: ContextEntry[]): void
addEntry(entry: ContextEntry): void
getRecentEntries(limit, type?): ContextEntry[]
searchEntries(query, maxResults): ContextEntry[]
deleteEntry(id): boolean
clearAll(): void
getSummary(): ContextSummary
}
Input β Path Validation β Binary Detection β Command Sanitization β SQL Validation
(validatePath) (isBinaryFile) (sanitizeCommand) (validateSQLQuery)
let currentWorkingDir: string = BASE_DIR;
getWorkingDir(): string
setWorkingDir(newDir: string): boolean
resetWorkingDir(): void
resolvePath(userPath: string): string
getAllowedBases(): string[]
User Path Input
β
βββ Empty check βββββββββββββββββΊ Reject
β
βββ UNC path check (\\\\) βββββββΊ Reject
β
βββ Relative path?
β β
β βββ Yes: Resolve against basePath
β β β
β β βββ Within base? ββββΊ Allow
β β βββ Outside base? βββΊ Reject
β β
β βββ No (absolute):
β β
β βββ In allowed bases? βββΊ Allow
β βββ Outside allowed? ββββΊ Reject
Command String
β
βΌ
Layer 1: Dangerous Pattern Blocking
β
βββ Null byte injection ββββββββββΊ Reject
βββ IFS tampering ββββββββββββββββΊ Reject
βββ Dangerous patterns (rm -rf, sudo, etc.) ββΊ Reject
βββ Too many pipes (>2) ββββββββββΊ Reject
βββ Multiple semicolons (>1) ββββββΊ Reject
βββ Command substitution ($(), ``) ββΊ Reject
βββ Environment modification ββββββΊ Reject
β
βΌ
Layer 2: Tool-Category Enforcement (S6)
β
βββ classifyCommand() β Set<string>
β β
β βββ git * / api.github.com β 'gitOperations'
β βββ duckduckgo / google / bing β 'webSearch'
β βββ puppeteer / playwright / chromium β 'browserAutomation'
β βββ sqlite3 / mysql / psql β 'databaseQueries'
β βββ curl / wget / http β 'httpClient'
β βββ nohup / disown / & β 'backgroundCommands'
β β
β βΌ
β Check against config toggles
β β
β βββ Category disabled + !godMode ββΊ Reject
β βββ Category enabled or godMode βββΊ Allow
β
βΌ
Allow Execution
JavaScript Code
β
βββ require() detection ββββββββββΊ Reject
βββ eval() detection βββββββββββββΊ Reject
βββ fs/child_process access ββββββΊ Reject
βββ Function constructor βββββββββΊ Reject
βββ Dynamic import() βββββββββββββΊ Reject
βββ __proto__ access βββββββββββββΊ Reject
// Stops calculating if minimum possible score drops below threshold
function levenshteinSimilarity(a: string, b: string, minScore: number): number | null {
// Quick rejection for very different lengths
if (lenDiff / maxLen > (1 - minScore)) return null;
// Two-row optimization (saves memory vs full matrix)
// Early exit when row minimum exceeds threshold
}
// Concurrency-controlled batch processing
async function findFilesAsync(dirPath, pattern, maxDepth, concurrencyLimit = 4) {
// Process directories in batches
for (const batch of batches) {
await Promise.all(batch.map(dir => searchDir(dir, depth + 1)));
}
}
User Message
β
βΌ
promptPreprocessor()
β
βββ Check temporalAwareness config
β β
β βββ Enabled?
β β
β βββ Yes: Get cached datetime (5min TTL)
β β β
β β βββ Format: Standard ([Zeit: ...]) or HEUTE IST Mode
β β β
β β βββ Append timestamp to message end
β β
β βββ No: Skip
β
βΌ
Final Prompt sent to LLM (with timestamp suffix)
User Message + Attached Files
β
βΌ
promptPreprocessor()
β
βββ Detect directory paths ββββββββββΊ Inject confirmation prompt
β
βββ Document RAG enabled?
β
βββ Yes: Load embedding model
β β
β βββ Process files β chunks
β β
β βββ Semantic retrieval
β β
β βββ Filter by affinity threshold
β β
β βββ Inject relevant chunks into prompt
β
βββ No: Pass through unchanged
browser_open_page(url)
β
βΌ
BrowserSessionManager.getBrowser()
β
βββ Browser exists & connected? ββββΊ Reuse
β
βββ No: Launch new Puppeteer instance
β
βββ Retry with exponential backoff (max 2)
β
βββ Reset inactivity timer (5 min)
β
βΌ
Navigate to URL
β
βββ Wait for selector (optional)
β
βββ Take screenshot (optional)
β
βββ Extract text content
Session Activity Detected
β
βΌ
auto_summarize_context(sessionEvents, configChanges)
β
βββ Analyze tool usage patterns (>3 uses = frequent pattern)
βββ Track configuration changes
βββ Identify important decisions
βββ Generate session summary
βΌ
ContextStorageManager.addEntry(entry)
β
βββ Load existing entries from .ai_toolbox_context.json
βββ Prepend new entry to array
βββ Enforce 1000-entry limit
βββ Atomic save (temp file + rename)
βΌ
Persistent Storage (.ai_toolbox_context.json)
β
βββ get_context_memory(limit, type?) β Retrieve entries
βββ search_context(query, maxResults) β Text-based search
βββ context_summary() β Statistics & counts
βββ delete_context_entry(id) / clearContextMemory(confirm) β Management
User Message Arrives
β
βΌ
promptPreprocessor()
β
βββ Check contextGuardEnabled config
β β
β βββ Enabled?
β β
β βββ Yes: Count tokens in history
β β β
β β βββ Below 90% threshold? βββΊ Skip compression
β β β
β β βββ Above 90% threshold?
β β β
β β βΌ
β β compressHistory(messages)
β β β
β β βββ Identify messages to compress (all except last 10)
β β βββ Send to summary model
β β β βββ Use contextGuardSummaryModel or current chat model
β β β
β β βββ Generate summary with preserved file paths/names
β β β
β β βββ Calculate tokens saved
β β β
β β βββ Inject visual indicator:
β β β
β β βββ π§ Emoji header
β β βββ Messages compressed count
β β βββ Tokens before β after (e.g., "~85k β ~42k")
β β βββ Percentage saved (e.g., "Saved ~43,000 tokens (~51%)")
β β βββ Timestamp
β β βββ Visual separator lines
β β
β βββ No: Skip ContextGuard processing
β
βΌ
Final Prompt sent to LLM (with or without compression indicator)
π§ **ContextGuard Compression Active**
βββββββββββββββββββββββββββββββββββββββββββββββ
β’ Compressed 15 message(s) into summary
β’ Tokens before: ~85k β after: ~42k
β’ **Saved ~43,000 tokens (~51%)**
β’ Timestamp: 19:15:32
βββββββββββββββββββββββββββββββββββββββββββββββ
### CONTEXT SUMMARY (from 15 messages)
[Summary content here...]
index.ts
βββ toolsProvider.ts
β βββ config.ts
β βββ stateManager.ts
β βββ backgroundCommands.ts
β βββ tools/*.ts (14 modules)
β βββ security.ts (shared)
β βββ workingDir.ts (shared)
β βββ performanceUtils.ts (shared)
βββ config.ts
βββ promptPreprocessor.ts
β βββ config.ts
βββ browserAutomationTools.ts (for cleanup)
ConfigSchema (Zod)
βββ Tool Gating (13 booleans)
βββ Execution Tools (4 booleans)
βββ Search Settings (3 fields)
βββ Browser Settings (2 fields)
βββ Git Settings (2 fields)
βββ Document RAG (3 fields)
βββ Security Settings (4 fields)
βββ State Management (2 fields)
βββ i18n (1 field)
βββ Notifications (1 field)
βββ Temporal Awareness (2 fields: temporalAwareness, dateFormatStyle)
βββ ContextGuard (6 fields): π v1.4.1
βββ contextGuardEnabled (boolean) β Master toggle
βββ contextGuardTokenLimit (number 1K-200K) β Compression threshold
βββ contextGuardSmartReading (boolean) β Keyword-based file reading
βββ contextGuardSummaryModel (string) β Dedicated summary model name
βββ contextGuardTerminalFilterEnabled (boolean) β Terminal output filtering
βββ contextGuardTerminalFilterLength (number 100-20K) β Max terminal chars
src/
βββ index.ts # Plugin entry point
βββ toolsProvider.ts # Tool registration + ToolRegistry class
βββ config.ts # Zod schema + UI schematics
βββ security.ts # Path/SQL/command validators
βββ stateManager.ts # Persistent state management
βββ workingDir.ts # Working directory manager
βββ performanceUtils.ts # Caching, async search, Levenshtein
βββ promptPreprocessor.ts # Document RAG + ContextGuard integration
βββ backgroundCommands.ts # Background process manager
βββ fuzzySearch.ts # Fuzzy file search implementation
βββ locales/ # i18n translation files
β βββ en.ts
β βββ de.ts
β βββ zh-CN.ts
β βββ zh-TW.ts
βββ tools/ # Tool category modules
β βββ fileSystemTools.ts # 17 file system tools
β βββ webResearchTools.ts # 4 web research tools
β βββ browserAutomationTools.ts # 5 browser tools
β βββ gitGithubTools.ts # 14 Git/GitHub tools
β βββ databaseTools.ts # 1 database tool
β βββ backgroundCommandTools.ts # 3 background command tools
β βββ executionTools.ts # 4 execution tools
β βββ utilityTools.ts # 7 utility tools
β βββ imageProcessingTools.ts # 4 image processing tools
β βββ httpClientTools.ts # 3 HTTP client tools
β βββ vectorRagTools.ts # 3 vector RAG tools
β βββ uiGenerationTools.ts # π 3 UI generation tools
β βββ contextManagementTools.ts # π 7 context management tools
βββ types/ # Type definitions
βββ types.d.ts
tests/ # Jest test suite
βββ security.test.ts
βββ security.edge-cases.test.ts
βββ config.test.ts
βββ stateManager.test.ts
βββ fileSystemTools.test.ts
βββ webResearchTools.test.ts
βββ browserAutomationTools.test.ts
βββ gitGithubTools.test.ts
βββ databaseTools.test.ts
βββ executionTools.test.ts
βββ utilityTools.test.ts
βββ backgroundCommands.test.ts
βββ toolsProvider.test.ts
βββ performanceUtils.test.ts
βββ fuzzySearch.test.ts
βββ workingDir.test.ts
βββ findLMStudioHome.test.ts
βββ i18n.test.ts
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β LM Studio Host β
β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Plugin Runner (Node.js) β β
β β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β AI Toolbox Plugin β β β
β β β β β β
β β β ββββββββββββββββ β β β
β β β β index.ts βββββ Entry Point (main function) β β β
β β β β (entry) β β β β
β β β ββββββββ¬ββββββββ β β β
β β β β β β β
β β β βΌ β β β
β β β βββββββββββββββββββββββββββββββββββββββββββββββββββ β β β
β β β β Core Services β β β β
β β β β ββββββββββββ ββββββββββββ ββββββββββββββββββββ β β β β
β β β β β config.tsβ βsecurity β βstateManager.ts β β β β β
β β β β β(Zod+UI) β β .ts β β(persistence) β β β β β
β β β β ββββββββββββ β(validators)β ββββββββββββββββββββ β β β β
β β β β ββββββββββββ β β β β
β β β β ββββββββββββ ββββββββββββ ββββββββββββββββββββ β β β β
β β β β βworkingDirβ βperformancβ βpromptPreprocessor β β β β β
β β β β β .ts β βeUtils.ts β β .ts β β β β β
β β β β β(path mgmtβ β(caching) β β(Document RAG + β β β β β
β β β β ββββββββββββ ββββββββββββ β ContextGuard) β β β β β
β β β β ββββββββββββββββββββ β β β β
β β β βββββββββββββββββββββββββββββββββββββββββββββββββββ β β β
β β β β β β
β β β ββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β
β β β β Tool Registration Layer β β β β
β β β β βββββββββββββββββββ ββββββββββββββββββββββββ β β β β
β β β β β toolsProvider.ts β β ToolRegistry β β β β β
β β β β β (factory fn) β β (central map) β β β β β
β β β β ββββββββββ¬βββββββββ ββββββββββββ¬ββββββββββββ β β β β
β β β βββββββββββββΌβββββββββββββββββββββββΌββββββββββββββ β β β
β β β β β β β β
β β β βββββββββββββ΄βββββββββββββββββββββββ΄ββββββββββββββ β β β
β β β β Tool Modules (14 files) β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β βfileSys β βwebRes β βbrowser β β git β β β β β
β β β β β (17) β β (4) β β (5) β β (14) β β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β β datab β βbackgnd β βexec β β utilityβ β β β β
β β β β β (1) β β cmd(3) β β (4) β β (7) β β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β β image β β http β β vector β β UI β β β β β
β β β β β (4) β β (3) β β RAG(3) β β Gen(3) β β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β ββββββββββ β β β β
β β β β β Context β β β β β
β β β β β Mgmt(7) β β β β β
β β β β ββββββββββ β β β β
β β β βββββββββββββββββββββββββββββββββββββββββββββββ β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β External Dependencies β β β
β β Puppeteer β simple-git β Tesseract.js β pdf-parse β β β
β β duck-duck-scrape β node:sqlite β node-notifier β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// index.ts
export function main(context: PluginContext) {
// 1. Register config schematics (UI toggles)
context.withConfigSchematics(configSchematics);
// 2. Register prompt preprocessor (Document RAG + ContextGuard)
context.withPromptPreprocessor(preprocess);
// 3. Register tools provider (all 80+ tools)
context.withToolsProvider(toolsProvider);
// 4. Setup cleanup handlers
process.on('SIGTERM', cleanupBrowserSession);
process.on('SIGINT', cleanupBrowserSession);
}
toolsProvider() called by LM Studio SDK
β
βΌ
createToolsProvider(config)
β
βΌ
new ToolsProvider(config)
β
βββ StateManager(config) βββββββΊ Load state from disk
βββ BackgroundCommandManager βββΊ Initialize process tracker
βββ ToolRegistry.registerAll()
β
βββ registerFileSystemTools() βββΊ 17 tools
βββ registerWebResearchTools() βββΊ 4 tools
βββ registerBrowserTools() βββΊ 5 tools
βββ registerGitTools() βββΊ 14 tools
βββ registerDatabaseTools() βββΊ 1 tool
βββ registerDocumentTools() βββΊ 1 tool
βββ registerBackgroundCommandTools() ββΊ 3 tools
βββ registerExecutionTools() βββΊ 4 tools (filtered)
βββ registerUtilityTools() βββΊ 7 tools
βββ registerImageProcessingTools() ββΊ 4 tools
βββ registerHttpClientTools() βββΊ 3 tools
βββ registerRagTools() βββΊ 3 tools
βββ registerUiGenerationTools() βββΊ 3 tools (π)
βββ registerContextManagementTools() ββΊ 7 tools (π)
β
βΌ
ToolRegistry.toolMap (Map<string, TypedTool>)
β
βΌ
Return Tool[] to SDK βββΊ SDK registers with LLM
Session Activity Occurs
β
βΌ
auto_summarize_context() called
β
βββ Analyze tool usage patterns
βββ Detect configuration changes
βββ Identify important decisions
βββ Generate summary
βΌ
ContextStorageManager.addEntry(entry)
β
βββ Load existing entries from .ai_toolbox_context.json
βββ Append new entry to beginning of array
βββ Limit to 1000 entries (prevent unbounded growth)
βββ Save atomically (temp file + rename)
βΌ
Persistent Storage (.ai_toolbox_context.json)
β
βββ get_context_memory() β Retrieve recent entries
βββ search_context(query) β Text-based search
βββ context_summary() β Statistics & counts
βββ delete_context_entry(id) β Remove specific entry
class ToolRegistry {
private toolMap = new Map<string, TypedTool>();
registerAll(config, stateManager, bgCommandManager): void
getAll(): Tool[]
get(name: string): TypedTool | undefined
has(name: string): boolean
}
class StateManager {
private state: Map<string, StateEntry>;
private runningSize: number; // O(1) size tracking
set(key, value): void // Debounced save (500ms)
get<T>(key): T | undefined
delete(key): boolean
getAllKeys(): string[]
clear(): void
}
class ContextStorageManager {
private storagePath: string; // .ai_toolbox_context.json
load(): ContextEntry[]
save(entries: ContextEntry[]): void
addEntry(entry: ContextEntry): void
getRecentEntries(limit, type?): ContextEntry[]
searchEntries(query, maxResults): ContextEntry[]
deleteEntry(id): boolean
clearAll(): void
getSummary(): ContextSummary
}
Input β Path Validation β Binary Detection β Command Sanitization β SQL Validation
(validatePath) (isBinaryFile) (sanitizeCommand) (validateSQLQuery)
let currentWorkingDir: string = BASE_DIR;
getWorkingDir(): string
setWorkingDir(newDir: string): boolean
resetWorkingDir(): void
resolvePath(userPath: string): string
getAllowedBases(): string[]
User Path Input
β
βββ Empty check βββββββββββββββββΊ Reject
β
βββ UNC path check (\\\\) βββββββΊ Reject
β
βββ Relative path?
β β
β βββ Yes: Resolve against basePath
β β β
β β βββ Within base? ββββΊ Allow
β β βββ Outside base? βββΊ Reject
β β
β βββ No (absolute):
β β
β βββ In allowed bases? βββΊ Allow
β βββ Outside allowed? ββββΊ Reject
Command String
β
βΌ
Layer 1: Dangerous Pattern Blocking
β
βββ Null byte injection ββββββββββΊ Reject
βββ IFS tampering ββββββββββββββββΊ Reject
βββ Dangerous patterns (rm -rf, sudo, etc.) ββΊ Reject
βββ Too many pipes (>2) ββββββββββΊ Reject
βββ Multiple semicolons (>1) ββββββΊ Reject
βββ Command substitution ($(), ``) ββΊ Reject
βββ Environment modification ββββββΊ Reject
β
βΌ
Layer 2: Tool-Category Enforcement (S6)
β
βββ classifyCommand() β Set<string>
β β
β βββ git * / api.github.com β 'gitOperations'
β βββ duckduckgo / google / bing β 'webSearch'
β βββ puppeteer / playwright / chromium β 'browserAutomation'
β βββ sqlite3 / mysql / psql β 'databaseQueries'
β βββ curl / wget / http β 'httpClient'
β βββ nohup / disown / & β 'backgroundCommands'
β β
β βΌ
β Check against config toggles
β β
β βββ Category disabled + !godMode ββΊ Reject
β βββ Category enabled or godMode βββΊ Allow
β
βΌ
Allow Execution
JavaScript Code
β
βββ require() detection ββββββββββΊ Reject
βββ eval() detection βββββββββββββΊ Reject
βββ fs/child_process access ββββββΊ Reject
βββ Function constructor βββββββββΊ Reject
βββ Dynamic import() βββββββββββββΊ Reject
βββ __proto__ access βββββββββββββΊ Reject
// Stops calculating if minimum possible score drops below threshold
function levenshteinSimilarity(a: string, b: string, minScore: number): number | null {
// Quick rejection for very different lengths
if (lenDiff / maxLen > (1 - minScore)) return null;
// Two-row optimization (saves memory vs full matrix)
// Early exit when row minimum exceeds threshold
}
// Concurrency-controlled batch processing
async function findFilesAsync(dirPath, pattern, maxDepth, concurrencyLimit = 4) {
// Process directories in batches
for (const batch of batches) {
await Promise.all(batch.map(dir => searchDir(dir, depth + 1)));
}
}
User Message
β
βΌ
promptPreprocessor()
β
βββ Check temporalAwareness config
β β
β βββ Enabled?
β β
β βββ Yes: Get cached datetime (5min TTL)
β β β
β β βββ Format: Standard ([Zeit: ...]) or HEUTE IST Mode
β β β
β β βββ Append timestamp to message end
β β
β βββ No: Skip
β
βΌ
Final Prompt sent to LLM (with timestamp suffix)
User Message + Attached Files
β
βΌ
promptPreprocessor()
β
βββ Detect directory paths ββββββββββΊ Inject confirmation prompt
β
βββ Document RAG enabled?
β
βββ Yes: Load embedding model
β β
β βββ Process files β chunks
β β
β βββ Semantic retrieval
β β
β βββ Filter by affinity threshold
β β
β βββ Inject relevant chunks into prompt
β
βββ No: Pass through unchanged
browser_open_page(url)
β
βΌ
BrowserSessionManager.getBrowser()
β
βββ Browser exists & connected? ββββΊ Reuse
β
βββ No: Launch new Puppeteer instance
β
βββ Retry with exponential backoff (max 2)
β
βββ Reset inactivity timer (5 min)
β
βΌ
Navigate to URL
β
βββ Wait for selector (optional)
β
βββ Take screenshot (optional)
β
βββ Extract text content
Session Activity Detected
β
βΌ
auto_summarize_context(sessionEvents, configChanges)
β
βββ Analyze tool usage patterns (>3 uses = frequent pattern)
βββ Track configuration changes
βββ Identify important decisions
βββ Generate session summary
βΌ
ContextStorageManager.addEntry(entry)
β
βββ Load existing entries from .ai_toolbox_context.json
βββ Prepend new entry to array
βββ Enforce 1000-entry limit
βββ Atomic save (temp file + rename)
βΌ
Persistent Storage (.ai_toolbox_context.json)
β
βββ get_context_memory(limit, type?) β Retrieve entries
βββ search_context(query, maxResults) β Text-based search
βββ context_summary() β Statistics & counts
βββ delete_context_entry(id) / clearContextMemory(confirm) β Management
User Message Arrives
β
βΌ
promptPreprocessor()
β
βββ Check contextGuardEnabled config
β β
β βββ Enabled?
β β
β βββ Yes: Count tokens in history
β β β
β β βββ Below 90% threshold? βββΊ Skip compression
β β β
β β βββ Above 90% threshold?
β β β
β β βΌ
β β compressHistory(messages)
β β β
β β βββ Identify messages to compress (all except last 10)
β β βββ Send to summary model
β β β βββ Use contextGuardSummaryModel or current chat model
β β β
β β βββ Generate summary with preserved file paths/names
β β β
β β βββ Calculate tokens saved
β β β
β β βββ Inject visual indicator:
β β β
β β βββ π§ Emoji header
β β βββ Messages compressed count
β β βββ Tokens before β after (e.g., "~85k β ~42k")
β β βββ Percentage saved (e.g., "Saved ~43,000 tokens (~51%)")
β β βββ Timestamp
β β βββ Visual separator lines
β β
β βββ No: Skip ContextGuard processing
β
βΌ
Final Prompt sent to LLM (with or without compression indicator)
π§ **ContextGuard Compression Active**
βββββββββββββββββββββββββββββββββββββββββββββββ
β’ Compressed 15 message(s) into summary
β’ Tokens before: ~85k β after: ~42k
β’ **Saved ~43,000 tokens (~51%)**
β’ Timestamp: 19:15:32
βββββββββββββββββββββββββββββββββββββββββββββββ
### CONTEXT SUMMARY (from 15 messages)
[Summary content here...]
index.ts
βββ toolsProvider.ts
β βββ config.ts
β βββ stateManager.ts
β βββ backgroundCommands.ts
β βββ tools/*.ts (14 modules)
β βββ security.ts (shared)
β βββ workingDir.ts (shared)
β βββ performanceUtils.ts (shared)
βββ config.ts
βββ promptPreprocessor.ts
β βββ config.ts
βββ browserAutomationTools.ts (for cleanup)
ConfigSchema (Zod)
βββ Tool Gating (13 booleans)
βββ Execution Tools (4 booleans)
βββ Search Settings (3 fields)
βββ Browser Settings (2 fields)
βββ Git Settings (2 fields)
βββ Document RAG (3 fields)
βββ Security Settings (4 fields)
βββ State Management (2 fields)
βββ i18n (1 field)
βββ Notifications (1 field)
βββ Temporal Awareness (2 fields: temporalAwareness, dateFormatStyle)
βββ ContextGuard (6 fields): π v1.4.1
βββ contextGuardEnabled (boolean) β Master toggle
βββ contextGuardTokenLimit (number 1K-200K) β Compression threshold
βββ contextGuardSmartReading (boolean) β Keyword-based file reading
βββ contextGuardSummaryModel (string) β Dedicated summary model name
βββ contextGuardTerminalFilterEnabled (boolean) β Terminal output filtering
βββ contextGuardTerminalFilterLength (number 100-20K) β Max terminal chars
src/
βββ index.ts # Plugin entry point
βββ toolsProvider.ts # Tool registration + ToolRegistry class
βββ config.ts # Zod schema + UI schematics
βββ security.ts # Path/SQL/command validators
βββ stateManager.ts # Persistent state management
βββ workingDir.ts # Working directory manager
βββ performanceUtils.ts # Caching, async search, Levenshtein
βββ promptPreprocessor.ts # Document RAG + ContextGuard integration
βββ backgroundCommands.ts # Background process manager
βββ fuzzySearch.ts # Fuzzy file search implementation
βββ locales/ # i18n translation files
β βββ en.ts
β βββ de.ts
β βββ zh-CN.ts
β βββ zh-TW.ts
βββ tools/ # Tool category modules
β βββ fileSystemTools.ts # 17 file system tools
β βββ webResearchTools.ts # 4 web research tools
β βββ browserAutomationTools.ts # 5 browser tools
β βββ gitGithubTools.ts # 14 Git/GitHub tools
β βββ databaseTools.ts # 1 database tool
β βββ backgroundCommandTools.ts # 3 background command tools
β βββ executionTools.ts # 4 execution tools
β βββ utilityTools.ts # 7 utility tools
β βββ imageProcessingTools.ts # 4 image processing tools
β βββ httpClientTools.ts # 3 HTTP client tools
β βββ vectorRagTools.ts # 3 vector RAG tools
β βββ uiGenerationTools.ts # π 3 UI generation tools
β βββ contextManagementTools.ts # π 7 context management tools
βββ types/ # Type definitions
βββ types.d.ts
tests/ # Jest test suite
βββ security.test.ts
βββ security.edge-cases.test.ts
βββ config.test.ts
βββ stateManager.test.ts
βββ fileSystemTools.test.ts
βββ webResearchTools.test.ts
βββ browserAutomationTools.test.ts
βββ gitGithubTools.test.ts
βββ databaseTools.test.ts
βββ executionTools.test.ts
βββ utilityTools.test.ts
βββ backgroundCommands.test.ts
βββ toolsProvider.test.ts
βββ performanceUtils.test.ts
βββ fuzzySearch.test.ts
βββ workingDir.test.ts
βββ findLMStudioHome.test.ts
βββ i18n.test.ts
**Key Design Decisions:**
- **ESM Package Mocking**: `archiver@8.x` and `unzipper` use ESM syntax which ts-jest cannot transform. Using `moduleNameMapper` with custom mocks is more reliable than `transformIgnorePatterns` for this case.
- **Test Isolation**: Each test file runs in isolation with fresh state
- **Security Test Coverage**: Comprehensive edge-case testing for all security validators (path traversal, ReDoS, SQL injection, command injection)
### Running Tests
```bash
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Run specific test file
npm test -- workingDir.test.ts
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β LM Studio Host β
β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Plugin Runner (Node.js) β β
β β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β AI Toolbox Plugin β β β
β β β β β β
β β β ββββββββββββββββ β β β
β β β β index.ts βββββ Entry Point (main function) β β β
β β β β (entry) β β β β
β β β ββββββββ¬ββββββββ β β β
β β β β β β β
β β β βΌ β β β
β β β βββββββββββββββββββββββββββββββββββββββββββββββββββ β β β
β β β β Core Services β β β β
β β β β ββββββββββββ ββββββββββββ ββββββββββββββββββββ β β β β
β β β β β config.tsβ βsecurity β βstateManager.ts β β β β β
β β β β β(Zod+UI) β β .ts β β(persistence) β β β β β
β β β β ββββββββββββ β(validators)β ββββββββββββββββββββ β β β β
β β β β ββββββββββββ β β β β
β β β β ββββββββββββ ββββββββββββ ββββββββββββββββββββ β β β β
β β β β βworkingDirβ βperformancβ βpromptPreprocessor β β β β β
β β β β β .ts β βeUtils.ts β β .ts β β β β β
β β β β β(path mgmtβ β(caching) β β(Document RAG + β β β β β
β β β β ββββββββββββ ββββββββββββ β ContextGuard) β β β β β
β β β β ββββββββββββββββββββ β β β β
β β β βββββββββββββββββββββββββββββββββββββββββββββββββββ β β β
β β β β β β
β β β ββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β
β β β β Tool Registration Layer β β β β
β β β β βββββββββββββββββββ ββββββββββββββββββββββββ β β β β
β β β β β toolsProvider.ts β β ToolRegistry β β β β β
β β β β β (factory fn) β β (central map) β β β β β
β β β β ββββββββββ¬βββββββββ ββββββββββββ¬ββββββββββββ β β β β
β β β βββββββββββββΌβββββββββββββββββββββββΌββββββββββββββ β β β
β β β β β β β β
β β β βββββββββββββ΄βββββββββββββββββββββββ΄ββββββββββββββ β β β
β β β β Tool Modules (14 files) β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β βfileSys β βwebRes β βbrowser β β git β β β β β
β β β β β (17) β β (4) β β (5) β β (14) β β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β β datab β βbackgnd β βexec β β utilityβ β β β β
β β β β β (1) β β cmd(3) β β (4) β β (7) β β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β β image β β http β β vector β β UI β β β β β
β β β β β (4) β β (3) β β RAG(3) β β Gen(3) β β β β β
β β β β ββββββββββ ββββββββββ ββββββββββ ββββββββββ β β β β
β β β β ββββββββββ β β β β
β β β β β Context β β β β β
β β β β β Mgmt(7) β β β β β
β β β β ββββββββββ β β β β
β β β βββββββββββββββββββββββββββββββββββββββββββββββ β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β External Dependencies β β β
β β Puppeteer β simple-git β Tesseract.js β pdf-parse β β β
β β duck-duck-scrape β node:sqlite β node-notifier β β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// index.ts
export function main(context: PluginContext) {
// 1. Register config schematics (UI toggles)
context.withConfigSchematics(configSchematics);
// 2. Register prompt preprocessor (Document RAG + ContextGuard)
context.withPromptPreprocessor(preprocess);
// 3. Register tools provider (all 80+ tools)
context.withToolsProvider(toolsProvider);
// 4. Setup cleanup handlers
process.on('SIGTERM', cleanupBrowserSession);
process.on('SIGINT', cleanupBrowserSession);
}
toolsProvider() called by LM Studio SDK
β
βΌ
createToolsProvider(config)
β
βΌ
new ToolsProvider(config)
β
βββ StateManager(config) βββββββΊ Load state from disk
βββ BackgroundCommandManager βββΊ Initialize process tracker
βββ ToolRegistry.registerAll()
β
βββ registerFileSystemTools() βββΊ 17 tools
βββ registerWebResearchTools() βββΊ 4 tools
βββ registerBrowserTools() βββΊ 5 tools
βββ registerGitTools() βββΊ 14 tools
βββ registerDatabaseTools() βββΊ 1 tool
βββ registerDocumentTools() βββΊ 1 tool
βββ registerBackgroundCommandTools() ββΊ 3 tools
βββ registerExecutionTools() βββΊ 4 tools (filtered)
βββ registerUtilityTools() βββΊ 7 tools
βββ registerImageProcessingTools() ββΊ 4 tools
βββ registerHttpClientTools() βββΊ 3 tools
βββ registerRagTools() βββΊ 3 tools
βββ registerUiGenerationTools() βββΊ 3 tools (π)
βββ registerContextManagementTools() ββΊ 7 tools (π)
β
βΌ
ToolRegistry.toolMap (Map<string, TypedTool>)
β
βΌ
Return Tool[] to SDK βββΊ SDK registers with LLM
Session Activity Occurs
β
βΌ
auto_summarize_context() called
β
βββ Analyze tool usage patterns
βββ Detect configuration changes
βββ Identify important decisions
βββ Generate summary
βΌ
ContextStorageManager.addEntry(entry)
β
βββ Load existing entries from .ai_toolbox_context.json
βββ Append new entry to beginning of array
βββ Limit to 1000 entries (prevent unbounded growth)
βββ Save atomically (temp file + rename)
βΌ
Persistent Storage (.ai_toolbox_context.json)
β
βββ get_context_memory() β Retrieve recent entries
βββ search_context(query) β Text-based search
βββ context_summary() β Statistics & counts
βββ delete_context_entry(id) β Remove specific entry
class ToolRegistry {
private toolMap = new Map<string, TypedTool>();
registerAll(config, stateManager, bgCommandManager): void
getAll(): Tool[]
get(name: string): TypedTool | undefined
has(name: string): boolean
}
class StateManager {
private state: Map<string, StateEntry>;
private runningSize: number; // O(1) size tracking
set(key, value): void // Debounced save (500ms)
get<T>(key): T | undefined
delete(key): boolean
getAllKeys(): string[]
clear(): void
}
class ContextStorageManager {
private storagePath: string; // .ai_toolbox_context.json
load(): ContextEntry[]
save(entries: ContextEntry[]): void
addEntry(entry: ContextEntry): void
getRecentEntries(limit, type?): ContextEntry[]
searchEntries(query, maxResults): ContextEntry[]
deleteEntry(id): boolean
clearAll(): void
getSummary(): ContextSummary
}
Input β Path Validation β Binary Detection β Command Sanitization β SQL Validation
(validatePath) (isBinaryFile) (sanitizeCommand) (validateSQLQuery)
let currentWorkingDir: string = BASE_DIR;
getWorkingDir(): string
setWorkingDir(newDir: string): boolean
resetWorkingDir(): void
resolvePath(userPath: string): string
getAllowedBases(): string[]
User Path Input
β
βββ Empty check βββββββββββββββββΊ Reject
β
βββ UNC path check (\\\\) βββββββΊ Reject
β
βββ Relative path?
β β
β βββ Yes: Resolve against basePath
β β β
β β βββ Within base? ββββΊ Allow
β β βββ Outside base? βββΊ Reject
β β
β βββ No (absolute):
β β
β βββ In allowed bases? βββΊ Allow
β βββ Outside allowed? ββββΊ Reject
Command String
β
βΌ
Layer 1: Dangerous Pattern Blocking
β
βββ Null byte injection ββββββββββΊ Reject
βββ IFS tampering ββββββββββββββββΊ Reject
βββ Dangerous patterns (rm -rf, sudo, etc.) ββΊ Reject
βββ Too many pipes (>2) ββββββββββΊ Reject
βββ Multiple semicolons (>1) ββββββΊ Reject
βββ Command substitution ($(), ``) ββΊ Reject
βββ Environment modification ββββββΊ Reject
β
βΌ
Layer 2: Tool-Category Enforcement (S6)
β
βββ classifyCommand() β Set<string>
β β
β βββ git * / api.github.com β 'gitOperations'
β βββ duckduckgo / google / bing β 'webSearch'
β βββ puppeteer / playwright / chromium β 'browserAutomation'
β βββ sqlite3 / mysql / psql β 'databaseQueries'
β βββ curl / wget / http β 'httpClient'
β βββ nohup / disown / & β 'backgroundCommands'
β β
β βΌ
β Check against config toggles
β β
β βββ Category disabled + !godMode ββΊ Reject
β βββ Category enabled or godMode βββΊ Allow
β
βΌ
Allow Execution
JavaScript Code
β
βββ require() detection ββββββββββΊ Reject
βββ eval() detection βββββββββββββΊ Reject
βββ fs/child_process access ββββββΊ Reject
βββ Function constructor βββββββββΊ Reject
βββ Dynamic import() βββββββββββββΊ Reject
βββ __proto__ access βββββββββββββΊ Reject
// Stops calculating if minimum possible score drops below threshold
function levenshteinSimilarity(a: string, b: string, minScore: number): number | null {
// Quick rejection for very different lengths
if (lenDiff / maxLen > (1 - minScore)) return null;
// Two-row optimization (saves memory vs full matrix)
// Early exit when row minimum exceeds threshold
}
// Concurrency-controlled batch processing
async function findFilesAsync(dirPath, pattern, maxDepth, concurrencyLimit = 4) {
// Process directories in batches
for (const batch of batches) {
await Promise.all(batch.map(dir => searchDir(dir, depth + 1)));
}
}
User Message
β
βΌ
promptPreprocessor()
β
βββ Check temporalAwareness config
β β
β βββ Enabled?
β β
β βββ Yes: Get cached datetime (5min TTL)
β β β
β β βββ Format: Standard ([Zeit: ...]) or HEUTE IST Mode
β β β
β β βββ Append timestamp to message end
β β
β βββ No: Skip
β
βΌ
Final Prompt sent to LLM (with timestamp suffix)
User Message + Attached Files
β
βΌ
promptPreprocessor()
β
βββ Detect directory paths ββββββββββΊ Inject confirmation prompt
β
βββ Document RAG enabled?
β
βββ Yes: Load embedding model
β β
β βββ Process files β chunks
β β
β βββ Semantic retrieval
β β
β βββ Filter by affinity threshold
β β
β βββ Inject relevant chunks into prompt
β
βββ No: Pass through unchanged
browser_open_page(url)
β
βΌ
BrowserSessionManager.getBrowser()
β
βββ Browser exists & connected? ββββΊ Reuse
β
βββ No: Launch new Puppeteer instance
β
βββ Retry with exponential backoff (max 2)
β
βββ Reset inactivity timer (5 min)
β
βΌ
Navigate to URL
β
βββ Wait for selector (optional)
β
βββ Take screenshot (optional)
β
βββ Extract text content
Session Activity Detected
β
βΌ
auto_summarize_context(sessionEvents, configChanges)
β
βββ Analyze tool usage patterns (>3 uses = frequent pattern)
βββ Track configuration changes
βββ Identify important decisions
βββ Generate session summary
βΌ
ContextStorageManager.addEntry(entry)
β
βββ Load existing entries from .ai_toolbox_context.json
βββ Prepend new entry to array
βββ Enforce 1000-entry limit
βββ Atomic save (temp file + rename)
βΌ
Persistent Storage (.ai_toolbox_context.json)
β
βββ get_context_memory(limit, type?) β Retrieve entries
βββ search_context(query, maxResults) β Text-based search
βββ context_summary() β Statistics & counts
βββ delete_context_entry(id) / clearContextMemory(confirm) β Management
User Message Arrives
β
βΌ
promptPreprocessor()
β
βββ Check contextGuardEnabled config
β β
β βββ Enabled?
β β
β βββ Yes: Count tokens in history
β β β
β β βββ Below 90% threshold? βββΊ Skip compression
β β β
β β βββ Above 90% threshold?
β β β
β β βΌ
β β compressHistory(messages)
β β β
β β βββ Identify messages to compress (all except last 10)
β β βββ Send to summary model
β β β βββ Use contextGuardSummaryModel or current chat model
β β β
β β βββ Generate summary with preserved file paths/names
β β β
β β βββ Calculate tokens saved
β β β
β β βββ Inject visual indicator:
β β β
β β βββ π§ Emoji header
β β βββ Messages compressed count
β β βββ Tokens before β after (e.g., "~85k β ~42k")
β β βββ Percentage saved (e.g., "Saved ~43,000 tokens (~51%)")
β β βββ Timestamp
β β βββ Visual separator lines
β β
β βββ No: Skip ContextGuard processing
β
βΌ
Final Prompt sent to LLM (with or without compression indicator)
π§ **ContextGuard Compression Active**
βββββββββββββββββββββββββββββββββββββββββββββββ
β’ Compressed 15 message(s) into summary
β’ Tokens before: ~85k β after: ~42k
β’ **Saved ~43,000 tokens (~51%)**
β’ Timestamp: 19:15:32
βββββββββββββββββββββββββββββββββββββββββββββββ
### CONTEXT SUMMARY (from 15 messages)
[Summary content here...]
index.ts
βββ toolsProvider.ts
β βββ config.ts
β βββ stateManager.ts
β βββ backgroundCommands.ts
β βββ tools/*.ts (14 modules)
β βββ security.ts (shared)
β βββ workingDir.ts (shared)
β βββ performanceUtils.ts (shared)
βββ config.ts
βββ promptPreprocessor.ts
β βββ config.ts
βββ browserAutomationTools.ts (for cleanup)
ConfigSchema (Zod)
βββ Tool Gating (13 booleans)
βββ Execution Tools (4 booleans)
βββ Search Settings (3 fields)
βββ Browser Settings (2 fields)
βββ Git Settings (2 fields)
βββ Document RAG (3 fields)
βββ Security Settings (4 fields)
βββ State Management (2 fields)
βββ i18n (1 field)
βββ Notifications (1 field)
βββ Temporal Awareness (2 fields: temporalAwareness, dateFormatStyle)
βββ ContextGuard (6 fields): π v1.4.1
βββ contextGuardEnabled (boolean) β Master toggle
βββ contextGuardTokenLimit (number 1K-200K) β Compression threshold
βββ contextGuardSmartReading (boolean) β Keyword-based file reading
βββ contextGuardSummaryModel (string) β Dedicated summary model name
βββ contextGuardTerminalFilterEnabled (boolean) β Terminal output filtering
βββ contextGuardTerminalFilterLength (number 100-20K) β Max terminal chars
src/
βββ index.ts # Plugin entry point
βββ toolsProvider.ts # Tool registration + ToolRegistry class
βββ config.ts # Zod schema + UI schematics
βββ security.ts # Path/SQL/command validators
βββ stateManager.ts # Persistent state management
βββ workingDir.ts # Working directory manager
βββ performanceUtils.ts # Caching, async search, Levenshtein
βββ promptPreprocessor.ts # Document RAG + ContextGuard integration
βββ backgroundCommands.ts # Background process manager
βββ fuzzySearch.ts # Fuzzy file search implementation
βββ locales/ # i18n translation files
β βββ en.ts
β βββ de.ts
β βββ zh-CN.ts
β βββ zh-TW.ts
βββ tools/ # Tool category modules
β βββ fileSystemTools.ts # 17 file system tools
β βββ webResearchTools.ts # 4 web research tools
β βββ browserAutomationTools.ts # 5 browser tools
β βββ gitGithubTools.ts # 14 Git/GitHub tools
β βββ databaseTools.ts # 1 database tool
β βββ backgroundCommandTools.ts # 3 background command tools
β βββ executionTools.ts # 4 execution tools
β βββ utilityTools.ts # 7 utility tools
β βββ imageProcessingTools.ts # 4 image processing tools
β βββ httpClientTools.ts # 3 HTTP client tools
β βββ vectorRagTools.ts # 3 vector RAG tools
β βββ uiGenerationTools.ts # π 3 UI generation tools
β βββ contextManagementTools.ts # π 7 context management tools
βββ types/ # Type definitions
βββ types.d.ts
tests/ # Jest test suite
βββ security.test.ts
βββ security.edge-cases.test.ts
βββ config.test.ts
βββ stateManager.test.ts
βββ fileSystemTools.test.ts
βββ webResearchTools.test.ts
βββ browserAutomationTools.test.ts
βββ gitGithubTools.test.ts
βββ databaseTools.test.ts
βββ executionTools.test.ts
βββ utilityTools.test.ts
βββ backgroundCommands.test.ts
βββ toolsProvider.test.ts
βββ performanceUtils.test.ts
βββ fuzzySearch.test.ts
βββ workingDir.test.ts
βββ findLMStudioHome.test.ts
βββ i18n.test.ts