@goodandready/dsh-context-lens 0.1.18 → 0.1.19
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 +107 -0
- package/README.md +86 -122
- package/README.ru.md +95 -120
- package/README.zh.md +99 -14
- package/lib/client.js +34 -9
- package/lib/tokens/tracker.js +0 -4
- package/package.json +3 -2
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@goodandready/dsh-context-lens` will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.1.19] - 2026-09-18
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
- **UI Slot Registration Error Diagnostics (#76)**: Replaced silent/empty `catch` blocks in `lib/client.js` for `sidebar.right.pane.tab`, `conversation.session.header.utilities`, and `betterSidebar` slot registrations with descriptive `console.warn` diagnostic logs. Added explicit fallback intention comments for locale snapshot handling.
|
|
12
|
+
|
|
13
|
+
### Refactored
|
|
14
|
+
- **Tracker Dead Code Cleanup (#77)**: Removed redundant, test-only `clearHistory` export from `lib/tokens/tracker.js`. History clearing is canonically and safely handled by `reset()`.
|
|
15
|
+
|
|
16
|
+
### Documentation
|
|
17
|
+
- **Keep a Changelog Standardization (#74)**: Extracted chronological release notes (`## Changed in v...`) from `README.md`, `README.ru.md`, and `README.zh.md` into centralized `CHANGELOG.md`. Consolidated all product feature documentation into comprehensive thematic sections. Included `CHANGELOG.md` in package distribution manifest (`package.json` files list).
|
|
18
|
+
|
|
19
|
+
## [0.1.18] - 2026-09-17
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
- **AI Tool ContentBlock Format (GH #2 / Gitea #71)**: Fixed output formatting across all 5 AI tools (`context_lens_status`, `context_lens_compress_preview`, `context_lens_skeletonize`, `context_lens_track`, `context_lens_clear_focus`). All tools now return structured `ContentBlock[]` arrays (`[{ type: 'text', text: ... }]`) instead of raw JSON strings, preventing session-poisoning `TypeError: content.some is not a function` exceptions in `@deepseek-ai/dsh-llm`.
|
|
23
|
+
- **HTTP Parameter Validation (#70)**: Replaced silent error swallows with explicit 400 Bad Request responses and diagnostic warning logging when parsing malformed URL queries or invalid session parameters.
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
- **In-App One-Click Auto-Updater (#61)**: Added standard updater module (`lib/updater.js`) with `/api/dsh-context-lens/update` endpoint and an in-app update banner with version badge and update button in the settings card.
|
|
27
|
+
|
|
28
|
+
### Security
|
|
29
|
+
- **HTTP Endpoint Hardening (#62, #63)**:
|
|
30
|
+
- `/clear-focus` strictly requires `POST` method (returns 405 on GET) and validates loopback / same-origin trusted source (403 on untrusted).
|
|
31
|
+
- `/compress-preview` strictly requires `POST`, verifies loopback / same-origin, caps request body at 256KB (413 on exceed), and validates `maxLines` parameter (clamped between 1 and 5000).
|
|
32
|
+
|
|
33
|
+
### Changed
|
|
34
|
+
- **UI Design System & Theme Alignment (#67, #68)**: Replaced text fallback chevron `▼` with an animated SVG 14x14 icon with smooth 180° rotation. Removed all hardcoded `rgba()` values in favor of DeepSeek Harness `--dsw-alias-*` theme variables.
|
|
35
|
+
- **Settings & Cordis Lifecycle (#64, #66)**: Injected `settingsScope` directly into client plugin dependencies and removed foreign `lanSettings` fallback. Wrapped settings and locale registrations in `ctx.effect` with disposable cleanups.
|
|
36
|
+
- **Code Decomposition (#69)**: Modularized server half into `lib/http.js`, `lib/tools.js`, `lib/updater.js`, and a compact `lib/index.js`.
|
|
37
|
+
- **Repository Hygiene (#65)**: Purged internal agent artifacts (`AGENTS.md`, `index.md`, `docs/plans/`) from tracked git tree and updated `.gitignore`.
|
|
38
|
+
|
|
39
|
+
## [0.1.17] - 2026-09-15
|
|
40
|
+
|
|
41
|
+
### Added
|
|
42
|
+
- **Focus Management UI**: Added active session focus path chips (`focus.paths`) and an instant "Clear focus" button in `StatusPanel`.
|
|
43
|
+
- **Configurable Budget Alert Threshold**: Added `budgetAlertPercent` (50–99%, default 90%) to `Config` and the settings card, allowing customizable budget alert levels.
|
|
44
|
+
- **Expanded AST Syntax**: Added pure regex AST skeletonization for C/C++ (`class`, methods, `#include`) and SQL DDL (`CREATE/ALTER TABLE`, `INDEX`).
|
|
45
|
+
|
|
46
|
+
### Changed
|
|
47
|
+
- **Multi-Language Standard**: Client bundle now strictly contains only canonical English (`en`) and Chinese (`zh`) dictionaries. Russian translations are provided externally via `dsh-russian-lang`.
|
|
48
|
+
|
|
49
|
+
## [0.1.16] - 2026-09-13
|
|
50
|
+
|
|
51
|
+
### Added
|
|
52
|
+
- **UI Error Boundary**: Wrapped visual components (`PluginCard`, `LensTab`, `StatusPanel`) in native React error boundaries with retry buttons, preventing parent crashes and React Error 310.
|
|
53
|
+
- **Reactive Settings Synchronization**: Added support for reading settings snapshots via `scope.getSnapshot()` and reactive subscriptions via `scope.subscribe()`.
|
|
54
|
+
|
|
55
|
+
### Changed
|
|
56
|
+
- **ClineBot Unified Style**: Migrated UI classes to the unified `.cl-*` design system with `--dsw-alias-*` CSS tokens.
|
|
57
|
+
- **Input Validation**: Added defensive input validation across all compression, skeletonization, and tracking functions.
|
|
58
|
+
|
|
59
|
+
## [0.1.15] - 2026-09-11
|
|
60
|
+
|
|
61
|
+
### Added
|
|
62
|
+
- **Native DSH Right Sidebar**: Added support for DeepSeek Harness 0.1.5-alpha.1+ native right sidebar via `ctx.sidebarRightTabs` and `sidebar.right.pane.tab` slot.
|
|
63
|
+
|
|
64
|
+
### Changed
|
|
65
|
+
- **Sidebar Coexistence**: Preserved legacy `dsh-better-sidebar` integration with deterministic, non-conflicting IDs (`@goodandready/dsh-context-lens` vs `dsh-context-lens:tab`) and graceful fallback across all 4 layouts.
|
|
66
|
+
|
|
67
|
+
## [0.1.14] - 2026-09-09
|
|
68
|
+
|
|
69
|
+
### Added
|
|
70
|
+
- **AST Multiline Signatures**: Added multiline function and method signature parsing for TypeScript, JavaScript, Rust, and Go.
|
|
71
|
+
- **Reset Tool**: Added `context_lens_reset` tool to reset token tracker statistics and compression history.
|
|
72
|
+
|
|
73
|
+
### Changed
|
|
74
|
+
- **Adaptive Polling**: Header chip pauses polling on hidden browser tabs (`visibilitychange`) and polls actively (4s) only when the popover is open.
|
|
75
|
+
- **Settings Atomicity**: Added atomic settings patch saving in `PluginCard`.
|
|
76
|
+
|
|
77
|
+
## [0.1.13] - 2026-09-07
|
|
78
|
+
|
|
79
|
+
### Fixed
|
|
80
|
+
- **Cordis Proxy Safety**: Guarded optional `betterSidebar` tab registration via `ctx.inject(['betterSidebar'], ...)` instead of direct property access on Cordis context proxy.
|
|
81
|
+
- **Settings Scope Guard**: Protected `_ctx.settingsScope` access in `PluginCard` with try/catch to avoid proxy errors on older hosts.
|
|
82
|
+
|
|
83
|
+
## [0.1.12] - 2026-09-05
|
|
84
|
+
|
|
85
|
+
### Changed
|
|
86
|
+
- **Component Refactoring**: Extracted shared `StatusPanel` component reused by `LensTab` and the `HeaderChip` popover.
|
|
87
|
+
|
|
88
|
+
## [0.1.11] - 2026-09-03
|
|
89
|
+
|
|
90
|
+
### Fixed
|
|
91
|
+
- **Audit Fixes**: Auto-compress honors configured `compressionMode`, `budgetLimit` halts token accumulation once exceeded, focus state is tracked per-session (`sessionId`), and Python imports are properly retained.
|
|
92
|
+
|
|
93
|
+
## [0.1.10] - 2026-08-30
|
|
94
|
+
|
|
95
|
+
### Added
|
|
96
|
+
- **Session Header Chip**: Registered header chip in `conversation.session.header.utilities` (`order: 7`) with interactive dropdown popover showing live token savings, budget progress, and recent operations.
|
|
97
|
+
|
|
98
|
+
## [0.1.9] - 2026-08-25
|
|
99
|
+
|
|
100
|
+
### Changed
|
|
101
|
+
- **Compatibility**: Removed obsolete kernel modules from client injects for DSH 0.1.2-rc.1.
|
|
102
|
+
|
|
103
|
+
## [0.1.8] - 2026-08-20
|
|
104
|
+
|
|
105
|
+
### Fixed
|
|
106
|
+
- **Tool Arguments**: Supported both `text` and `log` parameter names in `context_lens_compress_log`.
|
|
107
|
+
- **Tracker & Parsing**: Fixed cross-platform path resolution on Windows, dynamic `budgetLimit` propagation, ANSI terminal escape sequence stripping, and Rust `pub async fn` syntax support.
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
<div align="center">
|
|
4
4
|
|
|
5
|
-
<h3>
|
|
5
|
+
<h3>AST Code Skeletonizer, Terminal Log Condenser & Token Budget Guard 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>
|
|
@@ -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
|
-
<!-- Showcase
|
|
14
|
+
<!-- Showcase Button -->
|
|
15
15
|
<p align="center">
|
|
16
16
|
<a href="https://goodandready.app/"><img src="https://img.shields.io/badge/All_Author_Projects-goodandready.app-ff4500.svg?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e" alt="All Author Projects"></a>
|
|
17
17
|
</p>
|
|
@@ -36,179 +36,143 @@
|
|
|
36
36
|
|
|
37
37
|
---
|
|
38
38
|
|
|
39
|
-
## ⚡ Overview
|
|
39
|
+
## ⚡ Overview & The Problem
|
|
40
40
|
|
|
41
|
-
|
|
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
42
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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.
|
|
46
48
|
|
|
47
49
|
```mermaid
|
|
48
50
|
graph LR
|
|
49
|
-
subgraph RawContext [
|
|
50
|
-
Code[📁
|
|
51
|
-
Logs[📋 Test
|
|
51
|
+
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
|
|
52
54
|
end
|
|
53
55
|
|
|
54
|
-
subgraph LensEngine [Context
|
|
55
|
-
LensEngine --> Focus{
|
|
56
|
-
Focus -->|Focused
|
|
57
|
-
Focus -->|Surrounding Workspace| AST[AST Skeletonizer:
|
|
58
|
-
LensEngine --> LogFilter[
|
|
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]
|
|
59
61
|
end
|
|
60
62
|
|
|
61
|
-
subgraph
|
|
62
|
-
AST --> Agent[🤖 DSH Agent:
|
|
63
|
+
subgraph Output [Optimized Agent Context]
|
|
64
|
+
AST --> Agent[🤖 DSH Agent Context: Compact High-Value Prompt]
|
|
63
65
|
RawKeep --> Agent
|
|
64
66
|
LogFilter --> Agent
|
|
65
|
-
Agent --> Tracker[📊 Live Token Budget
|
|
67
|
+
Agent --> Tracker[📊 Live Token Telemetry & Budget Guard]
|
|
66
68
|
end
|
|
67
69
|
|
|
68
70
|
style RawContext fill:#1e1e2e,stroke:#89b4fa,stroke-width:2px,color:#cdd6f4
|
|
69
71
|
style LensEngine fill:#181825,stroke:#cba6f7,stroke-width:2px,color:#cdd6f4
|
|
70
|
-
style
|
|
72
|
+
style Output fill:#11111b,stroke:#a6e3a1,stroke-width:2px,color:#cdd6f4
|
|
71
73
|
```
|
|
72
74
|
|
|
73
75
|
---
|
|
74
76
|
|
|
75
|
-
## ✨
|
|
77
|
+
## ✨ Full Feature Breakdown
|
|
76
78
|
|
|
77
|
-
### 1. 🧬 Multi-Language AST
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
* Allows the agent to understand entire multi-package repository architectures without loading tens of thousands of implementation tokens.
|
|
79
|
+
### 1. 🧬 Multi-Language AST Structural Skeletonizer
|
|
80
|
+
* **Supported Languages**: TypeScript, JavaScript, Python, Go, C/C++, Rust, and SQL DDL.
|
|
81
|
+
* **Structural Preservation**: Retains imports, classes, structs, interfaces, exported types, function signatures, and doc comments while discarding inner implementation bodies.
|
|
82
|
+
* **Multiline Signature Support**: Seamlessly accumulates complex multiline generic arguments, return types, and parameter lists up to block delimiters.
|
|
83
|
+
* **Pure Regex Implementation**: Zero heavy native dependencies or binary parser overhead; runs lightning-fast across any platform.
|
|
83
84
|
|
|
84
|
-
### 2.
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
|
|
89
|
-
|
|
85
|
+
### 2. 📋 Heuristic Test & Build Log Condenser
|
|
86
|
+
* **Supported Test Runners & Tools**: Jest, Vitest, Pytest, Go test, Cargo, Webpack, Vite, TSC, Maven, Gradle.
|
|
87
|
+
* **Targeted Extraction**: Identifies and preserves critical error messages, stack traces, assertion differences (`Expected ... Received ...`), and failure context windows.
|
|
88
|
+
* **3 Aggressiveness Modes**:
|
|
89
|
+
- `raw`: Removes simple noise lines while keeping general execution order.
|
|
90
|
+
- `balanced`: Preserves failure sections with surrounding context windows (default).
|
|
91
|
+
- `aggressive`: Extracts strictly error lines and stack frames.
|
|
92
|
+
* **ANSI Stripping**: Cleans terminal escape codes and color formatting before processing.
|
|
90
93
|
|
|
91
94
|
### 3. 🎯 Active Path Focus Scoping (`context_lens_focus`)
|
|
92
|
-
*
|
|
93
|
-
* Files
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
* Calculates
|
|
98
|
-
*
|
|
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
|
+
|
|
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.
|
|
99
110
|
|
|
100
111
|
---
|
|
101
112
|
|
|
102
|
-
## 🛠️ Agent Tools Reference (
|
|
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.
|
|
103
116
|
|
|
104
117
|
| Tool Name | Parameters | Description |
|
|
105
118
|
|---|---|---|
|
|
106
|
-
| `context_lens_focus` | `paths: string[]`, `
|
|
107
|
-
| `context_lens_compress_log` | `text: string` *(or `log`)*, `mode?: "raw"
|
|
108
|
-
| `context_lens_compress_code` | `code: string`, `language?: string`, `maxDepth?: number`, `filePath?: string` | Generates a clean structural AST skeleton from raw source code |
|
|
109
|
-
| `
|
|
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 |
|
|
110
124
|
|
|
111
125
|
---
|
|
112
126
|
|
|
113
|
-
##
|
|
114
|
-
|
|
115
|
-
```bash
|
|
116
|
-
dsh plugin --profile web add @goodandready/dsh-context-lens
|
|
117
|
-
```
|
|
127
|
+
## 🔌 HTTP API Reference
|
|
118
128
|
|
|
119
|
-
|
|
120
|
-
|
|
129
|
+
| Endpoint | Method | Security Checks | Description |
|
|
130
|
+
|---|---|---|---|
|
|
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 |
|
|
121
135
|
|
|
122
136
|
---
|
|
123
137
|
|
|
124
138
|
## ⚙️ Configuration Reference (`settings.yaml`)
|
|
125
139
|
|
|
140
|
+
Settings can be modified via `settings.yaml` or directly in the DSH Web UI under **Settings → Plugins → Context Lens**.
|
|
141
|
+
|
|
126
142
|
```yaml
|
|
127
143
|
dsh-context-lens:
|
|
128
|
-
compressionMode: balanced # 'raw', 'balanced', or 'aggressive'
|
|
144
|
+
compressionMode: balanced # Log compression mode: 'raw', 'balanced', or 'aggressive'
|
|
129
145
|
astSkeletonMaxDepth: 3 # Maximum depth level for AST signature traversal (1..10)
|
|
130
146
|
tokenSavingsTracking: true # Track and display live token savings
|
|
131
147
|
autoCompressThreshold: 4000 # Auto-compression character threshold (0 to disable)
|
|
132
148
|
budgetLimit: 100000 # Session token budget limit
|
|
133
|
-
|
|
149
|
+
budgetAlertPercent: 90 # Budget percentage threshold triggering warning badge (50..99)
|
|
150
|
+
autoCollapse: true # Display warning in UI when budget is nearly exhausted
|
|
134
151
|
```
|
|
135
152
|
|
|
136
|
-
|
|
153
|
+
| Parameter | Type | Default | Description |
|
|
154
|
+
|---|---|---|---|
|
|
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 |
|
|
137
162
|
|
|
138
|
-
|
|
163
|
+
---
|
|
139
164
|
|
|
140
|
-
|
|
141
|
-
* **Fix**: Register session header chip in `conversation.session.header.utilities` (`order: 7`).
|
|
142
|
-
* **Fix**: Ensure chip is always visible (`◐ Lens` on initial session, `◐ <N>%` when savings available, `⚠` on low budget).
|
|
143
|
-
* **Feature**: Interactive dropdown Popover on chip click: token savings breakdown, budget progress bar, recent operations, and refresh button.
|
|
165
|
+
## 📦 Quick Installation
|
|
144
166
|
|
|
145
|
-
|
|
146
|
-
|
|
167
|
+
```bash
|
|
168
|
+
dsh plugin --profile web add @goodandready/dsh-context-lens
|
|
169
|
+
```
|
|
147
170
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
* **Fix**: Cross-platform path resolution in unit tests on Windows (`fileURLToPath`).
|
|
151
|
-
* **Fix**: Dynamic propagation of `budgetLimit` configuration into token tracker.
|
|
152
|
-
* **Fix**: ANSI terminal escape sequence stripping for colored logs.
|
|
153
|
-
* **Fix**: Expanded Rust syntax support (`pub async fn`, `pub(crate)`) and proper `#` comment prefix for Python.
|
|
171
|
+
> [!TIP]
|
|
172
|
+
> After installation, reload the DSH Web UI or restart the service (`systemctl --user restart dsh-web`) to activate context compression tools.
|
|
154
173
|
|
|
155
174
|
---
|
|
156
175
|
|
|
157
|
-
|
|
158
|
-
## Changed in v0.1.18
|
|
159
|
-
|
|
160
|
-
- **Critical Fix (#71, GH #2)**: Conformed `output.render` to DeepSeek Harness core contract by returning `ContentBlock[]` (`[{ type: 'text', text: ... }]`). Prevents irreversible DSH session poisoning caused by `TypeError: content.some is not a function` in `@deepseek-ai/dsh-llm`.
|
|
161
|
-
- **Security & Reliability (#62, #63, #70)**: Hardened HTTP endpoints (`/clear-focus`, `/compress-preview`, `/status`): strictly requires `POST` on write actions, enforces loopback/same-origin trust checks, caps body size to 256KB (413 on exceed), validates `maxLines` (1-5000), and handles malformed session queries with clear 400 responses.
|
|
162
|
-
- **One-Click In-App Updater (#61)**: Added canonical plugin updater module (`lib/updater.js`) with `/api/dsh-context-lens/update` endpoint and an in-app update UI banner with one-click update button in the settings card.
|
|
163
|
-
- **Settings & Lifecycle (#64, #66)**: Injected `settingsScope` directly into client plugin dependencies and removed foreign `lanSettings` fallback. Wrapped settings and locale registrations in `ctx.effect` with disposable cleanups.
|
|
164
|
-
- **UI & Theme Alignment (#67, #68)**: Implemented smooth vector SVG 14x14 chevron with 180° rotation animation and replaced hardcoded colors with `--dsw-alias-*` theme tokens for seamless light/dark mode presentation.
|
|
165
|
-
- **Repository Hygiene (#65)**: Purged internal agent artifacts (`AGENTS.md`, `index.md`, `docs/plans/`) from tracked git tree and added denylist to `.gitignore`.
|
|
166
|
-
|
|
167
176
|
## 📄 License
|
|
168
177
|
|
|
169
178
|
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
170
|
-
|
|
171
|
-
## Changed in v0.1.11
|
|
172
|
-
|
|
173
|
-
Audit fixes (#33–#47, #18):
|
|
174
|
-
|
|
175
|
-
- Auto-compress no longer forces `balanced`; uses configured `compressionMode`.
|
|
176
|
-
- `budgetLimit` stops token counting after the limit (matches settings description).
|
|
177
|
-
- Focus state is per-session (`sessionId`), not process-global.
|
|
178
|
-
- Settings card exposes `budgetLimit`, `autoCollapse`, `autoCompressThreshold`; low-budget shows a warning instead of force-closing the card.
|
|
179
|
-
- Client `betterSidebar` inject is optional; preview uses server `/dsh-context-lens/compress-preview`.
|
|
180
|
-
- Python imports kept in skeletons; Java locals no longer mistaken for signatures.
|
|
181
|
-
- Shared `estimateTokens` helper; unused `dsh-credentials` peer removed.
|
|
182
|
-
|
|
183
|
-
## Changed in v0.1.12
|
|
184
|
-
|
|
185
|
-
#43: extract shared `StatusPanel` used by LensTab and HeaderChip popover (budget bar, history, refresh).
|
|
186
|
-
|
|
187
|
-
## Changed in v0.1.13
|
|
188
|
-
|
|
189
|
-
- **Fix (#50)**: Guard optional `betterSidebar` tab registration via `ctx.inject(['betterSidebar'], ...)` instead of direct property access on Cordis context proxy, resolving `cannot get property "betterSidebar" without inject` on client boot.
|
|
190
|
-
- **Fix (#50)**: Safely guard `_ctx.settingsScope` access in `PluginCard` with try/catch to prevent proxy property errors.
|
|
191
|
-
- **Test**: Added regression test suite simulating strict Cordis Context Proxy behavior.
|
|
192
|
-
|
|
193
|
-
## Changed in v0.1.15
|
|
194
|
-
|
|
195
|
-
- **Feature (#54)**: Support native DSH right sidebar (`ctx.sidebarRightTabs` + `sidebar.right.pane.tab` slot) introduced in DSH 0.1.5-alpha.1.
|
|
196
|
-
- **Compatibility (#54)**: Preserve legacy `dsh-better-sidebar` integration with deterministic, non-conflicting IDs (`@goodandready/dsh-context-lens` vs `dsh-context-lens:tab`).
|
|
197
|
-
- **Resilience (#54)**: Clean boot and graceful fallback across all 4 layouts (Native only, Legacy only, Both active, Neither active).
|
|
198
|
-
- **Tests (#54)**: Added comprehensive test matrix in `test/sidebar-matrix-54.test.mjs`.
|
|
199
|
-
|
|
200
|
-
## Changed in v0.1.14
|
|
201
|
-
|
|
202
|
-
- **Fix (#52)**: Multiline AST signature parsing in `skeletonizer.js` for TypeScript, JavaScript, Rust, and Go with complex parameter types and return annotations.
|
|
203
|
-
- **Feature (#52)**: Registered `context_lens_reset` tool to allow resetting tracker statistics and history at the start of new tasks.
|
|
204
|
-
- **Quality & UX (#52)**: Dynamic RU/EN locale detection in `HeaderChip`, `LensTab`, and `StatusPanel` via `ctx.locale` for seamless UI integration.
|
|
205
|
-
- **Perf & Stability (#52)**: Adaptive polling in `HeaderChip` pausing on hidden tabs (`visibilitychange`) and polling actively (4s) only when popover is open.
|
|
206
|
-
- **Reliability (#52)**: Atomic settings save (`scope.patch` / `scope.setAll`) in `PluginCard` with graceful fallback.
|
|
207
|
-
|
|
208
|
-
### UI & Styling System (v0.1.16+)
|
|
209
|
-
|
|
210
|
-
Context Lens shares its visual language and component architecture with `dsh-clinebot`:
|
|
211
|
-
- **Native Design System**: 100% theme integration using `--dsw-alias-*` tokens.
|
|
212
|
-
- **Resilient UI Surfaces**: Every component (`PluginCard`, `LensTab`, `StatusPanel`) is protected by an `ErrorBoundary` with instant retry capability.
|
|
213
|
-
- **Reactive Settings**: Live updates via `scope.subscribe()` and zero-delay reads via `scope.getSnapshot()`.
|
|
214
|
-
- **Adaptive Telemetry**: Popover and tab display metric cards for tokens saved, percentage reduced, and live budget utilization.
|
package/README.ru.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
<div align="center">
|
|
4
4
|
|
|
5
|
-
<h3
|
|
5
|
+
<h3>AST-скелетонизатор кода, компрессор терминальных логов и Token Guard для 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
|
+
<!-- Кнопка перехода на витрину -->
|
|
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>Если вам нравится этот плагин, поставьте ему
|
|
28
|
+
⭐ <strong>Если вам нравится этот плагин, поставьте ему Star на GitHub</strong> — это покажет мне, что плагин полезен, и добавит мотивации продолжать его развитие.
|
|
29
29
|
<br><br>
|
|
30
|
-
🐛 <strong>Если вы нашли баг или хотите предложить
|
|
30
|
+
🐛 <strong>Если вы нашли баг или хотите предложить новую функцию</strong>, создайте Issue на GitHub на любом языке — я рассмотрю предложение и реализую полезные улучшения в одной из следующих версий плагина.
|
|
31
31
|
</td>
|
|
32
32
|
</tr>
|
|
33
33
|
</table>
|
|
@@ -36,168 +36,143 @@
|
|
|
36
36
|
|
|
37
37
|
---
|
|
38
38
|
|
|
39
|
-
## ⚡ Обзор
|
|
39
|
+
## ⚡ Обзор и решаемая проблема
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
При анализе крупных проектов и выполнении тестов контекстное окно языковой модели мгновенно заполняется реализацией второстепенных файлов и простынями логов. Это приводит к перерасходу токенов, росту задержек генерации и потере внимания агента.
|
|
42
42
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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**: Отслеживание экономии в реальном времени, визуальные бейджи и алерты при исчерпании лимита бюджета.
|
|
46
48
|
|
|
47
49
|
```mermaid
|
|
48
50
|
graph LR
|
|
49
|
-
subgraph RawContext [
|
|
50
|
-
Code[📁
|
|
51
|
-
Logs[📋 Логи тестов:
|
|
51
|
+
subgraph RawContext [Входные контекстные потоки]
|
|
52
|
+
Code[📁 Исходный код: Полные тела функций] --> LensEngine[Движок dsh-context-lens]
|
|
53
|
+
Logs[📋 Логи сборки и тестов: Многословный вывод] --> LensEngine
|
|
52
54
|
end
|
|
53
55
|
|
|
54
|
-
subgraph LensEngine [
|
|
55
|
-
LensEngine --> Focus{
|
|
56
|
+
subgraph LensEngine [Конвейер обработки контекста]
|
|
57
|
+
LensEngine --> Focus{Оценка фокуса}
|
|
56
58
|
Focus -->|Фокусный файл| RawKeep[Полный исходный код]
|
|
57
|
-
Focus
|
|
58
|
-
LensEngine --> LogFilter[Компрессор логов:
|
|
59
|
+
Focus -->|Внешний контекст| AST[AST-скелетонизатор: Типы и сигнатуры]
|
|
60
|
+
LensEngine --> LogFilter[Компрессор логов: Только ошибки и трейсы]
|
|
59
61
|
end
|
|
60
62
|
|
|
61
|
-
subgraph
|
|
62
|
-
AST --> Agent[🤖
|
|
63
|
+
subgraph Output [Оптимизированный контекст агента]
|
|
64
|
+
AST --> Agent[🤖 Контекст агента DSH: Компактный промпт]
|
|
63
65
|
RawKeep --> Agent
|
|
64
66
|
LogFilter --> Agent
|
|
65
|
-
Agent --> Tracker[📊
|
|
67
|
+
Agent --> Tracker[📊 Телеметрия экономии и Token Guard]
|
|
66
68
|
end
|
|
67
69
|
|
|
68
70
|
style RawContext fill:#1e1e2e,stroke:#89b4fa,stroke-width:2px,color:#cdd6f4
|
|
69
71
|
style LensEngine fill:#181825,stroke:#cba6f7,stroke-width:2px,color:#cdd6f4
|
|
70
|
-
style
|
|
72
|
+
style Output fill:#11111b,stroke:#a6e3a1,stroke-width:2px,color:#cdd6f4
|
|
71
73
|
```
|
|
72
74
|
|
|
73
75
|
---
|
|
74
76
|
|
|
75
|
-
## ✨
|
|
76
|
-
|
|
77
|
-
### 1. 🧬
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
*
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
*
|
|
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 и безопасная установка в один клик из карточки настроек.
|
|
99
110
|
|
|
100
111
|
---
|
|
101
112
|
|
|
102
|
-
## 🛠️
|
|
113
|
+
## 🛠️ Справочник инструментов агента (5 инструментов)
|
|
114
|
+
|
|
115
|
+
Все инструменты строго соответствуют контракту DSH: метод `output.render` возвращает массив `ContentBlock[]` (`[{ type: 'text', text: ... }]`), исключая повреждение сессий в ядре `@deepseek-ai/dsh-llm`.
|
|
103
116
|
|
|
104
117
|
| Имя инструмента | Параметры | Описание |
|
|
105
118
|
|---|---|---|
|
|
106
|
-
| `context_lens_focus` | `paths: string[]`, `
|
|
107
|
-
| `context_lens_compress_log` | `text: string` *(или `log`)*, `mode?: "raw"
|
|
108
|
-
| `context_lens_compress_code` | `code: string`, `language?: string`, `maxDepth?: number`, `filePath?: string` |
|
|
109
|
-
| `
|
|
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` | Сбрасывает накопленные счётчики и историю сжатий при старте новой задачи |
|
|
110
124
|
|
|
111
125
|
---
|
|
112
126
|
|
|
113
|
-
##
|
|
127
|
+
## 🔌 HTTP API плагина
|
|
114
128
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
129
|
+
| Маршрут | Метод | Защита и проверки | Описание |
|
|
130
|
+
|---|---|---|---|
|
|
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 |
|
|
118
135
|
|
|
119
136
|
---
|
|
120
137
|
|
|
121
|
-
## ⚙️
|
|
138
|
+
## ⚙️ Справочник настроек (`settings.yaml`)
|
|
139
|
+
|
|
140
|
+
Настройки доступны через `settings.yaml` или в интерфейсе DSH во вкладке **Настройки → Плагины → Context Lens**.
|
|
122
141
|
|
|
123
142
|
```yaml
|
|
124
143
|
dsh-context-lens:
|
|
125
|
-
compressionMode: balanced # 'raw', 'balanced' или 'aggressive'
|
|
126
|
-
astSkeletonMaxDepth: 3 # Максимальная глубина обхода AST
|
|
127
|
-
tokenSavingsTracking: true #
|
|
128
|
-
autoCompressThreshold: 4000 # Порог
|
|
144
|
+
compressionMode: balanced # Режим сжатия логов: 'raw', 'balanced', или 'aggressive'
|
|
145
|
+
astSkeletonMaxDepth: 3 # Максимальная глубина обхода сигнатур AST (1..10)
|
|
146
|
+
tokenSavingsTracking: true # Отслеживание и отображение экономии токенов
|
|
147
|
+
autoCompressThreshold: 4000 # Порог автосжатия логов в символах (0 для отключения)
|
|
129
148
|
budgetLimit: 100000 # Сессионный лимит бюджета токенов
|
|
130
|
-
|
|
149
|
+
budgetAlertPercent: 90 # Процент бюджета для вывода предупреждения (50..99)
|
|
150
|
+
autoCollapse: true # Отображение предупреждающего бейджа при исчерпании бюджета
|
|
131
151
|
```
|
|
132
152
|
|
|
133
|
-
|
|
153
|
+
| Параметр | Тип | По умолчанию | Описание |
|
|
154
|
+
|---|---|---|---|
|
|
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` | Отображение бейджа низкого бюджета в карточке настроек и шапке |
|
|
134
162
|
|
|
135
|
-
|
|
163
|
+
---
|
|
136
164
|
|
|
137
|
-
|
|
138
|
-
* **Fix**: Регистрация индикатора сессии в актуальном слоте ядра `conversation.session.header.utilities` (`order: 7`).
|
|
139
|
-
* **Fix**: Чип теперь отображается всегда (`◐ Lens` при отсутствии сжатий, `◐ <N>%` при наличии сэкономленных токенов, `⚠` при низком остатке бюджета).
|
|
140
|
-
* **Feature**: Интерактивный выпадающий Popover по клику на чип: детальные метрики токенов, шкала прогресса бюджета, последние 3 операции и кнопка обновления.
|
|
165
|
+
## 📦 Быстрая установка
|
|
141
166
|
|
|
142
|
-
|
|
143
|
-
|
|
167
|
+
```bash
|
|
168
|
+
dsh plugin --profile web add @goodandready/dsh-context-lens
|
|
169
|
+
```
|
|
144
170
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
* **Fix**: Кроссплатформенное разрешение путей в тестах на Windows (`fileURLToPath`).
|
|
148
|
-
* **Fix**: Динамическая передача и учёт `budgetLimit` в трекере токенов.
|
|
149
|
-
* **Fix**: Корректная обработка цветных логов с терминальными ANSI-кодами.
|
|
150
|
-
* **Fix**: Расширена поддержка Rust (`pub async fn`, `pub(crate)`) и правильные комментарии `#` для Python в AST-скелетонизаторе.
|
|
171
|
+
> [!TIP]
|
|
172
|
+
> После установки перезагрузите страницу Web UI или перезапустите сервис (`systemctl --user restart dsh-web`) для активации инструментов контекста.
|
|
151
173
|
|
|
152
174
|
---
|
|
153
175
|
|
|
154
|
-
|
|
155
|
-
## Изменения в v0.1.18
|
|
156
|
-
|
|
157
|
-
- **Критическое исправление (#71, GH #2)**: Приведение контракта `output.render` к стандарту ядра DeepSeek Harness: теперь возвращается массив `ContentBlock[]` (`[{ type: 'text', text: ... }]`). Полностью устранено необратимое повреждение сессий DSH с ошибкой `TypeError: content.some is not a function` в модуле `@deepseek-ai/dsh-llm`.
|
|
158
|
-
- **Безопасность и отказоустойчивость HTTP (#62, #63, #70)**: Защита маршрутов (`/clear-focus`, `/compress-preview`, `/status`): проверка метода (`POST` для изменений), верификация loopback и same-origin, ограничение размера тела запроса до 256 КБ (код 413 при превышении), клампинг `maxLines` (1–5000), возврат 400 Bad Request при невалидном идентификаторе сессии.
|
|
159
|
-
- **One-Click автообновление плагина (#61)**: Внедрен стандартный модуль автообновления `lib/updater.js`, endpoint `/api/dsh-context-lens/update` и блок проверки/установки обновления в карточке настроек.
|
|
160
|
-
- **Сервис настроек и жизненный цикл (#64, #66)**: Клиентский плагин объявляет зависимость `settingsScope`, убрана привязка к чужому сервису `lanSettings`. Регистрации настроек и локали обёрнуты в `ctx.effect` с корректными уборщиками.
|
|
161
|
-
- **Визуальная часть UI и темы (#67, #68)**: Запасной шеврон заменён на векторный SVG 14x14 с плавной анимацией поворота на 180°. Исключены захардкоженные цвета `rgba()`, интерфейс переведён на токены `--dsw-alias-*`.
|
|
162
|
-
- **Санитайзинг репозитория (#65)**: Из отслеживаемого дерева исключены внутренние файлы (`AGENTS.md`, `index.md`, `docs/plans/`), обновлён `.gitignore`.
|
|
163
|
-
|
|
164
176
|
## 📄 Лицензия
|
|
165
177
|
|
|
166
178
|
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
167
|
-
|
|
168
|
-
## Changed in v0.1.11
|
|
169
|
-
|
|
170
|
-
Исправления audit #33–#47 / #18: режим auto-compress не форсирует balanced; budgetLimit останавливает подсчёт; focus per-session; поля settings card; optional betterSidebar; серверный preview; Python imports / Java locals; общий estimateTokens; удалён unused peer dsh-credentials.
|
|
171
|
-
|
|
172
|
-
## Changed in v0.1.12
|
|
173
|
-
|
|
174
|
-
#43: extract shared `StatusPanel` used by LensTab and HeaderChip popover (budget bar, history, refresh).
|
|
175
|
-
|
|
176
|
-
## Changed in v0.1.13
|
|
177
|
-
|
|
178
|
-
- **Fix (#50)**: Безопасная регистрация вкладки BetterSidebar через `ctx.inject(['betterSidebar'], ...)` вместо прямого чтения свойства из Cordis Context Proxy. Устранена ошибка `cannot get property "betterSidebar" without inject` при загрузке клиентской половины в DSH.
|
|
179
|
-
- **Fix (#50)**: Безопасное обращение к `_ctx.settingsScope` в `PluginCard` через try/catch.
|
|
180
|
-
- **Тесты**: Добавлены регрессионные тесты со строгим Cordis Context Proxy.
|
|
181
|
-
|
|
182
|
-
## Changed in v0.1.15
|
|
183
|
-
|
|
184
|
-
- **Функциональность (#54)**: Поддержка встроенной правой боковой панели DSH (`ctx.sidebarRightTabs` + слот `sidebar.right.pane.tab`) из DSH 0.1.5-alpha.1.
|
|
185
|
-
- **Совместимость (#54)**: Сохранена интеграция с легаси `dsh-better-sidebar` с детерминированными неконфликтующими идентификаторами (`@goodandready/dsh-context-lens` и `dsh-context-lens:tab`).
|
|
186
|
-
- **Отказоустойчивость (#54)**: Чистая инициализация во всех 4 конфигурациях (только Native, только Legacy, обе активны, обе отсутствуют).
|
|
187
|
-
- **Тесты (#54)**: Добавлена матрица тестов в `test/sidebar-matrix-54.test.mjs`.
|
|
188
|
-
|
|
189
|
-
## Changed in v0.1.14
|
|
190
|
-
|
|
191
|
-
- **Исправление (#52)**: Поддержка многострочных сигнатур функций и методов в `skeletonizer.js` (TypeScript, JavaScript, Rust, Go) со сложными типами параметров и аннотациями возвращаемых значений.
|
|
192
|
-
- **Функция (#52)**: Добавлен инструмент `context_lens_reset` для сброса собранной статистики токенов и истории сжатий перед запуском новой задачи.
|
|
193
|
-
- **Качество и локализация (#52)**: Динамическое переключение языка интерфейса (RU/EN) в чипе шапки (`HeaderChip`), боковой вкладке (`LensTab`) и панели статуса (`StatusPanel`) через `ctx.locale`.
|
|
194
|
-
- **Производительность (#52)**: Адаптивный поллинг в `HeaderChip` с паузой при неактивной вкладке браузера (`document.visibilityState`) и учащённым опросом (4 сек) только при открытом поповере.
|
|
195
|
-
- **Стабильность (#52)**: Атомарное сохранение конфигурации в карточке настроек (`scope.patch` / `scope.setAll`) без риска частичной записи.
|
|
196
|
-
|
|
197
|
-
### Визуальный стиль и отказоустойчивость UI (v0.1.16+)
|
|
198
|
-
|
|
199
|
-
Context Lens приведен к единому стандарту оформления `dsh-clinebot`:
|
|
200
|
-
- **Нативные токены**: 100% совместимость со светлой и тёмной темами DSH через токены `--dsw-alias-*`.
|
|
201
|
-
- **Изоляция сбоев интерфейса**: Компоненты (`PluginCard`, `LensTab`, `StatusPanel`) обёрнуты в `ErrorBoundary` с кнопкой быстрого повтора («Retry»).
|
|
202
|
-
- **Реактивные настройки**: Автоматическое обновление через `scope.subscribe()` и мгновенное чтение через `scope.getSnapshot()`.
|
|
203
|
-
- **Наглядная телеметрия**: Компактные карточки метрик сэкономленных токенов, процента оптимизации и шкалы сессионного бюджета.
|
package/README.zh.md
CHANGED
|
@@ -36,11 +36,15 @@
|
|
|
36
36
|
|
|
37
37
|
---
|
|
38
38
|
|
|
39
|
-
## ⚡
|
|
39
|
+
## ⚡ 插件概览与问题背景
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
超长代码库上下文与冗长的构建/测试输出流会迅速填满大语言模型的上下文窗口,造成严重的 Token 资金浪费、显著增加推理延迟,并导致智能体注意力涣散与幻觉。
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
**`dsh-context-lens`** 提供了完整的上下文优化管线:
|
|
44
|
+
1. **工作区焦点聚焦 (`context_lens_focus`)**:对当前正在编辑的核心文件保持 100% 完整源码,将其余依赖代码库自动精简为轻量级 AST 骨架。
|
|
45
|
+
2. **多语言 AST 结构骨架化**:支持 TypeScript, JavaScript, Python, Go, C/C++, Rust, SQL DDL,完整保留类型、类结构与函数签名,将源码体积削减 **70–85%**。
|
|
46
|
+
3. **启发式测试日志压缩**:自动消除测试通过的冗余输出,精准萃取关键报错堆栈、断言差异与失败上下文,将日志体积削减高达 **90%**。
|
|
47
|
+
4. **会话 Token 遥测与预算守卫**:实时精确统计压缩前后节省的 Token 数量,支持自定义预算水位预警并在 DSH 界面直观显示。
|
|
44
48
|
|
|
45
49
|
```mermaid
|
|
46
50
|
graph LR
|
|
@@ -70,24 +74,105 @@ graph LR
|
|
|
70
74
|
|
|
71
75
|
---
|
|
72
76
|
|
|
73
|
-
##
|
|
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
|
+
* **定向错误萃取**:精准识别报错摘要、异常调用堆栈、断言匹配差异 (`Expected ... Received ...`) 与错误上下文窗口。
|
|
88
|
+
* **3 种压缩模式**:
|
|
89
|
+
- `raw`:过滤基础噪音行,保留总体执行日志。
|
|
90
|
+
- `balanced`:在压缩率与报错上下文之间保持平衡(默认推荐)。
|
|
91
|
+
- `aggressive`:严格仅保留报错行与堆栈帧。
|
|
92
|
+
* **ANSI 码清理**:预先剥离终端控制字符与彩色 ANSI 转义序列。
|
|
93
|
+
|
|
94
|
+
### 3. 🎯 会话文件焦点范围管理 (`context_lens_focus`)
|
|
95
|
+
* 允许针对当前任务设定一组活跃聚焦文件或目录。
|
|
96
|
+
* 焦点文件保持完整代码,未聚焦文件自动折叠为 AST 结构骨架。
|
|
97
|
+
* 焦点状态在会话级别严格隔离 (`sessionId`),可通过 UI 或 API 一键清除。
|
|
98
|
+
|
|
99
|
+
### 4. 📊 Token 消耗遥测与预算守卫
|
|
100
|
+
* 采用精准分词估算逻辑,实时计算压缩前后的 Token 变化。
|
|
101
|
+
* 统计累计节省 Token、压缩比率与会话预算百分比。
|
|
102
|
+
* 支持设置预警阈值 (`budgetAlertPercent`),预算临界时动态发出提示。
|
|
103
|
+
|
|
104
|
+
### 5. 🖥️ 视觉界面与双侧边栏原生集成
|
|
105
|
+
完全遵循 `.cl-*` 设计标准与 DeepSeek Harness `--dsw-alias-*` 主题变量系统:
|
|
106
|
+
* **对话顶栏微件**:挂载于 `conversation.session.header.utilities` 槽位(`order: 7`)。常态化显示效率徽章(`◐ Lens`, `◐ <N>%` 或 `⚠` 警告),点击展开包含详细数据与操作记录的交互式 Popover。
|
|
107
|
+
* **双侧边栏深度兼容**:同时支持 DSH 原生右侧边栏(`ctx.sidebarRightTabs` + `sidebar.right.pane.tab`)及旧版 `dsh-better-sidebar`,独立 ID 互不冲突。
|
|
108
|
+
* **ErrorBoundary 容灾屏障**:所有视图组件(`PluginCard`, `LensTab`, `StatusPanel`)均包裹在独立 React 错误边界内,避免页面崩溃。
|
|
109
|
+
* **一键平滑升级**:设置卡片实时检测 npm 最新版本并支持免命令行一键升级。
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## 🛠️ 智能体工具参考 (5 Tools)
|
|
114
|
+
|
|
115
|
+
所有工具严格遵循 DeepSeek Harness 核心工具契约规范,`output.render` 均返回规范的 `ContentBlock[]` 数组 (`[{ type: 'text', text: ... }]`),保障底层会话日志投影 100% 稳定可靠。
|
|
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` | 获取当前会话的累计 Token 节省统计、历史记录与预算状态 |
|
|
123
|
+
| `context_lens_reset` | `sessionId?: string` | 开启新任务时重置 Token 追踪计数器与历史记录 |
|
|
124
|
+
|
|
125
|
+
---
|
|
126
|
+
|
|
127
|
+
## 🔌 HTTP 接口参考
|
|
128
|
+
|
|
129
|
+
| 路由 | 请求方法 | 权限与安全策略 | 功能说明 |
|
|
130
|
+
|---|---|---|---|
|
|
131
|
+
| `/dsh-context-lens/status` | `GET` | 开放只读 | 查询会话 Token 节省数据、当前焦点路径与操作历史 |
|
|
132
|
+
| `/dsh-context-lens/clear-focus` | `POST` | 仅限环回 (Loopback) / 同源 | 清除指定会话的焦点路径设置(GET 请求返回 405) |
|
|
133
|
+
| `/dsh-context-lens/compress-preview` | `POST` | 仅限环回 / 同源 | 日志压缩预览(限制请求体 256KB,`maxLines` 范围 1–5000) |
|
|
134
|
+
| `/api/dsh-context-lens/update` | `GET`, `POST` | 环回 + 安全请求头校验 | 应用内一键升级模块,安全调用后台进行版本更新 |
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## ⚙️ 配置面板参考 (`settings.yaml`)
|
|
139
|
+
|
|
140
|
+
可通过 `settings.yaml` 或在 DSH Web 界面中的 **设置 → 插件设置 → Context Lens** 进行配置。
|
|
141
|
+
|
|
142
|
+
```yaml
|
|
143
|
+
dsh-context-lens:
|
|
144
|
+
compressionMode: balanced # 日志精简策略: 'raw', 'balanced', 或 'aggressive'
|
|
145
|
+
astSkeletonMaxDepth: 3 # AST 结构骨架最大解析深度 (1..10)
|
|
146
|
+
tokenSavingsTracking: true # 开启并展示实时 Token 节省监控
|
|
147
|
+
autoCompressThreshold: 4000 # 自动触发日志精简的字符长度阈值 (设为 0 禁用)
|
|
148
|
+
budgetLimit: 100000 # 单会话 Token 预算上限限额
|
|
149
|
+
budgetAlertPercent: 90 # 触发预警徽章的预算百分比水位 (50..99)
|
|
150
|
+
autoCollapse: true # 预算临界时在界面显示警告徽章
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
| 参数项 | 类型 | 默认值 | 功能说明 |
|
|
154
|
+
|---|---|---|---|
|
|
155
|
+
| `compressionMode` | `string` | `balanced` | 默认日志压缩激进度 (`raw`, `balanced`, `aggressive`) |
|
|
156
|
+
| `astSkeletonMaxDepth` | `number` | `3` | AST 骨架提取最大深度层级(1 至 10) |
|
|
157
|
+
| `tokenSavingsTracking` | `boolean` | `true` | 实时追踪压缩前后的 Token 节省数据 |
|
|
158
|
+
| `autoCompressThreshold` | `number` | `4000` | 超过该字符长度时自动执行日志压缩 |
|
|
159
|
+
| `budgetLimit` | `number` | `100000` | 单会话分配的最大 Token 预算上限 |
|
|
160
|
+
| `budgetAlertPercent` | `number` | `90` | 触发低预算预警的百分比阈值(50 至 99) |
|
|
161
|
+
| `autoCollapse` | `boolean` | `true` | 在设置卡片与顶栏徽章中显示预算告急提示 |
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
## 📦 快速安装
|
|
74
166
|
|
|
75
167
|
```bash
|
|
76
168
|
dsh plugin --profile web add @goodandready/dsh-context-lens
|
|
77
169
|
```
|
|
78
170
|
|
|
171
|
+
> [!TIP]
|
|
172
|
+
> 安装完成后,请刷新 DSH Web 界面或重启服务 (`systemctl --user restart dsh-web`) 以激活上下文压缩工具。
|
|
173
|
+
|
|
79
174
|
---
|
|
80
175
|
|
|
81
176
|
## 📄 开源协议
|
|
82
177
|
|
|
83
178
|
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
## v0.1.18 更新日志
|
|
87
|
-
|
|
88
|
-
- **严重问题修复 (#71, GH #2)**:严格遵循 DeepSeek Harness 核心工具返回规范,将 `output.render` 调整为返回 `ContentBlock[]` 数组 (`[{ type: 'text', text: ... }]`)。彻底解决第三方工具调用后会话写入非数组导致 `@deepseek-ai/dsh-llm` 报错 `TypeError: content.some is not a function` 并永久损坏会话的严重缺陷。
|
|
89
|
-
- **安全性与稳定性加固 (#62, #63, #70)**:全面加固 HTTP 接口 (`/clear-focus`, `/compress-preview`, `/status`):写操作严格要求 `POST` 请求,校验环回与同源请求来源,限制请求体上限为 256KB(超限返回 413),限制 `maxLines` 范围为 1–5000,无效 session 参数返回规范 400 错误。
|
|
90
|
-
- **一键在线更新支持 (#61)**:引入标准更新管理模块 (`lib/updater.js`) 及 `/api/dsh-context-lens/update` 接口,在设置卡片中增加版本检查与一键更新按钮。
|
|
91
|
-
- **设置域与生命周期规范 (#64, #66)**:客户端显式声明 `settingsScope` 依赖并移除对外部 `lanSettings` 的隐式依赖,将设置注册与多语言注册统一纳入 `ctx.effect` 生命周期清理管理。
|
|
92
|
-
- **UI 与主题深度适配 (#67, #68)**:将折叠箭头升级为 14x14 矢量 SVG 并支持平滑 180° 旋转动画,全面替换硬编码色值,使用 `--dsw-alias-*` 主题变量完美适配明暗主题。
|
|
93
|
-
- **仓库代码纯净性 (#65)**:从 Git 跟踪树中彻底剥离内部计划文件 (`AGENTS.md`, `index.md`, `docs/plans/`),并更新 `.gitignore` 防护清单。
|
package/lib/client.js
CHANGED
|
@@ -319,7 +319,9 @@ window.__ModuleLoader__.load({
|
|
|
319
319
|
const snap = ctx.locale.getSnapshot();
|
|
320
320
|
if (snap && snap.active && snap.active.startsWith('zh')) return zh;
|
|
321
321
|
}
|
|
322
|
-
} catch (err) {
|
|
322
|
+
} catch (err) {
|
|
323
|
+
/* intentional fallback: default to english on snapshot error */
|
|
324
|
+
}
|
|
323
325
|
return en;
|
|
324
326
|
}
|
|
325
327
|
|
|
@@ -653,7 +655,9 @@ window.__ModuleLoader__.load({
|
|
|
653
655
|
unsub = scope.subscribe(() => {
|
|
654
656
|
if (!cancelled) loadSnap();
|
|
655
657
|
});
|
|
656
|
-
} catch (_err) {
|
|
658
|
+
} catch (_err) {
|
|
659
|
+
console.warn('[dsh-context-lens] scope subscribe failed', _err && _err.message || _err);
|
|
660
|
+
}
|
|
657
661
|
}
|
|
658
662
|
|
|
659
663
|
return () => {
|
|
@@ -1052,17 +1056,28 @@ window.__ModuleLoader__.load({
|
|
|
1052
1056
|
const ok = ctx.slots.inject("sidebar.right.pane.tab", registerPaneTab);
|
|
1053
1057
|
if (!ok) console.warn("[dsh-context-lens] sidebar.right.pane.tab inject returned false");
|
|
1054
1058
|
} catch (e) {
|
|
1055
|
-
|
|
1059
|
+
console.warn("[dsh-context-lens] sidebar.right.pane.tab inject failed, falling back to direct register", e && e.message || e);
|
|
1060
|
+
try {
|
|
1061
|
+
registerPaneTab();
|
|
1062
|
+
} catch (e2) {
|
|
1063
|
+
console.warn("[dsh-context-lens] registerPaneTab direct register fallback failed", e2 && e2.message || e2);
|
|
1064
|
+
}
|
|
1056
1065
|
}
|
|
1057
1066
|
} else {
|
|
1058
|
-
try {
|
|
1067
|
+
try {
|
|
1068
|
+
registerPaneTab();
|
|
1069
|
+
} catch (err) {
|
|
1070
|
+
console.warn("[dsh-context-lens] registerPaneTab direct register failed", err && err.message || err);
|
|
1071
|
+
}
|
|
1059
1072
|
}
|
|
1060
1073
|
}
|
|
1061
1074
|
} catch (e) {
|
|
1062
1075
|
console.warn("[dsh-context-lens] native sidebar registration failed", e && e.message || e);
|
|
1063
1076
|
}
|
|
1064
1077
|
});
|
|
1065
|
-
} catch (err) {
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
console.warn("[dsh-context-lens] native sidebar inject failed", err && err.message || err);
|
|
1080
|
+
}
|
|
1066
1081
|
}
|
|
1067
1082
|
|
|
1068
1083
|
if (typeof ctx.inject === 'function') {
|
|
@@ -1087,7 +1102,9 @@ window.__ModuleLoader__.load({
|
|
|
1087
1102
|
console.warn('[dsh-context-lens] betterSidebar registerTab failed', e && e.message || e);
|
|
1088
1103
|
}
|
|
1089
1104
|
});
|
|
1090
|
-
} catch (err) {
|
|
1105
|
+
} catch (err) {
|
|
1106
|
+
console.warn('[dsh-context-lens] betterSidebar inject failed', err && err.message || err);
|
|
1107
|
+
}
|
|
1091
1108
|
}
|
|
1092
1109
|
|
|
1093
1110
|
if (ctx.slots) {
|
|
@@ -1107,11 +1124,19 @@ window.__ModuleLoader__.load({
|
|
|
1107
1124
|
try {
|
|
1108
1125
|
ctx.slots.inject('conversation.session.header.utilities', headerChipRegister);
|
|
1109
1126
|
} catch (e) {
|
|
1110
|
-
console.warn('[dsh-context-lens] utilities inject failed', e && e.message || e);
|
|
1111
|
-
try {
|
|
1127
|
+
console.warn('[dsh-context-lens] utilities inject failed, falling back to direct register', e && e.message || e);
|
|
1128
|
+
try {
|
|
1129
|
+
headerChipRegister();
|
|
1130
|
+
} catch (e2) {
|
|
1131
|
+
console.warn('[dsh-context-lens] headerChipRegister fallback failed', e2 && e2.message || e2);
|
|
1132
|
+
}
|
|
1112
1133
|
}
|
|
1113
1134
|
} else {
|
|
1114
|
-
try {
|
|
1135
|
+
try {
|
|
1136
|
+
headerChipRegister();
|
|
1137
|
+
} catch (err) {
|
|
1138
|
+
console.warn('[dsh-context-lens] headerChipRegister direct register failed', err && err.message || err);
|
|
1139
|
+
}
|
|
1115
1140
|
}
|
|
1116
1141
|
}
|
|
1117
1142
|
};
|
package/lib/tokens/tracker.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-context-lens",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.19",
|
|
4
4
|
"description": "DSH plugin for AST context compression, test log filtering, and token budget guard",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
"README.md",
|
|
17
17
|
"README.zh.md",
|
|
18
18
|
"README.ru.md",
|
|
19
|
-
"LICENSE"
|
|
19
|
+
"LICENSE",
|
|
20
|
+
"CHANGELOG.md"
|
|
20
21
|
],
|
|
21
22
|
"scripts": {
|
|
22
23
|
"test": "node --test test/*.test.mjs"
|