@goodandready/dsh-clinebot 0.3.7 → 0.3.9

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,30 @@ 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.9] - 2026-09-15
9
+
10
+ ### Added
11
+ - **Stale-While-Revalidate (SWR) Quota Caching**: Integrated SWR caching into `fetchUsageLimits` with a 20-second TTL. Instantaneous (<2ms) responses on `/dsh-clinebot/status` and `/dsh-clinebot/usage` with background revalidation.
12
+ - **Smart Quota-Aware Failover**: Account rotation automatically skips exhausted accounts (>=95% 5h usage) and selects the account with the lowest `percentUsed`. Supports auto-recovery once `resetsAt` timestamp is reached.
13
+ - **One-Click In-App Updater (`/dsh-clinebot/update`)**: Added canonical DSH updater endpoint (`lib/updater.js`) validating loopback origin, same-origin, and `x-dsh-plugin-update` header for safe in-app upgrades.
14
+ - **Complete Chinese Localization (`zh`)**: Added comprehensive native Chinese dictionary (67+ translation keys) to `lib/client.js`.
15
+ - **DSH Canon Compliance**: Cleanly separated external Russian translation (supplied via `dsh-russian-lang`), and normalized all slash command outputs to canonical English.
16
+
17
+ ### Fixed
18
+ - **Code Deduplication**: Eliminated duplicate credential and account pool helper functions between `lib/index.js` and `lib/cline-client.js`.
19
+ - **Network Keep-Alive & Cloudflare Handling**: Enforced persistent keep-alive connections on outbound requests and improved error extraction on HTML challenge responses.
20
+
21
+ ## [0.3.8] - 2026-09-12
22
+
23
+ ### Added
24
+ - **Stale-While-Revalidate (SWR) Network Probe** (Issue #18): Introduced in-memory SWR caching (`probeCache`) with 25s TTL for host health probes (`probeHealth`), reducing settings card status endpoint latency from ~500ms to <1ms on repeated calls while revalidating asynchronously in the background.
25
+ - **HTTP Keep-Alive Connection Reuse**: Added persistent `keepalive: true` connection options across all HTTP calls (`probeHealth`, `smokeChat`, `fetchUsageLimits`) to eliminate recurrent TCP/TLS handshakes to `api.cline.bot`.
26
+ - **Auto-Failover Account Rotation**: Implemented `rotateToNextAccount` to automatically rotate active accounts in the configured pool when encountering HTTP 429 rate limits or 100% quota exhaustion, instantly synchronizing DSH `llm-pi-ai` credentials without restarting.
27
+ - **Accurate Token Telemetry**: Extracted real usage metrics (`prompt_tokens`, `completion_tokens`, `total_tokens`) from chat completion responses, replacing static estimation counters.
28
+ - **Expanded Slash-Commands**: Extended `/cline` chat command with `/cline test [model]` (live smoke verification), `/cline ping` (real-time host connectivity test), and `/cline rotate` (manual failover).
29
+ - **Curated Models Catalog Expansion**: Added Claude 3.7 Sonnet (Hybrid Reasoning), GPT-4.5 Preview, o3-mini, Gemini 2.5 Pro / Flash, and Qwen 2.5 Coder 32B to the official `CLINE_MODELS` catalogue.
30
+ - **Debounced Model Picker Toggles**: Added 280ms debounce for model exclusion persistence in `lib/client.js`, providing 0ms UI checkbox responsiveness and preventing network request thrashing.
31
+
8
32
  ## [0.3.7] - 2026-09-10
9
33
 
10
34
  ### Fixed
package/README.md CHANGED
@@ -18,10 +18,20 @@
18
18
 
19
19
  <p align="center">
20
20
  <a href="README.md"><b>🇬🇧 English</b></a> •
21
- <a href="docs/README.ru.md"><b>🇷🇺 Русский</b></a> •
22
- <a href="docs/README.zh.md"><b>🇨🇳 中文说明</b></a>
21
+ <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
22
+ <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
23
23
  </p>
24
24
 
25
+ <table align="center">
26
+ <tr>
27
+ <td align="center">
28
+ ⭐ <strong>If you like this plugin, please star it on GitHub</strong> — it shows me that the plugin is useful to you and motivates me to keep developing it.
29
+ <br><br>
30
+ 🐛 <strong>If you find a bug or would like to request a feature</strong>, open a GitHub issue in any language — I will review your proposal and implement useful suggestions in a future plugin version.
31
+ </td>
32
+ </tr>
33
+ </table>
34
+
25
35
  </div>
26
36
 
27
37
  ---
@@ -37,6 +47,9 @@ Integrating ClinePass into DeepSeek Harness (DSH) natively poses key challenges:
37
47
  4. **Credential Security**: Storing API keys directly in plain settings is insecure.
38
48
 
39
49
  **`@goodandready/dsh-clinebot`** provides a complete solution:
50
+ * 🚀 **One-Click In-App Updater**: Upgrade `@goodandready/dsh-clinebot` directly from the DSH UI or trigger secure loopback updates via `/dsh-clinebot/update`.
51
+ * ⚡ **SWR Quota & Health Caching**: Instantaneous response time (<2ms) on status queries with background revalidation.
52
+ * 🔀 **Smart Quota-Aware Failover**: Automatic multi-account rotation skipping exhausted accounts and recovering when `resetsAt` is reached.
40
53
  * 🖥️ **Dedicated Settings Page**: Full-width page in DSH Settings (`Settings → ClineBot`).
41
54
  * 🔄 **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
55
  * ⚠️ **Quota Exhaustion Alerts**: Real-time visual warning banners when 5-hour rolling limit reaches 80% (warning) and 95% (exhausted), complete with countdown to reset.
package/README.ru.md ADDED
@@ -0,0 +1,199 @@
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
+ <table align="center">
26
+ <tr>
27
+ <td align="center">
28
+ ⭐ <strong>Если вам нравится этот плагин, поставьте ему звезду на GitHub</strong> — это покажет мне, что плагин вам полезен, и будет мотивировать меня развивать его дальше.
29
+ <br><br>
30
+ 🐛 <strong>Если вы нашли баг или хотите предложить новый функционал</strong>, создайте issue на GitHub на любом языке — я рассмотрю ваше предложение и реализую полезные идеи в одной из следующих версий плагина.
31
+ </td>
32
+ </tr>
33
+ </table>
34
+
35
+ </div>
36
+
37
+ ---
38
+
39
+ ## ⚡ Обзор и решаемая проблема
40
+
41
+ **ClinePass** (`https://cline.bot`) — сервис единой фиксированной подписки (\$9.99/мес), предоставляющий разработчикам повышенные лимиты (в 2–5 раз выше стандартных) на передовые open-weights модели программирования и рассуждений через единый OpenAI-совместимый интерфейс (`https://api.cline.bot/api/v1`).
42
+
43
+ Интеграция ClinePass в DeepSeek Harness (DSH) напрямую сопряжена со следующими сложностями:
44
+ 1. **Отсутствие эндпоинта `/v1/models`**: запрос `GET /v1/models` к `api.cline.bot` возвращает `404 Not Found`, из-за чего динамический поиск моделей в DSH падает или оставляет список пустым.
45
+ 2. **Специфический формат идентификаторов**: моделям требуется обязательный префикс `cline-pass/` (например, `cline-pass/deepseek-v4-flash`, `cline-pass/kimi-k3`).
46
+ 3. **Отслеживание лимитов**: 5-часовые и недельные скользящие окна расхода токенов требуют прозрачной визуализации в интерфейсе.
47
+ 4. **Безопасность ключей**: хранение API-токенов в открытых конфигурациях небезопасно.
48
+
49
+ Плагин **`@goodandready/dsh-clinebot`** решает эти задачи «из коробки»:
50
+ * 🚀 **Обновление в один клик**: Обновление плагина прямо из интерфейса DSH или через защищённый loopback-эндпоинт `/dsh-clinebot/update`.
51
+ * ⚡ **SWR-кэширование квот и здоровья**: Мгновенный ответ (<2 мс) на запросы статуса с фоновым обновлением данных без блокировки UI.
52
+ * 🔀 **Smart Quota-Aware Failover**: Интеллектуальная ротация аккаунтов с обходом исчерпанных лимитов и авто-восстановлением при наступлении `resetsAt`.
53
+ * 🖥️ **Отдельная страница в Настройках**: собственная полноэкранная страница в меню Настроек DSH (`Настройки → ClineBot`).
54
+ * 🔄 **Динамическая синхронизация моделей подписки**: автоматическое получение реального списка моделей из `GET /api/v1/users/me/plan` и мгновенное обновление провайдера DSH в один клик.
55
+ * ⚠️ **Предупреждения об исчерпании квоты**: баннеры предупреждения при достижении 80% (внимание) и 95% (исчерпано) 5-часового лимита с таймером сброса.
56
+ * 📈 **Метрики сессии**: учет количества запросов, расчетных токенов (Prompt / Completion), задержки и времени последнего вызова.
57
+ * 📊 **Дашборд лимитов подписки (Usage)**: наглядные прогресс-бары расхода 5-часового и недельного скользящего окна из официального API `GET /users/me/plan/usage-limits`.
58
+ * 🔑 **Сохранение ключа прямо из UI**: поле ввода ключа с маскировкой; сохранение напрямую в системный сервис `credentials` (`~/.dsh/.credentials.yaml`) без ручной правки файлов на сервере.
59
+ * 🎯 **Управление моделями в пикере**: включение/выключение отображения конкретных моделей в диалогах чата.
60
+ * 💬 **Слэш-команда `/cline` в чате**: просмотр остатка квот, предупреждений, статистики сессии, задержки и активной модели прямо из чата.
61
+
62
+ ---
63
+
64
+ ## 🏛️ Архитектура
65
+
66
+ ```mermaid
67
+ graph LR
68
+ subgraph UI [Интерфейс DSH]
69
+ Page["Отдельная страница (Настройки -> ClineBot)"]
70
+ QuotaBar["Прогресс-бары 5h и недельного лимита + Баннер предупреждений"]
71
+ KeyInput["Ввод и сохранение API-ключа"]
72
+ ModelPick["Динамическая синхронизация моделей и пикер"]
73
+ StatsCard["Метрики и статистика текущей сессии"]
74
+ end
75
+
76
+ subgraph PluginHost [Хост-часть dsh-clinebot]
77
+ HttpEndpoints["API: /api/plugins/dsh-clinebot/*"]
78
+ ClientCore["lib/cline-client.js"]
79
+ ModelCatalog["lib/models.js (Встроенные + Динамические из плана)"]
80
+ SlashCmd["Слэш-команда: /cline"]
81
+ end
82
+
83
+ subgraph DSHCore [Сервисы DSH]
84
+ Credentials["Сервис credentials (~/.dsh/.credentials.yaml)"]
85
+ PiAi["Настройки: llm-pi-ai.providers.clinebot"]
86
+ end
87
+
88
+ subgraph Upstream [Сервер Cline]
89
+ ClinePass["api.cline.bot/api/v1/chat/completions"]
90
+ ClineQuota["api.cline.bot/api/v1/users/me/plan/usage-limits"]
91
+ ClinePlan["api.cline.bot/api/v1/users/me/plan"]
92
+ end
93
+
94
+ Page -->|GET /status & /usage| HttpEndpoints
95
+ KeyInput -->|POST /save-key| HttpEndpoints
96
+ ModelPick -->|POST /models/sync| HttpEndpoints
97
+ HttpEndpoints --> Credentials
98
+ HttpEndpoints --> ClientCore
99
+ ClientCore --> ModelCatalog
100
+ HttpEndpoints -->|Атомарная мутация| PiAi
101
+ ClientCore -->|Чат| ClinePass
102
+ ClientCore -->|Квоты| ClineQuota
103
+ ClientCore -->|Тарифный план| ClinePlan
104
+ ```
105
+
106
+ ---
107
+
108
+ ## ✨ Структура модулей и возможности
109
+
110
+ * **`lib/models.js`**: каталог встроенных моделей ClinePass (11 моделей) и парсер моделей подписки (`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`).
111
+ * **`lib/cline-client.js`**:
112
+ * `fetchUsageLimits`: параллельный опрос `GET /users/me/plan/usage-limits`, `GET /users/me/plan` и `GET /users/me` с кэшированием в памяти.
113
+ * `sessionStats` / `recordSessionRequest`: счетчики сессии (запросы, токены, задержка, время).
114
+ * `saveCredentialKey`: атомарная запись ключей в `~/.dsh/.credentials.yaml`.
115
+ * `smokeChat`: замер задержки и тестовый пинг с фиксацией статистики.
116
+ * `buildPiAiProvider`: генерация конфигурации провайдера для `llm-pi-ai` (`api: 'openai-completions'`).
117
+ * **`lib/index.js`**: сервис Cordis, регистрация системных маршрутов (включая `/dsh-clinebot/models/sync`), расчет порогов предупреждения квоты и слэш-команды `/cline`.
118
+ * **`lib/client.js`**: полнофункциональный раздел настроек (`settings.section`, order 28) с баннерами предупреждений, карточкой статистики сессии, кнопкой синхронизации моделей плана и аккордеоном плагина (`settings.plugin.item`).
119
+
120
+ ---
121
+
122
+ ## 📦 Установка
123
+
124
+ ```bash
125
+ dsh plugin --profile web add @goodandready/dsh-clinebot
126
+ ```
127
+
128
+ Перезапустите экземпляр DeepSeek Harness и обновите вкладку в браузере.
129
+
130
+ ---
131
+
132
+ ## 💬 Слэш-команда `/cline` в чате
133
+
134
+ В любой сессии чата введите команду `/cline` для проверки остатка лимитов, предупреждений и статистики:
135
+
136
+ ```text
137
+ ### 🤖 ClinePass Status (ClinePass ($9.99/mo))
138
+ * Пинг хоста: ✅ 210 мс
139
+ * Активный ключ: CLINEBOT_API_KEY (credentials)
140
+ * Модель по умолчанию: `cline-pass/deepseek-v4-flash`
141
+
142
+ ⏱ 5-часовое окно: [████░░░░░░] 42% (сброс: 18:00)
143
+ 📅 Недельное окно: [██████░░░░] 60% (сброс: 08.09)
144
+ * Аккаунт: `developer@example.com`
145
+
146
+ 📈 Статистика текущей сессии:
147
+ * Запросов: 14 вызовов
148
+ * Токены: ~8,450 (Промпт: 6,100 | Ответ: 2,350)
149
+ * Задержка последнего ответа: 210 мс
150
+ ```
151
+
152
+ ---
153
+
154
+ ## ⚙️ Таблица конфигурации (`settings.yaml`)
155
+
156
+ ```yaml
157
+ dsh-clinebot:
158
+ enabled: true
159
+ baseUrl: https://api.cline.bot/api/v1
160
+ apiKeyEnv: CLINEBOT_API_KEY
161
+ defaultModel: cline-pass/deepseek-v4-flash
162
+ timeoutMs: 15000
163
+ smokeTimeoutMs: 25000
164
+ enabledModels:
165
+ - cline-pass/deepseek-v4-flash
166
+ - cline-pass/deepseek-v4-pro
167
+ - cline-pass/kimi-k3
168
+ - cline-pass/qwen3.7-max
169
+ dynamicModels: []
170
+ ```
171
+
172
+ ### Параметры конфигурации
173
+
174
+ | Параметр | Тип | По умолчанию | Описание |
175
+ |:---|:---|:---|:---|
176
+ | `enabled` | `boolean` | `true` | Включение моста провайдера ClineBot |
177
+ | `baseUrl` | `string` | `"https://api.cline.bot/api/v1"` | Базовый URL OpenAI-совместимого API ClinePass |
178
+ | `apiKeyEnv` | `string` | `"CLINEBOT_API_KEY"` | Имя переменной / ключа в хранилище credentials |
179
+ | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | Модель, выбираемая по умолчанию |
180
+ | `timeoutMs` | `number` | `15000` | Таймаут HTTP-запросов (мс) |
181
+ | `smokeTimeoutMs` | `number` | `25000` | Таймаут тестового пинга (мс) |
182
+ | `enabledModels` | `array` | `[...]` | Список моделей, активных в селекторе чата |
183
+ | `dynamicModels` | `array` | `[]` | Динамические модели, автоматически синхронизированные из тарифа |
184
+
185
+ ---
186
+
187
+ ## 🧪 Тестирование
188
+
189
+ Запуск автоматического набора тестов:
190
+
191
+ ```bash
192
+ npm test
193
+ ```
194
+
195
+ ---
196
+
197
+ ## 📄 Лицензия
198
+
199
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
package/README.zh.md ADDED
@@ -0,0 +1,201 @@
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
+ <table align="center">
26
+ <tr>
27
+ <td align="center">
28
+ ⭐ <strong>如果您喜欢这个插件,请在 GitHub 上为它点亮 Star</strong> — 这能让我知道插件对您有用,并鼓励我继续开发和维护它。
29
+ <br><br>
30
+ 🐛 <strong>如果您发现 Bug 或希望增加功能</strong>,请使用任意语言在 GitHub 上提交 Issue — 我会评估您的建议,并在后续版本中实现有价值的改进。
31
+ </td>
32
+ </tr>
33
+ </table>
34
+
35
+ </div>
36
+
37
+ ---
38
+
39
+ ## ⚡ 概述与解决的核心痛点
40
+
41
+ **ClinePass** (`https://cline.bot`) 是一项固定月费(\$9.99/月)的高性价比订阅服务,为开发者提供主流开源代码模型与推理模型 2–5 倍的高并发调用限额,统一通过 OpenAI 兼容接口 (`https://api.cline.bot/api/v1`) 提供服务。
42
+
43
+ 在将 ClinePass 接入 DeepSeek Harness (DSH) 时存在以下挑战:
44
+ 1. **缺失 `/v1/models` 接口**:`api.cline.bot` 的 `GET /v1/models` 会直接返回 `404 Not Found`,导致动态模型同步失败或模型列表为空。
45
+ 2. **专属模型前缀**:所有模型 ID 均需前缀 `cline-pass/`(如 `cline-pass/deepseek-v4-flash`, `cline-pass/kimi-k3`)。
46
+ 3. **用量额度监控**:5 小时滑动窗口与每周限额需要清晰直观的可视化进度监控。
47
+ 4. **安全凭据隔离**:禁止在明文配置中直接填写密钥。
48
+
49
+ **`@goodandready/dsh-clinebot`** 完美解决以上痛点:
50
+ * 🚀 **应用内一键更新**:直接在 DSH 界面检查并升级插件,或通过受保护的 `/dsh-clinebot/update` 进行本地安全更新。
51
+ * ⚡ **SWR 配额与健康状态缓存**:状态查询毫秒级响应(<2ms),并在后台静默更新,不阻塞前端渲染。
52
+ * 🔀 **智能配额故障转移 (Smart Failover)**:多账号池自动轮询,避开耗尽账号并在 `resetsAt` 到达后自动恢复。
53
+ * 🖥️ **专属设置大页**:在 DSH 设置中提供全宽独立页面(`设置 → ClineBot`)。
54
+ * 🔄 **订阅模型动态同步**:从官方 `GET /api/v1/users/me/plan` 自动提取真实包含模型,一键原子级同步至 DSH 提供商配置,无需等待插件更新。
55
+ * ⚠️ **额度耗尽实时预警**:当 5 小时滑动窗口达到 80%(警告黄色)和 95%(即将耗尽红色)时展示醒目预警横幅与重置倒计时。
56
+ * 📈 **会话统计与指标看板**:实时追踪请求调用次数、预估 Token(Prompt / Completion)、最近延迟及最后调用时间。
57
+ * 📊 **实时用量仪表盘**:调用官方 `GET /users/me/plan/usage-limits` API,实时渲染 5 小时与每周额度进度条及重置倒计时。
58
+ * 🔑 **界面直存密钥**:在 UI 中直接粘贴 API 密钥,通过 `ctx.credentials.set()` 自动安全保存至 `~/.dsh/.credentials.yaml`。
59
+ * 🎯 **模型选择器管理**:支持勾选开启/关闭特定模型在聊天选择器中的显示。
60
+ * 💬 **聊天斜杠指令 `/cline`**:在任意聊天框快速查询当前配额、预警横幅、会话指标统计、网络延迟与活跃模型。
61
+
62
+ ---
63
+
64
+ ## 🏛️ 架构设计
65
+
66
+ ```mermaid
67
+ graph LR
68
+ subgraph UI [DSH Web 前端界面]
69
+ Page["独立配置页 (设置 -> ClineBot)"]
70
+ QuotaBar["5小时与每周额度进度条 + 额度预警横幅"]
71
+ KeyInput["API 密钥直填与安全保存"]
72
+ ModelPick["模型动态同步与选择器管控"]
73
+ StatsCard["会话指标监控看板"]
74
+ end
75
+
76
+ subgraph PluginHost [dsh-clinebot 宿主运行环境]
77
+ HttpEndpoints["API 路由: /api/plugins/dsh-clinebot/*"]
78
+ ClientCore["lib/cline-client.js"]
79
+ ModelCatalog["lib/models.js (内置精选 + 动态订阅解析)"]
80
+ SlashCmd["斜杠指令: /cline"]
81
+ end
82
+
83
+ subgraph DSHCore [DSH 核心系统服务]
84
+ Credentials["凭据存储服务 (~/.dsh/.credentials.yaml)"]
85
+ PiAi["模型注册: llm-pi-ai.providers.clinebot"]
86
+ end
87
+
88
+ subgraph Upstream [Cline 官方云端]
89
+ ClinePass["api.cline.bot/api/v1/chat/completions"]
90
+ ClineQuota["api.cline.bot/api/v1/users/me/plan/usage-limits"]
91
+ ClinePlan["api.cline.bot/api/v1/users/me/plan"]
92
+ end
93
+
94
+ Page -->|GET /status & /usage| HttpEndpoints
95
+ KeyInput -->|POST /save-key| HttpEndpoints
96
+ ModelPick -->|POST /models/sync| HttpEndpoints
97
+ HttpEndpoints --> Credentials
98
+ HttpEndpoints --> ClientCore
99
+ ClientCore --> ModelCatalog
100
+ HttpEndpoints -->|原子级写入| PiAi
101
+ ClientCore -->|模型对话| ClinePass
102
+ ClientCore -->|额度查询| ClineQuota
103
+ ClientCore -->|套餐信息| ClinePlan
104
+ ```
105
+
106
+ ---
107
+
108
+ ## ✨ 核心模块与功能
109
+
110
+ * **`lib/models.js`**:管理 11 款官方精选内置模型以及套餐模型动态解析器(`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`)。
111
+ * **`lib/cline-client.js`**:
112
+ * `fetchUsageLimits`:高效并发轮询 `GET /users/me/plan/usage-limits`、`GET /users/me/plan` 与 `GET /users/me` 并进行内存缓存。
113
+ * `sessionStats` / `recordSessionRequest`:内存级会话度量记录器(请求次数、Token 估算、延迟、时间戳)。
114
+ * `saveCredentialKey`:将密钥安全写入 `~/.dsh/.credentials.yaml`。
115
+ * `smokeChat`:毫秒级网络探活与非流式延迟测试,并记录会话指标。
116
+ * `buildPiAiProvider`:构建 DSH `llm-pi-ai` 兼容的服务商定义 (`api: 'openai-completions'`)。
117
+ * **`lib/index.js`**:Cordis 插件主生命周期服务,注册后端 REST API 路由(含 `/dsh-clinebot/models/sync`)、额度预警计算与 `/cline` 聊天斜杠指令。
118
+ * **`lib/client.js`**:前端设置面板(`settings.section` 序号 28),内含预警横幅、会话指标卡片、一键模型同步按钮及插件折叠卡片。
119
+
120
+ ---
121
+
122
+ ## 📦 快速安装
123
+
124
+ 在 DeepSeek Harness Web 配置中安装:
125
+
126
+ ```bash
127
+ dsh plugin --profile web add @goodandready/dsh-clinebot
128
+ ```
129
+
130
+ 重启 DeepSeek Harness 实例并刷新浏览器页面。
131
+
132
+ ---
133
+
134
+ ## 💬 聊天斜杠指令 `/cline`
135
+
136
+ 在任何聊天会话中输入 `/cline` 即可即时检查配额、预警状态与会话指标:
137
+
138
+ ```text
139
+ ### 🤖 ClinePass Status (ClinePass ($9.99/mo))
140
+ * 响应延迟: ✅ 210 ms
141
+ * 活跃密钥: CLINEBOT_API_KEY (credentials)
142
+ * 默认模型: `cline-pass/deepseek-v4-flash`
143
+
144
+ ⏱ 5 小时窗口: [████░░░░░░] 42% (重置时间: 18:00)
145
+ 📅 每周窗口: [██████░░░░] 60% (重置时间: 09月08日)
146
+ * 绑定账号: `developer@example.com`
147
+
148
+ 📈 当前会话统计:
149
+ * 请求次数: 14 次
150
+ * Token 估算: ~8,450 (Prompt: 6,100 | Completion: 2,350)
151
+ * 最近延迟: 210 ms
152
+ ```
153
+
154
+ ---
155
+
156
+ ## ⚙️ 配置项参考 (`settings.yaml`)
157
+
158
+ ```yaml
159
+ dsh-clinebot:
160
+ enabled: true
161
+ baseUrl: https://api.cline.bot/api/v1
162
+ apiKeyEnv: CLINEBOT_API_KEY
163
+ defaultModel: cline-pass/deepseek-v4-flash
164
+ timeoutMs: 15000
165
+ smokeTimeoutMs: 25000
166
+ enabledModels:
167
+ - cline-pass/deepseek-v4-flash
168
+ - cline-pass/deepseek-v4-pro
169
+ - cline-pass/kimi-k3
170
+ - cline-pass/qwen3.7-max
171
+ dynamicModels: []
172
+ ```
173
+
174
+ ### 配置参数说明
175
+
176
+ | 参数项 | 类型 | 默认值 | 说明 |
177
+ |:---|:---|:---|:---|
178
+ | `enabled` | `boolean` | `true` | 是否启用 ClineBot 桥接插件 |
179
+ | `baseUrl` | `string` | `"https://api.cline.bot/api/v1"` | ClinePass OpenAI 兼容接口地址 |
180
+ | `apiKeyEnv` | `string` | `"CLINEBOT_API_KEY"` | 凭据管理系统中的密钥名称 |
181
+ | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | 默认选中的模型 ID |
182
+ | `timeoutMs` | `number` | `15000` | HTTP 请求超时时间(毫秒) |
183
+ | `smokeTimeoutMs` | `number` | `25000` | 探活测试超时时间(毫秒) |
184
+ | `enabledModels` | `array` | `[...]` | 允许在聊天下拉框中显示的可用模型列表 |
185
+ | `dynamicModels` | `array` | `[]` | 从官方套餐中自动同步的动态模型列表 |
186
+
187
+ ---
188
+
189
+ ## 🧪 测试
190
+
191
+ 运行自动化测试套件:
192
+
193
+ ```bash
194
+ npm test
195
+ ```
196
+
197
+ ---
198
+
199
+ ## 📄 许可证
200
+
201
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
package/docs/README.ru.md CHANGED
@@ -17,11 +17,21 @@
17
17
  </p>
18
18
 
19
19
  <p align="center">
20
- <a href="../README.md"><b>🇬🇧 English</b></a> •
20
+ <a href="README.md"><b>🇬🇧 English</b></a> •
21
21
  <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
22
22
  <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
23
23
  </p>
24
24
 
25
+ <table align="center">
26
+ <tr>
27
+ <td align="center">
28
+ ⭐ <strong>Если вам нравится этот плагин, поставьте ему звезду на GitHub</strong> — это покажет мне, что плагин вам полезен, и будет мотивировать меня развивать его дальше.
29
+ <br><br>
30
+ 🐛 <strong>Если вы нашли баг или хотите предложить новый функционал</strong>, создайте issue на GitHub на любом языке — я рассмотрю ваше предложение и реализую полезные идеи в одной из следующих версий плагина.
31
+ </td>
32
+ </tr>
33
+ </table>
34
+
25
35
  </div>
26
36
 
27
37
  ---
@@ -37,6 +47,9 @@
37
47
  4. **Безопасность ключей**: хранение API-токенов в открытых конфигурациях небезопасно.
38
48
 
39
49
  Плагин **`@goodandready/dsh-clinebot`** решает эти задачи «из коробки»:
50
+ * 🚀 **Обновление в один клик**: Обновление плагина прямо из интерфейса DSH или через защищённый loopback-эндпоинт `/dsh-clinebot/update`.
51
+ * ⚡ **SWR-кэширование квот и здоровья**: Мгновенный ответ (<2 мс) на запросы статуса с фоновым обновлением данных без блокировки UI.
52
+ * 🔀 **Smart Quota-Aware Failover**: Интеллектуальная ротация аккаунтов с обходом исчерпанных лимитов и авто-восстановлением при наступлении `resetsAt`.
40
53
  * 🖥️ **Отдельная страница в Настройках**: собственная полноэкранная страница в меню Настроек DSH (`Настройки → ClineBot`).
41
54
  * 🔄 **Динамическая синхронизация моделей подписки**: автоматическое получение реального списка моделей из `GET /api/v1/users/me/plan` и мгновенное обновление провайдера DSH в один клик.
42
55
  * ⚠️ **Предупреждения об исчерпании квоты**: баннеры предупреждения при достижении 80% (внимание) и 95% (исчерпано) 5-часового лимита с таймером сброса.
package/docs/README.zh.md CHANGED
@@ -17,11 +17,21 @@
17
17
  </p>
18
18
 
19
19
  <p align="center">
20
- <a href="../README.md"><b>🇬🇧 English</b></a> •
20
+ <a href="README.md"><b>🇬🇧 English</b></a> •
21
21
  <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
22
22
  <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
23
23
  </p>
24
24
 
25
+ <table align="center">
26
+ <tr>
27
+ <td align="center">
28
+ ⭐ <strong>如果您喜欢这个插件,请在 GitHub 上为它点亮 Star</strong> — 这能让我知道插件对您有用,并鼓励我继续开发和维护它。
29
+ <br><br>
30
+ 🐛 <strong>如果您发现 Bug 或希望增加功能</strong>,请使用任意语言在 GitHub 上提交 Issue — 我会评估您的建议,并在后续版本中实现有价值的改进。
31
+ </td>
32
+ </tr>
33
+ </table>
34
+
25
35
  </div>
26
36
 
27
37
  ---
@@ -37,6 +47,9 @@
37
47
  4. **安全凭据隔离**:禁止在明文配置中直接填写密钥。
38
48
 
39
49
  **`@goodandready/dsh-clinebot`** 完美解决以上痛点:
50
+ * 🚀 **应用内一键更新**:直接在 DSH 界面检查并升级插件,或通过受保护的 `/dsh-clinebot/update` 进行本地安全更新。
51
+ * ⚡ **SWR 配额与健康状态缓存**:状态查询毫秒级响应(<2ms),并在后台静默更新,不阻塞前端渲染。
52
+ * 🔀 **智能配额故障转移 (Smart Failover)**:多账号池自动轮询,避开耗尽账号并在 `resetsAt` 到达后自动恢复。
40
53
  * 🖥️ **专属设置大页**:在 DSH 设置中提供全宽独立页面(`设置 → ClineBot`)。
41
54
  * 🔄 **订阅模型动态同步**:从官方 `GET /api/v1/users/me/plan` 自动提取真实包含模型,一键原子级同步至 DSH 提供商配置,无需等待插件更新。
42
55
  * ⚠️ **额度耗尽实时预警**:当 5 小时滑动窗口达到 80%(警告黄色)和 95%(即将耗尽红色)时展示醒目预警横幅与重置倒计时。
@@ -18,7 +18,7 @@ The plugin consists of two runtime boundaries conforming to DSH authoring standa
18
18
  * Injects `['slots', 'locale', 'settingsScope']`.
19
19
  * Slots strictly and exclusively into `settings.plugin.item` (`key: NS`, `locale: NS`). Standalone top-level `settings.section` registration is omitted to maintain clean primary navigation in DSH and prevent side-list pollution.
20
20
  * Uses `refreshMirrorUntilVisible(ctx)` to invalidate and re-read the client settings mirror until the namespace is reported ready by the host.
21
- * Registers localized `en` and `ru` dictionaries with duplicate-safe guards (`ctx.locale.register()`).
21
+ * Registers localized `en` and `zh` dictionaries with duplicate-safe guards (`ctx.locale.register()`), while Russian translation is modularly supplied by `dsh-russian-lang`.
22
22
  * Reactive binding via `((ctx?.get && ctx.get('lanSettings')) || ctx?.settingsScope).bind({ namespace: NS })` with `useSyncExternalStore` guarding against `unavailable` / `loading` snapshot states. Form mutations write directly to `scope.set()`.
23
23
  * Uses native design tokens (`--dsw-alias-...`) with full dark/light theme support.
24
24
  * Injects isolated style tag tagged with `data-dsh-plugin="dsh-clinebot"`.
@@ -72,3 +72,17 @@ graph LR
72
72
  * **Reasoning Effort Support**: Models declaring `reasoningEfforts: ['low', 'medium', 'high', 'max']` expose native thinking controls within the DSH model picker, accompanied by UI badges (`🧠 Reasoning`).
73
73
  * **Offline Cold-Start Cache**: Discovered plan models are serialized locally to `modelsCachePath` (`~/.dsh/clinebot-models-cache.json`), ensuring models remain immediately available on cold boot even if the upstream network or Cline API is temporarily unavailable.
74
74
 
75
+
76
+ ## 6. Performance, Resilience & Telemetry (v0.3.8)
77
+ * **Stale-While-Revalidate (SWR) Network Probing**: `probeHealth()` utilizes an in-memory SWR cache (`probeCache`) with 25s TTL. Repeated `/status` queries return instantaneously (<1ms latency) with fresh host availability, asynchronously refreshing network latency in the background without blocking the client UI thread.
78
+ * **HTTP Keep-Alive Connection Reuse**: Outbound fetch calls to `api.cline.bot` enforce persistent connection keepalive (`keepalive: true`), eliminating recurrent TLS handshake and TCP connection establishment latency.
79
+ * **Auto-Failover Account Rotation**: When an active account encounters HTTP 429 (Rate Limit) or 100% quota depletion, `rotateToNextAccount()` automatically selects the next configured account in the pool, applies the update to DSH settings, and re-synchronizes credentials in `llm-pi-ai` in real time.
80
+ * **Accurate Token Telemetry**: Real usage metadata (`prompt_tokens`, `completion_tokens`, `total_tokens`) is parsed directly from chat completion responses and tracked in session telemetry (`sessionStats`).
81
+ * **Expanded Slash Commands**: Slash command `/cline` supports `/cline test [model]` (smoke test with latency, response and token metrics), `/cline ping` (real-time host connectivity test), and `/cline rotate` (round-robin active account rotation).
82
+ * **Debounced Model Selection**: Model exclusion checkboxes in `lib/client.js` utilize immediate optimistic UI rendering paired with a 280ms debounced persistence layer, ensuring smooth interaction without request thrashing.
83
+
84
+ ## 7. Stability, SWR Quotas, Smart Failover & One-Click In-App Updater (v0.3.9)
85
+ * **SWR Quota Caching (`fetchUsageLimits`)**: In-memory Stale-While-Revalidate caching for Cline usage limits (20s TTL). Returns quota statistics (<2ms) immediately on `/status` requests while refreshing quota windows in the background.
86
+ * **Smart Quota-Aware Failover**: Account failover evaluates cached rolling limits (5-hour window), automatically prioritizing accounts with the lowest `percentUsed` and respecting `resetsAt` timestamps for automatic account recovery.
87
+ * **One-Click In-App Updater (`/dsh-clinebot/update`)**: Integrates host-side one-click updater (`lib/updater.js`) with security verification (`isTrustedUpdateRequest`: loopback validation, same-origin checks, `x-dsh-plugin-update: 1` header). Allows seamless in-place updates from DSH UI.
88
+ * **Canonical DSH Localization Standard**: Source code complies with canonical DSH standards (English base canon, complete Chinese `zh` locale registration in client, external Russian translation provided by `dsh-russian-lang`). All slash command responses and system logs are localized to English.