@goodandready/dsh-clinebot 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,27 @@ All notable changes to `@goodandready/dsh-clinebot` will be documented in this f
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.3.0] - 2026-09-05
9
+
10
+ ### Added
11
+ - **Dynamic Subscription Models Sync**: Added integration with official ClinePass plan endpoint (`GET /api/v1/users/me/plan` -> `features.included`). Models available under the user's subscription plan are parsed dynamically, mapped with fallback IDs, and synced directly to DSH provider configuration without requiring manual updates.
12
+ - **Strict Real Provider Catalog**: Replaced manual custom model entry forms with one-click dynamic synchronization (`POST /dsh-clinebot/models/sync` and UI sync button), eliminating out-of-sync manual model entries and guaranteeing 100% provider alignment.
13
+ - **Rolling Window Quota Exhaustion Warnings**: Added real-time threshold detection and prominent UI warning banners when the 5-hour rolling limit reaches 80% (warning, amber) and 95% (exhausted, red), complete with dynamic countdowns to reset.
14
+ - **Session Metrics & Usage Tracking**: Added in-memory session telemetry displaying total requests executed, estimated prompt/completion/total tokens, last roundtrip latency, and timestamp of the last request in a dedicated UI metrics card.
15
+ - **Extended `/cline` Slash-Command**: Slash-command now outputs quota warning banners and active session metrics (total calls, tokens, last request) alongside rolling window progress bars.
16
+ - **Canonical Deployment Script**: Added `deploy.sh` script conforming to dhsplugins standard for automated profile installation and service restart (Issue #3).
17
+
18
+ ### Fixed
19
+ - **Slot Registration Smell**: Fixed dual unconditional slot registration: plugin card now registers primarily in `settings.plugin.item`, with graceful fallback to `settings.section` if not declared (Issue #5).
20
+ - **Settings Snapshot Status & Reactivity**: Integrated reactive `ctx.settingsScope` binding with `useSyncExternalStore`, checking snapshot status (`ready`, `loading`, `unavailable`) and propagating edits via `scope.set()` (Issue #6).
21
+ - **Slot Locales**: Attached `locale: NS` to slot options and registered localized dictionaries with `ctx.locale.register()` (Issue #7).
22
+ - **Button Hover State**: Fixed CSS button hover visibility regression on primary action buttons.
23
+
24
+ ## [0.2.1] - 2026-09-05
25
+
26
+ ### Fixed
27
+ - **Client Bundle Inject Compatibility**: Resolved client-side inject bundle loading for DSH web profile runtime.
28
+
8
29
  ## [0.2.0] - 2026-09-04
9
30
 
10
31
  ### Added
package/README.md CHANGED
@@ -13,13 +13,13 @@
13
13
 
14
14
  <!-- Author Showcase Link -->
15
15
  <p align="center">
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 Projects"></a>
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="GoodAndReady Showcase"></a>
17
17
  </p>
18
18
 
19
19
  <p align="center">
20
20
  <a href="README.md"><b>🇬🇧 English</b></a> •
21
- <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
22
- <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
21
+ <a href="docs/README.ru.md"><b>🇷🇺 Русский</b></a> •
22
+ <a href="docs/README.zh.md"><b>🇨🇳 中文说明</b></a>
23
23
  </p>
24
24
 
25
25
  </div>
@@ -38,11 +38,13 @@ Integrating ClinePass into DeepSeek Harness (DSH) natively poses key challenges:
38
38
 
39
39
  **`@goodandready/dsh-clinebot`** provides a complete solution:
40
40
  * 🖥️ **Dedicated Settings Page**: Full-width page in DSH Settings (`Settings → ClineBot`).
41
+ * 🔄 **Dynamic Subscription Model Sync**: Automatically pulls real models included in your ClinePass plan directly from `GET /api/v1/users/me/plan` with one-click DSH provider sync.
42
+ * ⚠️ **Quota Exhaustion Alerts**: Real-time visual warning banners when 5-hour rolling limit reaches 80% (warning) and 95% (exhausted), complete with countdown to reset.
43
+ * 📈 **Session Metrics Telemetry**: Live dashboard tracking request counts, token consumption estimates, latency, and last-request timestamp.
41
44
  * 📊 **Live Quota Dashboard**: Visual progress bars for 5-hour rolling limits and weekly windows from the official `GET /users/me/plan/usage-limits` API.
42
45
  * 🔑 **In-UI Key Storage**: Paste your API key directly in the UI; it is saved securely via `ctx.credentials.set()` into `~/.dsh/.credentials.yaml`.
43
46
  * 🎯 **Model Picker Management**: Granular checkboxes to choose which models appear in the chat picker.
44
- * ➕ **Add Custom Models**: Add newly released ClinePass models directly from the UI without waiting for plugin updates.
45
- * 💬 **Slash-Command `/cline`**: Check quota, limits, latency, and active model directly from the DSH chat console.
47
+ * 💬 **Slash-Command `/cline`**: Check quota, limits, warnings, session metrics, latency, and active model directly from the DSH chat console.
46
48
 
47
49
  ---
48
50
 
@@ -52,15 +54,16 @@ Integrating ClinePass into DeepSeek Harness (DSH) natively poses key challenges:
52
54
  graph LR
53
55
  subgraph UI [DSH Web Interface]
54
56
  Page["Dedicated Page (Settings -> ClineBot)"]
55
- QuotaBar["5-Hour & Weekly Progress Bars"]
57
+ QuotaBar["5-Hour & Weekly Progress Bars & Warning Banner"]
56
58
  KeyInput["Direct Key Paste & Save"]
57
- ModelPick["Model Picker Controls & Custom Models"]
59
+ ModelPick["Dynamic Model Sync & Picker Controls"]
60
+ StatsCard["Session Metrics Telemetry"]
58
61
  end
59
62
 
60
63
  subgraph PluginHost [dsh-clinebot Host Runtime]
61
64
  HttpEndpoints["API: /api/plugins/dsh-clinebot/*"]
62
65
  ClientCore["lib/cline-client.js"]
63
- ModelCatalog["lib/models.js (Curated + Custom)"]
66
+ ModelCatalog["lib/models.js (Curated + Dynamic Plan)"]
64
67
  SlashCmd["Command: /cline"]
65
68
  end
66
69
 
@@ -72,17 +75,19 @@ graph LR
72
75
  subgraph Upstream [Cline Cloud]
73
76
  ClinePass["api.cline.bot/api/v1/chat/completions"]
74
77
  ClineQuota["api.cline.bot/api/v1/users/me/plan/usage-limits"]
78
+ ClinePlan["api.cline.bot/api/v1/users/me/plan"]
75
79
  end
76
80
 
77
81
  Page -->|GET /status & /usage| HttpEndpoints
78
82
  KeyInput -->|POST /save-key| HttpEndpoints
79
- ModelPick -->|POST /register & /models| HttpEndpoints
83
+ ModelPick -->|POST /models/sync| HttpEndpoints
80
84
  HttpEndpoints --> Credentials
81
85
  HttpEndpoints --> ClientCore
82
86
  ClientCore --> ModelCatalog
83
87
  HttpEndpoints -->|Atomic Mutate| PiAi
84
88
  ClientCore -->|Chat| ClinePass
85
89
  ClientCore -->|Usage Limits| ClineQuota
90
+ ClientCore -->|Plan Features| ClinePlan
86
91
  ```
87
92
 
88
93
  ---
@@ -90,16 +95,17 @@ graph LR
90
95
  ## ✨ Features & Module Breakdown
91
96
 
92
97
  * **`lib/models.js`**:
93
- Manages the curated catalog (11 built-in models) and user-added custom models (`getAllModels`, `validateCustomModel`).
98
+ Manages the curated catalog (11 built-in models) and dynamically parses subscription plan models (`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`).
94
99
  * **`lib/cline-client.js`**:
95
- * `fetchUsageLimits`: queries `GET /users/me/plan/usage-limits` and `GET /users/me` with in-memory caching.
100
+ * `fetchUsageLimits`: queries `GET /users/me/plan/usage-limits`, `GET /users/me/plan`, and `GET /users/me` with in-memory caching.
101
+ * `sessionStats` / `recordSessionRequest`: in-memory telemetry recording requests count, tokens, latency, and timestamps.
96
102
  * `saveCredentialKey`: writes credentials directly into `~/.dsh/.credentials.yaml`.
97
- * `smokeChat`: tests latency via non-streaming ping.
103
+ * `smokeChat`: tests latency via non-streaming ping and updates session metrics.
98
104
  * `buildPiAiProvider`: builds the DSH `llm-pi-ai` structure (`api: 'openai-completions'`).
99
105
  * **`lib/index.js`**:
100
- Cordis service module managing routes, credentials, and registering the `/cline` slash command.
106
+ Cordis service module managing routes (including `POST /dsh-clinebot/models/sync`), quota warnings threshold evaluation, credentials, and registering the `/cline` slash command.
101
107
  * **`lib/client.js`**:
102
- Full-featured dedicated Settings section (`settings.section`, order 28) and plugin accordion (`settings.plugin.item`).
108
+ Full-featured dedicated Settings section (`settings.section`, order 28) with live quota bars, exhaustion warning banner, session metrics telemetry card, one-click plan sync button, and plugin accordion (`settings.plugin.item`).
103
109
 
104
110
  ---
105
111
 
@@ -109,27 +115,36 @@ graph LR
109
115
  dsh plugin --profile web add @goodandready/dsh-clinebot
110
116
  ```
111
117
 
118
+ Restart your DeepSeek Harness instance and refresh the browser.
119
+
112
120
  ---
113
121
 
114
122
  ## 💬 Slash-Command `/cline`
115
123
 
116
- From any DSH chat session, type `/cline` to inspect quota:
124
+ From any DSH chat session, type `/cline` to inspect quota, warning alerts, and session telemetry:
117
125
 
118
126
  ```text
119
127
  ### 🤖 ClinePass Status (ClinePass ($9.99/mo))
120
- * Пинг хоста: ✅ 210 мс
121
- * Активный ключ: CLINEBOT_API_KEY (credentials)
122
- * Модель по умолчанию: `cline-pass/deepseek-v4-flash`
123
-
124
- ⏱ 5-часовое окно: [████░░░░░░] 42% (сброс: 18:00)
125
- 📅 Недельное окно: [██████░░░░] 60% (сброс: 08.09)
126
- * Аккаунт: `developer@example.com`
128
+ * Latency: ✅ 210 ms
129
+ * Active Key: CLINEBOT_API_KEY (credentials)
130
+ * Default Model: `cline-pass/deepseek-v4-flash`
131
+
132
+ ⏱ 5-Hour Window: [████░░░░░░] 42% (resets: 18:00)
133
+ 📅 Weekly Window: [██████░░░░] 60% (resets: Sep 8)
134
+ * Account: `developer@example.com`
135
+
136
+ 📈 Session Metrics:
137
+ * Requests: 14 calls
138
+ * Tokens: ~8,450 (Prompt: 6,100 | Completion: 2,350)
139
+ * Last Latency: 210 ms
127
140
  ```
128
141
 
129
142
  ---
130
143
 
131
144
  ## ⚙️ Configuration Reference (`settings.yaml`)
132
145
 
146
+ Configure options in `settings.yaml` or directly inside the Web UI:
147
+
133
148
  ```yaml
134
149
  dsh-clinebot:
135
150
  enabled: true
@@ -143,7 +158,30 @@ dsh-clinebot:
143
158
  - cline-pass/deepseek-v4-pro
144
159
  - cline-pass/kimi-k3
145
160
  - cline-pass/qwen3.7-max
146
- customModels: []
161
+ dynamicModels: []
162
+ ```
163
+
164
+ ### Configuration Parameters
165
+
166
+ | Parameter | Type | Default | Description |
167
+ |:---|:---|:---|:---|
168
+ | `enabled` | `boolean` | `true` | Enable or disable the ClineBot provider bridge |
169
+ | `baseUrl` | `string` | `"https://api.cline.bot/api/v1"` | ClinePass OpenAI-compatible base URL |
170
+ | `apiKeyEnv` | `string` | `"CLINEBOT_API_KEY"` | Environment variable / credentials key name |
171
+ | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | Default selected model ID |
172
+ | `timeoutMs` | `number` | `15000` | HTTP request timeout in milliseconds |
173
+ | `smokeTimeoutMs` | `number` | `25000` | Smoke test latency ping timeout |
174
+ | `enabledModels` | `array` | `[...]` | List of models exposed in the DSH chat picker |
175
+ | `dynamicModels` | `array` | `[]` | Dynamic models automatically synced from the official plan |
176
+
177
+ ---
178
+
179
+ ## 🧪 Testing
180
+
181
+ Run the automated test suite:
182
+
183
+ ```bash
184
+ npm test
147
185
  ```
148
186
 
149
187
  ---
@@ -0,0 +1,186 @@
1
+ # 📦 @goodandready/dsh-clinebot
2
+
3
+ <div align="center">
4
+
5
+ <h3>Нативное подключение провайдера ClineBot / ClinePass для DeepSeek Harness</h3>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/@goodandready/dsh-clinebot"><img src="https://img.shields.io/npm/v/@goodandready/dsh-clinebot.svg?style=for-the-badge&color=6366f1&labelColor=1e1b4b" alt="npm version"></a>
9
+ <a href="../LICENSE"><img src="https://img.shields.io/github/license/GooDAnDReaDY/dsh-clinebot.svg?style=for-the-badge&color=10b981&labelColor=064e3b" alt="license"></a>
10
+ <a href="https://github.com/topics/dsh-plugin"><img src="https://img.shields.io/badge/DSH-Plugin-8b5cf6.svg?style=for-the-badge&labelColor=2e1065" alt="DSH Plugin"></a>
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
+ </p>
13
+
14
+ <!-- Обязательная кнопка перехода на витрину всех проектов -->
15
+ <p align="center">
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
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="../README.md"><b>🇬🇧 English</b></a> •
21
+ <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
22
+ <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
23
+ </p>
24
+
25
+ </div>
26
+
27
+ ---
28
+
29
+ ## ⚡ Обзор и решаемая проблема
30
+
31
+ **ClinePass** (`https://cline.bot`) — сервис единой фиксированной подписки (\$9.99/мес), предоставляющий разработчикам повышенные лимиты (в 2–5 раз выше стандартных) на передовые open-weights модели программирования и рассуждений через единый OpenAI-совместимый интерфейс (`https://api.cline.bot/api/v1`).
32
+
33
+ Интеграция ClinePass в DeepSeek Harness (DSH) напрямую сопряжена со следующими сложностями:
34
+ 1. **Отсутствие эндпоинта `/v1/models`**: запрос `GET /v1/models` к `api.cline.bot` возвращает `404 Not Found`, из-за чего динамический поиск моделей в DSH падает или оставляет список пустым.
35
+ 2. **Специфический формат идентификаторов**: моделям требуется обязательный префикс `cline-pass/` (например, `cline-pass/deepseek-v4-flash`, `cline-pass/kimi-k3`).
36
+ 3. **Отслеживание лимитов**: 5-часовые и недельные скользящие окна расхода токенов требуют прозрачной визуализации в интерфейсе.
37
+ 4. **Безопасность ключей**: хранение API-токенов в открытых конфигурациях небезопасно.
38
+
39
+ Плагин **`@goodandready/dsh-clinebot`** решает эти задачи «из коробки»:
40
+ * 🖥️ **Отдельная страница в Настройках**: собственная полноэкранная страница в меню Настроек DSH (`Настройки → ClineBot`).
41
+ * 🔄 **Динамическая синхронизация моделей подписки**: автоматическое получение реального списка моделей из `GET /api/v1/users/me/plan` и мгновенное обновление провайдера DSH в один клик.
42
+ * ⚠️ **Предупреждения об исчерпании квоты**: баннеры предупреждения при достижении 80% (внимание) и 95% (исчерпано) 5-часового лимита с таймером сброса.
43
+ * 📈 **Метрики сессии**: учет количества запросов, расчетных токенов (Prompt / Completion), задержки и времени последнего вызова.
44
+ * 📊 **Дашборд лимитов подписки (Usage)**: наглядные прогресс-бары расхода 5-часового и недельного скользящего окна из официального API `GET /users/me/plan/usage-limits`.
45
+ * 🔑 **Сохранение ключа прямо из UI**: поле ввода ключа с маскировкой; сохранение напрямую в системный сервис `credentials` (`~/.dsh/.credentials.yaml`) без ручной правки файлов на сервере.
46
+ * 🎯 **Управление моделями в пикере**: включение/выключение отображения конкретных моделей в диалогах чата.
47
+ * 💬 **Слэш-команда `/cline` в чате**: просмотр остатка квот, предупреждений, статистики сессии, задержки и активной модели прямо из чата.
48
+
49
+ ---
50
+
51
+ ## 🏛️ Архитектура
52
+
53
+ ```mermaid
54
+ graph LR
55
+ subgraph UI [Интерфейс DSH]
56
+ Page["Отдельная страница (Настройки -> ClineBot)"]
57
+ QuotaBar["Прогресс-бары 5h и недельного лимита + Баннер предупреждений"]
58
+ KeyInput["Ввод и сохранение API-ключа"]
59
+ ModelPick["Динамическая синхронизация моделей и пикер"]
60
+ StatsCard["Метрики и статистика текущей сессии"]
61
+ end
62
+
63
+ subgraph PluginHost [Хост-часть dsh-clinebot]
64
+ HttpEndpoints["API: /api/plugins/dsh-clinebot/*"]
65
+ ClientCore["lib/cline-client.js"]
66
+ ModelCatalog["lib/models.js (Встроенные + Динамические из плана)"]
67
+ SlashCmd["Слэш-команда: /cline"]
68
+ end
69
+
70
+ subgraph DSHCore [Сервисы DSH]
71
+ Credentials["Сервис credentials (~/.dsh/.credentials.yaml)"]
72
+ PiAi["Настройки: llm-pi-ai.providers.clinebot"]
73
+ end
74
+
75
+ subgraph Upstream [Сервер Cline]
76
+ ClinePass["api.cline.bot/api/v1/chat/completions"]
77
+ ClineQuota["api.cline.bot/api/v1/users/me/plan/usage-limits"]
78
+ ClinePlan["api.cline.bot/api/v1/users/me/plan"]
79
+ end
80
+
81
+ Page -->|GET /status & /usage| HttpEndpoints
82
+ KeyInput -->|POST /save-key| HttpEndpoints
83
+ ModelPick -->|POST /models/sync| HttpEndpoints
84
+ HttpEndpoints --> Credentials
85
+ HttpEndpoints --> ClientCore
86
+ ClientCore --> ModelCatalog
87
+ HttpEndpoints -->|Атомарная мутация| PiAi
88
+ ClientCore -->|Чат| ClinePass
89
+ ClientCore -->|Квоты| ClineQuota
90
+ ClientCore -->|Тарифный план| ClinePlan
91
+ ```
92
+
93
+ ---
94
+
95
+ ## ✨ Структура модулей и возможности
96
+
97
+ * **`lib/models.js`**: каталог встроенных моделей ClinePass (11 моделей) и парсер моделей подписки (`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`).
98
+ * **`lib/cline-client.js`**:
99
+ * `fetchUsageLimits`: параллельный опрос `GET /users/me/plan/usage-limits`, `GET /users/me/plan` и `GET /users/me` с кэшированием в памяти.
100
+ * `sessionStats` / `recordSessionRequest`: счетчики сессии (запросы, токены, задержка, время).
101
+ * `saveCredentialKey`: атомарная запись ключей в `~/.dsh/.credentials.yaml`.
102
+ * `smokeChat`: замер задержки и тестовый пинг с фиксацией статистики.
103
+ * `buildPiAiProvider`: генерация конфигурации провайдера для `llm-pi-ai` (`api: 'openai-completions'`).
104
+ * **`lib/index.js`**: сервис Cordis, регистрация системных маршрутов (включая `/dsh-clinebot/models/sync`), расчет порогов предупреждения квоты и слэш-команды `/cline`.
105
+ * **`lib/client.js`**: полнофункциональный раздел настроек (`settings.section`, order 28) с баннерами предупреждений, карточкой статистики сессии, кнопкой синхронизации моделей плана и аккордеоном плагина (`settings.plugin.item`).
106
+
107
+ ---
108
+
109
+ ## 📦 Установка
110
+
111
+ ```bash
112
+ dsh plugin --profile web add @goodandready/dsh-clinebot
113
+ ```
114
+
115
+ Перезапустите экземпляр DeepSeek Harness и обновите вкладку в браузере.
116
+
117
+ ---
118
+
119
+ ## 💬 Слэш-команда `/cline` в чате
120
+
121
+ В любой сессии чата введите команду `/cline` для проверки остатка лимитов, предупреждений и статистики:
122
+
123
+ ```text
124
+ ### 🤖 ClinePass Status (ClinePass ($9.99/mo))
125
+ * Пинг хоста: ✅ 210 мс
126
+ * Активный ключ: CLINEBOT_API_KEY (credentials)
127
+ * Модель по умолчанию: `cline-pass/deepseek-v4-flash`
128
+
129
+ ⏱ 5-часовое окно: [████░░░░░░] 42% (сброс: 18:00)
130
+ 📅 Недельное окно: [██████░░░░] 60% (сброс: 08.09)
131
+ * Аккаунт: `developer@example.com`
132
+
133
+ 📈 Статистика текущей сессии:
134
+ * Запросов: 14 вызовов
135
+ * Токены: ~8,450 (Промпт: 6,100 | Ответ: 2,350)
136
+ * Задержка последнего ответа: 210 мс
137
+ ```
138
+
139
+ ---
140
+
141
+ ## ⚙️ Таблица конфигурации (`settings.yaml`)
142
+
143
+ ```yaml
144
+ dsh-clinebot:
145
+ enabled: true
146
+ baseUrl: https://api.cline.bot/api/v1
147
+ apiKeyEnv: CLINEBOT_API_KEY
148
+ defaultModel: cline-pass/deepseek-v4-flash
149
+ timeoutMs: 15000
150
+ smokeTimeoutMs: 25000
151
+ enabledModels:
152
+ - cline-pass/deepseek-v4-flash
153
+ - cline-pass/deepseek-v4-pro
154
+ - cline-pass/kimi-k3
155
+ - cline-pass/qwen3.7-max
156
+ dynamicModels: []
157
+ ```
158
+
159
+ ### Параметры конфигурации
160
+
161
+ | Параметр | Тип | По умолчанию | Описание |
162
+ |:---|:---|:---|:---|
163
+ | `enabled` | `boolean` | `true` | Включение моста провайдера ClineBot |
164
+ | `baseUrl` | `string` | `"https://api.cline.bot/api/v1"` | Базовый URL OpenAI-совместимого API ClinePass |
165
+ | `apiKeyEnv` | `string` | `"CLINEBOT_API_KEY"` | Имя переменной / ключа в хранилище credentials |
166
+ | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | Модель, выбираемая по умолчанию |
167
+ | `timeoutMs` | `number` | `15000` | Таймаут HTTP-запросов (мс) |
168
+ | `smokeTimeoutMs` | `number` | `25000` | Таймаут тестового пинга (мс) |
169
+ | `enabledModels` | `array` | `[...]` | Список моделей, активных в селекторе чата |
170
+ | `dynamicModels` | `array` | `[]` | Динамические модели, автоматически синхронизированные из тарифа |
171
+
172
+ ---
173
+
174
+ ## 🧪 Тестирование
175
+
176
+ Запуск автоматического набора тестов:
177
+
178
+ ```bash
179
+ npm test
180
+ ```
181
+
182
+ ---
183
+
184
+ ## 📄 Лицензия
185
+
186
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
@@ -0,0 +1,188 @@
1
+ # 📦 @goodandready/dsh-clinebot
2
+
3
+ <div align="center">
4
+
5
+ <h3>适用于 DeepSeek Harness 的 ClineBot / ClinePass 原生模型提供商伴侣插件</h3>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/@goodandready/dsh-clinebot"><img src="https://img.shields.io/npm/v/@goodandready/dsh-clinebot.svg?style=for-the-badge&color=6366f1&labelColor=1e1b4b" alt="npm version"></a>
9
+ <a href="../LICENSE"><img src="https://img.shields.io/github/license/GooDAnDReaDY/dsh-clinebot.svg?style=for-the-badge&color=10b981&labelColor=064e3b" alt="license"></a>
10
+ <a href="https://github.com/topics/dsh-plugin"><img src="https://img.shields.io/badge/DSH-Plugin-8b5cf6.svg?style=for-the-badge&labelColor=2e1065" alt="DSH Plugin"></a>
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
+ </p>
13
+
14
+ <!-- 作者所有项目展示页面链接 -->
15
+ <p align="center">
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
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="../README.md"><b>🇬🇧 English</b></a> •
21
+ <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
22
+ <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
23
+ </p>
24
+
25
+ </div>
26
+
27
+ ---
28
+
29
+ ## ⚡ 概述与解决的核心痛点
30
+
31
+ **ClinePass** (`https://cline.bot`) 是一项固定月费(\$9.99/月)的高性价比订阅服务,为开发者提供主流开源代码模型与推理模型 2–5 倍的高并发调用限额,统一通过 OpenAI 兼容接口 (`https://api.cline.bot/api/v1`) 提供服务。
32
+
33
+ 在将 ClinePass 接入 DeepSeek Harness (DSH) 时存在以下挑战:
34
+ 1. **缺失 `/v1/models` 接口**:`api.cline.bot` 的 `GET /v1/models` 会直接返回 `404 Not Found`,导致动态模型同步失败或模型列表为空。
35
+ 2. **专属模型前缀**:所有模型 ID 均需前缀 `cline-pass/`(如 `cline-pass/deepseek-v4-flash`, `cline-pass/kimi-k3`)。
36
+ 3. **用量额度监控**:5 小时滑动窗口与每周限额需要清晰直观的可视化进度监控。
37
+ 4. **安全凭据隔离**:禁止在明文配置中直接填写密钥。
38
+
39
+ **`@goodandready/dsh-clinebot`** 完美解决以上痛点:
40
+ * 🖥️ **专属设置大页**:在 DSH 设置中提供全宽独立页面(`设置 → ClineBot`)。
41
+ * 🔄 **订阅模型动态同步**:从官方 `GET /api/v1/users/me/plan` 自动提取真实包含模型,一键原子级同步至 DSH 提供商配置,无需等待插件更新。
42
+ * ⚠️ **额度耗尽实时预警**:当 5 小时滑动窗口达到 80%(警告黄色)和 95%(即将耗尽红色)时展示醒目预警横幅与重置倒计时。
43
+ * 📈 **会话统计与指标看板**:实时追踪请求调用次数、预估 Token(Prompt / Completion)、最近延迟及最后调用时间。
44
+ * 📊 **实时用量仪表盘**:调用官方 `GET /users/me/plan/usage-limits` API,实时渲染 5 小时与每周额度进度条及重置倒计时。
45
+ * 🔑 **界面直存密钥**:在 UI 中直接粘贴 API 密钥,通过 `ctx.credentials.set()` 自动安全保存至 `~/.dsh/.credentials.yaml`。
46
+ * 🎯 **模型选择器管理**:支持勾选开启/关闭特定模型在聊天选择器中的显示。
47
+ * 💬 **聊天斜杠指令 `/cline`**:在任意聊天框快速查询当前配额、预警横幅、会话指标统计、网络延迟与活跃模型。
48
+
49
+ ---
50
+
51
+ ## 🏛️ 架构设计
52
+
53
+ ```mermaid
54
+ graph LR
55
+ subgraph UI [DSH Web 前端界面]
56
+ Page["独立配置页 (设置 -> ClineBot)"]
57
+ QuotaBar["5小时与每周额度进度条 + 额度预警横幅"]
58
+ KeyInput["API 密钥直填与安全保存"]
59
+ ModelPick["模型动态同步与选择器管控"]
60
+ StatsCard["会话指标监控看板"]
61
+ end
62
+
63
+ subgraph PluginHost [dsh-clinebot 宿主运行环境]
64
+ HttpEndpoints["API 路由: /api/plugins/dsh-clinebot/*"]
65
+ ClientCore["lib/cline-client.js"]
66
+ ModelCatalog["lib/models.js (内置精选 + 动态订阅解析)"]
67
+ SlashCmd["斜杠指令: /cline"]
68
+ end
69
+
70
+ subgraph DSHCore [DSH 核心系统服务]
71
+ Credentials["凭据存储服务 (~/.dsh/.credentials.yaml)"]
72
+ PiAi["模型注册: llm-pi-ai.providers.clinebot"]
73
+ end
74
+
75
+ subgraph Upstream [Cline 官方云端]
76
+ ClinePass["api.cline.bot/api/v1/chat/completions"]
77
+ ClineQuota["api.cline.bot/api/v1/users/me/plan/usage-limits"]
78
+ ClinePlan["api.cline.bot/api/v1/users/me/plan"]
79
+ end
80
+
81
+ Page -->|GET /status & /usage| HttpEndpoints
82
+ KeyInput -->|POST /save-key| HttpEndpoints
83
+ ModelPick -->|POST /models/sync| HttpEndpoints
84
+ HttpEndpoints --> Credentials
85
+ HttpEndpoints --> ClientCore
86
+ ClientCore --> ModelCatalog
87
+ HttpEndpoints -->|原子级写入| PiAi
88
+ ClientCore -->|模型对话| ClinePass
89
+ ClientCore -->|额度查询| ClineQuota
90
+ ClientCore -->|套餐信息| ClinePlan
91
+ ```
92
+
93
+ ---
94
+
95
+ ## ✨ 核心模块与功能
96
+
97
+ * **`lib/models.js`**:管理 11 款官方精选内置模型以及套餐模型动态解析器(`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`)。
98
+ * **`lib/cline-client.js`**:
99
+ * `fetchUsageLimits`:高效并发轮询 `GET /users/me/plan/usage-limits`、`GET /users/me/plan` 与 `GET /users/me` 并进行内存缓存。
100
+ * `sessionStats` / `recordSessionRequest`:内存级会话度量记录器(请求次数、Token 估算、延迟、时间戳)。
101
+ * `saveCredentialKey`:将密钥安全写入 `~/.dsh/.credentials.yaml`。
102
+ * `smokeChat`:毫秒级网络探活与非流式延迟测试,并记录会话指标。
103
+ * `buildPiAiProvider`:构建 DSH `llm-pi-ai` 兼容的服务商定义 (`api: 'openai-completions'`)。
104
+ * **`lib/index.js`**:Cordis 插件主生命周期服务,注册后端 REST API 路由(含 `/dsh-clinebot/models/sync`)、额度预警计算与 `/cline` 聊天斜杠指令。
105
+ * **`lib/client.js`**:前端设置面板(`settings.section` 序号 28),内含预警横幅、会话指标卡片、一键模型同步按钮及插件折叠卡片。
106
+
107
+ ---
108
+
109
+ ## 📦 快速安装
110
+
111
+ 在 DeepSeek Harness Web 配置中安装:
112
+
113
+ ```bash
114
+ dsh plugin --profile web add @goodandready/dsh-clinebot
115
+ ```
116
+
117
+ 重启 DeepSeek Harness 实例并刷新浏览器页面。
118
+
119
+ ---
120
+
121
+ ## 💬 聊天斜杠指令 `/cline`
122
+
123
+ 在任何聊天会话中输入 `/cline` 即可即时检查配额、预警状态与会话指标:
124
+
125
+ ```text
126
+ ### 🤖 ClinePass Status (ClinePass ($9.99/mo))
127
+ * 响应延迟: ✅ 210 ms
128
+ * 活跃密钥: CLINEBOT_API_KEY (credentials)
129
+ * 默认模型: `cline-pass/deepseek-v4-flash`
130
+
131
+ ⏱ 5 小时窗口: [████░░░░░░] 42% (重置时间: 18:00)
132
+ 📅 每周窗口: [██████░░░░] 60% (重置时间: 09月08日)
133
+ * 绑定账号: `developer@example.com`
134
+
135
+ 📈 当前会话统计:
136
+ * 请求次数: 14 次
137
+ * Token 估算: ~8,450 (Prompt: 6,100 | Completion: 2,350)
138
+ * 最近延迟: 210 ms
139
+ ```
140
+
141
+ ---
142
+
143
+ ## ⚙️ 配置项参考 (`settings.yaml`)
144
+
145
+ ```yaml
146
+ dsh-clinebot:
147
+ enabled: true
148
+ baseUrl: https://api.cline.bot/api/v1
149
+ apiKeyEnv: CLINEBOT_API_KEY
150
+ defaultModel: cline-pass/deepseek-v4-flash
151
+ timeoutMs: 15000
152
+ smokeTimeoutMs: 25000
153
+ enabledModels:
154
+ - cline-pass/deepseek-v4-flash
155
+ - cline-pass/deepseek-v4-pro
156
+ - cline-pass/kimi-k3
157
+ - cline-pass/qwen3.7-max
158
+ dynamicModels: []
159
+ ```
160
+
161
+ ### 配置参数说明
162
+
163
+ | 参数项 | 类型 | 默认值 | 说明 |
164
+ |:---|:---|:---|:---|
165
+ | `enabled` | `boolean` | `true` | 是否启用 ClineBot 桥接插件 |
166
+ | `baseUrl` | `string` | `"https://api.cline.bot/api/v1"` | ClinePass OpenAI 兼容接口地址 |
167
+ | `apiKeyEnv` | `string` | `"CLINEBOT_API_KEY"` | 凭据管理系统中的密钥名称 |
168
+ | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | 默认选中的模型 ID |
169
+ | `timeoutMs` | `number` | `15000` | HTTP 请求超时时间(毫秒) |
170
+ | `smokeTimeoutMs` | `number` | `25000` | 探活测试超时时间(毫秒) |
171
+ | `enabledModels` | `array` | `[...]` | 允许在聊天下拉框中显示的可用模型列表 |
172
+ | `dynamicModels` | `array` | `[]` | 从官方套餐中自动同步的动态模型列表 |
173
+
174
+ ---
175
+
176
+ ## 🧪 测试
177
+
178
+ 运行自动化测试套件:
179
+
180
+ ```bash
181
+ npm test
182
+ ```
183
+
184
+ ---
185
+
186
+ ## 📄 许可证
187
+
188
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
@@ -0,0 +1,63 @@
1
+ # Design Contract: `@goodandready/dsh-clinebot`
2
+
3
+ ## 1. Executive Summary
4
+ `@goodandready/dsh-clinebot` is a companion plugin for DeepSeek Harness (DSH) enabling native integration of the **ClineBot / ClinePass** subscription provider. Because ClinePass is an OpenAI-compatible endpoint whose `GET /v1/models` returns `404 Not Found`, dynamic discovery is impossible. This plugin acts as the bridge: delivering a curated catalog of open-weights models, securely resolving credentials, exposing health and smoke tests, and mutating the DSH `llm-pi-ai` provider registry.
5
+
6
+ ## 2. Architecture & Cordis Lifecycles
7
+ The plugin consists of two runtime boundaries conforming to DSH authoring standards:
8
+
9
+ ### 2.1 Host Runtime (`lib/index.js`, `lib/cline-client.js`, `lib/models.js`, `lib/http.js`)
10
+ * **Cordis Service Registration**: Injects `['settings', 'webServer', 'credentials']`.
11
+ * **Credential Isolation**: The plugin NEVER stores plain API keys in its configuration. The setting `apiKeyEnv` holds the credential identifier (default: `CLINEBOT_API_KEY`), resolved via `ctx.credentials.resolve()` or `process.env`.
12
+ * **State Synchronization**: Mutates the core `llm-pi-ai` settings space (`op: 'set', path: ['providers', 'clinebot']`) when enabled or registered.
13
+
14
+ ### 2.2 Client Runtime (`lib/client.js`)
15
+ * Self-registering module via `window.__ModuleLoader__.load({ id: '@goodandready/dsh-clinebot', factory })`.
16
+ * Injects `['slots', 'locale', 'settingsScope']`.
17
+ * Slots into `settings.plugin.item` (primary) with `key: NS` and `locale: NS`, and graceful fallback to `settings.section` if not declared.
18
+ * Registers localized `en` and `ru` dictionaries via `ctx.locale.register()`.
19
+ * Reactive binding via `ctx.settingsScope.bind({ namespace: NS })` with `useSyncExternalStore` guarding against `unavailable` / `loading` snapshot states.
20
+ * Uses native design tokens (`--dsw-alias-...`) with full dark/light theme support.
21
+
22
+ ```mermaid
23
+ graph LR
24
+ subgraph Client [DSH Web Interface]
25
+ UI[Settings Card: ClineBot]
26
+ SmokeBtn[Smoke Test Button]
27
+ RegBtn[Register in DSH Models]
28
+ end
29
+
30
+ subgraph Host [DSH Node.js Runtime]
31
+ API["HTTP API: /api/plugins/dsh-clinebot/*"]
32
+ ClientHelper["lib/cline-client.js"]
33
+ Catalog["lib/models.js (Static 11 Models)"]
34
+ CredService[DSH Credentials Service]
35
+ PiAiSettings["DSH Settings: llm-pi-ai"]
36
+ end
37
+
38
+ subgraph Remote [Cline Service]
39
+ ClineAPI["api.cline.bot/api/v1"]
40
+ end
41
+
42
+ UI -->|GET /status| API
43
+ SmokeBtn -->|POST /smoke| API
44
+ RegBtn -->|POST /register| API
45
+ API --> CredService
46
+ API --> ClientHelper
47
+ ClientHelper --> Catalog
48
+ API -->|Mutate| PiAiSettings
49
+ ClientHelper -->|POST /chat/completions| ClineAPI
50
+ ```
51
+
52
+ ## 3. UI/UX Contract
53
+ * **Badges**:
54
+ * Host connectivity: `Host online (<ms>)` (green) / `Host unreachable` (red).
55
+ * Credential presence: `Key ✓ (credentials|env)` (green) / `Key missing` (amber).
56
+ * Registration status: `DSH Registered` (green) / `Not Registered` (amber).
57
+ * **Model Picker**: Interactive checklist of all 11 official models with multi-select and vision capability indicators.
58
+ * **Non-destructive actions**: Unregister cleanly removes the provider entry from DSH without touching other providers or configurations.
59
+
60
+ ## 4. Security & Isolation
61
+ * CSRF / Cross-site protection: All mutating routes (`/register`, `/unregister`, `/smoke`, `/models`) validate `isTrustedSettingsRequest(req)` (`Sec-Fetch-Site !== 'cross-site'`).
62
+ * Body size limits: Request payloads are strictly capped at 256 KB.
63
+ * Sensitive credential data is never returned across the HTTP API (only `{ present: boolean, source: string, envName: string }`).