Forked from crunch3r/ai-toolbox
Forked from crunch3r/ai-toolbox
src / config.ts
src / config.ts
import { z } from 'zod';
import { createConfigSchematics } from '@lmstudio/sdk';
import type { UiLabels } from './locales/types.js'; // UL-v2 step-5 (27.10): type-only โ erased at runtime, never jest-resolved (same convention as hostLanguage.ts)
// ==================== Zod Schema (validation) ====================
export const ConfigSchema = z.object({
// Tool Categories (enable/disable individual tools)
fileSystem: z.boolean().default(true),
webSearch: z.boolean().default(true),
browserAutomation: z.boolean().default(false),
gitOperations: z.boolean().default(false),
packageManage: z.boolean().default(false).describe('โ ๏ธ Enable package manager (npm/pip/cargo) operations. Disabled by default for security.'),
databaseQueries: z.boolean().default(false),
documentParsing: z.boolean().default(true),
backgroundCommands: z.boolean().default(false),
// โโ ๐ NEW TOOL CATEGORIES โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
imageProcessing: z.boolean().default(true).describe('Enable image OCR, screenshot, and comparison tools'),
httpClient: z.boolean().default(false).describe('Enable generic HTTP client for REST API calls'),
vectorRAG: z.boolean().default(true).describe('Enable semantic search with vector embeddings'),
uiGeneration: z.boolean().default(true).describe('Enable interactive UI generation and rendering tools (ON by default since 10.10, owner decision โ aligns with DEFAULT_CONFIG / schematics)'),
contextManagement: z.boolean().default(true).describe('Enable automatic context tracking and memory management'),
textProcessing: z.boolean().default(true).describe('Enable text processing tools (sed/awk equivalents)'),
refactorCode: z.boolean().default(true).describe('Enable AST-based code refactoring tools (rename, move, extract, unused import cleanup)'),
utility: z.boolean().default(true).describe('Enable Utility & Maintenance Tools (backup, chart generation, markdown preview, line operations)'),
// โโ ๐ TASK PLANNING TOOLS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
taskPlanning: z.boolean().default(true).describe('Enable structured multi-step workflow tools (create_plan, update_plan_step, get_plan)'),
// โโ ๐งญ TOOL ORDERING (cluster-aware, wired 18.09) โโโโโโโโโโโโโโโโโโโโโโโ
clusterAwareToolOrder: z.boolean().default(true).describe('Sort exposed tools by priority tier + module centrality instead of alphabetically'),
// โโ โ ๏ธ GOD MODE (Enable ALL tools at once) โโโโโโโโโโโโโโโโโโโโโโ
godMode: z.boolean().default(false).describe('โ ๏ธ WARNING: Enables every tool category. Use with caution.'),
// โโ ๐ DOCUMENT RAG / CHAT WITH FILES โโโโโโโโโโโโโโโโโโโโโโโโโโโ
documentRAG: z.boolean().default(true).describe('Enable file indexing and semantic search for chat'),
retrievalLimit: z.number().min(1).max(20).default(5).describe('Maximum number of relevant chunks to retrieve'),
retrievalAffinityThreshold: z.number().min(0.0).max(1.0).default(0.5).describe('Minimum similarity score for a chunk to be considered relevant (0-1)'),
// Execution tools โ individual toggles (granular control)
executionJavaScript: z.boolean().default(true).describe('Allow run_javascript tool'),
executionPython: z.boolean().default(true).describe('Allow run_python tool'),
executionTerminal: z.boolean().default(false).describe('Allow run_in_terminal tool'),
executionShell: z.boolean().default(false).describe('Allow execute_command tool'),
executionTests: z.boolean().default(false).describe('โ ๏ธ Allow run_tests tool. Disabled by default for security.'),
// โโ Web Search Settings โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
searchFallbackChain: z.enum(['ddg-api', 'ddg-fetch', 'google', 'bing']).default('ddg-api').describe('Primary search engine (auto-fallback to others)'),
maxSearchResults: z.number().min(1).max(50).default(10),
safesearch: z.enum(['0', '1', '2']).default('1'),
// โโ Browser Settings โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
browserTimeout: z.number().min(1000).max(30000).default(5000),
headlessMode: z.boolean().default(false).describe('Run browser without GUI'),
// Git Settings
gitAutoCommit: z.boolean().default(false),
defaultBranch: z.string().default('main'),
// Security Settings
pathValidationEnabled: z.boolean().default(true),
binaryFileDetection: z.boolean().default(true),
regexReDoSProtection: z.boolean().default(true),
maxRegexLength: z.number().min(1).max(1000).default(500),
// State Management
statePersistenceEnabled: z.boolean().default(true),
// ๐น SPEC-C (20.09, memory-store incident): default raised 51200 โ 262144 (256 KiB) โ the old value left ~3.5 KB headroom after a normal session and one more write poisoned the store permanently.
stateMaxSize: z.number().min(1024).max(1048576).default(262144),
// i18n Settings
// ๐ UNIFIED LANGUAGE v2 (step 5, 27.10): 'auto' = follow the chain โ LM Studio host language โ OS locale first tag โ English.
// Per-turn prompt texts resolve fresh each turn in promptPreprocessor.resolveTurnLanguage() ('auto' falls through by
// construction โ it is not a shipped locale code); panel labels are baked ONCE per boot from the same chain (src/uiLabelBake.ts).
language: z.enum(['auto', 'en', 'de', 'es', 'zh-CN', 'zh-TW']).default('auto').describe("'auto' follows the LM Studio host language, then your OS locale, and falls back to English. Pick a concrete language to pin both prompt texts and panel labels."),
// Notification Settings
notificationsEnabled: z.boolean().default(true),
// ๐ฆ PLUGIN UPDATE CHECK (19.10; source switched to the published hub .VERSION file per owner GO, see src/updateChecker.ts): quiet hub check โ notify only when a strictly-newer release exists
updateCheckEnabled: z.boolean().default(true).describe('Quietly check the LM Studio hub for newer plugin releases (published .VERSION file) and show an in-app notification or in-chat line when one is found'),
// Temporal Awareness (merged from up_to_date)
temporalAwareness: z.boolean().default(true).describe('Enable automatic date/time injection into prompts'),
dateFormatStyle: z.enum(['standard', 'heuteIst']).default('standard').describe('Date format style for temporal awareness'),
// โโ ๐ง CONTEXT GUARD SETTINGS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
contextGuardEnabled: z.boolean().default(true).describe('Enable ContextGuard token management and history compression'),
contextGuardCompressionPercent: z.number().min(50).max(100).default(90).describe('History compression triggers at this percentage of the effective context window (the active model\'s reported window; built-in 30k fallback when unavailable)'),
contextGuardAgenticDensity: z.number().min(1).max(20).default(3.6).describe('Chars-per-token density used to estimate token counts from character length for agentic content (prose + tool output mix; live-measured band ~3.2-3.4, see provenance in tokenStatsManager.ts)'),
// Budget-Guard-Arc (05.11, owner ruling 04.11): deterministic context-limit protection โ M1 pre-call cost gate on the
// read path (advisory_threshold_pct), M2 budget-aware spill (spill_threshold_pct; consistent with safety_margin: limitร(1โmargin)=limitร0.92),
// M3 auto-persist session memory at the 85% edge (autopause_threshold_pct). enabled=false โ byte-identical legacy
// behavior โ rollback without a code revert. Provenance: src/budgetGuard.ts + RESEARCH_budget-guard.md (freigegeben 04.11).
budgetGuard: z.object({
enabled: z.boolean().default(true).describe('Master switch for the Budget Guard (M1 pre-call gate, M2 spill cap, M3 auto-persist). Default true since 06.11 (owner order); set false to restore byte-identical legacy behavior.'),
advisory_threshold_pct: z.number().min(1).max(99).default(80).describe('M1: projected context usage above this % of the limit โ read tools return a self-describing advisory instead of the full payload (owner ruling 04.11).'),
spill_threshold_pct: z.number().min(1).max(99).default(92).describe('M2: tool results are spilled to disk beyond this % of the limit (budget-relative cap; the stricter of absolute vs budget wins) (owner ruling 04.11).'),
autopause_threshold_pct: z.number().min(1).max(99).default(85).describe('M3: automatic session-memory persist at this % edge, max once per session, marker auto_saved=true (owner ruling 04.11).'),
safety_margin_pct: z.number().min(0).max(50).default(8).describe('M2: reserve kept out of the context limit for M2 budget math โ limitร(1โmargin/100); default 8 โ spill at 92%, consistent with spill_threshold_pct.'),
}).default({ enabled: true, advisory_threshold_pct: 80, spill_threshold_pct: 92, autopause_threshold_pct: 85, safety_margin_pct: 8 }), // Budget-Guard-Arc (05.11 Triage): object-level .default() โ a LEGACY saved config omits the block entirely; child defaults alone do not make an ABSENT key optional (zod required-object โ ConfigSchema.parse({}) ZodError path:['budgetGuard'], broke config.test.ts + ulv2BytePin.test.ts on the 05.11 full run). enabled flipped falseโtrue 06.11 per owner order (default ON; legacy behavior only when explicitly OFF)
// Budget-Guard-Arc (05.11) flat host-facing keys: getGlobalPluginConfig().get() is typed over FLAT scalar schematics field
// names only โ the nested budgetGuard block above is assembled from these five in toolsProvider.ts (house pattern, cf. L241).
// No UI label objects are attached: plain literals keep the change out of the UiLabels/locale surface entirely.
budgetGuardEnabled: z.boolean().default(true), // flipped falseโtrue 06.11 per owner order (master switch ON by default; explicit OFF = byte-identical legacy)
budgetGuardAdvisoryThresholdPct: z.number().min(1).max(99).default(80),
budgetGuardSpillThresholdPct: z.number().min(1).max(99).default(92),
budgetGuardAutopauseThresholdPct: z.number().min(1).max(99).default(85),
budgetGuardSafetyMarginPct: z.number().min(0).max(50).default(8),
contextGuardForceSummaryOnCompress: z.boolean().default(true).describe('Forced cross-session continuity save (07.10 arc C): when compression triggers, a structured session summary is generated via the Summary Model and persisted BEFORE history is compressed'),
contextGuardSmartReading: z.boolean().default(true).describe('Enable keyword-based smart file reading'),
contextGuardSummaryModel: z.string().default('').describe('LM Studio model name for summarization (leave empty to use current chat model)'),
contextGuardTerminalFilterEnabled: z.boolean().default(true).describe('Enable terminal output filtering'),
contextGuardTerminalFilterLength: z.number().min(100).max(20000).default(2000).describe('Max chars before terminal output is filtered'),
// โโ C COMPACTION FAMILY (24.09): pre-summarization pruning of oversized tool payloads โโ
compactionEnabled: z.boolean().default(true).describe('Prune oversized tool payloads BEFORE history summarization; verbatim copies are stored in .ai_toolbox/compaction/'),
compactionMaxResultBytes: z.number().min(1024).max(1048576).default(16384).describe('Byte budget per tool-result payload before pre-summarization pruning (default 16 KiB)'),
contextUsageFooter: z.boolean().default(true).describe('LLM-side limit awareness: surface a compact context-usage footer on tool results once projected chat usage crosses half the window โ appended to string results and added as an additive ctx_footer field on plain-object results (format A, near-limit advisory at >=90%)'),
// โโ ๐ค AUTO-TRACKING SETTINGS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
autoTrackingEnabled: z.boolean().default(true).describe('Automatically tracks decisions, completions, and bug fixes in the background.'),
autoTrackTokenThreshold: z.number().min(10).max(100).default(75).describe('Trigger session memory save when token usage reaches this percentage (default: 75%)'),
autoTrackDecisions: z.boolean().default(true).describe('Auto-track decisions and conclusions ("I decided", "conclusion")'),
autoTrackCompletions: z.boolean().default(true).describe('Auto-track task completions ("successfully completed", "finished")'),
autoTrackErrors: z.boolean().default(true).describe('Auto-track bug fixes and error resolutions ("fixed the bug")'),
autoSummaryInterval: z.number().min(10).max(200).default(50).describe('Messages between automatic session summaries'),
});
export type PluginConfig = z.infer<typeof ConfigSchema>;
/**
* Default configuration object
*/
export const DEFAULT_CONFIG: PluginConfig = {
fileSystem: true,
webSearch: true,
browserAutomation: false,
gitOperations: false,
packageManage: false,
databaseQueries: false,
documentParsing: true,
backgroundCommands: false,
imageProcessing: true,
httpClient: false,
textProcessing: true,
refactorCode: true,
utility: true,
uiGeneration: true,
contextManagement: true,
vectorRAG: true,
godMode: false,
documentRAG: true,
retrievalLimit: 5,
retrievalAffinityThreshold: 0.5,
executionJavaScript: true,
executionPython: true,
executionTerminal: false,
executionShell: false,
executionTests: false,
searchFallbackChain: 'ddg-api',
maxSearchResults: 10,
safesearch: '1',
browserTimeout: 5000,
headlessMode: false,
gitAutoCommit: false,
defaultBranch: 'main',
pathValidationEnabled: true,
binaryFileDetection: true,
regexReDoSProtection: true,
maxRegexLength: 500,
statePersistenceEnabled: true,
// ๐น SPEC-C (20.09): matches the zod default above โ 262144 (was 51200). See spec C / memory-store incident.
stateMaxSize: 262144,
// ๐ UL-v2 step-5 (27.10): default raised 'en' โ 'auto' โ follows the host app / OS locale chain; concrete picks persist to .ai_toolbox_state.json (see uiLabelBake.ts)
language: 'auto',
notificationsEnabled: true,
// ๐ฆ 19.10 plugin update check (src/updateChecker.ts; hub .VERSION source per owner GO): quiet hub check + in-app/in-chat notify โ matches the zod default above
updateCheckEnabled: true,
temporalAwareness: true,
dateFormatStyle: 'standard',
contextGuardEnabled: true,
contextGuardCompressionPercent: 90, // ๐ ContextGuard: compression trigger as % of effective context window (replaces absolute contextGuardTokenLimit, 07.10)
contextGuardAgenticDensity: 3.6, // ๐ข agentic chars-per-token density (user-editable menu field, 15.10) โ default raised 3.4โ3.6 on 15.10 owner instruction (ABOVE the live-measured band ~3.2-3.4; not probe-justified); provenance in tokenStatsManager.ts
budgetGuardEnabled: true, // Budget-Guard-Arc (05.11) master switch โ flipped OFFโON by owner order 06.11; explicit false restores byte-identical legacy behavior
budgetGuard: { // nested consumer-facing block (assembled from the flat keys in toolsProvider.ts); both sets are part of PluginConfig
enabled: true, advisory_threshold_pct: 80, spill_threshold_pct: 92, autopause_threshold_pct: 85, safety_margin_pct: 8,
},
budgetGuardAdvisoryThresholdPct: 80, // M1 pre-call cost gate edge on the read path (owner ruling 04.11)
budgetGuardSpillThresholdPct: 92, // M2 budget-aware spill edge โ stricter of absolute vs budget wins
budgetGuardAutopauseThresholdPct: 85, // M3 auto-persist session-memory edge, max once per session
budgetGuardSafetyMarginPct: 8, // M2 reserve โ limitร(1โmargin)=limitร0.92 โ consistent with spill threshold (default 8 โ budget = limit ร 0.92)
contextGuardForceSummaryOnCompress: true, // ๐พ Arc C (07.10): forced structured session-memory save at the compression trigger โ generated before history destruction; telemetry checkpoint remains the fallback on any failure
contextGuardSmartReading: true,
contextGuardSummaryModel: '',
contextGuardTerminalFilterEnabled: true,
contextGuardTerminalFilterLength: 2000,
compactionEnabled: true,
compactionMaxResultBytes: 16384,
// LLM-side limit awareness (02.10; widened 03.10 per option B): context-usage footer โ appended to string
// tool results AND added as an additive ctx_footer field on plain-object results, gated at 50% usage
contextUsageFooter: true,
autoTrackingEnabled: true,
autoTrackTokenThreshold: 75,
autoTrackDecisions: true,
autoTrackCompletions: true,
autoTrackErrors: true,
autoSummaryInterval: 50,
taskPlanning: true,
clusterAwareToolOrder: true,
};
/**
* Check if ANY execution tool is enabled (legacy compatibility)
*/
export function hasAnyExecutionTool(config: PluginConfig): boolean {
return config.executionJavaScript || config.executionPython ||
config.executionTerminal || config.executionShell || config.executionTests;
}
// ==================== LM Studio UI Schematics ====================
// These define the toggle switches that appear in LM Studio's settings panel.
/**
* UNIFIED LANGUAGE v2 (step 5, 27.10): settings-panel schematics builder. When a locale's UiLabels bundle is
* passed, every panel label (displayName/subtitle/hint + localized select options) comes from it; without one the
* English literals below are used โ byte-identical to the pre-v2 panel text. Field KEYS, types and default values
* never change between builds: only human-readable strings do. The 'language' row gains the step-5 'auto' option.
* searchFallbackChain options stay English by design (brand/engine names โ see types.ts UiLabels docblock).
*/
export function buildConfigSchematics(ui?: UiLabels) {
return createConfigSchematics()
// ๐ LANGUAGE (top of menu by design)
.field('language', 'select', {
displayName: ui?.languageRow.displayName ?? '๐ Language',
options: [ { value: 'auto', displayName: ui?.languageRow.options.auto ?? 'Automatic (follows LM Studio)' },
{ value: 'en', displayName: ui?.languageRow.options.en ?? 'English' },
{ value: 'de', displayName: ui?.languageRow.options.de ?? 'Deutsch (German)' },
{ value: 'es', displayName: ui?.languageRow.options.es ?? 'Espaรฑol' },
{ value: 'zh-CN', displayName: ui?.languageRow.options.zhCN ?? 'Simplified Chinese' },
{ value: 'zh-TW', displayName: ui?.languageRow.options.zhTW ?? 'Traditional Chinese' },
],
}, DEFAULT_CONFIG.language)
// โ ๏ธ GOD MODE - TOP PRIORITY WARNING TOGGLE โ ๏ธ
.field('godMode', 'boolean', {
displayName: ui?.godMode.displayName ?? 'โกโ ๏ธ GOD MODE - Enable ALL Tools โ ๏ธโก',
subtitle: ui?.godMode.subtitle ?? 'WARNING: Activates every tool category instantly. Use with caution.',
hint: ui?.godMode.hint ?? 'When enabled, ALL individual toggles are bypassed and every tool is activated regardless of settings.',
}, DEFAULT_CONFIG.godMode)
// ๐๏ธ TOOL CATEGORIES (Hauptschalter) ๐๏ธ
.field('fileSystem', 'boolean', { displayName: ui?.fileSystem.displayName ?? '๐ File System Tools', hint: ui?.fileSystem.hint ?? 'Enable file read/write/search operations' }, DEFAULT_CONFIG.fileSystem)
.field('webSearch', 'boolean', { displayName: ui?.webSearch.displayName ?? '๐ Web & Research Tools', hint: ui?.webSearch.hint ?? 'Enable DuckDuckGo/Wikipedia search' }, DEFAULT_CONFIG.webSearch)
// ๐ GIT & GITHUB TOOLS (visuelle Gruppierung) ๐
.field('packageManage', 'boolean', {
displayName: ui?.packageManage.displayName ?? 'Package Management Tools',
subtitle: ui?.packageManage.subtitle ?? 'npm/pip/cargo operations',
hint: ui?.packageManage.hint ?? 'Enable package manager tools. Disabled by default for security.',
}, DEFAULT_CONFIG.packageManage)
.field('gitOperations', 'boolean', {
displayName: ui?.gitOperations.displayName ?? '๐ Git & GitHub Tools',
subtitle: ui?.gitOperations.subtitle ?? 'Version Control & API',
hint: ui?.gitOperations.hint ?? 'Enable git operations and GitHub API access.',
}, DEFAULT_CONFIG.gitOperations)
.field('gitAutoCommit', 'boolean', {
displayName: ui?.gitAutoCommit.displayName ?? '๐พ Git Auto-Commit',
subtitle: ui?.gitAutoCommit.subtitle ?? 'โ๏ธ Part of Git & GitHub Tools',
hint: ui?.gitAutoCommit.hint ?? 'Automatically commit changes after operations',
}, DEFAULT_CONFIG.gitAutoCommit)
.field('defaultBranch', 'string', {
displayName: ui?.defaultBranch.displayName ?? '๐ฟ Default Branch',
placeholder: 'main',
subtitle: ui?.defaultBranch.subtitle ?? 'โ๏ธ Part of Git & GitHub Tools',
hint: ui?.defaultBranch.hint ?? 'Branch name for new repositories and git operations',
}, DEFAULT_CONFIG.defaultBranch)
.field('databaseQueries', 'boolean', { displayName: ui?.databaseQueries.displayName ?? '๐๏ธ Database Queries', hint: ui?.databaseQueries.hint ?? 'Enable read-only SQLite queries' }, DEFAULT_CONFIG.databaseQueries)
.field('documentParsing', 'boolean', { displayName: ui?.documentParsing.displayName ?? '๐ Document Parsing', hint: ui?.documentParsing.hint ?? 'Enable PDF/DOCX document reading' }, DEFAULT_CONFIG.documentParsing)
.field('backgroundCommands', 'boolean', { displayName: ui?.backgroundCommands.displayName ?? 'โณ Background Commands', hint: ui?.backgroundCommands.hint ?? 'Enable long-running process tracking' }, DEFAULT_CONFIG.backgroundCommands)
// ๐โโ NEW TOOL CATEGORIES ๐โโ
.field('imageProcessing', 'boolean', {
displayName: ui?.imageProcessing.displayName ?? '๐ผ๏ธ Image Processing Tools',
subtitle: ui?.imageProcessing.subtitle ?? 'OCR, Screenshots & Comparison',
hint: ui?.imageProcessing.hint ?? 'Enable image OCR (Tesseract.js), screenshot capture, and image comparison tools.',
}, DEFAULT_CONFIG.imageProcessing)
.field('httpClient', 'boolean', {
displayName: ui?.httpClient.displayName ?? '๐ HTTP Client Tools',
subtitle: ui?.httpClient.subtitle ?? 'Generic REST API Client',
hint: ui?.httpClient.hint ?? 'Enable generic HTTP client for making requests to any REST API (GET, POST, PUT, DELETE).',
}, DEFAULT_CONFIG.httpClient)
.field('vectorRAG', 'boolean', {
displayName: ui?.vectorRag.displayName ?? '๐ Vector RAG / Semantic Search',
subtitle: ui?.vectorRag.subtitle ?? 'Semantic Document Search',
hint: ui?.vectorRag.hint ?? 'Enable semantic search with vector embeddings for intelligent document retrieval.',
}, DEFAULT_CONFIG.vectorRAG)
.field('uiGeneration', 'boolean', {
displayName: ui?.uiGeneration.displayName ?? '๐จ Interactive UI Generation Tools',
subtitle: ui?.uiGeneration.subtitle ?? 'Generate and render interactive UI components',
hint: ui?.uiGeneration.hint ?? 'Enable tools for generating HTML/CSS/JS components (buttons, forms, charts, dashboards) and rendering them in the browser.',
}, DEFAULT_CONFIG.uiGeneration)
.field('contextManagement', 'boolean', {
displayName: ui?.contextManagement.displayName ?? '๐ง Auto-Context Management Tools',
subtitle: ui?.contextManagement.subtitle ?? 'Automatic session tracking and memory management',
hint: ui?.contextManagement.hint ?? 'Enable tools for automatically saving important decisions, patterns, and configurations to persistent memory.',
}, DEFAULT_CONFIG.contextManagement)
// ๐ DOCUMENT RAG / CHAT WITH FILES ๐
// ๐ DOCUMENT RAG / CHAT WITH FILES ๐
.field('documentRAG', 'boolean', {
displayName: ui?.documentRAG.displayName ?? '๐ Document RAG / Chat with Files',
subtitle: ui?.documentRAG.subtitle ?? 'Enable file indexing and semantic search for chat',
hint: ui?.documentRAG.hint ?? 'Attach documents to your chat messages. The plugin will automatically retrieve relevant content from attached files using semantic search.',
}, DEFAULT_CONFIG.documentRAG)
.field('textProcessing', 'boolean', {
displayName: ui?.textProcessing.displayName ?? '๐ Text Processing Tools (sed/awk equivalents)',
subtitle: ui?.textProcessing.subtitle ?? 'Regex-based text transformations and field extraction',
hint: ui?.textProcessing.hint ?? 'Enable tools for bulk text replacement, pattern matching, and structured data extraction without shell dependencies.',
}, DEFAULT_CONFIG.textProcessing)
.field('refactorCode', 'boolean', {
displayName: ui?.refactorCode.displayName ?? '๐ง AST Code Refactoring Tools',
subtitle: ui?.refactorCode.subtitle ?? 'Rename, move, extract functions & clean unused imports',
hint: ui?.refactorCode.hint ?? 'Enable AST-based code refactoring tools (rename_identifier, move_function, extract_function, unused_import_cleanup).',
}, DEFAULT_CONFIG.refactorCode)
.field('utility', 'boolean', {
displayName: ui?.utility.displayName ?? '๐ ๏ธ Utility & Maintenance Tools',
subtitle: ui?.utility.subtitle ?? 'Backup, chart generation, markdown preview, line operations',
hint: ui?.utility.hint ?? 'Enable utility tools (create_backup, list_backups, restore_backup, delete_backup, cleanup_backups, generate_chart, markdown_preview).',
}, DEFAULT_CONFIG.utility)
// โโ ๐ TASK PLANNING TOOLS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.field('taskPlanning', 'boolean', {
displayName: ui?.taskPlanning.displayName ?? '๐ Task Planning Tools',
subtitle: ui?.taskPlanning.subtitle ?? 'Structured multi-step workflow tools',
hint: ui?.taskPlanning.hint ?? 'Enable create_plan, update_plan_step, and get_plan tools for structured task execution.',
}, DEFAULT_CONFIG.taskPlanning)
// โโ ๐งญ CLUSTER-AWARE TOOL ORDERING (18.09) โโโโโโโโโโโโโโโโโโโโโโโ
.field('clusterAwareToolOrder', 'boolean', {
displayName: ui?.clusterAwareToolOrder.displayName ?? '๐งญ Cluster-Aware Tool Ordering',
subtitle: ui?.clusterAwareToolOrder.subtitle ?? 'Sort exposed tools by priority tier + module centrality instead of alphabetically.',
hint: ui?.clusterAwareToolOrder.hint ?? 'Uses the static ARCHITECTURE.md dependency graph (no fs I/O). Disable to restore legacy alphabetical order.',
}, DEFAULT_CONFIG.clusterAwareToolOrder)
.field('retrievalLimit', 'numeric', {
displayName: ui?.retrievalLimit.displayName ?? '๐ข Retrieval Limit',
subtitle: ui?.retrievalLimit.subtitle ?? 'Max chunks to return per query',
min: 1, max: 20, int: true,
hint: ui?.retrievalLimit.hint ?? 'Maximum number of relevant document chunks to retrieve for each query.',
}, DEFAULT_CONFIG.retrievalLimit)
.field('retrievalAffinityThreshold', 'numeric', {
displayName: ui?.retrievalAffinityThreshold.displayName ?? '๐ฏ Retrieval Affinity Threshold',
subtitle: ui?.retrievalAffinityThreshold.subtitle ?? 'Minimum relevance score (0-1)',
min: 0.0, max: 1.0, step: 0.01,
hint: ui?.retrievalAffinityThreshold.hint ?? 'Chunks below this similarity score will be filtered out. Lower = more results but potentially less relevant.',
}, DEFAULT_CONFIG.retrievalAffinityThreshold)
// โก EXECUTION TOOLS (Gefรคhrlich!) โก
.field('executionJavaScript', 'boolean', {
displayName: ui?.executionJavaScript.displayName ?? 'โก Allow JavaScript Execution',
subtitle: ui?.executionJavaScript.subtitle ?? "Enables the 'run_javascript' tool",
hint: ui?.executionJavaScript.hint ?? 'WARNING: code runs on your machine.',
}, DEFAULT_CONFIG.executionJavaScript)
.field('executionPython', 'boolean', {
displayName: ui?.executionPython.displayName ?? '๐ Allow Python Execution',
subtitle: ui?.executionPython.subtitle ?? "Enables the 'run_python' tool",
hint: ui?.executionPython.hint ?? 'WARNING: code runs on your machine.',
}, DEFAULT_CONFIG.executionPython)
.field('executionTerminal', 'boolean', {
displayName: ui?.executionTerminal.displayName ?? '๐ป Allow Terminal Execution',
subtitle: ui?.executionTerminal.subtitle ?? "Enables the 'run_in_terminal' tool",
hint: ui?.executionTerminal.hint ?? 'Opens real terminal windows.',
}, DEFAULT_CONFIG.executionTerminal)
.field('executionShell', 'boolean', {
displayName: ui?.executionShell.displayName ?? '๐ง Allow Shell Command Execution',
subtitle: ui?.executionShell.subtitle ?? "Enables the 'execute_command' tool",
hint: ui?.executionShell.hint ?? 'WARNING: commands run on your machine.',
}, DEFAULT_CONFIG.executionShell)
.field('executionTests', 'boolean', {
displayName: ui?.executionTests.displayName ?? '๐งช Allow Test Execution',
subtitle: ui?.executionTests.subtitle ?? "Enables the 'run_tests' tool",
hint: ui?.executionTests.hint ?? 'WARNING: runs npm jest / pytest / go test โ can install packages and execute code.',
}, DEFAULT_CONFIG.executionTests)
// ๐ SEARCH SETTINGS ๐
.field('searchFallbackChain', 'select', {
displayName: ui?.searchFallbackChain.displayName ?? '๐ Search Fallback Chain',
hint: ui?.searchFallbackChain.hint ?? 'Primary search engine. Auto-falls back to others if unavailable.',
options: [
{ value: 'ddg-api', displayName: 'DuckDuckGo API' },
{ value: 'ddg-fetch', displayName: 'DuckDuckGo Fetch' },
{ value: 'google', displayName: 'Google' },
{ value: 'bing', displayName: 'Bing' },
],
}, DEFAULT_CONFIG.searchFallbackChain)
.field('maxSearchResults', 'numeric', { min: 1, max: 50, int: true }, DEFAULT_CONFIG.maxSearchResults)
.field('safesearch', 'select', {
displayName: ui?.safesearch.displayName ?? '๐ก๏ธ Safe Search',
options: [ { value: '0', displayName: ui?.safesearch.options.off ?? 'Off' },
{ value: '1', displayName: ui?.safesearch.options.moderate ?? 'Moderate' },
{ value: '2', displayName: ui?.safesearch.options.strict ?? 'Strict' },
],
}, DEFAULT_CONFIG.safesearch)
// ๐ฅ๏ธ BROWSER AUTOMATION TOOLS ๐ฅ๏ธ
.field('browserAutomation', 'boolean', {
displayName: ui?.browserAutomation.displayName ?? '๐ฅ๏ธ Browser Automation Tools',
subtitle: ui?.browserAutomation.subtitle ?? 'Headless browser control & automation',
hint: ui?.browserAutomation.hint ?? 'Enable Puppeteer-based headless browser automation for web scraping, testing, and UI interaction.',
}, DEFAULT_CONFIG.browserAutomation)
.field('browserTimeout', 'numeric', {
displayName: ui?.browserTimeout.displayName ?? 'โฑ๏ธ Browser Timeout',
subtitle: ui?.browserTimeout.subtitle ?? 'โ๏ธ Part of Browser Automation Tools',
min: 1000, max: 30000, int: true,
hint: ui?.browserTimeout.hint ?? 'Maximum time (ms) to wait for browser operations before timing out.',
}, DEFAULT_CONFIG.browserTimeout)
.field('headlessMode', 'boolean', {
displayName: ui?.headlessMode.displayName ?? '๐ป Headless Mode',
subtitle: ui?.headlessMode.subtitle ?? 'โ๏ธ Part of Browser Automation Tools',
hint: ui?.headlessMode.hint ?? 'Run browser without GUI (recommended for automation).',
}, DEFAULT_CONFIG.headlessMode)
// ๐ SECURITY SETTINGS ๐
.field('pathValidationEnabled', 'boolean', { displayName: ui?.pathValidationEnabled.displayName ?? '๐ Path Validation', hint: ui?.pathValidationEnabled.hint ?? 'Prevent directory traversal attacks' }, DEFAULT_CONFIG.pathValidationEnabled)
.field('binaryFileDetection', 'boolean', { displayName: ui?.binaryFileDetection.displayName ?? '๐ Binary File Detection', hint: ui?.binaryFileDetection.hint ?? 'Detect binary files via null byte check' }, DEFAULT_CONFIG.binaryFileDetection)
.field('regexReDoSProtection', 'boolean', { displayName: ui?.regexReDoSProtection.displayName ?? '๐ก๏ธ ReDoS Protection', hint: ui?.regexReDoSProtection.hint ?? 'Protect against regex denial-of-service' }, DEFAULT_CONFIG.regexReDoSProtection)
.field('maxRegexLength', 'numeric', { min: 1, max: 1000, int: true }, DEFAULT_CONFIG.maxRegexLength)
// ๐ฝ STATE MANAGEMENT ๐ฝ
.field('statePersistenceEnabled', 'boolean', { displayName: ui?.statePersistenceEnabled.displayName ?? '๐ฝ State Persistence', hint: ui?.statePersistenceEnabled.hint ?? 'Persist tool execution state between sessions' }, DEFAULT_CONFIG.statePersistenceEnabled)
.field('stateMaxSize', 'numeric', { min: 1024, max: 1048576, int: true }, DEFAULT_CONFIG.stateMaxSize)
.field('notificationsEnabled', 'boolean', { displayName: ui?.notificationsEnabled.displayName ?? '๐ Desktop Notifications', hint: ui?.notificationsEnabled.hint ?? 'Show system notifications' }, DEFAULT_CONFIG.notificationsEnabled)
// โโ ๐ฆ PLUGIN UPDATE CHECK (19.10) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.field('updateCheckEnabled', 'boolean', {
displayName: ui?.updateCheckEnabled.displayName ?? '๐ Plugin Update Check',
subtitle: ui?.updateCheckEnabled.subtitle ?? 'Quiet LM Studio hub .VERSION check โ no new tools, no OS permissions',
hint: ui?.updateCheckEnabled.hint ?? "Once per day the plugin quietly checks the published LM Studio hub .VERSION file for a strictly-newer release. If one exists it notifies via desktop toast (Desktop Notifications ON) or a single in-chat line (OFF). Silent when you are up to date or on a dismissed version; state survives reinstalls.",
}, DEFAULT_CONFIG.updateCheckEnabled)
// โฐ TEMPORAL AWARENESS (from up_to_date)
.field('temporalAwareness', 'boolean', {
displayName: ui?.temporalAwareness.displayName ?? 'โฐ Temporal Awareness',
subtitle: ui?.temporalAwareness.subtitle ?? 'Injects current date/time into every message',
hint: ui?.temporalAwareness.hint ?? 'Enables the AI to know the current time.',
}, DEFAULT_CONFIG.temporalAwareness)
.field('dateFormatStyle', 'select', {
displayName: ui?.dateFormatStyle.displayName ?? '๐
Date Format Style',
options: [ { value: 'standard', displayName: ui?.dateFormatStyle.options.standard ?? 'Standard ([Zeit: ...])' },
{ value: 'heuteIst', displayName: ui?.dateFormatStyle.options.heuteIst ?? 'HEUTE IST Mode (Prominent)' },
],
}, DEFAULT_CONFIG.dateFormatStyle)
// โโ ๐ง CONTEXT GUARD SETTINGS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.field('contextGuardEnabled', 'boolean', {
displayName: ui?.contextGuardEnabled.displayName ?? '๐ง ContextGuard Token Management',
subtitle: ui?.contextGuardEnabled.subtitle ?? 'Automatic history compression & smart reading',
hint: ui?.contextGuardEnabled.hint ?? 'Automatically compresses chat history when token limit is reached. Enables smart file reading and terminal output filtering.',
}, DEFAULT_CONFIG.contextGuardEnabled)
.field('contextGuardCompressionPercent', 'numeric', {
displayName: ui?.contextGuardCompressionPercent.displayName ?? '๐ Compression Trigger (% of Context Window)',
subtitle: ui?.contextGuardCompressionPercent.subtitle ?? 'โ๏ธ ContextGuard Setting',
min: 50, max: 100, int: true,
hint: ui?.contextGuardCompressionPercent.hint ?? 'History compression triggers when context usage reaches this percentage of the active model\'s context window. If LM Studio reports the model\'s real window it is used; otherwise a built-in 30k fallback applies.',
}, DEFAULT_CONFIG.contextGuardCompressionPercent)
// ๐ข Agentic chars-per-token density (15.10 owner request "make it user editable"): reseeded per turn into the
// tokenStatsManager live state by promptPreprocessor.preprocess(); changing it here NEVER requires a test edit.
.field('contextGuardAgenticDensity', 'numeric', {
displayName: ui?.contextGuardAgenticDensity.displayName ?? '๐ข Agentic Chars-per-Token Density',
subtitle: ui?.contextGuardAgenticDensity.subtitle ?? 'โ๏ธ ContextGuard Setting',
min: 1, max: 20, step: 0.1,
hint: ui?.contextGuardAgenticDensity.hint ?? 'Chars per token used to estimate tokens from character length (agentic mix of prose + tool output; live-measured band ~3.2-3.4 โ default 3.6 is owner-set above that band). Higher = denser content = fewer estimated tokens; lower estimates more and triggers compaction earlier.',
}, DEFAULT_CONFIG.contextGuardAgenticDensity)
// ๐พ Arc C (07.10): forced structured session-memory save at the compression trigger โ generated + persisted BEFORE history destruction (see persistGeneratedSessionSummary); non-fatal by design, the telemetry checkpoint stays as fallback.
.field('contextGuardForceSummaryOnCompress', 'boolean', {
displayName: ui?.contextGuardForceSummaryOnCompress.displayName ?? '๐พ Force Session-Memory Save Before Compression',
subtitle: ui?.contextGuardForceSummaryOnCompress.subtitle ?? 'โ๏ธ ContextGuard Setting',
hint: ui?.contextGuardForceSummaryOnCompress.hint ?? "When context reaches your Compression Trigger, a structured session summary (task description, accomplishments, pending tasks) is generated with the Summary Model and persisted BEFORE history is compressed. Non-fatal: on any failure the previous telemetry checkpoint still runs.",
}, DEFAULT_CONFIG.contextGuardForceSummaryOnCompress)
.field('contextGuardSmartReading', 'boolean', {
displayName: ui?.contextGuardSmartReading.displayName ?? '๐ Smart File Reading',
subtitle: ui?.contextGuardSmartReading.subtitle ?? 'โ๏ธ ContextGuard Setting',
hint: ui?.contextGuardSmartReading.hint ?? 'Extracts keywords from user queries to read only relevant portions of files. Saves tokens and speeds up responses.',
}, DEFAULT_CONFIG.contextGuardSmartReading)
.field('contextGuardSummaryModel', 'string', {
displayName: ui?.contextGuardSummaryModel.displayName ?? '๐ค Summary Model Name',
subtitle: ui?.contextGuardSummaryModel.subtitle ?? 'โ๏ธ ContextGuard Setting',
placeholder: '(leave empty for current chat model)',
hint: ui?.contextGuardSummaryModel.hint ?? 'LM Studio model name used for history summarization. Leave empty to use your current chat model.',
}, DEFAULT_CONFIG.contextGuardSummaryModel)
.field('contextGuardTerminalFilterEnabled', 'boolean', {
displayName: ui?.contextGuardTerminalFilterEnabled.displayName ?? '๐ Terminal Output Filtering',
subtitle: ui?.contextGuardTerminalFilterEnabled.subtitle ?? 'โ๏ธ ContextGuard Setting',
hint: ui?.contextGuardTerminalFilterEnabled.hint ?? 'Automatically truncates long terminal outputs to save tokens.',
}, DEFAULT_CONFIG.contextGuardTerminalFilterEnabled)
.field('contextGuardTerminalFilterLength', 'numeric', {
displayName: ui?.contextGuardTerminalFilterLength.displayName ?? '๐ Max Terminal Output Length',
subtitle: ui?.contextGuardTerminalFilterLength.subtitle ?? 'โ๏ธ ContextGuard Setting',
min: 100, max: 20000, int: true,
hint: ui?.contextGuardTerminalFilterLength.hint ?? 'Maximum characters before terminal output is truncated and summarized.',
}, DEFAULT_CONFIG.contextGuardTerminalFilterLength)
// โโ C COMPACTION FAMILY (24.09): pre-summarization pruning of oversized tool payloads โโ
.field('compactionEnabled', 'boolean', {
displayName: ui?.compactionEnabled.displayName ?? 'โ๏ธ Compaction Pre-Summarization Pruning',
subtitle: ui?.compactionEnabled.subtitle ?? 'โ๏ธ C Compaction Family',
hint: ui?.compactionEnabled.hint ?? 'Before history is summarized, tool payloads above the byte budget are replaced by a head/tail preview plus an opaque locator; the full result stays stored verbatim in .ai_toolbox/compaction/.',
}, DEFAULT_CONFIG.compactionEnabled)
.field('compactionMaxResultBytes', 'numeric', {
displayName: ui?.compactionMaxResultBytes.displayName ?? '๐ Max Tool Result Before Pruning (bytes)',
subtitle: ui?.compactionMaxResultBytes.subtitle ?? 'โ๏ธ C Compaction Family',
min: 1024, max: 1048576, int: true,
hint: ui?.compactionMaxResultBytes.hint ?? 'Byte budget per tool-result payload in chat history. Results above this are pruned to preview + locator before summarization (verbatim copy stored on disk).',
}, DEFAULT_CONFIG.compactionMaxResultBytes)
// โโ LLM-SIDE LIMIT AWARENESS (02.10; widened 03.10 per option B): context-usage footer on ALL tool results โโ
.field('contextUsageFooter', 'boolean', {
displayName: ui?.contextUsageFooter.displayName ?? '๐ Context Usage Footer in Tool Results',
subtitle: ui?.contextUsageFooter.subtitle ?? 'โ๏ธ LLM-side Limit Awareness',
hint: ui?.contextUsageFooter.hint ?? "Once projected context usage crosses half of the model's window, every tool result gains a short footer like [ctx ~48.3k/64k = 76%] โ appended to string results and added as an additive ctx_footer field on plain-object results (every registered tool returns one) โ so the model always sees current token usage. At >=90% a near-limit advisory is added.",
}, DEFAULT_CONFIG.contextUsageFooter)
// โโ ๐ค AUTO-TRACKING SETTINGS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.field('autoTrackingEnabled', 'boolean', {
displayName: ui?.autoTrackingEnabled.displayName ?? '๐ค Auto-Tracking Enabled',
subtitle: ui?.autoTrackingEnabled.subtitle ?? 'Automatically remember important events',
hint: ui?.autoTrackingEnabled.hint ?? 'Silently tracks decisions, completions, and bug fixes in the background. Enabled by default.',
}, DEFAULT_CONFIG.autoTrackingEnabled)
.field('autoTrackTokenThreshold', 'numeric', {
displayName: ui?.autoTrackTokenThreshold.displayName ?? 'Auto-Track Token Threshold',
subtitle: ui?.autoTrackTokenThreshold.subtitle ?? 'Auto-Tracking Setting',
min: 10, max: 100, int: true,
hint: ui?.autoTrackTokenThreshold.hint ?? 'Trigger session memory save when token usage reaches this percentage (default: 75%). Helps prevent context overflow.',
}, DEFAULT_CONFIG.autoTrackTokenThreshold)
.field('autoTrackDecisions', 'boolean', {
displayName: ui?.autoTrackDecisions.displayName ?? '๐ Track Decisions Automatically',
subtitle: ui?.autoTrackDecisions.subtitle ?? 'โ๏ธ Auto-Tracking Setting',
hint: ui?.autoTrackDecisions.hint ?? 'Detects phrases like "I decided", "conclusion", "going with".',
}, DEFAULT_CONFIG.autoTrackDecisions)
.field('autoTrackCompletions', 'boolean', {
displayName: ui?.autoTrackCompletions.displayName ?? 'โ
Track Completions Automatically',
subtitle: ui?.autoTrackCompletions.subtitle ?? 'โ๏ธ Auto-Tracking Setting',
hint: ui?.autoTrackCompletions.hint ?? 'Detects phrases like "successfully completed", "finished implementing".',
}, DEFAULT_CONFIG.autoTrackCompletions)
.field('autoTrackErrors', 'boolean', {
displayName: ui?.autoTrackErrors.displayName ?? '๐ Track Bug Fixes Automatically',
subtitle: ui?.autoTrackErrors.subtitle ?? 'โ๏ธ Auto-Tracking Setting',
hint: ui?.autoTrackErrors.hint ?? 'Detects phrases like "fixed the bug", "resolved the issue".',
}, DEFAULT_CONFIG.autoTrackErrors)
.field('autoSummaryInterval', 'numeric', {
displayName: ui?.autoSummaryInterval.displayName ?? '๐ Session Summary Interval',
subtitle: ui?.autoSummaryInterval.subtitle ?? 'โ๏ธ Auto-Tracking Setting',
min: 10, max: 200, int: true,
hint: ui?.autoSummaryInterval.hint ?? 'Number of messages between automatic session summaries. Higher = less frequent.',
}, DEFAULT_CONFIG.autoSummaryInterval)
// Budget-Guard-Arc (05.11): flat host-facing keys โ getGlobalPluginConfig().get() is typed over these field names;
// toolsProvider.ts assembles the nested budgetGuard block from them. i18n wired 06.11 per owner rule โalle Tool-Beschreibungen
// IMMER รผbersetztโ: ui?.โฆ ?? EN-literal (supersedes the original arc's deliberate 'no UiLabels/locale surface' decision).
.field('budgetGuardEnabled', 'boolean', { displayName: ui?.budgetGuardEnabled.displayName ?? '๐ก๏ธ Budget Guard (context-limit protection)', hint: ui?.budgetGuardEnabled.hint ?? 'Master switch for the deterministic context budget guard โ M1 pre-call read gate, M2 budget-aware spill cap, M3 auto-persist at 85% edge. ON by default (06.11); turn OFF to restore byte-identical legacy behavior.' }, DEFAULT_CONFIG.budgetGuardEnabled)
.field('budgetGuardAdvisoryThresholdPct', 'numeric', { displayName: ui?.budgetGuardAdvisoryThresholdPct.displayName ?? '๐ข Budget Guard Advisory Threshold (%)', subtitle: ui?.budgetGuardAdvisoryThresholdPct.subtitle ?? 'โ๏ธ Budget Guard Setting', hint: ui?.budgetGuardAdvisoryThresholdPct.hint ?? 'M1 pre-call read gate: above this % of the context limit, read tools return a self-describing budget advisory instead of the full payload.', min: 1, max: 99, int: true }, DEFAULT_CONFIG.budgetGuardAdvisoryThresholdPct)
.field('budgetGuardSpillThresholdPct', 'numeric', { displayName: ui?.budgetGuardSpillThresholdPct.displayName ?? 'โ๏ธ Budget Guard Spill Threshold (%)', subtitle: ui?.budgetGuardSpillThresholdPct.subtitle ?? 'โ๏ธ Budget Guard Setting', hint: ui?.budgetGuardSpillThresholdPct.hint ?? 'M2 spill cap: tool results are spilled to disk beyond this % of the limit (the stricter of absolute vs budget-relative bound wins).', min: 1, max: 99, int: true }, DEFAULT_CONFIG.budgetGuardSpillThresholdPct)
.field('budgetGuardAutopauseThresholdPct', 'numeric', { displayName: ui?.budgetGuardAutopauseThresholdPct.displayName ?? '๐พ Budget Guard Auto-Persist Edge (%)', subtitle: ui?.budgetGuardAutopauseThresholdPct.subtitle ?? 'โ๏ธ Budget Guard Setting', hint: ui?.budgetGuardAutopauseThresholdPct.hint ?? 'M3: automatic session-memory persist at this % edge, max once per session.', min: 1, max: 99, int: true }, DEFAULT_CONFIG.budgetGuardAutopauseThresholdPct)
.field('budgetGuardSafetyMarginPct', 'numeric', { displayName: ui?.budgetGuardSafetyMarginPct.displayName ?? '๐งฎ Budget Guard Safety Margin (%)', subtitle: ui?.budgetGuardSafetyMarginPct.subtitle ?? 'โ๏ธ Budget Guard Setting', hint: ui?.budgetGuardSafetyMarginPct.hint ?? 'Reserve kept out of the context limit for M2 budget math โ limit ร (1 โ margin/100); default 8 โ spill at 92 %.', min: 0, max: 50, int: true }, DEFAULT_CONFIG.budgetGuardSafetyMarginPct)
// โโ ๐ ๏ธ GRAMMAR PARSER LIMITS (P0 Fix) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.build();
}
// ==================== Utility Functions ====================
/**
* Validates a config object against the schema.
* Returns the validated config if valid, throws on invalid input.
*/
export function validateConfig(config: Partial<PluginConfig>): PluginConfig {
const result = ConfigSchema.safeParse(config);
if (!result.success) {
throw new Error(
`Invalid configuration:\n${result.error.errors.map((e) => ` - ${e.path.join('.')}: ${e.message}`).join('\n')}`
);
}
return result.data;
}
/**
* Checks if a specific tool category is enabled in the config.
* @param config - The plugin configuration object
* @param category - The tool category to check (must be a key of PluginConfig)
* @returns true if the category is enabled, false otherwise
*/
export function isToolEnabled(config: PluginConfig, category: keyof PluginConfig): boolean {
const value = config[category];
return typeof value === 'boolean' && value === true;
}
/** Module-level English build โ consumed by promptPreprocessor.ts and the tests. Keys/types/defaults are identical across all locale builds; only label strings differ (see buildConfigSchematics above). */
export const configSchematics = buildConfigSchematics(); // EN literals (byte-identical to the pre-v2 panel text except the new auto option + default)import { z } from 'zod';
import { createConfigSchematics } from '@lmstudio/sdk';
import type { UiLabels } from './locales/types.js'; // UL-v2 step-5 (27.10): type-only โ erased at runtime, never jest-resolved (same convention as hostLanguage.ts)
// ==================== Zod Schema (validation) ====================
export const ConfigSchema = z.object({
// Tool Categories (enable/disable individual tools)
fileSystem: z.boolean().default(true),
webSearch: z.boolean().default(true),
browserAutomation: z.boolean().default(false),
gitOperations: z.boolean().default(false),
packageManage: z.boolean().default(false).describe('โ ๏ธ Enable package manager (npm/pip/cargo) operations. Disabled by default for security.'),
databaseQueries: z.boolean().default(false),
documentParsing: z.boolean().default(true),
backgroundCommands: z.boolean().default(false),
// โโ ๐ NEW TOOL CATEGORIES โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
imageProcessing: z.boolean().default(true).describe('Enable image OCR, screenshot, and comparison tools'),
httpClient: z.boolean().default(false).describe('Enable generic HTTP client for REST API calls'),
vectorRAG: z.boolean().default(true).describe('Enable semantic search with vector embeddings'),
uiGeneration: z.boolean().default(true).describe('Enable interactive UI generation and rendering tools (ON by default since 10.10, owner decision โ aligns with DEFAULT_CONFIG / schematics)'),
contextManagement: z.boolean().default(true).describe('Enable automatic context tracking and memory management'),
textProcessing: z.boolean().default(true).describe('Enable text processing tools (sed/awk equivalents)'),
refactorCode: z.boolean().default(true).describe('Enable AST-based code refactoring tools (rename, move, extract, unused import cleanup)'),
utility: z.boolean().default(true).describe('Enable Utility & Maintenance Tools (backup, chart generation, markdown preview, line operations)'),
// โโ ๐ TASK PLANNING TOOLS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
taskPlanning: z.boolean().default(true).describe('Enable structured multi-step workflow tools (create_plan, update_plan_step, get_plan)'),
// โโ ๐งญ TOOL ORDERING (cluster-aware, wired 18.09) โโโโโโโโโโโโโโโโโโโโโโโ
clusterAwareToolOrder: z.boolean().default(true).describe('Sort exposed tools by priority tier + module centrality instead of alphabetically'),
// โโ โ ๏ธ GOD MODE (Enable ALL tools at once) โโโโโโโโโโโโโโโโโโโโโโ
godMode: z.boolean().default(false).describe('โ ๏ธ WARNING: Enables every tool category. Use with caution.'),
// โโ ๐ DOCUMENT RAG / CHAT WITH FILES โโโโโโโโโโโโโโโโโโโโโโโโโโโ
documentRAG: z.boolean().default(true).describe('Enable file indexing and semantic search for chat'),
retrievalLimit: z.number().min(1).max(20).default(5).describe('Maximum number of relevant chunks to retrieve'),
retrievalAffinityThreshold: z.number().min(0.0).max(1.0).default(0.5).describe('Minimum similarity score for a chunk to be considered relevant (0-1)'),
// Execution tools โ individual toggles (granular control)
executionJavaScript: z.boolean().default(true).describe('Allow run_javascript tool'),
executionPython: z.boolean().default(true).describe('Allow run_python tool'),
executionTerminal: z.boolean().default(false).describe('Allow run_in_terminal tool'),
executionShell: z.boolean().default(false).describe('Allow execute_command tool'),
executionTests: z.boolean().default(false).describe('โ ๏ธ Allow run_tests tool. Disabled by default for security.'),
// โโ Web Search Settings โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
searchFallbackChain: z.enum(['ddg-api', 'ddg-fetch', 'google', 'bing']).default('ddg-api').describe('Primary search engine (auto-fallback to others)'),
maxSearchResults: z.number().min(1).max(50).default(10),
safesearch: z.enum(['0', '1', '2']).default('1'),
// โโ Browser Settings โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
browserTimeout: z.number().min(1000).max(30000).default(5000),
headlessMode: z.boolean().default(false).describe('Run browser without GUI'),
// Git Settings
gitAutoCommit: z.boolean().default(false),
defaultBranch: z.string().default('main'),
// Security Settings
pathValidationEnabled: z.boolean().default(true),
binaryFileDetection: z.boolean().default(true),
regexReDoSProtection: z.boolean().default(true),
maxRegexLength: z.number().min(1).max(1000).default(500),
// State Management
statePersistenceEnabled: z.boolean().default(true),
// ๐น SPEC-C (20.09, memory-store incident): default raised 51200 โ 262144 (256 KiB) โ the old value left ~3.5 KB headroom after a normal session and one more write poisoned the store permanently.
stateMaxSize: z.number().min(1024).max(1048576).default(262144),
// i18n Settings
// ๐ UNIFIED LANGUAGE v2 (step 5, 27.10): 'auto' = follow the chain โ LM Studio host language โ OS locale first tag โ English.
// Per-turn prompt texts resolve fresh each turn in promptPreprocessor.resolveTurnLanguage() ('auto' falls through by
// construction โ it is not a shipped locale code); panel labels are baked ONCE per boot from the same chain (src/uiLabelBake.ts).
language: z.enum(['auto', 'en', 'de', 'es', 'zh-CN', 'zh-TW']).default('auto').describe("'auto' follows the LM Studio host language, then your OS locale, and falls back to English. Pick a concrete language to pin both prompt texts and panel labels."),
// Notification Settings
notificationsEnabled: z.boolean().default(true),
// ๐ฆ PLUGIN UPDATE CHECK (19.10; source switched to the published hub .VERSION file per owner GO, see src/updateChecker.ts): quiet hub check โ notify only when a strictly-newer release exists
updateCheckEnabled: z.boolean().default(true).describe('Quietly check the LM Studio hub for newer plugin releases (published .VERSION file) and show an in-app notification or in-chat line when one is found'),
// Temporal Awareness (merged from up_to_date)
temporalAwareness: z.boolean().default(true).describe('Enable automatic date/time injection into prompts'),
dateFormatStyle: z.enum(['standard', 'heuteIst']).default('standard').describe('Date format style for temporal awareness'),
// โโ ๐ง CONTEXT GUARD SETTINGS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
contextGuardEnabled: z.boolean().default(true).describe('Enable ContextGuard token management and history compression'),
contextGuardCompressionPercent: z.number().min(50).max(100).default(90).describe('History compression triggers at this percentage of the effective context window (the active model\'s reported window; built-in 30k fallback when unavailable)'),
contextGuardAgenticDensity: z.number().min(1).max(20).default(3.6).describe('Chars-per-token density used to estimate token counts from character length for agentic content (prose + tool output mix; live-measured band ~3.2-3.4, see provenance in tokenStatsManager.ts)'),
// Budget-Guard-Arc (05.11, owner ruling 04.11): deterministic context-limit protection โ M1 pre-call cost gate on the
// read path (advisory_threshold_pct), M2 budget-aware spill (spill_threshold_pct; consistent with safety_margin: limitร(1โmargin)=limitร0.92),
// M3 auto-persist session memory at the 85% edge (autopause_threshold_pct). enabled=false โ byte-identical legacy
// behavior โ rollback without a code revert. Provenance: src/budgetGuard.ts + RESEARCH_budget-guard.md (freigegeben 04.11).
budgetGuard: z.object({
enabled: z.boolean().default(true).describe('Master switch for the Budget Guard (M1 pre-call gate, M2 spill cap, M3 auto-persist). Default true since 06.11 (owner order); set false to restore byte-identical legacy behavior.'),
advisory_threshold_pct: z.number().min(1).max(99).default(80).describe('M1: projected context usage above this % of the limit โ read tools return a self-describing advisory instead of the full payload (owner ruling 04.11).'),
spill_threshold_pct: z.number().min(1).max(99).default(92).describe('M2: tool results are spilled to disk beyond this % of the limit (budget-relative cap; the stricter of absolute vs budget wins) (owner ruling 04.11).'),
autopause_threshold_pct: z.number().min(1).max(99).default(85).describe('M3: automatic session-memory persist at this % edge, max once per session, marker auto_saved=true (owner ruling 04.11).'),
safety_margin_pct: z.number().min(0).max(50).default(8).describe('M2: reserve kept out of the context limit for M2 budget math โ limitร(1โmargin/100); default 8 โ spill at 92%, consistent with spill_threshold_pct.'),
}).default({ enabled: true, advisory_threshold_pct: 80, spill_threshold_pct: 92, autopause_threshold_pct: 85, safety_margin_pct: 8 }), // Budget-Guard-Arc (05.11 Triage): object-level .default() โ a LEGACY saved config omits the block entirely; child defaults alone do not make an ABSENT key optional (zod required-object โ ConfigSchema.parse({}) ZodError path:['budgetGuard'], broke config.test.ts + ulv2BytePin.test.ts on the 05.11 full run). enabled flipped falseโtrue 06.11 per owner order (default ON; legacy behavior only when explicitly OFF)
// Budget-Guard-Arc (05.11) flat host-facing keys: getGlobalPluginConfig().get() is typed over FLAT scalar schematics field
// names only โ the nested budgetGuard block above is assembled from these five in toolsProvider.ts (house pattern, cf. L241).
// No UI label objects are attached: plain literals keep the change out of the UiLabels/locale surface entirely.
budgetGuardEnabled: z.boolean().default(true), // flipped falseโtrue 06.11 per owner order (master switch ON by default; explicit OFF = byte-identical legacy)
budgetGuardAdvisoryThresholdPct: z.number().min(1).max(99).default(80),
budgetGuardSpillThresholdPct: z.number().min(1).max(99).default(92),
budgetGuardAutopauseThresholdPct: z.number().min(1).max(99).default(85),
budgetGuardSafetyMarginPct: z.number().min(0).max(50).default(8),
contextGuardForceSummaryOnCompress: z.boolean().default(true).describe('Forced cross-session continuity save (07.10 arc C): when compression triggers, a structured session summary is generated via the Summary Model and persisted BEFORE history is compressed'),
contextGuardSmartReading: z.boolean().default(true).describe('Enable keyword-based smart file reading'),
contextGuardSummaryModel: z.string().default('').describe('LM Studio model name for summarization (leave empty to use current chat model)'),
contextGuardTerminalFilterEnabled: z.boolean().default(true).describe('Enable terminal output filtering'),
contextGuardTerminalFilterLength: z.number().min(100).max(20000).default(2000).describe('Max chars before terminal output is filtered'),
// โโ C COMPACTION FAMILY (24.09): pre-summarization pruning of oversized tool payloads โโ
compactionEnabled: z.boolean().default(true).describe('Prune oversized tool payloads BEFORE history summarization; verbatim copies are stored in .ai_toolbox/compaction/'),
compactionMaxResultBytes: z.number().min(1024).max(1048576).default(16384).describe('Byte budget per tool-result payload before pre-summarization pruning (default 16 KiB)'),
contextUsageFooter: z.boolean().default(true).describe('LLM-side limit awareness: surface a compact context-usage footer on tool results once projected chat usage crosses half the window โ appended to string results and added as an additive ctx_footer field on plain-object results (format A, near-limit advisory at >=90%)'),
// โโ ๐ค AUTO-TRACKING SETTINGS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
autoTrackingEnabled: z.boolean().default(true).describe('Automatically tracks decisions, completions, and bug fixes in the background.'),
autoTrackTokenThreshold: z.number().min(10).max(100).default(75).describe('Trigger session memory save when token usage reaches this percentage (default: 75%)'),
autoTrackDecisions: z.boolean().default(true).describe('Auto-track decisions and conclusions ("I decided", "conclusion")'),
autoTrackCompletions: z.boolean().default(true).describe('Auto-track task completions ("successfully completed", "finished")'),
autoTrackErrors: z.boolean().default(true).describe('Auto-track bug fixes and error resolutions ("fixed the bug")'),
autoSummaryInterval: z.number().min(10).max(200).default(50).describe('Messages between automatic session summaries'),
});
export type PluginConfig = z.infer<typeof ConfigSchema>;
/**
* Default configuration object
*/
export const DEFAULT_CONFIG: PluginConfig = {
fileSystem: true,
webSearch: true,
browserAutomation: false,
gitOperations: false,
packageManage: false,
databaseQueries: false,
documentParsing: true,
backgroundCommands: false,
imageProcessing: true,
httpClient: false,
textProcessing: true,
refactorCode: true,
utility: true,
uiGeneration: true,
contextManagement: true,
vectorRAG: true,
godMode: false,
documentRAG: true,
retrievalLimit: 5,
retrievalAffinityThreshold: 0.5,
executionJavaScript: true,
executionPython: true,
executionTerminal: false,
executionShell: false,
executionTests: false,
searchFallbackChain: 'ddg-api',
maxSearchResults: 10,
safesearch: '1',
browserTimeout: 5000,
headlessMode: false,
gitAutoCommit: false,
defaultBranch: 'main',
pathValidationEnabled: true,
binaryFileDetection: true,
regexReDoSProtection: true,
maxRegexLength: 500,
statePersistenceEnabled: true,
// ๐น SPEC-C (20.09): matches the zod default above โ 262144 (was 51200). See spec C / memory-store incident.
stateMaxSize: 262144,
// ๐ UL-v2 step-5 (27.10): default raised 'en' โ 'auto' โ follows the host app / OS locale chain; concrete picks persist to .ai_toolbox_state.json (see uiLabelBake.ts)
language: 'auto',
notificationsEnabled: true,
// ๐ฆ 19.10 plugin update check (src/updateChecker.ts; hub .VERSION source per owner GO): quiet hub check + in-app/in-chat notify โ matches the zod default above
updateCheckEnabled: true,
temporalAwareness: true,
dateFormatStyle: 'standard',
contextGuardEnabled: true,
contextGuardCompressionPercent: 90, // ๐ ContextGuard: compression trigger as % of effective context window (replaces absolute contextGuardTokenLimit, 07.10)
contextGuardAgenticDensity: 3.6, // ๐ข agentic chars-per-token density (user-editable menu field, 15.10) โ default raised 3.4โ3.6 on 15.10 owner instruction (ABOVE the live-measured band ~3.2-3.4; not probe-justified); provenance in tokenStatsManager.ts
budgetGuardEnabled: true, // Budget-Guard-Arc (05.11) master switch โ flipped OFFโON by owner order 06.11; explicit false restores byte-identical legacy behavior
budgetGuard: { // nested consumer-facing block (assembled from the flat keys in toolsProvider.ts); both sets are part of PluginConfig
enabled: true, advisory_threshold_pct: 80, spill_threshold_pct: 92, autopause_threshold_pct: 85, safety_margin_pct: 8,
},
budgetGuardAdvisoryThresholdPct: 80, // M1 pre-call cost gate edge on the read path (owner ruling 04.11)
budgetGuardSpillThresholdPct: 92, // M2 budget-aware spill edge โ stricter of absolute vs budget wins
budgetGuardAutopauseThresholdPct: 85, // M3 auto-persist session-memory edge, max once per session
budgetGuardSafetyMarginPct: 8, // M2 reserve โ limitร(1โmargin)=limitร0.92 โ consistent with spill threshold (default 8 โ budget = limit ร 0.92)
contextGuardForceSummaryOnCompress: true, // ๐พ Arc C (07.10): forced structured session-memory save at the compression trigger โ generated before history destruction; telemetry checkpoint remains the fallback on any failure
contextGuardSmartReading: true,
contextGuardSummaryModel: '',
contextGuardTerminalFilterEnabled: true,
contextGuardTerminalFilterLength: 2000,
compactionEnabled: true,
compactionMaxResultBytes: 16384,
// LLM-side limit awareness (02.10; widened 03.10 per option B): context-usage footer โ appended to string
// tool results AND added as an additive ctx_footer field on plain-object results, gated at 50% usage
contextUsageFooter: true,
autoTrackingEnabled: true,
autoTrackTokenThreshold: 75,
autoTrackDecisions: true,
autoTrackCompletions: true,
autoTrackErrors: true,
autoSummaryInterval: 50,
taskPlanning: true,
clusterAwareToolOrder: true,
};
/**
* Check if ANY execution tool is enabled (legacy compatibility)
*/
export function hasAnyExecutionTool(config: PluginConfig): boolean {
return config.executionJavaScript || config.executionPython ||
config.executionTerminal || config.executionShell || config.executionTests;
}
// ==================== LM Studio UI Schematics ====================
// These define the toggle switches that appear in LM Studio's settings panel.
/**
* UNIFIED LANGUAGE v2 (step 5, 27.10): settings-panel schematics builder. When a locale's UiLabels bundle is
* passed, every panel label (displayName/subtitle/hint + localized select options) comes from it; without one the
* English literals below are used โ byte-identical to the pre-v2 panel text. Field KEYS, types and default values
* never change between builds: only human-readable strings do. The 'language' row gains the step-5 'auto' option.
* searchFallbackChain options stay English by design (brand/engine names โ see types.ts UiLabels docblock).
*/
export function buildConfigSchematics(ui?: UiLabels) {
return createConfigSchematics()
// ๐ LANGUAGE (top of menu by design)
.field('language', 'select', {
displayName: ui?.languageRow.displayName ?? '๐ Language',
options: [ { value: 'auto', displayName: ui?.languageRow.options.auto ?? 'Automatic (follows LM Studio)' },
{ value: 'en', displayName: ui?.languageRow.options.en ?? 'English' },
{ value: 'de', displayName: ui?.languageRow.options.de ?? 'Deutsch (German)' },
{ value: 'es', displayName: ui?.languageRow.options.es ?? 'Espaรฑol' },
{ value: 'zh-CN', displayName: ui?.languageRow.options.zhCN ?? 'Simplified Chinese' },
{ value: 'zh-TW', displayName: ui?.languageRow.options.zhTW ?? 'Traditional Chinese' },
],
}, DEFAULT_CONFIG.language)
// โ ๏ธ GOD MODE - TOP PRIORITY WARNING TOGGLE โ ๏ธ
.field('godMode', 'boolean', {
displayName: ui?.godMode.displayName ?? 'โกโ ๏ธ GOD MODE - Enable ALL Tools โ ๏ธโก',
subtitle: ui?.godMode.subtitle ?? 'WARNING: Activates every tool category instantly. Use with caution.',
hint: ui?.godMode.hint ?? 'When enabled, ALL individual toggles are bypassed and every tool is activated regardless of settings.',
}, DEFAULT_CONFIG.godMode)
// ๐๏ธ TOOL CATEGORIES (Hauptschalter) ๐๏ธ
.field('fileSystem', 'boolean', { displayName: ui?.fileSystem.displayName ?? '๐ File System Tools', hint: ui?.fileSystem.hint ?? 'Enable file read/write/search operations' }, DEFAULT_CONFIG.fileSystem)
.field('webSearch', 'boolean', { displayName: ui?.webSearch.displayName ?? '๐ Web & Research Tools', hint: ui?.webSearch.hint ?? 'Enable DuckDuckGo/Wikipedia search' }, DEFAULT_CONFIG.webSearch)
// ๐ GIT & GITHUB TOOLS (visuelle Gruppierung) ๐
.field('packageManage', 'boolean', {
displayName: ui?.packageManage.displayName ?? 'Package Management Tools',
subtitle: ui?.packageManage.subtitle ?? 'npm/pip/cargo operations',
hint: ui?.packageManage.hint ?? 'Enable package manager tools. Disabled by default for security.',
}, DEFAULT_CONFIG.packageManage)
.field('gitOperations', 'boolean', {
displayName: ui?.gitOperations.displayName ?? '๐ Git & GitHub Tools',
subtitle: ui?.gitOperations.subtitle ?? 'Version Control & API',
hint: ui?.gitOperations.hint ?? 'Enable git operations and GitHub API access.',
}, DEFAULT_CONFIG.gitOperations)
.field('gitAutoCommit', 'boolean', {
displayName: ui?.gitAutoCommit.displayName ?? '๐พ Git Auto-Commit',
subtitle: ui?.gitAutoCommit.subtitle ?? 'โ๏ธ Part of Git & GitHub Tools',
hint: ui?.gitAutoCommit.hint ?? 'Automatically commit changes after operations',
}, DEFAULT_CONFIG.gitAutoCommit)
.field('defaultBranch', 'string', {
displayName: ui?.defaultBranch.displayName ?? '๐ฟ Default Branch',
placeholder: 'main',
subtitle: ui?.defaultBranch.subtitle ?? 'โ๏ธ Part of Git & GitHub Tools',
hint: ui?.defaultBranch.hint ?? 'Branch name for new repositories and git operations',
}, DEFAULT_CONFIG.defaultBranch)
.field('databaseQueries', 'boolean', { displayName: ui?.databaseQueries.displayName ?? '๐๏ธ Database Queries', hint: ui?.databaseQueries.hint ?? 'Enable read-only SQLite queries' }, DEFAULT_CONFIG.databaseQueries)
.field('documentParsing', 'boolean', { displayName: ui?.documentParsing.displayName ?? '๐ Document Parsing', hint: ui?.documentParsing.hint ?? 'Enable PDF/DOCX document reading' }, DEFAULT_CONFIG.documentParsing)
.field('backgroundCommands', 'boolean', { displayName: ui?.backgroundCommands.displayName ?? 'โณ Background Commands', hint: ui?.backgroundCommands.hint ?? 'Enable long-running process tracking' }, DEFAULT_CONFIG.backgroundCommands)
// ๐โโ NEW TOOL CATEGORIES ๐โโ
.field('imageProcessing', 'boolean', {
displayName: ui?.imageProcessing.displayName ?? '๐ผ๏ธ Image Processing Tools',
subtitle: ui?.imageProcessing.subtitle ?? 'OCR, Screenshots & Comparison',
hint: ui?.imageProcessing.hint ?? 'Enable image OCR (Tesseract.js), screenshot capture, and image comparison tools.',
}, DEFAULT_CONFIG.imageProcessing)
.field('httpClient', 'boolean', {
displayName: ui?.httpClient.displayName ?? '๐ HTTP Client Tools',
subtitle: ui?.httpClient.subtitle ?? 'Generic REST API Client',
hint: ui?.httpClient.hint ?? 'Enable generic HTTP client for making requests to any REST API (GET, POST, PUT, DELETE).',
}, DEFAULT_CONFIG.httpClient)
.field('vectorRAG', 'boolean', {
displayName: ui?.vectorRag.displayName ?? '๐ Vector RAG / Semantic Search',
subtitle: ui?.vectorRag.subtitle ?? 'Semantic Document Search',
hint: ui?.vectorRag.hint ?? 'Enable semantic search with vector embeddings for intelligent document retrieval.',
}, DEFAULT_CONFIG.vectorRAG)
.field('uiGeneration', 'boolean', {
displayName: ui?.uiGeneration.displayName ?? '๐จ Interactive UI Generation Tools',
subtitle: ui?.uiGeneration.subtitle ?? 'Generate and render interactive UI components',
hint: ui?.uiGeneration.hint ?? 'Enable tools for generating HTML/CSS/JS components (buttons, forms, charts, dashboards) and rendering them in the browser.',
}, DEFAULT_CONFIG.uiGeneration)
.field('contextManagement', 'boolean', {
displayName: ui?.contextManagement.displayName ?? '๐ง Auto-Context Management Tools',
subtitle: ui?.contextManagement.subtitle ?? 'Automatic session tracking and memory management',
hint: ui?.contextManagement.hint ?? 'Enable tools for automatically saving important decisions, patterns, and configurations to persistent memory.',
}, DEFAULT_CONFIG.contextManagement)
// ๐ DOCUMENT RAG / CHAT WITH FILES ๐
// ๐ DOCUMENT RAG / CHAT WITH FILES ๐
.field('documentRAG', 'boolean', {
displayName: ui?.documentRAG.displayName ?? '๐ Document RAG / Chat with Files',
subtitle: ui?.documentRAG.subtitle ?? 'Enable file indexing and semantic search for chat',
hint: ui?.documentRAG.hint ?? 'Attach documents to your chat messages. The plugin will automatically retrieve relevant content from attached files using semantic search.',
}, DEFAULT_CONFIG.documentRAG)
.field('textProcessing', 'boolean', {
displayName: ui?.textProcessing.displayName ?? '๐ Text Processing Tools (sed/awk equivalents)',
subtitle: ui?.textProcessing.subtitle ?? 'Regex-based text transformations and field extraction',
hint: ui?.textProcessing.hint ?? 'Enable tools for bulk text replacement, pattern matching, and structured data extraction without shell dependencies.',
}, DEFAULT_CONFIG.textProcessing)
.field('refactorCode', 'boolean', {
displayName: ui?.refactorCode.displayName ?? '๐ง AST Code Refactoring Tools',
subtitle: ui?.refactorCode.subtitle ?? 'Rename, move, extract functions & clean unused imports',
hint: ui?.refactorCode.hint ?? 'Enable AST-based code refactoring tools (rename_identifier, move_function, extract_function, unused_import_cleanup).',
}, DEFAULT_CONFIG.refactorCode)
.field('utility', 'boolean', {
displayName: ui?.utility.displayName ?? '๐ ๏ธ Utility & Maintenance Tools',
subtitle: ui?.utility.subtitle ?? 'Backup, chart generation, markdown preview, line operations',
hint: ui?.utility.hint ?? 'Enable utility tools (create_backup, list_backups, restore_backup, delete_backup, cleanup_backups, generate_chart, markdown_preview).',
}, DEFAULT_CONFIG.utility)
// โโ ๐ TASK PLANNING TOOLS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.field('taskPlanning', 'boolean', {
displayName: ui?.taskPlanning.displayName ?? '๐ Task Planning Tools',
subtitle: ui?.taskPlanning.subtitle ?? 'Structured multi-step workflow tools',
hint: ui?.taskPlanning.hint ?? 'Enable create_plan, update_plan_step, and get_plan tools for structured task execution.',
}, DEFAULT_CONFIG.taskPlanning)
// โโ ๐งญ CLUSTER-AWARE TOOL ORDERING (18.09) โโโโโโโโโโโโโโโโโโโโโโโ
.field('clusterAwareToolOrder', 'boolean', {
displayName: ui?.clusterAwareToolOrder.displayName ?? '๐งญ Cluster-Aware Tool Ordering',
subtitle: ui?.clusterAwareToolOrder.subtitle ?? 'Sort exposed tools by priority tier + module centrality instead of alphabetically.',
hint: ui?.clusterAwareToolOrder.hint ?? 'Uses the static ARCHITECTURE.md dependency graph (no fs I/O). Disable to restore legacy alphabetical order.',
}, DEFAULT_CONFIG.clusterAwareToolOrder)
.field('retrievalLimit', 'numeric', {
displayName: ui?.retrievalLimit.displayName ?? '๐ข Retrieval Limit',
subtitle: ui?.retrievalLimit.subtitle ?? 'Max chunks to return per query',
min: 1, max: 20, int: true,
hint: ui?.retrievalLimit.hint ?? 'Maximum number of relevant document chunks to retrieve for each query.',
}, DEFAULT_CONFIG.retrievalLimit)
.field('retrievalAffinityThreshold', 'numeric', {
displayName: ui?.retrievalAffinityThreshold.displayName ?? '๐ฏ Retrieval Affinity Threshold',
subtitle: ui?.retrievalAffinityThreshold.subtitle ?? 'Minimum relevance score (0-1)',
min: 0.0, max: 1.0, step: 0.01,
hint: ui?.retrievalAffinityThreshold.hint ?? 'Chunks below this similarity score will be filtered out. Lower = more results but potentially less relevant.',
}, DEFAULT_CONFIG.retrievalAffinityThreshold)
// โก EXECUTION TOOLS (Gefรคhrlich!) โก
.field('executionJavaScript', 'boolean', {
displayName: ui?.executionJavaScript.displayName ?? 'โก Allow JavaScript Execution',
subtitle: ui?.executionJavaScript.subtitle ?? "Enables the 'run_javascript' tool",
hint: ui?.executionJavaScript.hint ?? 'WARNING: code runs on your machine.',
}, DEFAULT_CONFIG.executionJavaScript)
.field('executionPython', 'boolean', {
displayName: ui?.executionPython.displayName ?? '๐ Allow Python Execution',
subtitle: ui?.executionPython.subtitle ?? "Enables the 'run_python' tool",
hint: ui?.executionPython.hint ?? 'WARNING: code runs on your machine.',
}, DEFAULT_CONFIG.executionPython)
.field('executionTerminal', 'boolean', {
displayName: ui?.executionTerminal.displayName ?? '๐ป Allow Terminal Execution',
subtitle: ui?.executionTerminal.subtitle ?? "Enables the 'run_in_terminal' tool",
hint: ui?.executionTerminal.hint ?? 'Opens real terminal windows.',
}, DEFAULT_CONFIG.executionTerminal)
.field('executionShell', 'boolean', {
displayName: ui?.executionShell.displayName ?? '๐ง Allow Shell Command Execution',
subtitle: ui?.executionShell.subtitle ?? "Enables the 'execute_command' tool",
hint: ui?.executionShell.hint ?? 'WARNING: commands run on your machine.',
}, DEFAULT_CONFIG.executionShell)
.field('executionTests', 'boolean', {
displayName: ui?.executionTests.displayName ?? '๐งช Allow Test Execution',
subtitle: ui?.executionTests.subtitle ?? "Enables the 'run_tests' tool",
hint: ui?.executionTests.hint ?? 'WARNING: runs npm jest / pytest / go test โ can install packages and execute code.',
}, DEFAULT_CONFIG.executionTests)
// ๐ SEARCH SETTINGS ๐
.field('searchFallbackChain', 'select', {
displayName: ui?.searchFallbackChain.displayName ?? '๐ Search Fallback Chain',
hint: ui?.searchFallbackChain.hint ?? 'Primary search engine. Auto-falls back to others if unavailable.',
options: [
{ value: 'ddg-api', displayName: 'DuckDuckGo API' },
{ value: 'ddg-fetch', displayName: 'DuckDuckGo Fetch' },
{ value: 'google', displayName: 'Google' },
{ value: 'bing', displayName: 'Bing' },
],
}, DEFAULT_CONFIG.searchFallbackChain)
.field('maxSearchResults', 'numeric', { min: 1, max: 50, int: true }, DEFAULT_CONFIG.maxSearchResults)
.field('safesearch', 'select', {
displayName: ui?.safesearch.displayName ?? '๐ก๏ธ Safe Search',
options: [ { value: '0', displayName: ui?.safesearch.options.off ?? 'Off' },
{ value: '1', displayName: ui?.safesearch.options.moderate ?? 'Moderate' },
{ value: '2', displayName: ui?.safesearch.options.strict ?? 'Strict' },
],
}, DEFAULT_CONFIG.safesearch)
// ๐ฅ๏ธ BROWSER AUTOMATION TOOLS ๐ฅ๏ธ
.field('browserAutomation', 'boolean', {
displayName: ui?.browserAutomation.displayName ?? '๐ฅ๏ธ Browser Automation Tools',
subtitle: ui?.browserAutomation.subtitle ?? 'Headless browser control & automation',
hint: ui?.browserAutomation.hint ?? 'Enable Puppeteer-based headless browser automation for web scraping, testing, and UI interaction.',
}, DEFAULT_CONFIG.browserAutomation)
.field('browserTimeout', 'numeric', {
displayName: ui?.browserTimeout.displayName ?? 'โฑ๏ธ Browser Timeout',
subtitle: ui?.browserTimeout.subtitle ?? 'โ๏ธ Part of Browser Automation Tools',
min: 1000, max: 30000, int: true,
hint: ui?.browserTimeout.hint ?? 'Maximum time (ms) to wait for browser operations before timing out.',
}, DEFAULT_CONFIG.browserTimeout)
.field('headlessMode', 'boolean', {
displayName: ui?.headlessMode.displayName ?? '๐ป Headless Mode',
subtitle: ui?.headlessMode.subtitle ?? 'โ๏ธ Part of Browser Automation Tools',
hint: ui?.headlessMode.hint ?? 'Run browser without GUI (recommended for automation).',
}, DEFAULT_CONFIG.headlessMode)
// ๐ SECURITY SETTINGS ๐
.field('pathValidationEnabled', 'boolean', { displayName: ui?.pathValidationEnabled.displayName ?? '๐ Path Validation', hint: ui?.pathValidationEnabled.hint ?? 'Prevent directory traversal attacks' }, DEFAULT_CONFIG.pathValidationEnabled)
.field('binaryFileDetection', 'boolean', { displayName: ui?.binaryFileDetection.displayName ?? '๐ Binary File Detection', hint: ui?.binaryFileDetection.hint ?? 'Detect binary files via null byte check' }, DEFAULT_CONFIG.binaryFileDetection)
.field('regexReDoSProtection', 'boolean', { displayName: ui?.regexReDoSProtection.displayName ?? '๐ก๏ธ ReDoS Protection', hint: ui?.regexReDoSProtection.hint ?? 'Protect against regex denial-of-service' }, DEFAULT_CONFIG.regexReDoSProtection)
.field('maxRegexLength', 'numeric', { min: 1, max: 1000, int: true }, DEFAULT_CONFIG.maxRegexLength)
// ๐ฝ STATE MANAGEMENT ๐ฝ
.field('statePersistenceEnabled', 'boolean', { displayName: ui?.statePersistenceEnabled.displayName ?? '๐ฝ State Persistence', hint: ui?.statePersistenceEnabled.hint ?? 'Persist tool execution state between sessions' }, DEFAULT_CONFIG.statePersistenceEnabled)
.field('stateMaxSize', 'numeric', { min: 1024, max: 1048576, int: true }, DEFAULT_CONFIG.stateMaxSize)
.field('notificationsEnabled', 'boolean', { displayName: ui?.notificationsEnabled.displayName ?? '๐ Desktop Notifications', hint: ui?.notificationsEnabled.hint ?? 'Show system notifications' }, DEFAULT_CONFIG.notificationsEnabled)
// โโ ๐ฆ PLUGIN UPDATE CHECK (19.10) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.field('updateCheckEnabled', 'boolean', {
displayName: ui?.updateCheckEnabled.displayName ?? '๐ Plugin Update Check',
subtitle: ui?.updateCheckEnabled.subtitle ?? 'Quiet LM Studio hub .VERSION check โ no new tools, no OS permissions',
hint: ui?.updateCheckEnabled.hint ?? "Once per day the plugin quietly checks the published LM Studio hub .VERSION file for a strictly-newer release. If one exists it notifies via desktop toast (Desktop Notifications ON) or a single in-chat line (OFF). Silent when you are up to date or on a dismissed version; state survives reinstalls.",
}, DEFAULT_CONFIG.updateCheckEnabled)
// โฐ TEMPORAL AWARENESS (from up_to_date)
.field('temporalAwareness', 'boolean', {
displayName: ui?.temporalAwareness.displayName ?? 'โฐ Temporal Awareness',
subtitle: ui?.temporalAwareness.subtitle ?? 'Injects current date/time into every message',
hint: ui?.temporalAwareness.hint ?? 'Enables the AI to know the current time.',
}, DEFAULT_CONFIG.temporalAwareness)
.field('dateFormatStyle', 'select', {
displayName: ui?.dateFormatStyle.displayName ?? '๐
Date Format Style',
options: [ { value: 'standard', displayName: ui?.dateFormatStyle.options.standard ?? 'Standard ([Zeit: ...])' },
{ value: 'heuteIst', displayName: ui?.dateFormatStyle.options.heuteIst ?? 'HEUTE IST Mode (Prominent)' },
],
}, DEFAULT_CONFIG.dateFormatStyle)
// โโ ๐ง CONTEXT GUARD SETTINGS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.field('contextGuardEnabled', 'boolean', {
displayName: ui?.contextGuardEnabled.displayName ?? '๐ง ContextGuard Token Management',
subtitle: ui?.contextGuardEnabled.subtitle ?? 'Automatic history compression & smart reading',
hint: ui?.contextGuardEnabled.hint ?? 'Automatically compresses chat history when token limit is reached. Enables smart file reading and terminal output filtering.',
}, DEFAULT_CONFIG.contextGuardEnabled)
.field('contextGuardCompressionPercent', 'numeric', {
displayName: ui?.contextGuardCompressionPercent.displayName ?? '๐ Compression Trigger (% of Context Window)',
subtitle: ui?.contextGuardCompressionPercent.subtitle ?? 'โ๏ธ ContextGuard Setting',
min: 50, max: 100, int: true,
hint: ui?.contextGuardCompressionPercent.hint ?? 'History compression triggers when context usage reaches this percentage of the active model\'s context window. If LM Studio reports the model\'s real window it is used; otherwise a built-in 30k fallback applies.',
}, DEFAULT_CONFIG.contextGuardCompressionPercent)
// ๐ข Agentic chars-per-token density (15.10 owner request "make it user editable"): reseeded per turn into the
// tokenStatsManager live state by promptPreprocessor.preprocess(); changing it here NEVER requires a test edit.
.field('contextGuardAgenticDensity', 'numeric', {
displayName: ui?.contextGuardAgenticDensity.displayName ?? '๐ข Agentic Chars-per-Token Density',
subtitle: ui?.contextGuardAgenticDensity.subtitle ?? 'โ๏ธ ContextGuard Setting',
min: 1, max: 20, step: 0.1,
hint: ui?.contextGuardAgenticDensity.hint ?? 'Chars per token used to estimate tokens from character length (agentic mix of prose + tool output; live-measured band ~3.2-3.4 โ default 3.6 is owner-set above that band). Higher = denser content = fewer estimated tokens; lower estimates more and triggers compaction earlier.',
}, DEFAULT_CONFIG.contextGuardAgenticDensity)
// ๐พ Arc C (07.10): forced structured session-memory save at the compression trigger โ generated + persisted BEFORE history destruction (see persistGeneratedSessionSummary); non-fatal by design, the telemetry checkpoint stays as fallback.
.field('contextGuardForceSummaryOnCompress', 'boolean', {
displayName: ui?.contextGuardForceSummaryOnCompress.displayName ?? '๐พ Force Session-Memory Save Before Compression',
subtitle: ui?.contextGuardForceSummaryOnCompress.subtitle ?? 'โ๏ธ ContextGuard Setting',
hint: ui?.contextGuardForceSummaryOnCompress.hint ?? "When context reaches your Compression Trigger, a structured session summary (task description, accomplishments, pending tasks) is generated with the Summary Model and persisted BEFORE history is compressed. Non-fatal: on any failure the previous telemetry checkpoint still runs.",
}, DEFAULT_CONFIG.contextGuardForceSummaryOnCompress)
.field('contextGuardSmartReading', 'boolean', {
displayName: ui?.contextGuardSmartReading.displayName ?? '๐ Smart File Reading',
subtitle: ui?.contextGuardSmartReading.subtitle ?? 'โ๏ธ ContextGuard Setting',
hint: ui?.contextGuardSmartReading.hint ?? 'Extracts keywords from user queries to read only relevant portions of files. Saves tokens and speeds up responses.',
}, DEFAULT_CONFIG.contextGuardSmartReading)
.field('contextGuardSummaryModel', 'string', {
displayName: ui?.contextGuardSummaryModel.displayName ?? '๐ค Summary Model Name',
subtitle: ui?.contextGuardSummaryModel.subtitle ?? 'โ๏ธ ContextGuard Setting',
placeholder: '(leave empty for current chat model)',
hint: ui?.contextGuardSummaryModel.hint ?? 'LM Studio model name used for history summarization. Leave empty to use your current chat model.',
}, DEFAULT_CONFIG.contextGuardSummaryModel)
.field('contextGuardTerminalFilterEnabled', 'boolean', {
displayName: ui?.contextGuardTerminalFilterEnabled.displayName ?? '๐ Terminal Output Filtering',
subtitle: ui?.contextGuardTerminalFilterEnabled.subtitle ?? 'โ๏ธ ContextGuard Setting',
hint: ui?.contextGuardTerminalFilterEnabled.hint ?? 'Automatically truncates long terminal outputs to save tokens.',
}, DEFAULT_CONFIG.contextGuardTerminalFilterEnabled)
.field('contextGuardTerminalFilterLength', 'numeric', {
displayName: ui?.contextGuardTerminalFilterLength.displayName ?? '๐ Max Terminal Output Length',
subtitle: ui?.contextGuardTerminalFilterLength.subtitle ?? 'โ๏ธ ContextGuard Setting',
min: 100, max: 20000, int: true,
hint: ui?.contextGuardTerminalFilterLength.hint ?? 'Maximum characters before terminal output is truncated and summarized.',
}, DEFAULT_CONFIG.contextGuardTerminalFilterLength)
// โโ C COMPACTION FAMILY (24.09): pre-summarization pruning of oversized tool payloads โโ
.field('compactionEnabled', 'boolean', {
displayName: ui?.compactionEnabled.displayName ?? 'โ๏ธ Compaction Pre-Summarization Pruning',
subtitle: ui?.compactionEnabled.subtitle ?? 'โ๏ธ C Compaction Family',
hint: ui?.compactionEnabled.hint ?? 'Before history is summarized, tool payloads above the byte budget are replaced by a head/tail preview plus an opaque locator; the full result stays stored verbatim in .ai_toolbox/compaction/.',
}, DEFAULT_CONFIG.compactionEnabled)
.field('compactionMaxResultBytes', 'numeric', {
displayName: ui?.compactionMaxResultBytes.displayName ?? '๐ Max Tool Result Before Pruning (bytes)',
subtitle: ui?.compactionMaxResultBytes.subtitle ?? 'โ๏ธ C Compaction Family',
min: 1024, max: 1048576, int: true,
hint: ui?.compactionMaxResultBytes.hint ?? 'Byte budget per tool-result payload in chat history. Results above this are pruned to preview + locator before summarization (verbatim copy stored on disk).',
}, DEFAULT_CONFIG.compactionMaxResultBytes)
// โโ LLM-SIDE LIMIT AWARENESS (02.10; widened 03.10 per option B): context-usage footer on ALL tool results โโ
.field('contextUsageFooter', 'boolean', {
displayName: ui?.contextUsageFooter.displayName ?? '๐ Context Usage Footer in Tool Results',
subtitle: ui?.contextUsageFooter.subtitle ?? 'โ๏ธ LLM-side Limit Awareness',
hint: ui?.contextUsageFooter.hint ?? "Once projected context usage crosses half of the model's window, every tool result gains a short footer like [ctx ~48.3k/64k = 76%] โ appended to string results and added as an additive ctx_footer field on plain-object results (every registered tool returns one) โ so the model always sees current token usage. At >=90% a near-limit advisory is added.",
}, DEFAULT_CONFIG.contextUsageFooter)
// โโ ๐ค AUTO-TRACKING SETTINGS โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.field('autoTrackingEnabled', 'boolean', {
displayName: ui?.autoTrackingEnabled.displayName ?? '๐ค Auto-Tracking Enabled',
subtitle: ui?.autoTrackingEnabled.subtitle ?? 'Automatically remember important events',
hint: ui?.autoTrackingEnabled.hint ?? 'Silently tracks decisions, completions, and bug fixes in the background. Enabled by default.',
}, DEFAULT_CONFIG.autoTrackingEnabled)
.field('autoTrackTokenThreshold', 'numeric', {
displayName: ui?.autoTrackTokenThreshold.displayName ?? 'Auto-Track Token Threshold',
subtitle: ui?.autoTrackTokenThreshold.subtitle ?? 'Auto-Tracking Setting',
min: 10, max: 100, int: true,
hint: ui?.autoTrackTokenThreshold.hint ?? 'Trigger session memory save when token usage reaches this percentage (default: 75%). Helps prevent context overflow.',
}, DEFAULT_CONFIG.autoTrackTokenThreshold)
.field('autoTrackDecisions', 'boolean', {
displayName: ui?.autoTrackDecisions.displayName ?? '๐ Track Decisions Automatically',
subtitle: ui?.autoTrackDecisions.subtitle ?? 'โ๏ธ Auto-Tracking Setting',
hint: ui?.autoTrackDecisions.hint ?? 'Detects phrases like "I decided", "conclusion", "going with".',
}, DEFAULT_CONFIG.autoTrackDecisions)
.field('autoTrackCompletions', 'boolean', {
displayName: ui?.autoTrackCompletions.displayName ?? 'โ
Track Completions Automatically',
subtitle: ui?.autoTrackCompletions.subtitle ?? 'โ๏ธ Auto-Tracking Setting',
hint: ui?.autoTrackCompletions.hint ?? 'Detects phrases like "successfully completed", "finished implementing".',
}, DEFAULT_CONFIG.autoTrackCompletions)
.field('autoTrackErrors', 'boolean', {
displayName: ui?.autoTrackErrors.displayName ?? '๐ Track Bug Fixes Automatically',
subtitle: ui?.autoTrackErrors.subtitle ?? 'โ๏ธ Auto-Tracking Setting',
hint: ui?.autoTrackErrors.hint ?? 'Detects phrases like "fixed the bug", "resolved the issue".',
}, DEFAULT_CONFIG.autoTrackErrors)
.field('autoSummaryInterval', 'numeric', {
displayName: ui?.autoSummaryInterval.displayName ?? '๐ Session Summary Interval',
subtitle: ui?.autoSummaryInterval.subtitle ?? 'โ๏ธ Auto-Tracking Setting',
min: 10, max: 200, int: true,
hint: ui?.autoSummaryInterval.hint ?? 'Number of messages between automatic session summaries. Higher = less frequent.',
}, DEFAULT_CONFIG.autoSummaryInterval)
// Budget-Guard-Arc (05.11): flat host-facing keys โ getGlobalPluginConfig().get() is typed over these field names;
// toolsProvider.ts assembles the nested budgetGuard block from them. i18n wired 06.11 per owner rule โalle Tool-Beschreibungen
// IMMER รผbersetztโ: ui?.โฆ ?? EN-literal (supersedes the original arc's deliberate 'no UiLabels/locale surface' decision).
.field('budgetGuardEnabled', 'boolean', { displayName: ui?.budgetGuardEnabled.displayName ?? '๐ก๏ธ Budget Guard (context-limit protection)', hint: ui?.budgetGuardEnabled.hint ?? 'Master switch for the deterministic context budget guard โ M1 pre-call read gate, M2 budget-aware spill cap, M3 auto-persist at 85% edge. ON by default (06.11); turn OFF to restore byte-identical legacy behavior.' }, DEFAULT_CONFIG.budgetGuardEnabled)
.field('budgetGuardAdvisoryThresholdPct', 'numeric', { displayName: ui?.budgetGuardAdvisoryThresholdPct.displayName ?? '๐ข Budget Guard Advisory Threshold (%)', subtitle: ui?.budgetGuardAdvisoryThresholdPct.subtitle ?? 'โ๏ธ Budget Guard Setting', hint: ui?.budgetGuardAdvisoryThresholdPct.hint ?? 'M1 pre-call read gate: above this % of the context limit, read tools return a self-describing budget advisory instead of the full payload.', min: 1, max: 99, int: true }, DEFAULT_CONFIG.budgetGuardAdvisoryThresholdPct)
.field('budgetGuardSpillThresholdPct', 'numeric', { displayName: ui?.budgetGuardSpillThresholdPct.displayName ?? 'โ๏ธ Budget Guard Spill Threshold (%)', subtitle: ui?.budgetGuardSpillThresholdPct.subtitle ?? 'โ๏ธ Budget Guard Setting', hint: ui?.budgetGuardSpillThresholdPct.hint ?? 'M2 spill cap: tool results are spilled to disk beyond this % of the limit (the stricter of absolute vs budget-relative bound wins).', min: 1, max: 99, int: true }, DEFAULT_CONFIG.budgetGuardSpillThresholdPct)
.field('budgetGuardAutopauseThresholdPct', 'numeric', { displayName: ui?.budgetGuardAutopauseThresholdPct.displayName ?? '๐พ Budget Guard Auto-Persist Edge (%)', subtitle: ui?.budgetGuardAutopauseThresholdPct.subtitle ?? 'โ๏ธ Budget Guard Setting', hint: ui?.budgetGuardAutopauseThresholdPct.hint ?? 'M3: automatic session-memory persist at this % edge, max once per session.', min: 1, max: 99, int: true }, DEFAULT_CONFIG.budgetGuardAutopauseThresholdPct)
.field('budgetGuardSafetyMarginPct', 'numeric', { displayName: ui?.budgetGuardSafetyMarginPct.displayName ?? '๐งฎ Budget Guard Safety Margin (%)', subtitle: ui?.budgetGuardSafetyMarginPct.subtitle ?? 'โ๏ธ Budget Guard Setting', hint: ui?.budgetGuardSafetyMarginPct.hint ?? 'Reserve kept out of the context limit for M2 budget math โ limit ร (1 โ margin/100); default 8 โ spill at 92 %.', min: 0, max: 50, int: true }, DEFAULT_CONFIG.budgetGuardSafetyMarginPct)
// โโ ๐ ๏ธ GRAMMAR PARSER LIMITS (P0 Fix) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
.build();
}
// ==================== Utility Functions ====================
/**
* Validates a config object against the schema.
* Returns the validated config if valid, throws on invalid input.
*/
export function validateConfig(config: Partial<PluginConfig>): PluginConfig {
const result = ConfigSchema.safeParse(config);
if (!result.success) {
throw new Error(
`Invalid configuration:\n${result.error.errors.map((e) => ` - ${e.path.join('.')}: ${e.message}`).join('\n')}`
);
}
return result.data;
}
/**
* Checks if a specific tool category is enabled in the config.
* @param config - The plugin configuration object
* @param category - The tool category to check (must be a key of PluginConfig)
* @returns true if the category is enabled, false otherwise
*/
export function isToolEnabled(config: PluginConfig, category: keyof PluginConfig): boolean {
const value = config[category];
return typeof value === 'boolean' && value === true;
}
/** Module-level English build โ consumed by promptPreprocessor.ts and the tests. Keys/types/defaults are identical across all locale builds; only label strings differ (see buildConfigSchematics above). */
export const configSchematics = buildConfigSchematics(); // EN literals (byte-identical to the pre-v2 panel text except the new auto option + default)