@goodandready/dsh-ollama-cloud-provider 0.1.39 → 0.1.41

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
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.41 — 2026-11-21
4
+
5
+ - Settings: the page is a list of collapsible cards (`<details>/<summary>`, keyboard accessible) with the DSH card metrics (12px radius, 15px/600 title, 14×16 header); Key and the model editor are open by default, the quota card opens on its 80 % warning and Discover opens on an error. Actions inside a header no longer toggle the card (#148).
6
+ - Localization: one typed `locale.register(NS, { en, zh })` call, a shared `format.ts` for relative time and dates (following the DSH language), translated routing reasons and quota labels, so the Chinese UI no longer mixes English strings (#149).
7
+ - Config: record validation lives only in `config.ts`; `routes-values` delegates to it, including manual models and account rules with the same 1..10,000,000 bounds, so a value can no longer be saved and then silently dropped (#146).
8
+ - Documentation: install instructions are registry-first in all three languages; all 45 settings are listed; RU/ZH gained the web search/fetch section; all three gained Troubleshooting; ZH gained the settings-page section; `dist/*.tgz` removed (#150).
9
+ - Release record: DESIGN, index and CHANGELOG match the code; `scripts/smoke-load.mjs` is fixed, builds-aware and runs inside `npm run check` without network (#151).
10
+ - Refactor: unused exports removed, the NDJSON/SSE idle reader shared, and account labels computed in one place (#147).
11
+ - Audit: `relativeLabel` rolls 60m→1h and 24h→1d, invalid locale tags no longer throw, and the shared card CSS no longer affects non-collapsible cards.
12
+
13
+ 198 tests.
14
+
15
+ ## 0.1.40 — 2026-11-21
16
+
17
+ - Settings: an empty numeric field is now unset (`null`) instead of being replaced by a default, invalid values are reported per field and block the save, and `configWritable` disables Save on a read-only host (#140).
18
+ - Settings: manual-model rows keep a stable identity while editing, account key buffers are tied to the row, and a cancelled drag clears its state (#141).
19
+ - Catalog: cold loads are single-flight, a failed refresh is stored with a zero timestamp instead of looking fresh, and one scheduler reads `autoRefresh`/`refreshMinutes` on every tick (#139).
20
+ - Diagnostics: a catalog failure surfaces as `providerError` instead of an empty model list, the local usage rate limit is reported as a rate limit, and quota refresh errors are shown (#144).
21
+ - Transports: tool-call ids stay stable within a block even when the upstream id arrives late, NDJSON/SSE frames are capped at 1 MiB, idle timeouts keep their `TIMEOUT` code, and readers are cancelled cleanly (#145, #152).
22
+ - Security: `redirect: 'error'` on every key-bearing request, `0600/0700` state files, prototype keys ignored, discovery pinned to the validated IP, `providerError`/`source` redacted (#152).
23
+
24
+ 194 tests.
25
+
3
26
  ## 0.1.39 — 2026-11-15
4
27
 
5
28
  - Security: loopback Host detection now requires an IP literal, so a DNS-rebinding page can no longer pass the read host gate or the update endpoint (#135).
@@ -17,7 +40,7 @@
17
40
  - Architecture & Contracts: established canonical `docs/design/DESIGN.md` (following `project-design-contract`), `AGENTS.md`, `index.md`, `deploy.sh`, and `docs/deployment/DEPLOYMENT.md` (#127).
18
41
  - Artifact Guard & Packaging: implemented automated pack guard `scripts/pack-check.mjs` preventing root release tarballs and enforcing DSH Store file size limit (<256 KiB) as part of `npm run check` and `npm run release` (#128, #131).
19
42
  - Publication Boundary: established `.gitattributes` publication layer with `export-ignore` excluding internal documents, deployment scripts, plans, and `scripts/` from public exports while maintaining git tracking (#130).
20
- - Error Diagnostics & Health: replaced 10 unmonitored silent catches across adapter, catalog, index, routes, and transports with `bestEffortFailed` logging via `ctx.logger`; augmented `GET /dsh-ollama/health` with provider error surfacing (`ok: false` and `error` field) on discovery failures (#131).
43
+ - Error Diagnostics & Health: replaced 10 unmonitored silent catches across adapter, catalog, index, routes, and transports with `bestEffortFailed` logging via `ctx.logger`; augmented `GET /dsh-ollama/health` with provider error surfacing (`ok: false` and `providerError` field) on discovery failures (#131).
21
44
  - Modularity: decomposed monolithic 6033-line `lib/index.js` into clean domain-separated modules (`routes.js`, `adapter.js`, `config.js`, etc.) with `tsdown` unbundling, reducing primary entry point to ~150 lines (#131).
22
45
  - Repository Hygiene: audited and pruned 12 stale and detached worktrees, documenting SHAs and ancestor relationships (#129).
23
46
 
@@ -28,7 +51,7 @@
28
51
  ## 0.1.36 — 2026-11-09
29
52
 
30
53
  - Resilience: shortened 401/403 credential rejection cooldown from 24 hours to 5 minutes, added explicit reset endpoint (`POST /dsh-ollama/cooldowns/reset`) and "Reset cooldowns" UI action in settings page, and surfaced exact remaining wait time and root cause (`INVALID_CREDENTIAL`, `QUOTA`, `RATE_LIMIT`) when all keys are cooling (#117).
31
- - Security & Hygiene: untracked internal agent instructions (`AGENTS.md`), project metadata (`index.md`), Gitea templates (`.gitea/`), and internal design/audit documentation (`docs/`) from git mirror trees and added them to `.gitignore`, preventing public leakage to external mirrors (#118).
54
+ - Security & Hygiene: untracked internal agent instructions (`AGENTS.md`), project metadata (`index.md`), Gitea templates (`.gitea/`), and internal design/audit documentation (`docs/`) from git mirror trees and added them to `.gitattributes` with `export-ignore`, preventing leakage into archive-based mirrors (#118).
32
55
  - Security: added `trustedHost` check to `readOnly` route validation, rejecting DNS rebinding attacks on `/dsh-ollama/health` and `/dsh-ollama/status` when non-local `Host` headers are supplied (#119).
33
56
  - Protocol Conformance: prioritized token exhaustion `done_reason === 'length'` (`max-tokens`) over partial in-band tool call markers in native transport streaming (`src/transports/native.ts`) (#120).
34
57
  - State Persistence: replaced direct file writes with atomic file write (`atomicWriteFile` using temp file + `rename`) for `cooldowns.json` and `sticky.json` to prevent file corruption on unexpected crashes (#121).
@@ -435,7 +458,7 @@ Audit fixes (Gitea #1–#15):
435
458
  - Heatmap and theme values no longer hardcode colors (#10).
436
459
  - Test-connection requests disable thinking and use a 32-token budget (#11).
437
460
  - The request log is flushed on shutdown (#12).
438
- - Architecture documentation moved to `docs/design/ARCHITECTURE.md`; the
461
+ - Architecture documentation consolidated into `docs/design/DESIGN.md`; the
439
462
  design contract lives in `docs/design/DESIGN.md` (#13).
440
463
  - Added wiring, analytics, route-guard and adapter regression tests (#14).
441
464
  - Account rows show the 7-day spend without a meaningless percentage (#15).
package/README.md CHANGED
@@ -117,34 +117,18 @@ graph LR
117
117
 
118
118
  ## Install
119
119
 
120
- Build and pack first:
120
+ Install the published package from the registry:
121
121
 
122
122
  ```bash
123
- npm install
124
- npm run build
125
- npm pack
126
- ```
127
-
128
- Install the published package:
129
-
130
- ```bash
131
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.39
123
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.41
132
124
  # DSH Desktop:
133
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.39
134
- ```
135
-
136
- Or install the packed tarball into a profile:
137
-
138
- ```bash
139
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
140
- # DSH Desktop:
141
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
125
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.41
142
126
  ```
143
127
 
144
128
  Restart dsh (or DSH Desktop), then pick **Ollama Cloud** in the model picker.
145
129
 
146
- > **Use the tarball, not the directory.** On dsh 0.2.1-rc.2/rc.3 the Desktop CLI aliases a local
147
- > directory passed to `dsh plugin add` and overwrites the target's `package.json`.
130
+ The exact registry version is the supported installation source. Build and pack from source only
131
+ when developing the plugin itself; see [Development](#development).
148
132
 
149
133
  ## Configure
150
134
 
@@ -172,6 +156,49 @@ Restart dsh (or DSH Desktop), then pick **Ollama Cloud** in the model picker.
172
156
 
173
157
  Every field except `apiKey` is volatile and appears in dsh settings.
174
158
 
159
+ ### Settings reference
160
+
161
+ | Field | Default | Meaning |
162
+ |---|---|---|
163
+ | `apiKeyEnv` | `OLLAMA_API_KEY` | Credential-reference name of the primary key. |
164
+ | `apiKey` | — | Literal key, composition only; never commit. |
165
+ | `apiBase` | `https://ollama.com` | Native API root. |
166
+ | `openAiBase` | `https://ollama.com/v1` | OpenAI-compatible root. |
167
+ | `usageUrl` | `https://ollama.com/api/usage` | Spend endpoint. |
168
+ | `balanceUrl` | `https://ollama.com/api/balance` | Balance endpoint. |
169
+ | `transport` | `native` | Default wire protocol. |
170
+ | `modelTransports` | `{}` | Per-model protocol override. |
171
+ | `requestTimeoutMs` | `300000` | Response-header timeout per attempt. |
172
+ | `streamIdleTimeoutMs` | `300000` | Max gap between stream chunks. |
173
+ | `attemptTimeoutMs` | `0` | Whole-attempt budget; `0` disables it. |
174
+ | `retryMaxRetries` | `0` | In-adapter retries before rotation. |
175
+ | `retryBaseDelayMs` | `250` | Backoff base. |
176
+ | `retryMaxDelayMs` | `2000` | Backoff cap. |
177
+ | `retryJitter` | `0.2` | Backoff jitter (0–1). |
178
+ | `visibleModels` | `[]` | Explicit allowlist when not showing all. |
179
+ | `showAllModels` | `false` | Ignore the allowlist and show everything. |
180
+ | `modelVisibility` | `{}` | Per-model explicit show/hide. |
181
+ | `manualModels` | `[]` | Hand-defined models absent from the catalog. |
182
+ | `modelOverrides` | `{}` | Per-model capabilities, context and reasoning. |
183
+ | `modelOrder` | `[]` | Picker order. |
184
+ | `filterModelsByPlan` | `true` | Hide models the plan cannot use. |
185
+ | `contextWindow` | model meta | Global context override. |
186
+ | `contextWindowOverrides` | `{}` | Per-model context override. |
187
+ | `maxOutputTokens` | model meta | Global output cap. |
188
+ | `temperature`…`topP`/`minP` | provider default | Sampling. |
189
+ | `seed`, `repeatPenalty`, `repeatLastN` | provider default | Sampling. |
190
+ | `numCtx`, `keepAlive`, `stop` | provider default | Native generation controls. |
191
+ | `autoRefresh` | `true` | Refresh the catalog in the background. |
192
+ | `refreshMinutes` | `1440` | Refresh interval; `0` = mount only. |
193
+ | `accounts` | `[]` | Extra keys with `label` and `apiKeyEnv`. |
194
+ | `modelAccountRules` | `[]` | Glob `pattern → account` routing. |
195
+ | `stickySession` | `true` | Keep one account per conversation. |
196
+ | `activeAccount` | `""` | Pin one account by label. |
197
+ | `showSidebarQuota` | `false` | Show the sidebar quota card. |
198
+ | `planLabel` | `""` | Optional label next to the provider name. |
199
+ | `priceOverrides` | `{}` | Per-model price overrides. |
200
+ | `userAgent` | `dsh-ollama-cloud-provider/<version>` | Outbound User-Agent. |
201
+
175
202
  ### Keys
176
203
 
177
204
  1. `config.apiKey` (composition only, `role('secret')`).
@@ -212,14 +239,18 @@ Open **Settings → Ollama Cloud**:
212
239
  - **Key** — status, paste a key, clear it, run **Test connection** against a chosen model. The probe disables thinking so the reply is visible.
213
240
  - **Balance and usage** — credit bar or legacy windows, spend windows, warning at 80 % and exhausted at 95 %.
214
241
  - **Accounts** — extra keys, per-account spend, pin, remove, set a key, reset cooldowns.
242
+ - **Service status** — reachability probe with latency and the last check time.
215
243
  - **Model → account rules** — glob rules.
216
244
  - **Routing** — sticky session per conversation.
217
245
  - **Models** — search, refresh the live catalog, hide models, override the wire transport per model, see price, context and capabilities.
246
+ - **Manual catalog entries** — add models the catalog does not list.
247
+ - **Generation defaults** — sampling and output limits.
218
248
  - **Connection** — native and OpenAI bases, usage and balance endpoints, transport, timeouts, output cap and context override.
249
+ - **Discover** — probe an unsaved endpoint with a one-shot key before saving it.
219
250
  - **Sidebar** — show or hide the quota card, and an optional plan label (for example `PRO`) shown next to the provider name.
220
251
  - **Plugin update** — current/latest version and **Update now**.
221
252
 
222
- The Host serves `/dsh-ollama/state`, `/health`, `/status`, `/analytics`, `/usage`, `/balance`, `/config`, `/key`, `/key/clear`, `/refresh`, `/models/refresh`, `/test` and `/update`. `/status` probes the public tag endpoint without a key or quota. Writes require JSON, an `Origin` or `Referer` matching `Host` (the Desktop renderer is identified by its `dsh-auth-*` cookie and desktop user agent when both headers are absent), and are restricted to loopback (`127.0.0.1` / `::1`); a write without any source identity is rejected with 403.
253
+ The Host serves `/dsh-ollama/state`, `/health`, `/status`, `/analytics`, `/usage`, `/balance`, `/config`, `/key`, `/key/clear`, `/refresh`, `/models/refresh`, `/discover`, `/test` and `/update`. `/status` probes the public tag endpoint without a key or quota. Writes require JSON, an `Origin` or `Referer` matching `Host` (the Desktop renderer is identified by its `dsh-auth-*` cookie and desktop user agent when both headers are absent), and are restricted to loopback (`127.0.0.1` / `::1`); a write without any source identity is rejected with 403.
223
254
 
224
255
  ## Command
225
256
 
@@ -250,7 +281,7 @@ Checked live on 2026-10-21:
250
281
  npm run typecheck
251
282
  npm test
252
283
  npm run build
253
- npm run check # typecheck + tests + build
284
+ npm run check # typecheck + tests + build + smoke-load + pack:check
254
285
  npm run release # check + packed tarball
255
286
  node scripts/probe.mjs
256
287
  ```
@@ -270,6 +301,16 @@ The Ollama Cloud settings page in DSH Desktop (dark theme): configured credentia
270
301
  - Custom endpoint URLs must be absolute `http(s)` without embedded credentials or fragments; link-local and metadata addresses are refused.
271
302
  - `/status` is cached for 10 seconds, while refresh, test and endpoint-discovery routes are single-flight and rate-limited.
272
303
 
304
+ ## Troubleshooting
305
+
306
+ - **No models in the picker** — open `GET /dsh-ollama/health`; `providerError` names the catalog failure. Check `apiBase`, network access and the key.
307
+ - **401/403** — the key is rejected and cooled for 5 minutes; fix the credential, then reset cooldowns in Settings or call `POST /dsh-ollama/cooldowns/reset`.
308
+ - **All accounts cooling** — the error carries the remaining wait and the reason (`INVALID_CREDENTIAL`, `QUOTA`, `RATE_LIMIT`).
309
+ - **Usage is unavailable after several refreshes** — `/api/usage` allows 10 requests per minute; the plugin reports `usage rate limit reached; retry shortly` instead of an outage. Wait a minute.
310
+ - **Update button is disabled** — the DSH CLI entry was not found at runtime; install the exact version with `dsh plugin --profile web add ...@<version>`.
311
+ - **Settings are read-only** — the host's settings service is read-only; Save is disabled and the badge says why.
312
+ - **502/504 from the gateway** — the key rotates to the next account; the routing table shows `rotation`.
313
+
273
314
  ## Limitations
274
315
 
275
316
  - **Cloud only.** Local `http://localhost:11434` is not registered as a route.
package/README.ru.md CHANGED
@@ -99,31 +99,32 @@ graph LR
99
99
 
100
100
  ## Установка
101
101
 
102
- Сборка и упаковка из исходного кода:
102
+ Установите опубликованный пакет из registry:
103
103
 
104
104
  ```bash
105
- npm install
106
- npm run build
107
- npm pack
105
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.41
106
+ # DSH Desktop:
107
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.41
108
108
  ```
109
109
 
110
- Установка опубликованного пакета из npm:
110
+ После установки перезапустите dsh (или DSH Desktop) и выберите **Ollama Cloud** в списке моделей.
111
111
 
112
- ```bash
113
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.39
114
- # DSH Desktop:
115
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.39
116
- ```
112
+ Поддерживаемый источник установки — точная версия из registry. Сборка из исходников нужна только
113
+ при разработке самого плагина; см. `README.md`, раздел Development.
117
114
 
118
- Либо установка из упакованного tarball:
115
+ ## Веб-поиск и загрузка страниц
119
116
 
120
- ```bash
121
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
122
- # DSH Desktop:
123
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
124
- ```
117
+ Если в DSH есть сервис `web`, плагин регистрирует Ollama Cloud как провайдера поиска и загрузки
118
+ страниц (`id: ollama-cloud`). Используются `POST <apiBase>/api/web_search` и
119
+ `POST <apiBase>/api/web_fetch` с тем же credential reference, что и чат. Редиректы запрещены,
120
+ транспортный сбой повторяется один раз, результаты поиска ограничены 10, текст страницы — 256 KiB.
125
121
 
126
- После установки перезапустите dsh (или DSH Desktop) и выберите **Ollama Cloud** в списке моделей.
122
+ ```yaml
123
+ - id: web
124
+ config:
125
+ searchProvider: ollama-cloud
126
+ fetchProvider: ollama-cloud
127
+ ```
127
128
 
128
129
  ## Конфигурация
129
130
 
@@ -149,6 +150,49 @@ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud
149
150
 
150
151
  Все поля, кроме `apiKey`, доступны для изменения в интерфейсе настроек DSH.
151
152
 
153
+ ### Справочник настроек
154
+
155
+ | Поле | По умолчанию |
156
+ |---|---|
157
+ | `apiKeyEnv` | `OLLAMA_API_KEY` |
158
+ | `apiKey` | — (только composition) |
159
+ | `apiBase` | `https://ollama.com` |
160
+ | `openAiBase` | `https://ollama.com/v1` |
161
+ | `usageUrl` | `https://ollama.com/api/usage` |
162
+ | `balanceUrl` | `https://ollama.com/api/balance` |
163
+ | `transport` | `native` |
164
+ | `modelTransports` | `{}` |
165
+ | `requestTimeoutMs` | `300000` |
166
+ | `streamIdleTimeoutMs` | `300000` |
167
+ | `attemptTimeoutMs` | `0` (выключен) |
168
+ | `retryMaxRetries` | `0` |
169
+ | `retryBaseDelayMs` | `250` |
170
+ | `retryMaxDelayMs` | `2000` |
171
+ | `retryJitter` | `0.2` |
172
+ | `visibleModels` | `[]` |
173
+ | `showAllModels` | `false` |
174
+ | `modelVisibility` | `{}` |
175
+ | `manualModels` | `[]` |
176
+ | `modelOverrides` | `{}` |
177
+ | `modelOrder` | `[]` |
178
+ | `filterModelsByPlan` | `true` |
179
+ | `contextWindow` | из метаданных модели |
180
+ | `contextWindowOverrides` | `{}` |
181
+ | `maxOutputTokens` | из метаданных модели |
182
+ | `temperature`, `topK`, `topP`, `minP` | значение провайдера |
183
+ | `seed`, `repeatPenalty`, `repeatLastN` | значение провайдера |
184
+ | `numCtx`, `keepAlive`, `stop` | значение провайдера |
185
+ | `autoRefresh` | `true` |
186
+ | `refreshMinutes` | `1440` (`0` — только при старте) |
187
+ | `accounts` | `[]` |
188
+ | `modelAccountRules` | `[]` |
189
+ | `stickySession` | `true` |
190
+ | `activeAccount` | `""` |
191
+ | `showSidebarQuota` | `false` |
192
+ | `planLabel` | `""` |
193
+ | `priceOverrides` | `{}` |
194
+ | `userAgent` | `dsh-ollama-cloud-provider/<версия>` |
195
+
152
196
  ### Получение и хранение ключей
153
197
 
154
198
  1. `config.apiKey` в файле конфигурации (`role('secret')`).
@@ -186,9 +230,15 @@ modelAccountRules:
186
230
  - **Key**: статус ключа, вставка, очистка, кнопка **Test connection**.
187
231
  - **Balance & Usage**: шкалы кредитов, окна расходов, предупреждения при 80% и 95%.
188
232
  - **Accounts**: управление пулом дополнительных учетных записей.
233
+ - **Service status**: доступность, задержка и время последней проверки.
189
234
  - **Model rules**: настройка правил ротации по моделям.
235
+ - **Routing**: sticky-сессия для диалога.
190
236
  - **Models**: поиск, принудительное обновление каталога моделей, allowlist, переопределение транспорта.
191
- - **Connection**: базовые адреса, таймауты, лимиты токенов.
237
+ - **Manual catalog entries**: добавление моделей, которых нет в каталоге.
238
+ - **Generation defaults**: параметры сэмплинга и лимиты вывода.
239
+ - **Connection**: базовые адреса, таймауты, лимиты токенов, переопределение контекста.
240
+ - **Discover**: проверка несохранённого эндпоинта одноразовым ключом.
241
+ - **Sidebar**: показ карточки квоты и метка плана.
192
242
  - **Plugin update**: проверка обновлений и кнопка **Update now**.
193
243
 
194
244
  ## Визуальная верификация
@@ -223,6 +273,16 @@ modelAccountRules:
223
273
  - Собственные адреса эндпоинтов должны быть абсолютными `http(s)` без встроенных учётных данных и фрагментов; link-local и metadata-адреса отклоняются.
224
274
  - `/status` кэшируется на 10 секунд, а маршруты обновления, теста и поиска эндпоинтов ограничены по частоте и выполняются в единственном экземпляре.
225
275
 
276
+ ## Диагностика
277
+
278
+ - **В списке моделей пусто** — проверьте `GET /dsh-ollama/health`: поле `providerError` называет причину. Проверьте `apiBase`, сеть и ключ.
279
+ - **401/403** — ключ отклонён и остывает 5 минут; исправьте credential, затем сбросьте cooldowns в настройках или вызовите `POST /dsh-ollama/cooldowns/reset`.
280
+ - **Все аккаунты остывают** — ошибка содержит оставшееся время и причину (`INVALID_CREDENTIAL`, `QUOTA`, `RATE_LIMIT`).
281
+ - **Расход «недоступен» после нескольких обновлений** — `/api/usage` допускает 10 запросов в минуту; плагин сообщает `usage rate limit reached; retry shortly`. Подождите минуту.
282
+ - **Кнопка обновления неактивна** — CLI DSH не найден в runtime; установите точную версию через `dsh plugin --profile web add ...@<версия>`.
283
+ - **Настройки read-only** — сервис настроек хоста только для чтения; Save отключён, бейдж объясняет причину.
284
+ - **502/504 от шлюза** — ключ переключается на следующий аккаунт; в таблице маршрутизации видно `rotation`.
285
+
226
286
  ## Ограничения
227
287
 
228
288
  - Только Ollama Cloud; локальный сервис `http://localhost:11434` данным плагином не регистрируется.
package/README.zh.md CHANGED
@@ -98,31 +98,30 @@ graph LR
98
98
 
99
99
  ## 安装指南
100
100
 
101
- 从源码构建与打包:
101
+ 从 registry 安装已发布版本:
102
102
 
103
103
  ```bash
104
- npm install
105
- npm run build
106
- npm pack
104
+ dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.41
105
+ # DSH 桌面端:
106
+ dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.41
107
107
  ```
108
108
 
109
- 从 npm 安装已发布版本:
109
+ 安装完成后重启 dsh 或 DSH 桌面端,在模型列表中选择 **Ollama Cloud** 即可。
110
110
 
111
- ```bash
112
- dsh plugin --profile web add @goodandready/dsh-ollama-cloud-provider@0.1.39
113
- # DSH 桌面端:
114
- dsh plugin --profile desktop add @goodandready/dsh-ollama-cloud-provider@0.1.39
115
- ```
111
+ 受支持的安装来源是 registry 中的精确版本。只有在开发插件本身时才需要从源码构建;参见 `README.md` 的 Development 一节。
116
112
 
117
- 或通过打包文件安装:
113
+ ## 网页搜索与抓取
118
114
 
119
- ```bash
120
- dsh plugin --profile web add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
121
- # DSH 桌面端:
122
- dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud-provider-0.1.39.tgz
123
- ```
115
+ 当 DSH 提供 `web` 服务时,插件会把 Ollama Cloud 注册为搜索和抓取提供商(`id: ollama-cloud`)。
116
+ 使用与聊天相同的凭据引用调用 `POST <apiBase>/api/web_search` 和 `POST <apiBase>/api/web_fetch`。
117
+ 禁止重定向,传输失败重试一次,搜索结果上限 10 条,页面文本上限 256 KiB。
124
118
 
125
- 安装完成后重启 dsh 或 DSH 桌面端,在模型列表中选择 **Ollama Cloud** 即可。
119
+ ```yaml
120
+ - id: web
121
+ config:
122
+ searchProvider: ollama-cloud
123
+ fetchProvider: ollama-cloud
124
+ ```
126
125
 
127
126
  ## 配置示例
128
127
 
@@ -148,6 +147,49 @@ dsh plugin --profile desktop add /absolute/path/to/goodandready-dsh-ollama-cloud
148
147
 
149
148
  除 `apiKey` 外的所有配置项均可在 DSH 设置页直接修改。
150
149
 
150
+ ### 配置项参考
151
+
152
+ | 配置项 | 默认值 |
153
+ |---|---|
154
+ | `apiKeyEnv` | `OLLAMA_API_KEY` |
155
+ | `apiKey` | —(仅限 composition) |
156
+ | `apiBase` | `https://ollama.com` |
157
+ | `openAiBase` | `https://ollama.com/v1` |
158
+ | `usageUrl` | `https://ollama.com/api/usage` |
159
+ | `balanceUrl` | `https://ollama.com/api/balance` |
160
+ | `transport` | `native` |
161
+ | `modelTransports` | `{}` |
162
+ | `requestTimeoutMs` | `300000` |
163
+ | `streamIdleTimeoutMs` | `300000` |
164
+ | `attemptTimeoutMs` | `0`(关闭) |
165
+ | `retryMaxRetries` | `0` |
166
+ | `retryBaseDelayMs` | `250` |
167
+ | `retryMaxDelayMs` | `2000` |
168
+ | `retryJitter` | `0.2` |
169
+ | `visibleModels` | `[]` |
170
+ | `showAllModels` | `false` |
171
+ | `modelVisibility` | `{}` |
172
+ | `manualModels` | `[]` |
173
+ | `modelOverrides` | `{}` |
174
+ | `modelOrder` | `[]` |
175
+ | `filterModelsByPlan` | `true` |
176
+ | `contextWindow` | 模型元数据 |
177
+ | `contextWindowOverrides` | `{}` |
178
+ | `maxOutputTokens` | 模型元数据 |
179
+ | `temperature`、`topK`、`topP`、`minP` | 提供商默认值 |
180
+ | `seed`、`repeatPenalty`、`repeatLastN` | 提供商默认值 |
181
+ | `numCtx`、`keepAlive`、`stop` | 提供商默认值 |
182
+ | `autoRefresh` | `true` |
183
+ | `refreshMinutes` | `1440`(`0` 表示仅启动时) |
184
+ | `accounts` | `[]` |
185
+ | `modelAccountRules` | `[]` |
186
+ | `stickySession` | `true` |
187
+ | `activeAccount` | `""` |
188
+ | `showSidebarQuota` | `false` |
189
+ | `planLabel` | `""` |
190
+ | `priceOverrides` | `{}` |
191
+ | `userAgent` | `dsh-ollama-cloud-provider/<版本>` |
192
+
151
193
  ### 密钥配置
152
194
 
153
195
  1. DSH 配置中的 `config.apiKey`。
@@ -174,6 +216,23 @@ DSH Desktop(暗黑主题)中的 Ollama Cloud 设置与用量面板:
174
216
 
175
217
  ![Ollama Cloud 设置](media/visual-verification.png)
176
218
 
219
+ ## 设置页
220
+
221
+ 在 **设置 → Ollama Cloud** 中:
222
+ - **密钥** — 状态、粘贴、清除、测试连接。
223
+ - **余额与用量** — 额度条、支出窗口、80%/95% 提示。
224
+ - **账号** — 额外密钥、花费、固定、移除、设置密钥、重置冷却。
225
+ - **服务状态** — 可用性、延迟与最近检查时间。
226
+ - **模型→账号规则** — glob 规则。
227
+ - **路由** — 会话粘性。
228
+ - **模型** — 搜索、刷新目录、隐藏模型、每模型传输、价格/上下文/能力。
229
+ - **手动目录条目** — 添加目录中不存在的模型。
230
+ - **生成默认值** — 采样与输出限制。
231
+ - **连接** — 基础地址、超时、输出上限、上下文覆盖。
232
+ - **发现** — 使用一次性密钥探测未保存的端点。
233
+ - **侧边栏** — 显示/隐藏配额卡片与计划标签。
234
+ - **插件更新** — 当前/最新版本与立即更新。
235
+
177
236
  ## 常用指令
178
237
 
179
238
  ```bash
@@ -193,6 +252,16 @@ DSH Desktop(暗黑主题)中的 Ollama Cloud 设置与用量面板:
193
252
  - 自定义端点必须是完整的 `http(s)` 地址,不得包含账号密码或片段;link-local 与 metadata 地址会被拒绝。
194
253
  - `/status` 缓存 10 秒;刷新、测试与端点发现路由为单飞并限流。
195
254
 
255
+ ## 故障排查
256
+
257
+ - **模型列表为空** — 打开 `GET /dsh-ollama/health`,`providerError` 会给出原因;检查 `apiBase`、网络和密钥。
258
+ - **401/403** — 密钥被拒绝并冷却 5 分钟;修复凭据后,在设置中重置冷却或调用 `POST /dsh-ollama/cooldowns/reset`。
259
+ - **所有账号都在冷却** — 错误会包含剩余时间和原因(`INVALID_CREDENTIAL`、`QUOTA`、`RATE_LIMIT`)。
260
+ - **多次刷新后用量显示不可用** — `/api/usage` 限制每分钟 10 次;插件会提示 `usage rate limit reached; retry shortly`,请稍等一分钟。
261
+ - **更新按钮不可用** — 运行时未找到 DSH CLI;使用 `dsh plugin --profile web add ...@<版本>` 安装精确版本。
262
+ - **设置为只读** — 宿主的设置服务为只读;保存已禁用,徽章会说明原因。
263
+ - **网关 502/504** — 密钥会切换到下一个账号;路由表中会显示 `rotation`。
264
+
196
265
  ## 限制与注意事项
197
266
 
198
267
  - 仅支持 Ollama Cloud 云端模型;不会注册本地 `http://localhost:11434` 路由。
package/lib/adapter.js CHANGED
@@ -31,10 +31,16 @@ function effortName(id) {
31
31
  }
32
32
  async function atomicWriteFile(filePath, data) {
33
33
  const dir = dirname(filePath);
34
- await mkdir(dir, { recursive: true });
34
+ await mkdir(dir, {
35
+ recursive: true,
36
+ mode: 448
37
+ });
35
38
  const tmp = join(dir, `.${basename(filePath)}.${randomUUID()}.tmp`);
36
39
  try {
37
- await writeFile(tmp, data, "utf8");
40
+ await writeFile(tmp, data, {
41
+ encoding: "utf8",
42
+ mode: 384
43
+ });
38
44
  await rename(tmp, filePath);
39
45
  } catch (error) {
40
46
  await rm(tmp, { force: true }).catch((err) => bestEffortFailed("atomicWriteFile:rm-tmp", err));
@@ -394,6 +400,7 @@ var OllamaCloudAdapter = class extends LlmAdapter {
394
400
  method: "POST",
395
401
  headers,
396
402
  body: JSON.stringify(body),
403
+ redirect: "error",
397
404
  signal: controller.signal
398
405
  });
399
406
  if (attempt < policy.maxRetries && isRetryableStatus(response.status)) {
@@ -56,8 +56,14 @@ async function saveCatalogSnapshot(baseURL, ids, meta) {
56
56
  meta
57
57
  };
58
58
  try {
59
- await mkdir(dirname(path), { recursive: true });
60
- await writeFile(temp, `${JSON.stringify(payload)}\n`, "utf8");
59
+ await mkdir(dirname(path), {
60
+ recursive: true,
61
+ mode: 448
62
+ });
63
+ await writeFile(temp, `${JSON.stringify(payload)}\n`, {
64
+ encoding: "utf8",
65
+ mode: 384
66
+ });
61
67
  await rename(temp, path);
62
68
  } catch (error) {
63
69
  bestEffortFailed("catalog cache write failed", error);
@@ -0,0 +1,34 @@
1
+ // src/catalog-scheduler.ts
2
+ /**
3
+ * The single owner of periodic catalog refresh. It re-reads the live settings on
4
+ * every tick, so changing `autoRefresh` or `refreshMinutes` applies without a
5
+ * restart, and it never runs two refreshes for the same due moment.
6
+ */
7
+ function createCatalogScheduler(options) {
8
+ const now = options.now ?? Date.now;
9
+ let last = now();
10
+ const check = () => {
11
+ try {
12
+ const config = options.current();
13
+ if (!config.autoRefresh) return;
14
+ const minutes = Math.floor(config.refreshMinutes);
15
+ if (!Number.isFinite(minutes) || minutes <= 0) return;
16
+ const at = now();
17
+ if (at - last < minutes * 6e4) return;
18
+ last = at;
19
+ const result = options.refresh();
20
+ if (result !== void 0) Promise.resolve(result).catch((error) => options.onError?.(error));
21
+ } catch (error) {
22
+ options.onError?.(error);
23
+ }
24
+ };
25
+ const timer = setInterval(check, options.tickMs ?? 6e4);
26
+ timer.unref?.();
27
+ return {
28
+ check,
29
+ dispose: () => clearInterval(timer)
30
+ };
31
+ }
32
+ export { createCatalogScheduler };
33
+
34
+ //# sourceMappingURL=catalog-scheduler.js.map
package/lib/catalog.js CHANGED
@@ -7,7 +7,6 @@ import { formatPrice, priceFor } from "./pricing.js";
7
7
  import { normalizeThinking } from "./reasoning.js";
8
8
  import { modelsUrlFor, tagsUrlFor } from "./routing.js";
9
9
  // src/catalog.ts
10
- const CATALOG_TTL_MS = 6e5;
11
10
  const CATALOG_TIMEOUT_MS = 15e3;
12
11
  const liveMeta = /* @__PURE__ */ new Map();
13
12
  const cache = /* @__PURE__ */ new Map();
@@ -125,6 +124,7 @@ async function fetchJson(url, config, fetchImpl, signal) {
125
124
  accept: "application/json",
126
125
  "user-agent": config.userAgent
127
126
  },
127
+ redirect: "error",
128
128
  signal
129
129
  });
130
130
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -154,10 +154,27 @@ async function refreshCatalog(config, fetchImpl = fetch, force = false) {
154
154
  }
155
155
  const cached = cache.get(key);
156
156
  if (!force && cached !== void 0) {
157
- if (config.autoRefresh && Date.now() - cached.at >= CATALOG_TTL_MS) refreshInBackground(config, fetchImpl, key);
157
+ const ttl = catalogTtlMs(config);
158
+ if (ttl > 0 && (cached.at === 0 || Date.now() - cached.at >= ttl)) refreshShared(config, fetchImpl, key, true);
158
159
  return cached.ids;
159
160
  }
160
- return refreshNow(config, fetchImpl, key, cached !== void 0, generation);
161
+ return refreshShared(config, fetchImpl, key, cached !== void 0);
162
+ }
163
+ function catalogTtlMs(config) {
164
+ if (!config.autoRefresh || config.refreshMinutes <= 0) return 0;
165
+ return Math.max(1, Math.floor(config.refreshMinutes)) * 6e4;
166
+ }
167
+ function refreshShared(config, fetchImpl, key, keepOnFailure) {
168
+ const existing = inflight.get(key);
169
+ if (existing !== void 0) return existing;
170
+ const task = refreshNow(config, fetchImpl, key, keepOnFailure, generation).catch((error) => {
171
+ bestEffortFailed("catalog:fetchModels", error);
172
+ return cache.get(key)?.ids ?? Object.keys(GENERATED_MODELS);
173
+ }).finally(() => {
174
+ if (inflight.get(key) === task) inflight.delete(key);
175
+ });
176
+ inflight.set(key, task);
177
+ return task;
161
178
  }
162
179
  async function refreshNow(config, fetchImpl, key, keepOnFailure, epoch) {
163
180
  const budget = createAttemptBudget(CATALOG_TIMEOUT_MS);
@@ -176,6 +193,7 @@ async function refreshNow(config, fetchImpl, key, keepOnFailure, epoch) {
176
193
  if (live.length > 0) {
177
194
  const ids = adoptLive(live, tags, key);
178
195
  if (ids.length > 0) {
196
+ if (epoch !== generation) return ids;
179
197
  cache.set(key, {
180
198
  at: Date.now(),
181
199
  ids
@@ -190,6 +208,7 @@ async function refreshNow(config, fetchImpl, key, keepOnFailure, epoch) {
190
208
  if (discovered.length > 0) {
191
209
  for (const liveKey of liveMeta.keys()) if (liveKey.startsWith(`${key}|`)) liveMeta.delete(liveKey);
192
210
  const ids = discovered;
211
+ if (epoch !== generation) return ids;
193
212
  cache.set(key, {
194
213
  at: Date.now(),
195
214
  ids
@@ -204,21 +223,11 @@ async function refreshNow(config, fetchImpl, key, keepOnFailure, epoch) {
204
223
  }
205
224
  const fallback = Object.keys(GENERATED_MODELS);
206
225
  if (epoch === generation) cache.set(key, {
207
- at: Date.now(),
226
+ at: 0,
208
227
  ids: fallback
209
228
  });
210
229
  return fallback;
211
230
  }
212
- function refreshInBackground(config, fetchImpl, key) {
213
- if (inflight.has(key)) return;
214
- const task = refreshNow(config, fetchImpl, key, true, generation).catch((err) => {
215
- bestEffortFailed("catalog:fetchModels", err);
216
- return cache.get(key)?.ids ?? Object.keys(GENERATED_MODELS);
217
- }).finally(() => {
218
- inflight.delete(key);
219
- });
220
- inflight.set(key, task);
221
- }
222
231
  function clearCatalogCache() {
223
232
  generation += 1;
224
233
  cache.clear();