@goodandready/dsh-clinebot 0.5.8 → 0.5.10

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,32 @@ 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.5.10] - 2026-10-01
9
+
10
+ ### Fixed
11
+ - **Native Cosmokit Volatile Box & Proxy Target Preservation (Issues #157, #173)**: Preserved native Cosmokit `{ get }` volatile references without scalar overwrites during config mutations, and ensured extensible proxy targets for frozen configurations to prevent `TypeError: 'ownKeys' on proxy` invariants.
12
+ - **In-Memory Stats Retention Across Config Updates (Issue #158)**: Retained unwritten in-memory metrics across unrelated configuration saves (`PUT /config`) without reloading from disk or dropping unpersisted counters. Flushes pending metrics before switching storage paths when `statsPath` changes.
13
+ - **Account Pool Least-Used Routing on Empty Active Account (Issue #162)**: Allowed automatic least-used quota routing when `activeAccount` is set to an empty string or `"auto"`, preventing unintended pinning of the primary default account.
14
+ - **Native DSH Provider Compatibility Flag Normalization (Issue #163)**: Removed obsolete session affinity compatibility flags (`sendSessionAffinityHeaders`, `sessionAffinityFormat`) rejected by native DSH `llm-pi-ai`, restoring clean catalog registration and model resolution.
15
+ - **Disk Models Cache Isolation by Account & Endpoint (Issue #168)**: Keyed on-disk models cache (`saveModelsDiskCache`/`loadModelsDiskCache`) to specific account and endpoint identities, preventing cross-account model pollution and false `planSynced: true` indications in offline mode.
16
+ - **Process Group Termination & Zombie Prevention in Updater (Issue #172)**: Spanned updater processes with `detached: true` on POSIX, transmitting `SIGTERM` and `SIGKILL` across the entire process group (`-child.pid`) on timeout to guarantee complete termination of spawned child/grandchild processes and prompt lock release.
17
+ - **Session Router Bounded Memory Capacity on Manual Pin (Issue #183)**: Enforced strict capacity bounds (`MAX_SESSIONS = 1000`) on manual pin branches in `resolveSessionAccount`, ensuring LRU eviction and preventing unbounded memory growth.
18
+ - **Transactional Account Deletion & Secret Preservation (Issue #184)**: Persisted configuration updates prior to unsetting credentials in `handleDeleteAccount`, preventing irrevocable API key loss if settings persistence fails, and rolling back settings on credential deletion failures.
19
+ - **Non-Stream Proxy Response Body Deadline & Fail-Closed Error Handling (Issue #185)**: Wrapped non-streaming proxy response body reading in a `Promise.race` deadline bounded by `streamIdleTimeoutMs`, aborting upstream requests and returning HTTP 504 Gateway Timeout or 502 Bad Gateway with error metrics on stalls or socket drops instead of false HTTP 200 `{}`.
20
+ - **Localized Quota Countdown & Duplicate Chinese Reset Label Elimination (Issue #175)**: Added localized `quota.resetting` keys in `zh` ("正在重置") and `en` ("Resetting…") and handled resetting countdown states cleanly in `makeT` and `ProgressBar`, eliminating awkward "resetting后重置" strings.
21
+ - **Documentation & DESIGN Contract Alignment (Issue #177)**: Removed obsolete `settings.yaml` references across all documentation, updated runtime defaults (`cline-pass/deepseek-v4-flash`, timeouts 15s/25s/30s), documented 256 KiB control vs 64 MiB proxy body limits, and documented auto-routing policies.
22
+ - **Native DSH Adapter Integration Test Coverage (Issue #173)**: Added regression and integration tests verifying native DSH `llm-pi-ai` provider registration without `catalogError` and validating reactive volatile schema behavior.
23
+
24
+ ## [0.5.9] - 2026-10-01
25
+
26
+ ### Fixed
27
+ - **Updater Timeout Exit & SIGKILL Escalation (Issue #172)**: Ensured `installExact` child process cleanup waits for the operating system process to fully terminate via `exit`/`close` events before releasing profile locks or rejecting update promises. On timeout, sends `SIGTERM`, waits for a grace period, and escalates to `SIGKILL` for stubborn subprocesses.
28
+ - **Proxy Client Disconnection SSE Abort Fixture (Issue #173)**: Validated client disconnection handling against a real Node.js loopback HTTP fixture with client TCP stream destruction, asserting upstream `reader.cancel()` and fetch `signal.aborted` without relying exclusively on synthetic mocks.
29
+ - **Dependency Manifest & Lockfile Synchronization (Issue #174)**: Regenerated `package-lock.json` via clean npm resolution for all 21 dependencies to ensure deterministic, clean `npm ci` builds across environments, while maintaining proper exclusion of the lockfile from package archives.
30
+ - **UI Locale Key Completeness & Reasoning/Quota Strings (Issue #175)**: Resolved missing locale keys across `en` and `zh` dictionaries for structured quota countdowns/warnings, reasoning tags and effort selectors, capability badges, smoke test diagnostic outputs, and ErrorBoundary alerts. Added regression test asserting 100% dictionary completeness and symmetry for client `t()` calls.
31
+ - **Update Check State Machine & Error Handling (Issue #176)**: Implemented explicit update state machine (`idle`, `checking`, `current`, `available`, `error`) in `UpdateBanner` and `settings-page.js`. Eliminated false "✓ Up to date" status indicators on failed network checks or when `latestCheckFailed: true`, and added retry action.
32
+ - **Documentation & Design Contract Modernization (Issue #177)**: Synchronized `README.md`, `README.ru.md`, `README.zh.md`, and `docs/design/DESIGN.md` with active runtime contracts: documented dynamic subscription catalog, custom models, active configuration schema (`disabledModels`, `proxyMode`, `accounts`), corrected route prefixes (`/dsh-clinebot/*`), and documented all 4 registered UI seats and release testing workflows.
33
+
8
34
  ## [0.5.8] - 2026-09-30
9
35
 
10
36
  ### Fixed
package/README.md CHANGED
@@ -74,7 +74,7 @@ graph LR
74
74
  end
75
75
 
76
76
  subgraph PluginHost [dsh-clinebot Host Runtime]
77
- HttpEndpoints["API: /api/plugins/dsh-clinebot/*"]
77
+ HttpEndpoints["API: /dsh-clinebot/*"]
78
78
  ClientCore["lib/cline-client.js"]
79
79
  ModelCatalog["lib/models.js (Curated + Dynamic Plan)"]
80
80
  SlashCmd["Command: /cline"]
@@ -108,7 +108,7 @@ graph LR
108
108
  ## ✨ Features & Module Breakdown
109
109
 
110
110
  * **`lib/models.js`**:
111
- Manages the curated catalog (11 built-in models) with full reasoning effort mappings (`off: null`, `low`, `medium`, `high`, `max`), upstream 200k context limit declarations, and dynamic subscription plan model parsing (`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`).
111
+ Manages the dynamic subscription catalog and fallback models with full reasoning effort mappings (`off: null`, `low`, `medium`, `high`, `max`), upstream 200k context limit declarations, user-defined custom models, and dynamic subscription plan model parsing (`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`).
112
112
  * **`lib/cline-client.js`**:
113
113
  * `fetchUsageLimits`: queries `GET /users/me/plan/usage-limits`, `GET /users/me/plan`, and `GET /users/me` with in-memory caching.
114
114
  * `sessionStats` / `recordSessionRequest`: in-memory telemetry recording requests count, tokens, latency, and timestamps.
@@ -154,55 +154,80 @@ From any DSH chat session, type `/cline` to inspect quota, warning alerts, and s
154
154
 
155
155
  ---
156
156
 
157
- ## ⚙️ Configuration Reference (`settings.yaml`)
157
+ ## ⚙️ Configuration Reference (DSH Settings & Web UI)
158
158
 
159
- Configure options in `settings.yaml` or directly inside the Web UI:
159
+ In modern DeepSeek Harness (0.1.7+), settings are managed natively via the DSH Web UI Settings card or `PUT /dsh-clinebot/config`, with API keys persisted securely in DSH Credentials storage (`~/.dsh/.credentials.yaml`).
160
160
 
161
161
  ```yaml
162
162
  dsh-clinebot:
163
163
  enabled: true
164
164
  baseUrl: https://api.cline.bot/api/v1
165
165
  apiKeyEnv: CLINEBOT_API_KEY
166
- defaultModel: cline-pass/deepseek-v4-flash
167
- timeoutMs: 15000
168
- smokeTimeoutMs: 25000
169
- enabledModels:
170
- - cline-pass/deepseek-v4-flash
171
- - cline-pass/deepseek-v4-pro
172
- - cline-pass/kimi-k3
173
- - cline-pass/qwen3.7-max
174
- dynamicModels: []
166
+ defaultModel: your-default-model
167
+ proxyMode: true
168
+ disabledModels: []
169
+ customModels: []
170
+ modelReasoningDefaults:
171
+ your-reasoning-model: high
172
+ modelContextOverrides: []
173
+ statsPath: ~/.dsh/clinebot-stats.json
174
+ timeoutMs: 30000
175
+ smokeTimeoutMs: 60000
176
+ streamIdleTimeoutMs: 60000
177
+ accounts:
178
+ - label: Team Key
179
+ apiKeyEnv: CLINEBOT_API_KEY_2
175
180
  ```
176
181
 
177
182
  ### Configuration Parameters
178
183
 
179
184
  | Parameter | Type | Default | Description |
180
185
  |:---|:---|:---|:---|
181
- | `enabled` | `boolean` | `true` | Enable or disable the ClineBot provider bridge |
186
+ | `enabled` | `boolean` | `true` | Enable or disable the ClineBot provider bridge in DSH |
182
187
  | `baseUrl` | `string` | `"https://api.cline.bot/api/v1"` | ClinePass OpenAI-compatible base URL |
183
188
  | `apiKeyEnv` | `string` | `"CLINEBOT_API_KEY"` | Environment variable / credentials key name |
184
- | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | Default selected model ID |
189
+ | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | Default selected model ID for chat and smoke tests |
190
+ | `disabledModels` | `array` | `[]` | List of model IDs hidden from the DSH chat picker (new subscription models are auto-enabled) |
191
+ | `customModels` | `array` | `[]` | User-defined gateway models (`[{ id, name, contextLength, maxTokens, category, isReasoning }]`) |
192
+ | `modelReasoningDefaults` | `object` | `{}` | Configured default reasoning effort per model (`low`, `medium`, `high`, `max`) |
185
193
  | `modelContextOverrides` | `array` | `[]` | User-defined model context length and max token overrides |
186
- | `timeoutMs` | `number` | `15000` | HTTP request timeout in milliseconds |
187
- | `smokeTimeoutMs` | `number` | `25000` | Smoke test latency ping timeout |
188
- | `enabledModels` | `array` | `[...]` | List of models exposed in the DSH chat picker |
194
+ | `proxyMode` | `boolean` | `true` | Enable local transparent loopback proxy for sticky sessions and automatic 429 failover |
195
+ | `statsPath` | `string` | `"~/.dsh/clinebot-stats.json"` | Persistent on-disk path for token usage analytics |
196
+ | `accounts` | `array` | `[]` | Additional accounts for multi-account failover and quota rotation (`[{ label, apiKeyEnv }]`) |
197
+ | `activeAccount` | `string` | `""` | Manually pinned active account env name (empty for least-used auto routing) |
198
+ | `timeoutMs` | `number` | `15000` | HTTP probe timeout in milliseconds |
199
+ | `smokeTimeoutMs` | `number` | `25000` | Timeout for smoke test chat completions in milliseconds |
200
+ | `streamIdleTimeoutMs` | `number` | `30000` | Idle timeout between SSE stream chunks in milliseconds |
201
+ | `enabledModels` | `array` | *(deprecated)* | Read-only in public config; rejected on `PUT /config` in favor of `disabledModels` |
189
202
  | `dynamicModels` | `array` | `[]` | Dynamic models automatically synced from the official plan |
190
203
 
191
204
  ---
192
205
 
193
206
  ## 🌐 HTTP API Endpoints
194
207
 
195
- All endpoints are registered under `/dsh-clinebot/*` and protected against untrusted cross-site origins (same-origin and loopback allowed):
208
+ All endpoints are registered under `/dsh-clinebot/*` and protected against untrusted cross-site origins (same-origin and loopback allowed). Control endpoints enforce a 256 KiB request payload limit; the loopback proxy endpoint supports up to 64 MiB payloads (`MAX_PROXY_BODY_BYTES`):
196
209
 
210
+ ### Management & Control Endpoints (Max 256 KiB)
197
211
  * `GET /dsh-clinebot/status` — Live status report including provider health, active credential, quota, and session metrics.
198
212
  * `GET /dsh-clinebot/config` — Diagnostic endpoint returning public configuration without secret keys.
199
213
  * `PUT /dsh-clinebot/config` — Update configuration fields. Accepts only known schema properties (unknown fields or deprecated `enabledModels` return `400 Bad Request`).
200
214
  * `POST /dsh-clinebot/key/verify` — Validates a candidate API key against `api.cline.bot` and returns account email and plan name.
201
215
  * `POST /dsh-clinebot/save-key` — Saves a key into DSH credentials service under a valid `CLINEBOT_API_KEY*` name.
202
216
  * `POST /dsh-clinebot/models/sync` — Synchronizes models with your active subscription plan.
203
- * `POST /dsh-clinebot/models/toggle` — Toggles models via `disabledModels`.
204
- * `POST /dsh-clinebot/accounts/active` — Pins an active account from the account pool.
217
+ * `POST /dsh-clinebot/models/toggle` — Toggles models via `disabledModels` (atomic Volatile preservation).
218
+ * `POST /dsh-clinebot/models/custom` / `DELETE /dsh-clinebot/models/custom` — Manage custom user-defined models.
219
+ * `POST /dsh-clinebot/models/context` / `DELETE /dsh-clinebot/models/context` — Manage model context length overrides.
220
+ * `POST /dsh-clinebot/accounts` — Add account to the multi-account pool.
221
+ * `POST /dsh-clinebot/accounts/delete` — Delete account from the pool with atomic credential preservation.
222
+ * `POST /dsh-clinebot/accounts/active` — Switch or pin active account (or empty for auto least-used routing).
223
+ * `POST /dsh-clinebot/stats/reset` — Reset session request and token statistics.
205
224
  * `POST /dsh-clinebot/smoke` — Runs a live latency test ping.
225
+ * `GET /dsh-clinebot/update/status` — Query available GitHub releases and plugin updates.
226
+ * `POST /dsh-clinebot/update/apply` — Apply version upgrade with process-group cleanup and lockfile sync.
227
+
228
+ ### OpenAI-Compatible Loopback Proxy (Max 64 MiB)
229
+ * `POST /dsh-clinebot/v1/chat/completions` — Transparent local proxy supporting streaming SSE and non-streaming responses, Bearer token authentication, sticky session affinity with least-used quota allocation, body read watchdog (`streamIdleTimeoutMs`), and automatic 429 failover.
230
+ * `GET /dsh-clinebot/v1/models` — OpenAI-compatible catalog listing all active plan and custom models.
206
231
 
207
232
  ---
208
233
 
package/README.ru.md CHANGED
@@ -74,7 +74,7 @@ graph LR
74
74
  end
75
75
 
76
76
  subgraph PluginHost [Хост-часть dsh-clinebot]
77
- HttpEndpoints["API: /api/plugins/dsh-clinebot/*"]
77
+ HttpEndpoints["API: /dsh-clinebot/*"]
78
78
  ClientCore["lib/cline-client.js"]
79
79
  ModelCatalog["lib/models.js (Встроенные + Динамические из плана)"]
80
80
  SlashCmd["Слэш-команда: /cline"]
@@ -107,7 +107,7 @@ graph LR
107
107
 
108
108
  ## ✨ Структура модулей и возможности
109
109
 
110
- * **`lib/models.js`**: каталог встроенных моделей ClinePass (11 моделей с полной поддержкой уровней размышлений `Off` / `Low` / `Medium` / `High` / `Max` и фиксацией лимита шлюза в 200k токенов) и парсер моделей подписки (`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`).
110
+ * **`lib/models.js`**: динамический каталог моделей подписки и встроенных шаблонов с поддержкой уровней рассуждения (`Off` / `Low` / `Medium` / `High` / `Max`), контекстных лимитов, пользовательских моделей (`customModels`) и парсинга тарифа (`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`).
111
111
  * **`lib/cline-client.js`**:
112
112
  * `fetchUsageLimits`: параллельный опрос `GET /users/me/plan/usage-limits`, `GET /users/me/plan` и `GET /users/me` с кэшированием в памяти.
113
113
  * `sessionStats` / `recordSessionRequest`: счетчики сессии (запросы, токены, задержка, время).
@@ -151,53 +151,80 @@ dsh plugin --profile web add @goodandready/dsh-clinebot
151
151
 
152
152
  ---
153
153
 
154
- ## ⚙️ Таблица конфигурации (`settings.yaml`)
154
+ ## ⚙️ Конфигурация (Настройки DSH и Web UI)
155
+
156
+ В современном DeepSeek Harness (0.1.7+) настройки управляются через карточку в Web UI или `PUT /dsh-clinebot/config`, а секретные ключи безопасно хранятся в DSH Credentials (`~/.dsh/.credentials.yaml`).
155
157
 
156
158
  ```yaml
157
159
  dsh-clinebot:
158
160
  enabled: true
159
161
  baseUrl: https://api.cline.bot/api/v1
160
162
  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: []
163
+ defaultModel: your-default-model
164
+ proxyMode: true
165
+ disabledModels: []
166
+ customModels: []
167
+ modelReasoningDefaults:
168
+ your-reasoning-model: high
169
+ modelContextOverrides: []
170
+ statsPath: ~/.dsh/clinebot-stats.json
171
+ timeoutMs: 30000
172
+ smokeTimeoutMs: 60000
173
+ streamIdleTimeoutMs: 60000
174
+ accounts:
175
+ - label: Team Key
176
+ apiKeyEnv: CLINEBOT_API_KEY_2
170
177
  ```
171
178
 
172
179
  ### Параметры конфигурации
173
180
 
174
181
  | Параметр | Тип | По умолчанию | Описание |
175
182
  |:---|:---|:---|:---|
176
- | `enabled` | `boolean` | `true` | Включение моста провайдера ClineBot |
183
+ | `enabled` | `boolean` | `true` | Включение моста провайдера ClineBot в DSH |
177
184
  | `baseUrl` | `string` | `"https://api.cline.bot/api/v1"` | Базовый URL OpenAI-совместимого API ClinePass |
178
185
  | `apiKeyEnv` | `string` | `"CLINEBOT_API_KEY"` | Имя переменной / ключа в хранилище credentials |
179
- | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | Модель, выбираемая по умолчанию |
186
+ | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | Модель, выбираемая по умолчанию для чата и smoke-тестов |
187
+ | `disabledModels` | `array` | `[]` | Список отключённых моделей (новые модели подписки включаются автоматически) |
188
+ | `customModels` | `array` | `[]` | Пользовательские модели шлюза (`[{ id, name, contextLength, maxTokens, category, isReasoning }]`) |
189
+ | `modelReasoningDefaults` | `object` | `{}` | Значения thinking effort по умолчанию для моделей (`low`, `medium`, `high`, `max`) |
180
190
  | `modelContextOverrides` | `array` | `[]` | Пользовательские переопределения размера контекста и лимита токенов |
191
+ | `proxyMode` | `boolean` | `true` | Включение локального прозрачного loopback-прокси с сессионным роутингом и failover |
192
+ | `statsPath` | `string` | `"~/.dsh/clinebot-stats.json"` | Путь к файлу персистентной аналитики использования токенов |
193
+ | `accounts` | `array` | `[]` | Дополнительные аккаунты для ротации квоты и failover (`[{ label, apiKeyEnv }]`) |
194
+ | `activeAccount` | `string` | `""` | Принудительно закреплённый аккаунт (пусто для автоматического выбора least-used) |
181
195
  | `timeoutMs` | `number` | `15000` | Таймаут HTTP-запросов (мс) |
182
- | `smokeTimeoutMs` | `number` | `25000` | Таймаут тестового пинга (мс) |
183
- | `enabledModels` | `array` | `[...]` | Список моделей, активных в селекторе чата |
196
+ | `smokeTimeoutMs` | `number` | `25000` | Таймаут тестового пинга инференса (мс) |
197
+ | `streamIdleTimeoutMs` | `number` | `30000` | Таймаут ожидания между чанками SSE-потока (мс) |
198
+ | `enabledModels` | `array` | *(устарело)* | Только для чтения в public config; отклоняется при `PUT /config` в пользу `disabledModels` |
184
199
  | `dynamicModels` | `array` | `[]` | Динамические модели, автоматически синхронизированные из тарифа |
185
200
 
186
201
  ---
187
202
 
188
203
  ## 🌐 Маршруты HTTP API
189
204
 
190
- Все маршруты регистрируются с префиксом `/dsh-clinebot/*` и защищены от несанкционированных межсайтовых запросов (разрешены same-origin и loopback):
205
+ Все маршруты регистрируются с префиксом `/dsh-clinebot/*` и защищены от межсайтовых запросов (разрешены same-origin и loopback). Управляющие эндпоинты ограничены лимитом 256 КиБ; прокси-эндпоинт поддерживает до 64 МиБ полезной нагрузки (`MAX_PROXY_BODY_BYTES`):
191
206
 
207
+ ### Управляющие эндпоинты (макс. 256 КиБ)
192
208
  * `GET /dsh-clinebot/status` — Текущее состояние провайдера, активный аккаунт, квоты и статистика сессий.
193
209
  * `GET /dsh-clinebot/config` — Диагностический маршрут, возвращающий открытую конфигурацию (без секретов).
194
- * `PUT /dsh-clinebot/config` — Обновление параметров конфигурации. Принимает только известные поля схемы (неизвестные поля и устаревшее `enabledModels` возвращают `400 Bad Request`).
195
- * `POST /dsh-clinebot/key/verify` — Проверка API-ключа на сервере `api.cline.bot` с возвратом email и названия тарифа.
196
- * `POST /dsh-clinebot/save-key` — Сохранение ключа в сервис credentials DSH под именем шаблона `CLINEBOT_API_KEY*`.
210
+ * `PUT /dsh-clinebot/config` — Обновление параметров конфигурации (устаревший `enabledModels` блокируется).
211
+ * `POST /dsh-clinebot/key/verify` — Проверка API-ключа на сервере `api.cline.bot` с возвратом email и тарифа.
212
+ * `POST /dsh-clinebot/save-key` — Сохранение ключа в сервис credentials DSH под именем `CLINEBOT_API_KEY*`.
197
213
  * `POST /dsh-clinebot/models/sync` — Синхронизация списка моделей с официальным тарифом ClinePass.
198
- * `POST /dsh-clinebot/models/toggle` — Включение и отключение моделей через `disabledModels`.
199
- * `POST /dsh-clinebot/accounts/active` — Назначение активного аккаунта из пула.
214
+ * `POST /dsh-clinebot/models/toggle` — Включение и отключение моделей через `disabledModels` с сохранением Volatile-ссылок.
215
+ * `POST /dsh-clinebot/models/custom` / `DELETE /dsh-clinebot/models/custom` — Управление пользовательскими моделями.
216
+ * `POST /dsh-clinebot/models/context` / `DELETE /dsh-clinebot/models/context` — Переопределение контекстного окна моделей.
217
+ * `POST /dsh-clinebot/accounts` — Добавление аккаунта в пул ротации.
218
+ * `POST /dsh-clinebot/accounts/delete` — Удаление аккаунта с атомарной защитой секретного ключа.
219
+ * `POST /dsh-clinebot/accounts/active` — Назначение активного аккаунта из пула (или пусто для auto least-used).
220
+ * `POST /dsh-clinebot/stats/reset` — Сброс счётчиков запросов и токенов.
200
221
  * `POST /dsh-clinebot/smoke` — Выполнение тестового пинга задержки.
222
+ * `GET /dsh-clinebot/update/status` — Проверка наличия обновлений плагина.
223
+ * `POST /dsh-clinebot/update/apply` — Обновление плагина с корректным завершением групп процессов и блокировками профиля.
224
+
225
+ ### OpenAI-совместимый loopback-прокси (макс. 64 МиБ)
226
+ * `POST /dsh-clinebot/v1/chat/completions` — Прозрачный локальный прокси с поддержкой SSE и нестриминговых ответов, Bearer-аутентификацией, сессионной липкостью и least-used распределением квот, контролем дедлайнов (`streamIdleTimeoutMs`) и автоматическим 429 failover.
227
+ * `GET /dsh-clinebot/v1/models` — Каталог моделей в стандарте OpenAI API.
201
228
 
202
229
  ---
203
230
 
package/README.zh.md CHANGED
@@ -74,7 +74,7 @@ graph LR
74
74
  end
75
75
 
76
76
  subgraph PluginHost [dsh-clinebot 宿主运行环境]
77
- HttpEndpoints["API 路由: /api/plugins/dsh-clinebot/*"]
77
+ HttpEndpoints["API 路由: /dsh-clinebot/*"]
78
78
  ClientCore["lib/cline-client.js"]
79
79
  ModelCatalog["lib/models.js (内置精选 + 动态订阅解析)"]
80
80
  SlashCmd["斜杠指令: /cline"]
@@ -107,7 +107,7 @@ graph LR
107
107
 
108
108
  ## ✨ 核心模块与功能
109
109
 
110
- * **`lib/models.js`**:管理 11 款官方精选内置模型(提供完整的 `Off` / `Low` / `Medium` / `High` / `Max` 思考强度映射、上游 200k 上下文容量标注)以及套餐模型动态解析器(`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`)。
110
+ * **`lib/models.js`**:管理动态订阅模型目录与内置精选模板(提供完整的 `Off` / `Low` / `Medium` / `High` / `Max` 思考强度映射、上游 200k 上下文容量标注、自定义模型支持)以及套餐模型动态解析器(`parsePlanIncludedModels`, `getAllModels`, `getDynamicModels`)。
111
111
  * **`lib/cline-client.js`**:
112
112
  * `fetchUsageLimits`:高效并发轮询 `GET /users/me/plan/usage-limits`、`GET /users/me/plan` 与 `GET /users/me` 并进行内存缓存。
113
113
  * `sessionStats` / `recordSessionRequest`:内存级会话度量记录器(请求次数、Token 估算、延迟、时间戳)。
@@ -153,53 +153,80 @@ dsh plugin --profile web add @goodandready/dsh-clinebot
153
153
 
154
154
  ---
155
155
 
156
- ## ⚙️ 配置项参考 (`settings.yaml`)
156
+ ## ⚙️ 配置项参考 (DSH 设置与 Web UI)
157
+
158
+ 在现代 DeepSeek Harness (0.1.7+) 中,各项配置通过 Web UI 或 `PUT /dsh-clinebot/config` 原生管理,密钥安全存储于 DSH Credentials 凭据中心 (`~/.dsh/.credentials.yaml`)。
157
159
 
158
160
  ```yaml
159
161
  dsh-clinebot:
160
162
  enabled: true
161
163
  baseUrl: https://api.cline.bot/api/v1
162
164
  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: []
165
+ defaultModel: your-default-model
166
+ proxyMode: true
167
+ disabledModels: []
168
+ customModels: []
169
+ modelReasoningDefaults:
170
+ your-reasoning-model: high
171
+ modelContextOverrides: []
172
+ statsPath: ~/.dsh/clinebot-stats.json
173
+ timeoutMs: 30000
174
+ smokeTimeoutMs: 60000
175
+ streamIdleTimeoutMs: 60000
176
+ accounts:
177
+ - label: Team Key
178
+ apiKeyEnv: CLINEBOT_API_KEY_2
172
179
  ```
173
180
 
174
181
  ### 配置参数说明
175
182
 
176
183
  | 参数项 | 类型 | 默认值 | 说明 |
177
184
  |:---|:---|:---|:---|
178
- | `enabled` | `boolean` | `true` | 是否启用 ClineBot 桥接插件 |
185
+ | `enabled` | `boolean` | `true` | 是否在 DSH 中启用 ClineBot 桥接插件 |
179
186
  | `baseUrl` | `string` | `"https://api.cline.bot/api/v1"` | ClinePass OpenAI 兼容接口地址 |
180
187
  | `apiKeyEnv` | `string` | `"CLINEBOT_API_KEY"` | 凭据管理系统中的密钥名称 |
181
- | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | 默认选中的模型 ID |
188
+ | `defaultModel` | `string` | `"cline-pass/deepseek-v4-flash"` | 默认选中的模型 ID(用于对话及探活) |
189
+ | `disabledModels` | `array` | `[]` | 在选择器中隐藏的模型 ID 列表(新订阅模型默认自动启用) |
190
+ | `customModels` | `array` | `[]` | 用户自定义网关模型 (`[{ id, name, contextLength, maxTokens, category, isReasoning }]`) |
191
+ | `modelReasoningDefaults` | `object` | `{}` | 各模型默认思考强度配置 (`low`, `medium`, `high`, `max`) |
182
192
  | `modelContextOverrides` | `array` | `[]` | 用户自定义模型上下文窗口与最大 Token 数量覆盖 |
183
- | `timeoutMs` | `number` | `15000` | HTTP 请求超时时间(毫秒) |
193
+ | `proxyMode` | `boolean` | `true` | 启用透明本地环回代理以支持会话粘性路由与 429 自动故障转移 |
194
+ | `statsPath` | `string` | `"~/.dsh/clinebot-stats.json"` | 本地持久化 Token 用量统计文件路径 |
195
+ | `accounts` | `array` | `[]` | 额外轮转账号池 (`[{ label, apiKeyEnv }]`) |
196
+ | `activeAccount` | `string` | `""` | 手动指定的主账号(为空时自动按最低配额消耗优先路由) |
197
+ | `timeoutMs` | `number` | `15000` | HTTP 请求探测超时时间(毫秒) |
184
198
  | `smokeTimeoutMs` | `number` | `25000` | 探活测试超时时间(毫秒) |
185
- | `enabledModels` | `array` | `[...]` | 允许在聊天下拉框中显示的可用模型列表 |
199
+ | `streamIdleTimeoutMs` | `number` | `30000` | SSE 流式输出块间空闲超时时间(毫秒) |
200
+ | `enabledModels` | `array` | *(已废弃)* | 仅在 public config 中只读提供,`PUT /config` 时禁止写入并请使用 `disabledModels` |
186
201
  | `dynamicModels` | `array` | `[]` | 从官方套餐中自动同步的动态模型列表 |
187
202
 
188
203
  ---
189
204
 
190
205
  ## 🌐 HTTP API 接口说明
191
206
 
192
- 所有接口注册于 `/dsh-clinebot/*` 路径,并受到严格的跨站防护保护(仅允许同源或环回请求):
207
+ 所有接口挂载于 `/dsh-clinebot/*` 路径,并受到跨站请求防护(仅放行同源或环回请求)。管理接口限制请求体上限 256 KiB;环回推理代理接口支持最高 64 MiB 有效载荷 (`MAX_PROXY_BODY_BYTES`):
193
208
 
209
+ ### 管理与控制接口(上限 256 KiB)
194
210
  * `GET /dsh-clinebot/status` — 服务运行状态,包括健康探活、当前凭据名称、配额限制及会话统计。
195
- * `GET /dsh-clinebot/config` — 诊断接口,安全获取脱敏后的公共配置。
196
- * `PUT /dsh-clinebot/config` — 更新配置项。仅接受模式中的已知字段(未知字段或已废弃的 `enabledModels` 返回 `400 Bad Request`)。
197
- * `POST /dsh-clinebot/key/verify` — 向 `api.cline.bot` 发送探活请求实时验证密钥,返回绑定邮箱及套餐名称。
198
- * `POST /dsh-clinebot/save-key` — 将 API 密钥安全存储到 DSH credentials 服务。
199
- * `POST /dsh-clinebot/models/sync` — 同步 ClinePass 官方套餐内包含的全部动态模型。
200
- * `POST /dsh-clinebot/models/toggle` — 通过 `disabledModels` 批量切换模型可用性。
201
- * `POST /dsh-clinebot/accounts/active` — 从多账号池中指定当前主账号。
211
+ * `GET /dsh-clinebot/config` — 诊断接口,安全获取脱敏后的公共配置(不含敏感密钥)。
212
+ * `PUT /dsh-clinebot/config` — 更新配置项(严格校验模式,已废弃的 `enabledModels` 被拦截)。
213
+ * `POST /dsh-clinebot/key/verify` — 实时验证 API 密钥有效性,返回绑定邮箱及套餐名称。
214
+ * `POST /dsh-clinebot/save-key` — 将 API 密钥安全写入 DSH 凭据服务。
215
+ * `POST /dsh-clinebot/models/sync` — 手动同步官方套餐动态模型列表。
216
+ * `POST /dsh-clinebot/models/toggle` — 批量切换模型可用性(更新 `disabledModels` 并保留 Volatile 引用)。
217
+ * `POST /dsh-clinebot/models/custom` / `DELETE /dsh-clinebot/models/custom` — 自定义模型增删。
218
+ * `POST /dsh-clinebot/models/context` / `DELETE /dsh-clinebot/models/context` — 上下文窗口与最大 Token 覆盖。
219
+ * `POST /dsh-clinebot/accounts` — 添加多账号备用凭据。
220
+ * `POST /dsh-clinebot/accounts/delete` — 删除账号(具备原子化凭据保护)。
221
+ * `POST /dsh-clinebot/accounts/active` — 指定活动账号(为空时自动启用最低用量优先路由)。
222
+ * `POST /dsh-clinebot/stats/reset` — 重置会话与 Token 消耗统计。
202
223
  * `POST /dsh-clinebot/smoke` — 发起快速探测并返回实时延迟。
224
+ * `GET /dsh-clinebot/update/status` — 查询插件版本更新状态。
225
+ * `POST /dsh-clinebot/update/apply` — 应用版本更新(支持进程树完全清理与锁文件保护)。
226
+
227
+ ### OpenAI 兼容环回代理接口(上限 64 MiB)
228
+ * `POST /dsh-clinebot/v1/chat/completions` — 本地透明代理,支持 SSE 流式与完整响应、会话粘性路由、最低用量负载均衡、响应体超时防护 (`streamIdleTimeoutMs`) 以及 429 自动故障转移。
229
+ * `GET /dsh-clinebot/v1/models` — 符合 OpenAI API 规范的模型列表。
203
230
 
204
231
  ---
205
232
 
@@ -84,9 +84,11 @@ export async function resolveAccountPool(ctx, cfg) {
84
84
  const envName = textSetting(slot.apiKeyEnv) || (i === 0 ? apiKeyEnv : `CLINEBOT_API_KEY_${i + 1}`)
85
85
  const keyInfo = await resolveKeyValue(ctx, envName)
86
86
  const slotId = slot.id || (i === 0 ? 'default' : `account-${i + 1}`)
87
- const isPinned = activeAccount === 'auto'
88
- ? false
89
- : (activeAccount ? (activeAccount === envName || activeAccount === slotId) : i === 0)
87
+ const isPinned = Boolean(
88
+ activeAccount &&
89
+ activeAccount !== 'auto' &&
90
+ (activeAccount === envName || activeAccount === slotId)
91
+ )
90
92
  const quota = keyInfo.value ? getAccountQuotaSnapshot(keyInfo.value, baseUrl) : null
91
93
  resolved.push({
92
94
  id: slotId,