@goodandready/dsh-context-lens 0.1.25 → 0.1.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,15 @@ All notable changes to `@goodandready/dsh-context-lens` will be documented in th
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.1.26] - 2026-09-26
9
+
10
+ ### Changed
11
+ - **Narrowed to Semantic Compression (#96)**: Delegated context budgeting, token counting, tool result pruning, and long result spilling to DSH core (>= 0.1.5-rc.3). Removed lib/tokens/, session budget calculations, and token savings telemetry.
12
+ - **Consolidated Agent Tools (#96)**: Streamlined tool footprint to exactly two tools:
13
+ - context_lens_code: multi-language AST code skeletonization and session path focus management (ction: 'skeleton' | 'focus' | 'get_focus' | 'clear_focus').
14
+ - context_lens_log: intelligent test and build log condenser (preserving failures, stack traces, and test summary; collapses passing runs to concise summary; discriminates test/build logs from plain commands in auto mode).
15
+ - **Streamlined UI & Removed Dead Routes (#96)**: Removed duplicate sidebar tabs, conversation utilities header chip, self-updater, and obsolete HTTP endpoints (/status, /compress-preview, /clear-focus). Retained clean settings card in DSH Settings with client-side interactive preview.
16
+
8
17
  ## [0.1.25] - 2026-09-25
9
18
 
10
19
  ### Fixed
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  <div align="center">
4
4
 
5
- <h3>AST Code Skeletonizer, Terminal Log Condenser & Token Budget Guard for DeepSeek Harness</h3>
5
+ <h3>Semantic AST Code Skeletonizer & Test Log Condenser for DeepSeek Harness</h3>
6
6
 
7
7
  <p align="center">
8
8
  <a href="https://www.npmjs.com/package/@goodandready/dsh-context-lens"><img src="https://img.shields.io/npm/v/@goodandready/dsh-context-lens.svg?style=for-the-badge&color=6366f1&labelColor=1e1b4b" alt="npm version"></a>
@@ -36,143 +36,94 @@
36
36
 
37
37
  ---
38
38
 
39
- ## ⚡ Overview & The Problem
39
+ ## ⚡ Overview & Semantic Compression Focus
40
40
 
41
- Large codebase contexts and verbose build/test logs quickly fill the LLM context window, waste token budget, slow down inference, and cause agent hallucination.
42
-
43
- **`dsh-context-lens`** solves this by providing:
44
- 1. **Active Focus Scoping**: Keeping full fidelity for files currently being edited, while collapsing surrounding workspace files into lightweight AST skeletons.
45
- 2. **Multi-Language AST Skeletonization**: Extracting structural types, classes, and method signatures across TypeScript, JavaScript, Python, Go, C/C++, Rust, and SQL, cutting raw code size by **70–85%**.
46
- 3. **Intelligent Terminal Log Compression**: Stripping noisy passing test lines and build boilerplate while preserving critical error stack traces and failure windows, cutting log size by up to **90%**.
47
- 4. **Session Token Telemetry & Budget Guard**: Live tracking of token savings with configurable budget alerts and visual indicators in the DSH Web UI.
41
+ > **Note on DSH Core vs Plugin Responsibility:**
42
+ > Context budgeting, token counting, tool result pruning (`head/middle/tail`), and spilling long results to disk (`dsh-spill-policy`, `dsh-compaction-tool-result-pruner`, `dsh-token-meter`) are natively managed by the **DSH core (>= 0.1.5)**.
43
+ > **`dsh-context-lens`** focuses strictly on what the core does not do — **semantic compression**:
44
+ > 1. **AST Code Skeletons**: Signatures, interfaces, exported types, and doc comments instead of whole function/method bodies across 9+ languages.
45
+ > 2. **Path-Based Focus**: Full code for active editing targets while surrounding workspace files remain skeletonized.
46
+ > 3. **Test & Build Log Compression**: Failures, errors, stack traces, and test summary instead of raw multi-megabyte terminal streams.
48
47
 
49
48
  ```mermaid
50
49
  graph LR
51
50
  subgraph RawContext [Raw Context Streams]
52
- Code[📁 Source Code: Lengthy Implementation Details] --> LensEngine[dsh-context-lens Engine]
53
- Logs[📋 Build/Test Logs: Verbose Success Noise] --> LensEngine
51
+ Code[📁 Source Code: Lengthy File Bodies] --> Lens[dsh-context-lens Semantic Engine]
52
+ Logs[📋 Test/Build Output: Verbose Stream] --> Lens
54
53
  end
55
54
 
56
- subgraph LensEngine [Context Processing Pipeline]
57
- LensEngine --> Focus{Focus Evaluator}
58
- Focus -->|Focused File| RawKeep[Full Code Details Retained]
59
- Focus -->|Surrounding Workspace| AST[AST Skeletonizer: Signatures & Types]
60
- LensEngine --> LogFilter[Log Condenser: Stack Traces & Errors Only]
55
+ subgraph Lens [Semantic Processing]
56
+ Lens --> Focus{Path Focus Check}
57
+ Focus -->|File in Focus| FullCode[Retain Full Implementation]
58
+ Focus -->|Surrounding Files| AST[AST Skeletonizer: Signatures & Types]
59
+ Lens --> LogCompress[Log Condenser: Errors, Stack & Summary]
61
60
  end
62
61
 
63
- subgraph Output [Optimized Agent Context]
64
- AST --> Agent[🤖 DSH Agent Context: Compact High-Value Prompt]
65
- RawKeep --> Agent
66
- LogFilter --> Agent
67
- Agent --> Tracker[📊 Live Token Telemetry & Budget Guard]
62
+ subgraph Output [Optimized Context]
63
+ FullCode --> Agent[🤖 AI Agent Context]
64
+ AST --> Agent
65
+ LogCompress --> Agent
66
+ Agent --> Core[⚙️ DSH Core Pruner & Spill Policy]
68
67
  end
69
68
 
70
69
  style RawContext fill:#1e1e2e,stroke:#89b4fa,stroke-width:2px,color:#cdd6f4
71
- style LensEngine fill:#181825,stroke:#cba6f7,stroke-width:2px,color:#cdd6f4
70
+ style Lens fill:#181825,stroke:#cba6f7,stroke-width:2px,color:#cdd6f4
72
71
  style Output fill:#11111b,stroke:#a6e3a1,stroke-width:2px,color:#cdd6f4
73
72
  ```
74
73
 
75
74
  ---
76
75
 
77
- ## ✨ Full Feature Breakdown
76
+ ## ✨ Features
78
77
 
79
78
  ### 1. 🧬 Multi-Language AST Structural Skeletonizer
80
- * **Supported Languages**: TypeScript, JavaScript, Python, Go, C/C++, Rust, and SQL DDL.
79
+ * **Supported Languages**: TypeScript, JavaScript, Python, Go, C/C++, Rust, Java, and SQL DDL.
81
80
  * **Structural Preservation**: Retains imports, classes, structs, interfaces, exported types, function signatures, and doc comments while discarding inner implementation bodies.
82
81
  * **Multiline Signature Support**: Seamlessly accumulates complex multiline generic arguments, return types, and parameter lists up to block delimiters.
83
82
  * **Pure Regex Implementation**: Zero heavy native dependencies or binary parser overhead; runs lightning-fast across any platform.
84
83
 
85
- ### 2. 📋 Heuristic Test & Build Log Condenser
86
- * **Supported Test Runners & Tools**: Jest, Vitest, Pytest, Go test, Cargo, Webpack, Vite, TSC, Maven, Gradle.
84
+ ### 2. 📋 Intelligent Test & Build Log Condenser
85
+ * **Supported Test Runners & Tools**: Jest, Vitest, Pytest, `node --test`, Go test, Cargo, Webpack, Vite, TSC, Maven, Gradle.
87
86
  * **Targeted Extraction**: Identifies and preserves critical error messages, stack traces, assertion differences (`Expected ... Received ...`), and failure context windows.
87
+ * **Successful Run Summarization**: Automatically collapses passing runs (0 failures) into concise summary lines.
88
+ * **Auto-Mode Discrimination**: Evaluates command context and text signatures to ensure normal non-test outputs are preserved untouched for core pruning.
88
89
  * **3 Aggressiveness Modes**:
89
- - `raw`: Removes simple noise lines while keeping general execution order.
90
+ - `raw`: Removes noise lines while keeping general execution order.
90
91
  - `balanced`: Preserves failure sections with surrounding context windows (default).
91
92
  - `aggressive`: Extracts strictly error lines and stack frames.
92
- * **ANSI Stripping**: Cleans terminal escape codes and color formatting before processing.
93
-
94
- ### 3. 🎯 Active Path Focus Scoping (`context_lens_focus`)
95
- * Allows designating specific files or folders as active working targets for the current task.
96
- * Files inside focus remain uncompressed; non-focused dependencies are automatically served as structural skeletons.
97
- * Focus state is strictly scoped per session (`sessionId`) and can be inspected or cleared instantly via UI or API.
98
93
 
99
- ### 4. 📊 Token Savings Tracking & Budget Telemetry
100
- * Calculates exact tokens before and after compression using accurate token estimation.
101
- * Tracks cumulative tokens saved, compression ratio, and session budget percentage.
102
- * Configurable warning threshold (`budgetAlertPercent`) dynamically alerts when the session budget approaches depletion.
103
-
104
- ### 5. 🖥️ Visual Surfaces & Dual Sidebar Integration
105
- Context Lens shares the unified `.cl-*` design language and `--dsw-alias-*` token system with `dsh-clinebot`:
106
- * **Conversation Header Chip**: Mounted in `conversation.session.header.utilities` (`order: 7`). Always displays efficiency badges (`◐ Lens`, `◐ <N>%`, or `⚠` alert) with an interactive dropdown Popover showing savings details and recent operations.
107
- * **Dual Sidebar Compatibility**: Supports both native DeepSeek Harness right sidebar (`ctx.sidebarRightTabs` + `sidebar.right.pane.tab` slot) and legacy `dsh-better-sidebar` with non-conflicting IDs.
108
- * **ErrorBoundary Protection**: Every UI component (`PluginCard`, `LensTab`, `StatusPanel`) is isolated inside React error boundaries with instant retry buttons, preventing parent UI crashes.
109
- * **One-Click In-App Updater**: Settings card displays live version checks against npm with a single-click update trigger.
94
+ ### 3. 🎯 Path Focus Management
95
+ * Designate specific files or folders as active working targets for the current task.
96
+ * Files in focus bypass AST skeletonization, returning complete implementation code.
97
+ * Focus state is strictly scoped per session (`sessionId`).
110
98
 
111
99
  ---
112
100
 
113
- ## 🛠️ Agent Tools Reference (5 Tools)
114
-
115
- All tools strictly conform to the DeepSeek Harness tool specification by providing `output.render` returning structured `ContentBlock[]` arrays (`[{ type: 'text', text: ... }]`), ensuring 100% session stability with core LLM stream processors.
101
+ ## 🛠️ Agent Tools Reference (Consolidated to 2 Tools)
116
102
 
117
- | Tool Name | Parameters | Description |
118
- |---|---|---|
119
- | `context_lens_focus` | `paths: string[]`, `sessionId?: string` | Sets active focus files/folders for the session; collapses surrounding workspace into AST skeletons |
120
- | `context_lens_compress_log` | `text: string` *(or `log`)*, `mode?: "raw"|"balanced"|"aggressive"`, `maxLines?: number`, `auto?: boolean` | Condenses terminal and test outputs, keeping only stack traces and failure windows |
121
- | `context_lens_compress_code` | `code: string`, `language?: string`, `maxDepth?: number`, `filePath?: string`, `sessionId?: string` | Generates a clean structural AST skeleton from raw source code |
122
- | `context_lens_track` | `sessionId?: string` | Returns real-time cumulative token savings, history, and budget status for the session |
123
- | `context_lens_reset` | `sessionId?: string` | Resets token tracker counters and compression history at the start of new tasks |
103
+ All tools strictly conform to the DeepSeek Harness tool specification by providing `output.render` returning structured `ContentBlock[]` arrays (`[{ type: 'text', text: ... }]`), ensuring 100% session stability.
124
104
 
125
- ---
126
-
127
- ## 🔌 HTTP API Reference
128
-
129
- | Endpoint | Method | Security Checks | Description |
105
+ | Tool Name | Action / Mode | Parameters | Description |
130
106
  |---|---|---|---|
131
- | `/dsh-context-lens/status` | `GET` | Open (safe read) | Returns session token savings stats, active focus paths, and compression history |
132
- | `/dsh-context-lens/clear-focus` | `POST` | Loopback / Same-Origin | Clears focused paths for the specified session (rejects GET with 405) |
133
- | `/dsh-context-lens/compress-preview` | `POST` | Loopback / Same-Origin | Preview log compression with 256KB body size limit and `maxLines` clamping (1–5000) |
134
- | `/api/dsh-context-lens/update` | `GET`, `POST` | Loopback + Security Header | In-app plugin updater checking npm registry and executing safe background updates |
107
+ | `context_lens_code` | `action: "skeleton"` (default) | `code`, `language?`, `maxDepth?`, `filePath?`, `sessionId?` | Generates a clean structural AST skeleton from raw source code (or returns full code if file is in session focus) |
108
+ | `context_lens_code` | `action: "focus"` | `paths: string[]`, `sessionId?` | Sets active focus file paths or patterns for the current session |
109
+ | `context_lens_code` | `action: "get_focus"` | `sessionId?` | Retrieves active focus paths for the session |
110
+ | `context_lens_code` | `action: "clear_focus"` | `sessionId?` | Clears focus paths for the session |
111
+ | `context_lens_log` | N/A | `text` *(or `log`)*, `mode?`, `maxLines?`, `auto?`, `command?` | Compresses test and build output logs, preserving failures, stack traces, and summary. In `auto: true`, only runs on recognized test/build outputs |
135
112
 
136
113
  ---
137
114
 
138
- ## ⚙️ Configuration Reference (`settings.yaml`)
115
+ ## ⚙️ Configuration Schema
139
116
 
140
- Settings can be modified via `settings.yaml` or directly in the DSH Web UI under **Settings → Plugins → Context Lens**.
117
+ Configured via the DSH Settings page (`plugins.row.config` / `plugins.item`):
141
118
 
142
- ```yaml
143
- dsh-context-lens:
144
- compressionMode: balanced # Log compression mode: 'raw', 'balanced', or 'aggressive'
145
- astSkeletonMaxDepth: 3 # Maximum depth level for AST signature traversal (1..10)
146
- tokenSavingsTracking: true # Track and display live token savings
147
- autoCompressThreshold: 4000 # Auto-compression character threshold (0 to disable)
148
- budgetLimit: 100000 # Session token budget limit
149
- budgetAlertPercent: 90 # Budget percentage threshold triggering warning badge (50..99)
150
- autoCollapse: true # Display warning in UI when budget is nearly exhausted
151
- ```
152
-
153
- | Parameter | Type | Default | Description |
119
+ | Property | Type | Default | Description |
154
120
  |---|---|---|---|
155
- | `compressionMode` | `string` | `balanced` | Default log compression aggressiveness (`raw`, `balanced`, `aggressive`) |
156
- | `astSkeletonMaxDepth` | `number` | `3` | Maximum nesting depth for AST signature parsing (1 to 10) |
157
- | `tokenSavingsTracking` | `boolean` | `true` | Track token savings before/after compression |
158
- | `autoCompressThreshold` | `number` | `4000` | Auto-compress terminal logs exceeding this character length (0 to disable) |
159
- | `budgetLimit` | `number` | `100000` | Total token budget limit allocated per session |
160
- | `budgetAlertPercent` | `number` | `90` | Budget alert threshold percentage triggering warnings (50 to 99) |
161
- | `autoCollapse` | `boolean` | `true` | Display low-budget warning badge in settings card and header chip |
162
-
163
- ---
164
-
165
- ## 📦 Quick Installation
166
-
167
- ```bash
168
- dsh plugin --profile web add @goodandready/dsh-context-lens
169
- ```
170
-
171
- > [!TIP]
172
- > After installation, reload the DSH Web UI or restart the service (`systemctl --user restart dsh-web`) to activate context compression tools.
121
+ | `compressionMode` | `string` | `'balanced'` | Log compression aggressiveness (`raw`, `balanced`, `aggressive`) |
122
+ | `astSkeletonMaxDepth` | `number` | `3` | Max depth for AST skeleton generation |
123
+ | `autoCompressThreshold` | `number` | `4000` | Character threshold for auto-compressing test/build logs (0 to disable) |
173
124
 
174
125
  ---
175
126
 
176
127
  ## 📄 License
177
128
 
178
- MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
129
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
package/README.ru.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  <div align="center">
4
4
 
5
- <h3>AST-скелетонизатор кода, компрессор терминальных логов и Token Guard для DeepSeek Harness</h3>
5
+ <h3>Смысловое AST-сжатие кода и логов тестов для DeepSeek Harness</h3>
6
6
 
7
7
  <p align="center">
8
8
  <a href="https://www.npmjs.com/package/@goodandready/dsh-context-lens"><img src="https://img.shields.io/npm/v/@goodandready/dsh-context-lens.svg?style=for-the-badge&color=6366f1&labelColor=1e1b4b" alt="npm version"></a>
@@ -11,7 +11,7 @@
11
11
  <a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node-20%2B-f59e0b.svg?style=for-the-badge&labelColor=451a03" alt="Node version"></a>
12
12
  </p>
13
13
 
14
- <!-- Кнопка перехода на витрину -->
14
+ <!-- Showcase Button -->
15
15
  <p align="center">
16
16
  <a href="https://goodandready.app/"><img src="https://img.shields.io/badge/Все_проекты_автора-goodandready.app-ff4500.svg?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e" alt="Все проекты автора"></a>
17
17
  </p>
@@ -25,9 +25,9 @@
25
25
  <table align="center">
26
26
  <tr>
27
27
  <td align="center">
28
- ⭐ <strong>Если вам нравится этот плагин, поставьте ему Star на GitHub</strong> — это покажет мне, что плагин полезен, и добавит мотивации продолжать его развитие.
28
+ ⭐ <strong>Если вам понравился этот плагин, пожалуйста, поставьте звезду на GitHub</strong> — это показывает, что плагин полезен, и мотивирует развивать его дальше.
29
29
  <br><br>
30
- 🐛 <strong>Если вы нашли баг или хотите предложить новую функцию</strong>, создайте Issue на GitHub на любом языке — я рассмотрю предложение и реализую полезные улучшения в одной из следующих версий плагина.
30
+ 🐛 <strong>Нашли ошибку или хотите предложить улучшение?</strong> Откройте issue на GitHub на любом языке — предложения рассматриваются при подготовке будущих версий.
31
31
  </td>
32
32
  </tr>
33
33
  </table>
@@ -36,143 +36,69 @@
36
36
 
37
37
  ---
38
38
 
39
- ## ⚡ Обзор и решаемая проблема
39
+ ## ⚡ Разделение ответственности: Ядро vs Плагин
40
40
 
41
- При анализе крупных проектов и выполнении тестов контекстное окно языковой модели мгновенно заполняется реализацией второстепенных файлов и простынями логов. Это приводит к перерасходу токенов, росту задержек генерации и потере внимания агента.
41
+ > **Бюджет контекста и обрезку результатов делает ядро (с 0.1.5). Этот плагин добавляет смысловое сжатие: AST-скелеты кода и сжатие логов тестов.**
42
42
 
43
- **`dsh-context-lens`** решает эту проблему комплексно:
44
- 1. **Фокусировка на активных путях (`context_lens_focus`)**: Редактируемые файлы передаются агенту целиком, а вспомогательные файлы рабочей зоны сворачиваются в легковесные AST-каркасы.
45
- 2. **Многоязыковая AST-скелетонизация**: Сжатие кода на **70–85%** с сохранением классов, типов, методов и сигнатур (TypeScript, JavaScript, Python, Go, C/C++, Rust, SQL).
46
- 3. **Эвристическая компрессия логов**: Удаление шума успешных проверок с сохранением ключевых ошибок и стек-трейсов, сжатие логов до **90%**.
47
- 4. **Сессионная телеметрия токенов и Token Guard**: Отслеживание экономии в реальном времени, визуальные бейджи и алерты при исчерпании лимита бюджета.
43
+ Штатные механизмы DeepSeek Harness (`dsh-compaction-tool-result-pruner`, `dsh-spill-policy`, `dsh-token-meter`) автоматически контролируют объем токенов, обрезают хвосты длинных ответов и сбрасывают гигантские дампы на диск. Плагин `dsh-context-lens` решает задачу, которую не может решить механический обрезчик — **смысловую компактификацию**:
44
+ 1. **AST-скелеты кода**: вместо тел функций и реализаций передаются сигнатуры, интерфейсы, экспортируемые типы и doc-комментарии (JS, TS, Python, Go, Rust, C/C++, Java, SQL).
45
+ 2. **Фокус на путях**: рабочие файлы сохраняются целиком, а окружающий код проекта сворачивается в скелеты.
46
+ 3. **Сжатие логов тестов и сборки**: вместо полотен терминала остаются ошибки, стек вызова и сводный итог. Авто-режим срабатывает **до** pruner'а ядра и исключительно на выводах тестов/сборки.
48
47
 
49
48
  ```mermaid
50
49
  graph LR
51
- subgraph RawContext [Входные контекстные потоки]
52
- Code[📁 Исходный код: Полные тела функций] --> LensEngine[Движок dsh-context-lens]
53
- Logs[📋 Логи сборки и тестов: Многословный вывод] --> LensEngine
50
+ subgraph RawContext [Входные потоки]
51
+ Code[📁 Исходный код: Длинные реализации] --> Lens[Движок dsh-context-lens]
52
+ Logs[📋 Логи сборки и тестов] --> Lens
54
53
  end
55
54
 
56
- subgraph LensEngine [Конвейер обработки контекста]
57
- LensEngine --> Focus{Оценка фокуса}
58
- Focus -->|Фокусный файл| RawKeep[Полный исходный код]
59
- Focus -->|Внешний контекст| AST[AST-скелетонизатор: Типы и сигнатуры]
60
- LensEngine --> LogFilter[Компрессор логов: Только ошибки и трейсы]
55
+ subgraph Lens [Смысловое сжатие]
56
+ Lens --> Focus{Проверка фокуса}
57
+ Focus -->|Файл в фокусе| FullCode[Полный код файла]
58
+ Focus -->|Окружающий код| AST[AST-скелетонизатор: Сигнатуры]
59
+ Lens --> LogCompress[Компрессор логов: Ошибки, стек, итог]
61
60
  end
62
61
 
63
- subgraph Output [Оптимизированный контекст агента]
64
- AST --> Agent[🤖 Контекст агента DSH: Компактный промпт]
65
- RawKeep --> Agent
66
- LogFilter --> Agent
67
- Agent --> Tracker[📊 Телеметрия экономии и Token Guard]
62
+ subgraph Output [Оптимальный контекст]
63
+ FullCode --> Agent[🤖 Контекст агента]
64
+ AST --> Agent
65
+ LogCompress --> Agent
66
+ Agent --> Core[⚙️ Pruner и Spill Policy ядра DSH]
68
67
  end
69
68
 
70
69
  style RawContext fill:#1e1e2e,stroke:#89b4fa,stroke-width:2px,color:#cdd6f4
71
- style LensEngine fill:#181825,stroke:#cba6f7,stroke-width:2px,color:#cdd6f4
70
+ style Lens fill:#181825,stroke:#cba6f7,stroke-width:2px,color:#cdd6f4
72
71
  style Output fill:#11111b,stroke:#a6e3a1,stroke-width:2px,color:#cdd6f4
73
72
  ```
74
73
 
75
74
  ---
76
75
 
77
- ## ✨ Полный разбор возможностей
78
-
79
- ### 1. 🧬 Многоязыковой AST-скелетонизатор
80
- * **Поддерживаемые языки**: TypeScript, JavaScript, Python, Go, C/C++, Rust, SQL DDL.
81
- * **Сохранение архитектурной структуры**: Оставляет импорты, классы, интерфейсы, сигнатуры функций и документирующие комментарии, вырезая громоздкие тела методов.
82
- * **Многострочные сигнатуры**: Корректно аккумулирует сложные типизированные параметры и возвращаемые промисы до терминаторов блоков.
83
- * **Чистый регулярный парсер**: Нулевой оверхед, отсутствие бинарных парсеров и мгновенная работа на любой ОС.
84
-
85
- ### 2. 📋 Эвристический компрессор логов тестирования и сборки
86
- * **Поддерживаемые инструменты**: Jest, Vitest, Pytest, Go test, Cargo, Webpack, Vite, TSC, Maven, Gradle.
87
- * **Точечная фильтрация**: Сохраняет сообщения об ошибках, стек-трейсы, различия в assert (`Expected ... Received ...`) и строки контекста падений.
88
- * **3 режима сжатия**:
89
- - `raw`: Фильтрация очевидного шума с сохранением общего хода выполнения.
90
- - `balanced`: Баланс между сжатием и контекстом вокруг упавших тестов (по умолчанию).
91
- - `aggressive`: Выделение строго строк ошибок и фреймов вызовов.
92
- * **Очистка ANSI**: Автоматическое удаление цветовых кодов терминала.
93
-
94
- ### 3. 🎯 Сессионная фокусировка (`context_lens_focus`)
95
- * Задаёт список рабочих файлов или каталогов, редактируемых в рамках текущей задачи.
96
- * Фокус строго изолирован в разрезе сессии (`sessionId`).
97
- * Сброс фокуса доступен в один клик через кнопку в интерфейсе или вызов `context_lens_focus` с пустым списком.
98
-
99
- ### 4. 📊 Трекер экономии токенов и Token Guard
100
- * Расчёт реального расхода до и после сжатия.
101
- * Отображение суммарно сэкономленных токенов, процента оптимизации и шкалы сессионного бюджета.
102
- * Настраиваемый порог предупреждения (`budgetAlertPercent`) с динамической сменой статуса индикатора.
103
-
104
- ### 5. 🖥️ Визуальные интерфейсы и совместимость с боковыми панелями
105
- Context Lens оформлен по единому стандарту дизайн-системы `.cl-*` и токенов `--dsw-alias-*`:
106
- * **Индикатор в шапке диалога**: Размещён в слоте `conversation.session.header.utilities` (`order: 7`). Показывает статус (`◐ Lens`, `◐ <N>%` или `⚠`) и открывает интерактивный Popover с метриками и историей операций.
107
- * **Поддержка двух боковых панелей**: Совместим как с нативной правой панелью DSH (`ctx.sidebarRightTabs` + слот `sidebar.right.pane.tab`), так и с легаси `dsh-better-sidebar`.
108
- * **Изоляция сбоев (ErrorBoundary)**: Все визуальные компоненты обёрнуты в защитные границы React с кнопкой повтора («Retry»).
109
- * **Встроенный One-Click апдейтер**: Проверка обновлений в npm и безопасная установка в один клик из карточки настроек.
76
+ ## 🛠️ Инструменты агента (2 консолидированных инструмента)
110
77
 
111
- ---
112
-
113
- ## 🛠️ Справочник инструментов агента (5 инструментов)
114
-
115
- Все инструменты строго соответствуют контракту DSH: метод `output.render` возвращает массив `ContentBlock[]` (`[{ type: 'text', text: ... }]`), исключая повреждение сессий в ядре `@deepseek-ai/dsh-llm`.
116
-
117
- | Имя инструмента | Параметры | Описание |
118
- |---|---|---|
119
- | `context_lens_focus` | `paths: string[]`, `sessionId?: string` | Назначает активные рабочие файлы сессии; сворачивает внешнее окружение в AST-каркасы |
120
- | `context_lens_compress_log` | `text: string` *(или `log`)*, `mode?: "raw"|"balanced"|"aggressive"`, `maxLines?: number`, `auto?: boolean` | Сжимает вывод тестов и терминала, сохраняя только ошибки и контекст падений |
121
- | `context_lens_compress_code` | `code: string`, `language?: string`, `maxDepth?: number`, `filePath?: string`, `sessionId?: string` | Формирует структурный AST-скелет из исходного кода |
122
- | `context_lens_track` | `sessionId?: string` | Возвращает накопленную статистику экономии токенов, историю и статус бюджета сессии |
123
- | `context_lens_reset` | `sessionId?: string` | Сбрасывает накопленные счётчики и историю сжатий при старте новой задачи |
78
+ Инструменты строго соблюдают контракт DSH: `output.render` возвращает массив `ContentBlock[]` (`[{ type: 'text', text: ... }]`).
124
79
 
125
- ---
126
-
127
- ## 🔌 HTTP API плагина
128
-
129
- | Маршрут | Метод | Защита и проверки | Описание |
80
+ | Инструмент | Действие / Режим | Параметры | Описание |
130
81
  |---|---|---|---|
131
- | `/dsh-context-lens/status` | `GET` | Открытый (safe read) | Возвращает сессионную статистику, активные пути фокуса и историю сжатий |
132
- | `/dsh-context-lens/clear-focus` | `POST` | Loopback / Same-Origin | Сбрасывает пути фокуса для указанной сессии (GET отклоняется с кодом 405) |
133
- | `/dsh-context-lens/compress-preview` | `POST` | Loopback / Same-Origin | Предпросмотр сжатия лога с лимитом тела 256 КБ и клампингом `maxLines` (1–5000) |
134
- | `/api/dsh-context-lens/update` | `GET`, `POST` | Loopback + заголовок защиты | Модуль фонового обновления плагина из официального реестра npm |
82
+ | `context_lens_code` | `action: "skeleton"` (по умолчанию) | `code`, `language?`, `maxDepth?`, `filePath?`, `sessionId?` | Генерирует структурный AST-скелет из кода (или возвращает полный код, если файл находится в фокусе сессии) |
83
+ | `context_lens_code` | `action: "focus"` | `paths: string[]`, `sessionId?` | Задает список путей активного фокуса для текущей сессии |
84
+ | `context_lens_code` | `action: "get_focus"` | `sessionId?` | Возвращает текущее состояние фокуса для сессии |
85
+ | `context_lens_code` | `action: "clear_focus"` | `sessionId?` | Очищает пути фокуса сессии |
86
+ | `context_lens_log` | N/A | `text` *(или `log`)*, `mode?`, `maxLines?`, `auto?`, `command?` | Сжимает вывод тестов и сборки, сохраняя ошибки, стеки и итог. В режиме `auto: true` применяется только к выводу тестов/сборки |
135
87
 
136
88
  ---
137
89
 
138
- ## ⚙️ Справочник настроек (`settings.yaml`)
90
+ ## ⚙️ Настройки плагина
139
91
 
140
- Настройки доступны через `settings.yaml` или в интерфейсе DSH во вкладке **Настройки → Плагины → Context Lens**.
92
+ Настраивается через страницу настроек DSH (`plugins.row.config` / `plugins.item`):
141
93
 
142
- ```yaml
143
- dsh-context-lens:
144
- compressionMode: balanced # Режим сжатия логов: 'raw', 'balanced', или 'aggressive'
145
- astSkeletonMaxDepth: 3 # Максимальная глубина обхода сигнатур AST (1..10)
146
- tokenSavingsTracking: true # Отслеживание и отображение экономии токенов
147
- autoCompressThreshold: 4000 # Порог автосжатия логов в символах (0 для отключения)
148
- budgetLimit: 100000 # Сессионный лимит бюджета токенов
149
- budgetAlertPercent: 90 # Процент бюджета для вывода предупреждения (50..99)
150
- autoCollapse: true # Отображение предупреждающего бейджа при исчерпании бюджета
151
- ```
152
-
153
- | Параметр | Тип | По умолчанию | Описание |
94
+ | Поле | Тип | По умолчанию | Описание |
154
95
  |---|---|---|---|
155
- | `compressionMode` | `string` | `balanced` | Базовый режим сжатия логов (`raw`, `balanced`, `aggressive`) |
156
- | `astSkeletonMaxDepth` | `number` | `3` | Максимальная глубина вложенности AST-сигнатур (от 1 до 10) |
157
- | `tokenSavingsTracking` | `boolean` | `true` | Расчёт сэкономленных токенов до и после сжатия |
158
- | `autoCompressThreshold` | `number` | `4000` | Порог авто-сжатия терминального вывода (символов) |
159
- | `budgetLimit` | `number` | `100000` | Выделенный бюджет токенов на одну сессию |
160
- | `budgetAlertPercent` | `number` | `90` | Процент расхода бюджета для активации предупреждения (от 50 до 99) |
161
- | `autoCollapse` | `boolean` | `true` | Отображение бейджа низкого бюджета в карточке настроек и шапке |
162
-
163
- ---
164
-
165
- ## 📦 Быстрая установка
166
-
167
- ```bash
168
- dsh plugin --profile web add @goodandready/dsh-context-lens
169
- ```
170
-
171
- > [!TIP]
172
- > После установки перезагрузите страницу Web UI или перезапустите сервис (`systemctl --user restart dsh-web`) для активации инструментов контекста.
96
+ | `compressionMode` | `string` | `'balanced'` | Агрессивность сжатия логов (`raw`, `balanced`, `aggressive`) |
97
+ | `astSkeletonMaxDepth` | `number` | `3` | Максимальная глубина вложенности AST-скелета |
98
+ | `autoCompressThreshold` | `number` | `4000` | Порог в символах для автосжатия логов тестов/сборки (0 для отключения) |
173
99
 
174
100
  ---
175
101
 
176
102
  ## 📄 Лицензия
177
103
 
178
- MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
104
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)