feat(m1): Ollama client, catalog, streaming chat and CLI (T1.1-T1.6)

Add endpoint policy and redirect-safe ephemeral HTTP client, error mapping, catalog cache and version checks, streaming chat with phase timeouts/cancellation, provisional Hy-MT3 prompt/language/request factory, warm-up policy, and sprachmittler-cli models/show/translate. Recapture the 7B fixtures; defer the 1.8B VERIFY items; document ADR-016. Also fix the signature checker's pipefail SIGPIPE issue.
This commit is contained in:
schihei committed 2026-11-26 13:04:22 +01:00
1 parent 7ca5c710ec
commit 26b493e7e5
93 files changed
+3732 -218

No files matched your search

+7 -1
View File
@@ -126,6 +126,8 @@ flowchart TD
App --> Capture
CLI[sprachmittler-cli] --> Core
CLI --> Eval
CLI --> Ollama
CLI --> Engines
Eval --> Core
Core --> Text
Core --> Ollama
@@ -142,6 +144,8 @@ flowchart TD
- `SprachmittlerCore` composes everything through **protocols** so each part can be faked in tests. It contains no model-specific branches and no AppKit.
- `SprachmittlerCapture` is the only module that imports `ApplicationServices`/`Accessibility` and touches `NSPasteboard`. It depends on `SprachmittlerCore` for domain types and protocols.
- `SprachmittlerEval` is linked into the CLI only, never into the app.
- `sprachmittler-cli` links `SprachmittlerOllama` and `SprachmittlerEngines` directly for the M1 commands; it is never linked into the app.
- `SprachmittlerTestSupport` is test-only and depends on `SprachmittlerCore` and `SprachmittlerOllama`; it is never linked into the app.
- The `App` target holds no business logic. Anything with a branch worth testing belongs in a package module.
### Third-party dependencies
@@ -398,6 +402,8 @@ public protocol OllamaCatalog: Sendable {
func installedModels() async throws -> [InstalledModel]
func show(model: String) async throws -> ModelDetails
func loadedModels() async throws -> [LoadedModel]
func refresh() async
func checkMinimumVersion() async throws
}
public protocol OllamaChatting: Sendable {
@@ -415,7 +421,7 @@ Implementation rules:
- `URLSession` with an **ephemeral** configuration, no cookies, no URL cache, no credential storage, and a delegate that **refuses redirects**.
- `URLSession.bytes(for:)` and line-by-line NDJSON decoding; carry partial lines across chunks.
- Cancellation: cancelling the consuming task cancels the URL task (`onTermination` → `task.cancel()`).
- Timeouts per phase, injectable: connect 3 s; first token 120 s (includes cold model load); idle 20 s; total per chunk 180 s.
- Timeouts per phase, injectable: connect and first token 120 s (includes cold model load; `URLSession` has no separate connect hook); idle 20 s; total per chunk 180 s.
- No `system` message, no `images`, no `think` (the model reports only `completion`). Send exactly one user message with the prompt.
- `keep_alive` comes from settings (`30m` default; `0` unloads after the request).
- `/api/show` results are cached per model digest for the app lifetime and invalidated on "Refresh models".
+7
View File
@@ -108,3 +108,10 @@ Status: Accepted
Context: The user may double-copy again, change the target language or close the panel while a request is streaming. Two overlapping streams would confuse the panel and waste compute.
Decision: `TranslationSession` is an actor with one active request. A new trigger or target change increments an epoch and cancels the previous URL task. Events from an older epoch are discarded. Chunks are translated sequentially. Copy does not change the session; Replace only runs from a `.ready` state with no blocking warnings.
Consequences: Fast, predictable updates and no orphaned requests. The previous translation is lost when the user triggers a new one; that is intentional and avoids history.
## ADR-016 — Provisional M1 Engines slice for the CLI
Status: Accepted (provisional; replaced in M2)
Context: T1.6 needs the documented Default prompt and the exact model language name before T2.2/T2.3 exist. Putting either in the CLI target would violate documented-prompts-only and the lint rule that prompt and language literals live in `SprachmittlerEngines`.
Decision: Add a provisional `ModelLanguage` with the 16 common targets from `LANGUAGES.md` §5, the byte-exact Default Translation prompt, the documented sampling values and `HyMT3RequestFactory` in `SprachmittlerEngines`. T2.3 replaces the table with all 102 languages; T2.1/T2.2 replace the factory with `TranslationAdapter`/`HyMT3Adapter`.
Consequences: The M1 CLI translates en→de and the other common targets without a free-form prompt. Unknown codes fail before the network. Only 16 targets resolve until T2.3, and no prompt literal or model tag appears outside Engines.
+14 -15
View File
@@ -60,7 +60,7 @@ The final line:
```
- Durations are nanoseconds. Map them into `ChatMetrics` (load, prompt eval, eval, total; token counts).
- `done_reason`: `"stop"` = normal end; `"length"` = hit `num_predict` → warning `truncated`, Replace disabled by default. Treat any other value as `"stop"` but log it at `.info`. **VERIFY** the full set of values.
- `done_reason`: `"stop"` = normal end; `"length"` = hit `num_predict` → warning `truncated`, Replace disabled by default. Observed values: `"stop"` and `"length"`; a client-aborted stream returns no final object. Treat any other value as `"stop"` but log it at `.info`.
- A line `{"error":"…"}` may appear mid-stream. Map it with §5 and stop.
### 1.2 Decoding rules
@@ -75,8 +75,7 @@ The final line:
| Phase | Default | Meaning |
|---|---|---|
| connect | 3 s | TCP connect plus TLS |
| firstToken | 120 s | request sent → first `message.content` byte; includes cold model load |
| connect + firstToken | 120 s | TCP/TLS connect plus request sent → first `message.content` byte; includes cold model load. `URLSession` has no separate connect hook, so the two share this budget. |
| idle | 20 s | gap between lines once streaming has started |
| totalPerChunk | 180 s | hard cap per chunk |
@@ -86,7 +85,7 @@ All injectable via a `Clock` for tests.
### 2.1 `GET /api/version`
`{"version":"0.40.18"}`. The minimum supported version is recorded in T1.1 and checked in onboarding.
`{"version":"0.40.18"}`. The minimum supported version is **0.40.0**, checked in onboarding and by the catalog.
### 2.2 `GET /api/tags`
@@ -111,7 +110,7 @@ Request `{"model":"hf.co/tencent/Hy-MT3-7B-GGUF:Q4_K_M"}`. Verified fields:
| `model_info` | `hunyuan-dense.context_length = 262144` | Informational; the card's translation context is 8192 |
| `license` | `null` in Ollama | Show the Hugging Face licence (Apache-2.0) in Settings |
**VERIFY** for the 1.8B tag and for future versions.
**VERIFY** for the 1.8B tag and for future versions. The 1.8B is not installed; its `/api/show` fields are deferred to T2.7/T7.4.
### 2.4 `GET /api/ps`
@@ -123,7 +122,7 @@ Used by diagnostics and the evaluation harness for resident memory. Not polled b
## 3. Warm-up
Optional (`warmUpOnLaunch`, local endpoint only): send `POST /api/chat` with the selected model, a fixed synthetic sentence (for example `Hello.`), `num_predict: 8`, and discard the output. **Never** use the user's text for warm-up. The request shape is the same as §1.
Optional (`warmUpOnLaunch`, local endpoint only): send `POST /api/chat` with the selected model, a fixed synthetic sentence (for example `Hello.`), `num_predict: 8`, and discard the output. **Never** use the user's text for warm-up. The request shape is the same as §1. A warm-up with `num_predict: 8` returns `done_reason: "length"`; discard it.
## 4. Option mapping
@@ -142,7 +141,7 @@ The names matter: Ollama does not read `repetition_penalty` or `max_tokens`. Do
| Condition | HTTP / transport | Map to |
|---|---|---|
| Connection refused / host unreachable | `URLError.cannotConnectToHost`, `.cannotFindHost`, connect timeout | `ollamaUnreachable` |
| Connection refused / host unreachable | `URLError.cannotConnectToHost`, `.cannotFindHost` | `ollamaUnreachable` |
| Redirect | 3xx (delegate refuses) | `endpointRejected(.redirect)` |
| Model not installed | typically 404 with body containing `not found` | `modelNotInstalled(model)` |
| Model has no Hy-MT3 adapter | discovery succeeds but name does not match | `noAdapter(model)` |
@@ -150,7 +149,7 @@ The names matter: Ollama does not read `repetition_penalty` or `max_tokens`. Do
| Out of memory / model failed to load | 500 with message containing `memory` or `load` | `server(status, message)` with recovery "Use the smaller 1.8B model or close other apps" |
| Context too small / prompt truncated | 400 or `done_reason: "length"` | `badRequest` / warning `truncated` |
| Error line mid-stream | `{"error":"…"}` | classify by message, else `server(0, message)` |
| First-token, idle or total timeout | timer | `timeout(phase)`; one retry before any delta |
| Connect, first-token, idle or total timeout | timer | `timeout(phase)`; one retry before any delta |
| Task cancelled | `CancellationError` / `URLError.cancelled` | `cancelled`; not an error for the UI |
| Other 4xx/5xx | status | `server(status, message)` |
@@ -177,17 +176,17 @@ Rules: synthetic inputs only; keep each fixture under 200 KB; never record priva
- The GGUF metadata reports `context_length = 262144`, but the model card documents **8192** for translation. Set `num_ctx: 8192`; do not rely on Ollama's default, which may be smaller and silently truncate.
- With `num_ctx: 8192`, `ollama ps` reported **6.49 GB** resident for the 7B Q4_K_M. Budget accordingly on 16 GB Macs.
## 8. Open VERIFY items
## 8. VERIFY status
Resolved on 2026-11-26 (Ollama 0.40.18, digest `262ac792aeb5`, M5 Pro 48 GB):
Verified on 2026-11-26 (Ollama 0.40.18, digest `262ac792aeb5`, M5 Pro 48 GB):
- `done_reason` observed: `stop` and `length` (the truncated fixture with `num_predict: 16` ends with `length`). No `load` value seen.
- `done_reason` observed: `stop` and `length` (the truncated fixture with `num_predict: 16` ends with `length`; `num_predict: 8` also ends with `length`). No `load` value seen. A client-aborted stream returns no final object at all.
- `keep_alive: "0"` unloads the 7B immediately: `/api/ps` showed no model at the first check after the response.
- Cold/first load observed: 0.80 s and 2.05 s in two runs; warm load ~1 ms.
- A `system` message was not sent; v1 does not send one.
- Ollama strips the template's `<|eos|>` from the returned content (observed: yes).
Still open:
Still open / deferred:
- Whether `keep_alive: "0"` fully unloads the model and how quickly `/api/ps` reflects it.
- The 1.8B tag behaviour: capabilities, context, memory, speed, quality.
- The full set of `done_reason` values on other inputs (e.g. an aborted stream).
- The 1.8B tag behaviour (capabilities, context, memory, speed, quality) is deferred to T2.7/T7.4 until that model is installed.
- Other `done_reason` values on future Ollama versions; treat unknown values as `stop` and log them.
+13 -6
View File
@@ -13,12 +13,12 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
- [x] T0.6 Environment record and smoke run — 2026-11-26
## M1 — Ollama text client
- [ ] T1.1 Capture fixtures, resolve VERIFY items
- [ ] T1.2 HTTP client, endpoint policy, redirects, error mapping
- [ ] T1.3 Catalog (version, tags, show, ps)
- [ ] T1.4 Streaming chat client (NDJSON, timeouts, cancellation)
- [ ] T1.5 Warm-up, keep-alive, unload
- [ ] T1.6 sprachmittler-cli models / show / translate
- [x] T1.1 Capture fixtures, resolve VERIFY items — 2026-11-26 · 7B resolved; 1.8B deferred
- [x] T1.2 HTTP client, endpoint policy, redirects, error mapping — 2026-11-26
- [x] T1.3 Catalog (version, tags, show, ps) — 2026-11-26
- [x] T1.4 Streaming chat client (NDJSON, timeouts, cancellation) — 2026-11-26
- [x] T1.5 Warm-up, keep-alive, unload — 2026-11-26
- [x] T1.6 sprachmittler-cli models / show / translate — 2026-11-26
## M2 — Hy-MT3 adapter and text pipeline
- [ ] T2.1 Adapter protocol, registry, sampling merge
@@ -100,3 +100,10 @@ Legend: `[ ]` open · `[~]` in progress · `[x]` done · `[!]` blocked (explain)
2026-11-26 · T0.4 · Added the 9 `os.Logger` categories, 8 `OSSignposter` intervals and a 12-hex `shortHash`; contract tests pass. `verify.sh` now lints Tests and checks Debug + Release signatures; `make install` preserves entitlements and Hardened Runtime. Leaf logging seam for M1/M2 is documented; `shortHash` must be logged with `privacy: .private`.
2026-11-26 · T0.5 · `make doctor` green; native V2 config resolves; agents/commands/skills and the `/status` command file are present. `/status` itself still needs one interactive TUI run.
2026-11-26 · T0.6 · `make smoke` with 7B Q4_K_M: 35 output tokens, 0.86 s warm, 46.96 tok/s, URL preserved. Environment table was already filled.
2026-11-26 · T1.1 · Re-ran `make fixtures` with the 7B (digest `262ac792aeb5`); every fixture < 200 KB and the new contract tests pass. `keep_alive:"0"` unloads immediately; `done_reason` observed `stop`/`length`; a client abort returns no final object. 1.8B VERIFY deferred to T2.7/T7.4.
2026-11-26 · T1.2 · Added `EndpointPolicy`, ephemeral/redirect-refusing `OllamaHTTPClient`, error-body parsing and the Core `SprachmittlerError` mapper. Endpoint, redirect, session and error tests pass; CLI unreachable exits 3.
2026-11-26 · T1.3 · Added `InstalledModel`/`ModelDetails`/`LoadedModel`, `OllamaVersion` and the actor `OllamaCatalogClient` with per-digest show caching and `refresh()`. Filter, `:latest`, parameter, cache and version tests pass.
2026-11-26 · T1.4 · Added the streaming `OllamaChatClient`: NDJSON lines, split-line handling, `done_reason`/metrics, mid-stream errors, first-token/idle/total timeouts with `ManualSleeper`, and cancellation that stops the URL task. All transport/chat tests pass.
2026-11-26 · T1.5 · Added the provisional Engines slice (`ModelLanguage`, 16 common names, byte-exact Default prompt, documented options, request factory) and the loopback-only warm-up policy. Warm-up uses fixed `Hello.` and `num_predict: 8`; unload uses `keep_alive:"0"`.
2026-11-26 · T1.6 · Implemented `sprachmittler-cli models`, `show` and `translate` (`--text/--file`, `--target`, `--model`, `--json`, `--include-source`). Live 7B checks: models/show, en→de text, JSON with null sourceLanguage/empty warnings, unreachable exit 3. The 102-language catalogue remains T2.3.
2026-11-26 · M1 · Review fixes: 180 s URLSession request/resource budget (no 60 s pre-emption), missing-`done` is an error, CLI diagnostics go to stderr and endpoint rejection exits 2, `CLIEnvironment` is the composition root, and cancellation/URL-task-stop tests are deterministic. Both reviewers approved.
+2 -1
View File
@@ -18,7 +18,8 @@ Framework: **Swift Testing** (`import Testing`, `@Test`, `#expect`) for all pack
- Every bug fix starts with a failing test, unless it is only reproducible manually. In that case, add a manual checklist item.
- No test may depend on the network or a real model unless it is in `SprachmittlerLiveTests`.
- Time-dependent logic (double-copy window, timeouts) takes an injected clock. Tests use a manual clock; never `Task.sleep` with real time.
- Fakes live in `SprachmittlerTestSupport`: `FakePasteboard`, `FakeClock`, `FakeOllamaTransport`, `FakeTextInserter`, `FakeAccessibility`, `FakeSettingsStore`, `TemporaryDirectory`.
- HTTP contract tests use a serialized `URLProtocol` stub; timeout tests use `ManualSleeper` and never real time.
- Fakes live in `SprachmittlerTestSupport`: `FakePasteboard`, `FakeClock`, `FakeOllamaHTTPTransport`, `FakeOllamaCatalog`, `FakeOllamaChat`, `ManualSleeper`, `FakeTextInserter`, `FakeAccessibility`, `FakeSettingsStore`, `TemporaryDirectory`.
- Fixtures live inside their test target (SwiftPM resources must sit within the target) and are loaded with `Bundle.module`. All fixtures are **synthetic**; never add private text.
- Golden files for prompts, Markdown and JSON output live next to the tests (`Fixtures/golden/`); update them only with an explanation in the commit message.
+2
View File
@@ -109,6 +109,8 @@ Do not require exact string equality: locales legitimately change decimal and th
No source text is included unless `--include-source` is passed explicitly for debugging. Never write this JSON to disk automatically.
Until T2.4, `sourceLanguage` is `null`; until T2.5, `warnings` is empty.
## 11. Tests
- Prompt selection for each content class; default stays default.