diff --git a/changelog.d/tools-say-the-default-and-the-pair.md b/changelog.d/tools-say-the-default-and-the-pair.md new file mode 100644 index 0000000000..708b8d16d4 --- /dev/null +++ b/changelog.d/tools-say-the-default-and-the-pair.md @@ -0,0 +1,6 @@ +### `darkbloom --opencode` and `--hermes` say what happened to your default model, and where the models run + +- OpenCode: Darkbloom's model becomes OpenCode's default only when OpenCode has none: neither of its global config files sets one (`opencode.json`, `opencode.jsonc`; OpenCode 2 doesn't read OpenCode 1's `config.json`), and its TUI remembers no model you picked with `/models` (`~/.local/state/opencode/model.json`). Its own line says so, and how to go back for good: ``New OpenCode sessions now use Darkbloom's Qwen 3.8 27B. To go back, remove "model" from ~/.config/opencode/opencode.jsonc or run the Undo below.`` When a file sets one, nothing is written for it, and the line names it: ``Your default stays exo/llama-3.3-70b; pick Darkbloom with /models.`` When OpenCode remembers a pick: ``Pick Darkbloom once with /models; OpenCode remembers it.`` The `Undo:` line stays. +- Hermes: Darkbloom still becomes the main model, and the line names the one it replaced: ``New Hermes chats now use Darkbloom's Qwen 3.8 27B (before: gpt-6-astra via opencodex). Switch back: hermes model``. Its headline matches OpenCode's (``✓ Hermes can use Darkbloom: 1 model.``). +- A start with a tool flag beside a local API that already serves names the URL the tools use, not the address it listens on: ``Darkbloom already serves at http://127.0.0.1:8001/v1; setting up OpenCode for it.`` (it said `0.0.0.0:8001` for a pair's). +- On a Mac whose local API is its pair's (the leading Mac's, or a member's relay), the tools name the pair's models ``Qwen 3.8 27B (your pair)``, not `(this Mac)`, for a pair of any size; a run again changes nothing. Hermes makes the pair's model its main one, as it does this Mac's, and a pair's models take their engine's word on image input and reasoning, as this Mac's do. diff --git a/docs/architecture/tool-integrations.md b/docs/architecture/tool-integrations.md index 8375598f07..011f3d5b46 100644 --- a/docs/architecture/tool-integrations.md +++ b/docs/architecture/tool-integrations.md @@ -41,9 +41,14 @@ flowchart LR (`provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift`): the file that holds exactly the key the discovery record names for that port. That is this Mac's own `local_token` whatever serves here: a pair's API takes it beside the pair's key, and on a pair's other Macs the relay's record names it too (it passes requests on - with the pair's key). Only a pair API an older build started names `cluster_local_token`. + with the pair's key). Only a pair API an older build started names `cluster_local_token`. The endpoint serves the + pair (`servesThePair`) when `local.json`'s pid is one of this Mac's running pair's processes + (`ClusterPairSummary.runningPairProcesses()`): its part's, as `status` decides whose API it is, or, while the part + runs, the cluster service's own, whose relays answer a member's local API for the pair (`ClusterService.relayTick`, + and `relayDiscovery` for Both, write `local.json` with the service's pid). 2. **Models.** `IntegrationModels.fetch` asks the endpoint's `GET /v1/models` with that key; `resolve` names each - chat model from the catalog (`display_name`, with where it runs: this Mac, your Macs, the network), takes its + chat model from the catalog (`display_name`, with where it runs: this Mac, or your pair when the endpoint serves + it, whatever its size; your Macs; the network), takes its context from the endpoint, else the catalog's maximum, its output cap as `min(max output, context / 4)` with `defaultOutputCap = 32_768`, and its capabilities from the catalog's names (tools on and text-only input when the catalog is unreachable). Image input for a model served here (this Mac, or the pair it leads or relays to) is its @@ -93,20 +98,29 @@ flowchart LR `providers.` value, or appends it in the file's indentation and trailing-comma style. The block has the base URL, `apiKey: "{file:}"` (under `~` in the home directory), `compatibility.maxTokensField: "max_tokens"` (OpenCode otherwise sends `max_completion_tokens`, which the engine ignores) and each model's name, `limit` and - `capabilities`. The top-level `model` is set only when no global config file sets one - (`OpenCodeConfigPlan.otherGlobalConfigSetsModel`): OpenCode loads `opencode.json`, then `opencode.jsonc`, and - Darkbloom edits the last that exists, so a `model` added to `.jsonc` would override the owner's in `.json`. - Project, system and managed configs load after the global ones and win over them, so a global `model` never - replaces theirs. + `capabilities`. The top-level `model` is set only when OpenCode has no default: no global config file sets one, + and its TUI remembers no model picked with `/models` (`OpenCodeConfigPlan.rememberedPick`). So Darkbloom never + sets a default over the owner's: Darkbloom edits the global file OpenCode loads last, where a `model` would win + over the other one's, and at every launch over the remembered pick ([OpenCode's config order](#opencodes-config-order)). + The edited file's own `model` wins over the other file's (`OpenCodeConfigPlan.otherGlobalDefault`, merged by + `GlobalDefault.merged`): a name stays and is named (`ToolConfigSummary.keptDefault`); `""`, `null`, two `model` + keys or a file that can't be read stays without a name. A remembered pick stays too + (`ToolConfigSummary.rememberedPick`), and the start says to pick Darkbloom once with `/models`. When Darkbloom + sets `model`, the start says how to go back for good: remove `model`, or run the undo (`/models` lasts only until + OpenCode quits). 4. **Hermes.** `HermesConfigPlan.plan` splices two top-level sections of `config.yaml` by lines: `providers.` (`api`, `key_cmd: "/bin/cat "`, `transport`, `default_model`, `extra_body.max_tokens` and each model's `context_length` / `supports_vision`) and `model` (`provider: "custom:"` and `default`; the previous endpoint's pins, `previousEndpointKeys`, go). Models under `minimumContext = 64_000`, Hermes' own floor, are left out; `extra_body.max_tokens` is the smallest output cap of the rest. Lists at their key's own indent, as PyYAML writes - them (so oMLX's `omlx launch hermes`, and Hermes up to v0.17), are part of that key. The block says nothing of - reasoning, which Hermes doesn't read there ([Hermes versions and limits](#hermes-versions-and-limits)). + them (so oMLX's `omlx launch hermes`, and Hermes up to v0.17), are part of that key. The main model is the one + already set when it is Darkbloom's and still usable, else the nearest usable one that isn't on the network (this + Mac or its pair, then your Macs); the one it replaces is named with its provider + (`ToolConfigSummary.replacedDefault`, `gpt-6-astra via opencodex`). The block says nothing of reasoning, which + Hermes doesn't read there ([Hermes versions and limits](#hermes-versions-and-limits)). 5. **Write.** `ToolConfigWriter.apply` makes the planned edit (invariants below) and returns the file, the backup - and the exact undo command. + and the exact undo command. `ToolIntegrationStep.lines` says them, with the default model on a line of its own + (`openCodeDefault`; Hermes' names the main model before). 6. **Follow the address.** A start without a tool flag that serves a local API reads each tool's provider block back (`OpenCodeConfigPlan.pointer`, `HermesConfigPlan.pointer`: the base URL, and the file `{file:}` or `key_cmd: /bin/cat ` reads) and compares it with that API: its base URL and `LocalEndpoint.tokenPath()`, or @@ -117,6 +131,21 @@ flowchart LR (`Local.localHostName()`, with `.local`) for an API on every address (`ToolAddress.thisMacsNames`). Single-Mac only: a paired Mac's start starts the pair and doesn't compare. +### OpenCode's config order + +What Darkbloom relies on about the order OpenCode 2 reads its configs in, from its source at release `v2.2.6` +([`dc2ffcf8bf`](https://github.com/anomalyco/opencode/tree/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06)). The code +keeps it in one place too: `OpenCodeConfigPlan.globalFileNames`. + +| OpenCode 2 | Its source | Darkbloom | +|---|---|---| +| Loads `opencode.json`, then `opencode.jsonc`, from its global folder, and not OpenCode 1's `config.json` | [`discovery.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/core/src/config/discovery.ts) (`names`), [`config.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/core/src/config.ts) (`loadDirectory`); test "does not load legacy config.json files" in [`config.test.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/core/test/config/config.test.ts) | `globalFileNames` | +| The default model is the `model` of the last config loaded that sets one | [`provider.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/core/src/config/plugin/provider.ts) (`Config.latest(loaded.entries, "model")`) | `GlobalDefault.merged` | +| Saves to the last of the two files that exists, else to a new `opencode.jsonc` | [`config.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/core/src/config.ts) (`update`) | `configFile` edits the same file: the global one loaded last | +| Loads remote (`.well-known/opencode`) and integration configs before the global files, and `OPENCODE_CONFIG`'s file, a project's `opencode.json`, `opencode.jsonc` and `.opencode` folder, `OPENCODE_CONFIG_CONTENT` and the managed files after them | [`config.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/core/src/config.ts) (`load`) | Reads only the global files: a `model` loaded after them wins over Darkbloom's too, and Darkbloom's wins over a remote or integration one | +| A new TUI session starts on `--model`, else the config's `model`, else the first valid model you picked with `/models` (`recent`, which `/models` adds to and OpenCode keeps in `model.json` in its state folder, `$XDG_STATE_HOME/opencode`, else `~/.local/state/opencode`), else the first model listed | [`local.tsx`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/tui/src/context/local.tsx) (`fallbackModel`; `path.join(paths.state, "model.json")`), [`model-preference.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/tui/src/model-preference.ts) (`addRecent`, `decodeModelPreference`), [`dialog-model.tsx`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/tui/src/component/dialog-model.tsx), [`global-roots.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/util/src/global-roots.ts); test "uses the last configured model and variant ahead of recents" in [`local-selection.test.tsx`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/tui/test/context/local-selection.test.tsx) | `rememberedPick` reads that file: a pick there stays the default, and no `model` is written over it | +| With `OPENCODE_CONFIG_DIR` set, reads that folder as its global one | [`global.ts`](https://github.com/anomalyco/opencode/blob/dc2ffcf8bf26f9e669b6aa22b95f50e12be15e06/packages/util/src/global.ts) | Not followed: `configFile` reads `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode` | + ## Invariants 1. No tool file holds the key: the planners take a key file's path, never a key; OpenCode's `{file:}` and Hermes' @@ -124,22 +153,29 @@ flowchart LR 2. Bytes outside the owned value or lines are unchanged: other providers, a V1 `provider` map, the owner's default model in OpenCode, every other Hermes section and the owner's comments. Comments inside a replaced value or on a replaced line are counted (`ToolConfigSummary.droppedComments`); the backup keeps them. -3. The `darkbloom` block is Darkbloom's whole: a run that changes it rewrites all of it, so a key the owner added +3. OpenCode's default is never set over one the owner set in a global file or by a `/models` pick OpenCode remembers: + `model` is written only when there is neither (`OpenCodeConfigPlan.plan`, `GlobalDefault.merged`, + `rememberedPick`), and the start names the one that stays. Hermes is the + exception: its main model is always Darkbloom's, as `ollama launch` and `omlx launch` make theirs, and the start + names the one it replaced (`ToolConfigSummary.replacedDefault`). +4. The `darkbloom` block is Darkbloom's whole: a run that changes it rewrites all of it, so a key the owner added inside it is replaced too (only comments are counted); the backup keeps it. -4. An edit is idempotent: the planners render deterministically, and equal bytes give `.unchanged`, with no backup and +5. An edit is idempotent: the planners render deterministically, and equal bytes give `.unchanged`, with no backup and no write (`ToolConfigWriter.apply`). That holds without the catalog too: the file's own entries stand in for it, so - a run offline never downgrades what a run online wrote. -5. A file a splice can't edit safely is refused before anything is written: malformed or ambiguous JSONC, a root or + a run offline never downgrades what a run online wrote. A model's name says where it runs, and is read back + without it (`IntegrationModel.displayName(in:)`), so it stays the same while the model runs in the same place + (`(your pair)` included). A default Darkbloom set is found again and left alone. +6. A file a splice can't edit safely is refused before anything is written: malformed or ambiguous JSONC, a root or `providers` that isn't an object, and in YAML several documents, tab indentation, anchors, aliases or merge keys, block text, inline or multi-line values in `providers` or `model` (`JSONCDocument`, `HermesEdit.checkSection`). -6. Each identity writes its own provider (`IntegrationProvider.current`: `darkbloom`, `darkbloom-dev`), so a test +7. Each identity writes its own provider (`IntegrationProvider.current`: `darkbloom`, `darkbloom-dev`), so a test build beside the production one adds a second block. -7. Before a change the exact bytes are copied to `/integrations/backups//.` +8. Before a change the exact bytes are copied to `/integrations/backups//.` (folder 0700, file 0600); `keptBackups = 5` of each file name stay, so two Hermes homes share the five `config.yaml` slots. The new bytes replace the file in one rename through `AtomicFile.write` (`provider-swift/Sources/ProviderCore/Service/AtomicFile.swift`) with the file's own mode; a symlinked config is written through and stays a link. -8. One lock, `/integrations/.lock`, serialises Darkbloom's own runs; the file is read again just before +9. One lock, `/integrations/.lock`, serialises Darkbloom's own runs; the file is read again just before the rename, and a change by the tool's own writer re-plans the edit once and refuses the second time. ## Failure modes @@ -168,9 +204,10 @@ flowchart LR | Concern | File, symbol | |---|---| -| Entry point, endpoint, identity, paths | `provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegration.swift` (`ToolIntegration.configure`, `IntegrationEndpoint.live`, `IntegrationProvider`) | -| Models | `provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift` (`IntegrationModels.fetch`, `resolve`) | -| OpenCode | `provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift`, `provider-swift/Sources/darkbloom/ToolIntegration/JSONCDocument.swift` | +| Entry point, endpoint, identity, paths | `provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegration.swift` (`ToolIntegration.configure`, `IntegrationEndpoint.live`, `servesThePair`, `IntegrationProvider`) | +| Models | `provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift` (`IntegrationModels.fetch`, `resolve`, `IntegrationModel.Location`) | +| OpenCode | `provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift` (`plan`, `globalFileNames`: OpenCode's config order; `GlobalDefault.merged`, `otherGlobalDefault`, `globalDefault(in:)`), `provider-swift/Sources/darkbloom/ToolIntegration/JSONCDocument.swift` | +| What a start says | `provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift` (`lines`, `changed`, `openCodeDefault`, `alreadyServes`) | | Hermes | `provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift` (`HermesConfigPlan.plan`, `previousEndpointKeys`), `provider-swift/Sources/darkbloom/ToolIntegration/HermesVersion.swift` (`HermesVersion.keyCommandWarning`) | | Plans and refusals | `provider-swift/Sources/darkbloom/ToolIntegration/ToolConfigPlan.swift` | | The wait for this Mac's models | `provider-swift/Sources/darkbloom/ToolIntegration/ModelLoadWait.swift` (`ModelLoadWait`, `ModelLoads`, `LiveLine`, `InterruptWatch`) | diff --git a/docs/developer/test.md b/docs/developer/test.md index d8b8d81d7c..055cbceba9 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -984,20 +984,24 @@ The [config writers'](../architecture/tool-integrations.md) suites are CPU-only and need no model, credential or live provider. The planners' goldens are inline strings; the writer and end-to-end cases use temp homes and fresh fake keys, and the live-endpoint case runs in a child process that alone points -`DARKBLOOM_LOCAL_DIR` at a temp folder. None reads a real OpenCode or Hermes -config. +`DARKBLOOM_LOCAL_DIR` at a temp folder. Every case that reaches +`IntegrationEndpoint.live` keeps it off this Mac's cluster service: it gives +`pairPart`, binds `ClusterPairSummary.readerForTesting`, or, in a child +process, calls `keepCommandsOffThisMacsCluster()`. None reads a real OpenCode +or Hermes config, or this Mac's cluster service. ```bash swift test --skip-build --no-parallel \ - --filter 'OpenCodeConfigPlanTests|HermesConfigPlanTests|HermesVersionTests|ToolConfigWriterTests|IntegrationModelsTests|ToolIntegrationTests|ModelLoadWaitTests|ToolAddressTests|AtomicFileTests|keyFileIsTheFileHoldingThePortsKey' + --filter 'OpenCodeConfigPlanTests|HermesConfigPlanTests|HermesVersionTests|ToolConfigWriterTests|IntegrationModelsTests|ToolIntegrationTests|ToolSetupWordsTests|ModelLoadWaitTests|ToolAddressTests|AtomicFileTests|keyFileIsTheFileHoldingThePortsKey' ``` | Coverage | Suites | |---|---| -| New file, an owner's commented JSONC file, strict `.json`, a V1 `provider` map, the default model (also when the other global file sets one), re-runs, refusals, the config file choice | `OpenCodeConfigPlanTests` | -| New file, Hermes' fresh-install `model: ""`, a file as oMLX writes it (PyYAML's column-0 lists too), the `model:` alias key, the kept default, the 64,000-token floor, quoting, refusals, every written key against Hermes' documented keys; the `key_cmd` version warning | `HermesConfigPlanTests`, `HermesVersionTests` | +| New file, an owner's commented JSONC file, strict `.json`, a V1 `provider` map, the default model (also when the other global file sets one, this file's own winning, named when kept; two `model` keys name none; a remembered `/models` pick, and how its `model.json` is read), re-runs, refusals, the config file choice | `OpenCodeConfigPlanTests` | +| New file, Hermes' fresh-install `model: ""`, a file as oMLX writes it (PyYAML's column-0 lists too), the `model:` alias key, the kept default, the main model it replaces, a pair's model as the main one, the 64,000-token floor, quoting, refusals, every written key against Hermes' documented keys; the `key_cmd` version warning | `HermesConfigPlanTests`, `HermesVersionTests` | | Backups (exact bytes, 0600, five kept), unchanged writes nothing, atomic replace, symlinks, a concurrent edit, dry run, the undo command run through `/bin/sh` | `ToolConfigWriterTests`, `AtomicFileTests` | -| Catalog names, limits and capability aliases; the fetch with the key file's key; `local.json`'s endpoint and key file; the modes of new files; the owner's default in the other global OpenCode file; no written file holds the key | `IntegrationModelsTests`, `ToolIntegrationTests`, `keyFileIsTheFileHoldingThePortsKey` | +| Catalog names, limits and capability aliases; a pair's models named `(your pair)`, with their engine's image input and reasoning; the fetch with the key file's key; `local.json`'s endpoint and key file; the modes of new files; the owner's default in the other global OpenCode file; no written file holds the key | `IntegrationModelsTests`, `ToolIntegrationTests`, `keyFileIsTheFileHoldingThePortsKey` | +| What a start says, in a temp home with a user's two OpenCode files and his Hermes config: the default model's own line (none set, set in either file, set without a name, OpenCode 1's `config.json`, a `/models` pick OpenCode remembers in a fake `model.json`, under `XDG_STATE_HOME` too), Hermes' main model before, the URL for an API on `0.0.0.0`, a pair's API (`(your pair)`, a member's relay, a run again online and offline changes nothing); every `Changed:` wording and default line | `ToolSetupWordsTests` | | The wait for this Mac's models (a scripted process and a clock that moves only between looks; every fake ends a wait at its bound, so a regression fails instead of hanging, and each suite has a one-minute limit), Ctrl-C (SIGUSR2 stands in for SIGINT), the run-again line; a plain start's notice, the address rule and the start's two hooks | `ModelLoadWaitTests`, `ToolAddressTests` | `scripts/integrations/opencode-smoke.sh` then runs the real OpenCode 2 on the diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index cf64a38429..e6418080dd 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -411,9 +411,12 @@ They run once, at `start`: `--bind` given, if any) and no option changes what serves (`--model`, `--all`, `--idle-timeout`, `--schedule`, `--autopilot`/`--no-autopilot`, `--coordinator-url`, `--choose`, `--no-me-first`, `--me-first-idle`, - `--route`): nothing starts. `Darkbloom already serves on :; - setting up OpenCode for it.`, then the tools (`Start.runningLocalAPI`). One - without a key (`--no-auth`) is named instead, and nothing starts (exit 1): + `--route`): nothing starts. `Darkbloom already serves at + http://127.0.0.1:8001/v1; setting up OpenCode for it.` (the URL the tools + use, `local.json`'s `base_url`: `127.0.0.1` for an API on `0.0.0.0`; + `ToolIntegrationStep.alreadyServes`), then the tools + (`Start.runningLocalAPI`). One without a key (`--no-auth`) is named + instead, and nothing starts (exit 1): ``✗ Darkbloom's local API on :8001 has no key (--no-auth); tools need one: start it without --no-auth.`` This Mac's relay to a pair's API while it answers `503` (the pair's other Mac away) is named too, in `status`'s words, @@ -462,8 +465,26 @@ They run once, at `start`: nothing and says the catalog wasn't reachable; a model new to the file gets its ID, and text input unless the endpoint lists images, and one line says to run the start again online for names and image support. - The result block names the file changed, the backup and a one-line undo, - then `Requests:` (where your requests go) and + Each model's name says where it runs: `(this Mac)`, `(your pair)` when the + local API is this Mac's part of a running pair (its pid is the part's, or the + cluster service's for a member's relay; `IntegrationEndpoint.servesThePair`), + `(your Macs)` or `(Darkbloom network, billed)`. + The result block names the file changed, the backup, the default model on a + line of its own and a one-line undo. OpenCode's default is set only when + OpenCode has none: neither of its global files (`opencode.json`, + `opencode.jsonc`; + [OpenCode's config order](../architecture/tool-integrations.md#opencodes-config-order)) + sets one, and its TUI remembers no `/models` pick (`model.json` in + `$XDG_STATE_HOME/opencode`, else `~/.local/state/opencode`; + `OpenCodeConfigPlan.rememberedPick`). Then: ``New OpenCode sessions now use + Darkbloom's Qwen 3.8 27B. To go back, remove "model" from + ~/.config/opencode/opencode.jsonc or run the Undo below.``; with a config + default, ``Your default stays exo/llama-3.3-70b; pick Darkbloom with + /models.``; with a remembered pick, ``Pick Darkbloom once with /models; + OpenCode remembers it.`` Hermes' main model + is always Darkbloom's, and the line names the one before: ``New Hermes chats + now use Darkbloom's Qwen 3.8 27B (before: gpt-6-astra via opencodex). Switch + back: hermes model``. Then `Requests:` (where your requests go) and `Other tools:` (`OPENAI_BASE_URL` and `OPENAI_API_KEY="$(cat )"`). No line or file holds the key, and no start screen shows it (`Start.localServerBanner`). The `--local` banner's `Your requests:` line diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md index 08e4f1fa34..5fa01ac493 100644 --- a/docs/provider/direct-mode.md +++ b/docs/provider/direct-mode.md @@ -386,7 +386,11 @@ coordinator's `self` list names this Mac's own builds by their aliases. The coordinator's lists are cached for 30 s and the catalog for 5 minutes; a coordinator that can't be reached leaves this Mac's models alone in the list and is asked again after 10 s. With `this-mac`, the list never leaves the Mac. -Integrations (OpenCode, Hermes) read this list. +Integrations (OpenCode, Hermes) read this list and name each model with where +it runs: `this-mac` is `(this Mac)`, or `(your pair)` on a pair's API (the +leading Mac's, or a member's relay to it; the pair's model, whatever the pair's +size); `my-macs` is `(your Macs)`, and `darkbloom` is `(Darkbloom network, +billed)`. ### Each model's whole window, on this Mac diff --git a/docs/provider/local-first.md b/docs/provider/local-first.md index 9f0787793a..8a4a1cc055 100644 --- a/docs/provider/local-first.md +++ b/docs/provider/local-first.md @@ -224,15 +224,38 @@ Then, in OpenCode, `/models` → Darkbloom. Hermes uses Darkbloom as its main model. - **Starts Darkbloom only if needed.** If this Mac's local API already runs, - nothing restarts: `Darkbloom already serves on 127.0.0.1:8001; setting up - OpenCode for it.` Otherwise `start` runs as usual, and the tools are set up - once the local API answers: a background start waits up to 30 seconds for it, - and **Only me**, which listens once its models are loaded, up to - `[backend] startup_preload_timeout_secs` (120) more. + nothing restarts: `Darkbloom already serves at http://127.0.0.1:8001/v1; + setting up OpenCode for it.` (the address the tools use, also for a pair's + API that listens on every address). Otherwise `start` runs as usual, and the + tools are set up once the local API answers: a background start waits up to + 30 seconds for it, and **Only me**, which listens once its models are loaded, + up to `[backend] startup_preload_timeout_secs` (120) more. - **What it changes:** one `darkbloom` provider in OpenCode's `~/.config/opencode/opencode.jsonc` (or your existing `opencode.json`), and in Hermes' `~/.hermes/config.yaml`, where it also becomes the main model, as Ollama and oMLX do. Everything else in those files stays as it was. +- **Your default model:** OpenCode's stays when its `opencode.json` or + `opencode.jsonc` in `~/.config/opencode` sets one (OpenCode 2 doesn't read + OpenCode 1's `config.json`). Nothing is written for it, and the start names + it: `Your default stays exo/llama-3.3-70b; pick Darkbloom with /models.` + Without one, OpenCode starts on the model you last picked with `/models`, + which it remembers (in `~/.local/state/opencode/model.json`); then nothing is + written either: `Pick Darkbloom once with /models; OpenCode remembers it.` + Only when OpenCode has neither does Darkbloom's first model become the + default for new sessions, on a line of its own that says how to go back: `New + OpenCode sessions now use Darkbloom's Qwen 3.8 27B. To go back, remove + "model" from ~/.config/opencode/opencode.jsonc or run the Undo below.` + (`/models` isn't a way back from it: a config's `model` comes first at every + launch.) In a project whose own `opencode.json` sets a model, or with + `OPENCODE_CONFIG` naming a file that does, OpenCode uses that one + ([OpenCode's config order](../architecture/tool-integrations.md#opencodes-config-order)). + Hermes always makes Darkbloom its main model and names the one before: `New + Hermes chats now use Darkbloom's Qwen 3.8 27B (before: gpt-6-astra via + opencodex). Switch back: hermes model`. +- **Where each model runs** is in its name: `Qwen 3.8 27B (this Mac)`, `(your + pair)` on a Mac whose local API is its pair's (the leading Mac's, or a + member's relay to it), whatever the pair's size, `(your Macs)`, or + `(Darkbloom network, billed)`. - **Your key stays out of them.** The tools read it from Darkbloom's own key file, and `darkbloom --opencode` never prints it. - **Undo in one line:** every change is backed up first, and the start prints @@ -242,13 +265,14 @@ model. ✓ OpenCode can use Darkbloom: 3 models. Changed: ~/.config/opencode/opencode.jsonc (added the "darkbloom" provider; nothing else changed) Backup: ~/.darkbloom/integrations/backups/opencode/opencode.jsonc.20261106T221500Z - Use it: in OpenCode, /models → Darkbloom. Your default model is unchanged. + Your default stays exo/llama-3.3-70b; pick Darkbloom with /models. Undo: cp '' '' ``` - When your OpenCode config sets no default model, Darkbloom's first model - becomes the default for new sessions, and the `Use it:` line names it - instead (`new sessions use darkbloom/`). + When Darkbloom's model became the default, the `Changed:` line says `added + the "darkbloom" provider and the default model`, and the line before `Undo:` + is `New OpenCode sessions now use Darkbloom's . To go back, remove + "model" from or run the Undo below.` - **It waits for your model.** While this Mac still loads the models it started with, the start waits before it writes anything, on one live line (`⠙ Loading Gemma 4 26B before setting up OpenCode… 42s`; without a terminal, diff --git a/docs/provider/quickstart.md b/docs/provider/quickstart.md index ea585d3e42..5eb320a772 100644 --- a/docs/provider/quickstart.md +++ b/docs/provider/quickstart.md @@ -126,10 +126,13 @@ listens: it listens once its models are loaded, so the start waits up to opencode ``` -In OpenCode, `/models` → **Darkbloom**, then pick a model. If your OpenCode -config sets no default model, Darkbloom's first model becomes the default for -new sessions; otherwise yours stays. The start's `Use it:` line says which. With -`--hermes`, Darkbloom is Hermes' main model: run `hermes`. Any other OpenAI +In OpenCode, `/models` → **Darkbloom**, then pick a model; OpenCode remembers +the pick. If neither your OpenCode config sets a default model nor OpenCode +remembers one you picked, Darkbloom's first model becomes the default for new +sessions; otherwise yours stays. The start says which on a line of its own +(`New OpenCode sessions now use Darkbloom's …`, `Your default stays …` or +`Pick Darkbloom once with /models; OpenCode remembers it.`). +With `--hermes`, Darkbloom is Hermes' main model: run `hermes`. Any other OpenAI client: `darkbloom local` prints the address, the key and a `curl` to try ([the local API](./direct-mode.md)). diff --git a/provider-swift/Sources/darkbloom/ClusterPairSummary+Live.swift b/provider-swift/Sources/darkbloom/ClusterPairSummary+Live.swift index eec6ea3d36..f03816564d 100644 --- a/provider-swift/Sources/darkbloom/ClusterPairSummary+Live.swift +++ b/provider-swift/Sources/darkbloom/ClusterPairSummary+Live.swift @@ -71,6 +71,19 @@ extension ClusterPairSummary { return ClusterService.publishedLive().flatMap { $0.child.running ? $0.child.pid : nil } } + /// The processes that serve this Mac's running pair (`pairProcesses(of:)`). Empty while a test gives the pair. + static func runningPairProcesses() -> Set { + readsThisMacsCluster ? pairProcesses(of: ClusterService.publishedLive()) : [] + } + + /// The processes that serve the pair `status` publishes, while this Mac's part of it runs: the part's provider + /// (`runningPartPID`), and the cluster service itself, whose relay answers a member's local API for the pair + /// (`ClusterService.relayTick` writes `local.json` with the service's own pid). + static func pairProcesses(of status: ClusterServiceStatus?) -> Set { + guard let status, status.child.running else { return [] } + return Set([status.child.pid, status.servicePID].compactMap { $0 }) + } + private static func localFacts() -> ClusterPairSummary { let agents = ClusterServiceAgent.status() let running = ClusterService.running() diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift b/provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift index 6740f19c87..7c67d78932 100644 --- a/provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift +++ b/provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift @@ -72,8 +72,7 @@ extension Start { guard let endpoint = runningLocalAPI(live, keyFile: { LocalEndpoint.keyFile(forPort: Int($0)) }) else { return false } - print("Darkbloom already serves on \(live.host):\(live.port); setting up " - + "\(ToolIntegrationStep.names(requestedTools)) for it.") + print(ToolIntegrationStep.alreadyServes(live, tools: requestedTools)) try await setUpToolsWithSavedSettings(endpoint, step: step, relayed: relayed) return true } diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift b/provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift index f2b98a8538..e27b9f46e7 100644 --- a/provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift +++ b/provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift @@ -26,6 +26,10 @@ enum HermesConfigPlan { /// The file's new bytes: Darkbloom's provider with the models Hermes can use (at least 64K context) and their /// context and vision, and Darkbloom as the main model, as `ollama launch` and `omlx launch` make theirs. + /// + /// Unlike OpenCode's default, which Darkbloom never sets over the owner's, Hermes' main model is always + /// Darkbloom's; the summary names the one it replaced (`replacedDefault`), so the start can say how to switch back. + /// A run again keeps Darkbloom's main model while Hermes can still use it, and names none as replaced. static func plan( existing: Data?, endpoint: IntegrationEndpoint, models listed: [IntegrationModel], provider: IntegrationProvider ) -> ToolConfigPlan { @@ -43,15 +47,16 @@ enum HermesConfigPlan { var edit = try HermesEdit(text: original, provider: provider) guard let main = edit.mainModel(among: usable) else { return .refused(.models(""" - Hermes needs a main model with at least 64K context on this Mac or your other Macs; Darkbloom \ - lists such models only on the network here. + Hermes needs a main model with at least 64K context on this Mac, its pair or your other Macs; \ + Darkbloom lists such models only on the network here. """)) } + let replaced = edit.replacedMain() let change = try edit.setProvider(endpoint: endpoint, models: usable, main: main) try edit.setMainModel(main) let text = edit.result() let summary = ToolConfigSummary( - provider: change, models: usable.map(\.id), defaultModel: main, + provider: change, models: usable.map(\.id), defaultModel: main, replacedDefault: replaced, leftOut: models.filter { ($0.contextLength ?? 0) < minimumContext }.map(\.id), droppedComments: text.map { edit.droppedComments(in: $0) } ?? 0, undescribed: usable.filter { $0.fallback != nil && entries[$0.id] == nil }.map(\.id)) @@ -137,17 +142,38 @@ private struct HermesEdit { // MARK: - The two sections /// The model `model.default` names when the main provider is already Darkbloom's and Hermes can still use it; - /// else this Mac's first usable model, else the first on the owner's other Macs. Never a network model by choice. + /// else this Mac's first usable model (or its pair's), else the first on the owner's other Macs. Never a network + /// model by choice. func mainModel(among usable: [IntegrationModel]) -> String? { - if let model, let children = try? children(of: model), - let selected = children.first(where: { $0.key == "provider" }).flatMap({ Self.scalar($0.value) }), - ["custom:\(provider.id)", provider.id].contains(selected), - let current = children.first(where: { $0.key == "default" || $0.key == "model" }) - .flatMap({ Self.scalar($0.value) }), - usable.contains(where: { $0.id == current }) { - return current - } - return (usable.first { $0.location == .thisMac } ?? usable.first { $0.location == .yourMacs })?.id + if let current = currentMain(), current.isDarkbloom, usable.contains(where: { $0.id == current.model }) { + return current.model + } + return usable.filter { $0.location != .network }.min { $0.location < $1.location }?.id + } + + /// The main model before this edit, as `model` names it (`default`, or its alias key `model`, or a bare model ID), + /// with its provider; nil without one. + func currentMain() -> (model: String, provider: String?, isDarkbloom: Bool)? { + guard let model else { return nil } + // A name, not YAML's null or an empty string. + func named(_ value: String) -> String? { + Self.scalar(value).flatMap { ["", "~", "null", "Null", "NULL"].contains($0) ? nil : $0 } + } + guard model.value.isEmpty else { return named(model.value).map { ($0, nil, false) } } + let children = (try? children(of: model)) ?? [] + func value(_ keys: Set) -> String? { children.first { keys.contains($0.key) }.flatMap { named($0.value) } } + guard let name = value(["default", "model"]) else { return nil } + let selected = value(["provider"]) + return (name, selected, selected.map { ["custom:\(provider.id)", provider.id].contains($0) } ?? false) + } + + /// The main model before this edit in plain words, `gpt-6-astra via opencodex`; nil without one, or when it was + /// Darkbloom's already. + func replacedMain() -> String? { + guard let current = currentMain(), !current.isDarkbloom else { return nil } + guard let selected = current.provider else { return current.model } + let named = selected.hasPrefix("custom:") ? String(selected.dropFirst("custom:".count)) : selected + return "\(current.model) via \(named)" } mutating func setProvider( diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift b/provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift index 9b24516204..0cd51bcbc1 100644 --- a/provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift +++ b/provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift @@ -7,6 +7,9 @@ struct IntegrationModel: Equatable, Sendable { /// `Comparable` gives them. enum Location: Comparable, CaseIterable, Sendable { case thisMac + /// The pair this Mac is part of, of two Macs or more: the local API is the pair's, and its models are the + /// pair's (`IntegrationEndpoint.servesThePair`). + case yourPair case yourMacs /// Other Darkbloom machines: the local router lists them only when the owner opted into "My Macs first". case network @@ -14,10 +17,20 @@ struct IntegrationModel: Equatable, Sendable { var label: String { switch self { case .thisMac: "this Mac" + case .yourPair: "your pair" case .yourMacs: "your Macs" case .network: "Darkbloom network, billed" } } + + /// The endpoint's own process serves the model, on this Mac or on the pair whose API it is, so what its engine + /// lists for the model (`input_modalities`) holds. Said by name, not by the tools' order. + var servedHere: Bool { + switch self { + case .thisMac, .yourPair: true + case .yourMacs, .network: false + } + } } let id: String @@ -81,7 +94,8 @@ struct IntegrationModel: Equatable, Sendable { /// `Qwen 3.8 27B (this Mac)`. static func name(_ display: String, at location: Location) -> String { "\(display) (\(location.label))" } - /// A tool's name for a model without where it runs: `Qwen 3.8 27B (this Mac)` gives `Qwen 3.8 27B`. + /// A tool's name for a model without where it runs: `Qwen 3.8 27B (this Mac)` gives `Qwen 3.8 27B`. Any place's + /// label comes off, so a run again, offline too, gives a model the same name while it runs in the same place. static func displayName(in name: String) -> String { for location in Location.allCases where name.hasSuffix(" (\(location.label))") { let display = name.dropLast(location.label.count + 3) @@ -197,7 +211,8 @@ enum IntegrationModels { } /// The tools' list: every chat model the endpoint lists, named and limited from the catalog when it is - /// reachable (`catalog` nil offline), ordered this Mac, your Macs, the network, then by name. + /// reachable (`catalog` nil offline), ordered this Mac (or your pair), your Macs, the network, then by name. The + /// endpoint's own models run `here`: on this Mac, or on the pair whose API it is. /// /// - Context: the endpoint's (what this engine admits now), else the catalog's maximum, else unknown. /// - Output cap: `min(max output, context / 4)`, the max output being the endpoint's, else the catalog's, else @@ -215,10 +230,12 @@ enum IntegrationModels { /// models). /// - A model the catalog doesn't describe carries `fallback`: a tool's own entry for it keeps its values /// (`keeping(_:entries:)`). - static func resolve(_ listed: [EndpointModel], catalog: CatalogSnapshot?) -> [IntegrationModel] { + static func resolve(_ listed: [EndpointModel], catalog: CatalogSnapshot?, + here: IntegrationModel.Location = .thisMac) -> [IntegrationModel] { var nearest: [String: (entry: EndpointModel, location: IntegrationModel.Location)] = [:] for entry in listed { - let location = location(ownedBy: entry.ownedBy) + let owner = location(ownedBy: entry.ownedBy) + let location = owner == .thisMac ? here : owner if let kept = nearest[entry.id], kept.location <= location { continue } nearest[entry.id] = (entry, location) } @@ -231,9 +248,9 @@ enum IntegrationModels { let capabilities = Set((details.model?.capabilities ?? []).map { $0.lowercased() }) let display = details.name.flatMap { $0.isEmpty ? nil : $0 } ?? entry.id // The engine's word, for a model served here. - let engineImageInput = location == .thisMac + let engineImageInput = location.servedHere ? entry.inputModalities.map { LocalInputModalities.takesImages($0) } : nil - let engineReasoning = location == .thisMac + let engineReasoning = location.servedHere ? entry.supportedFeatures.map { LocalModelFeatures.listsReasoning($0) } : nil return IntegrationModel( id: entry.id, name: IntegrationModel.name(display, at: location), location: location, @@ -250,7 +267,7 @@ enum IntegrationModels { return ordered(models) } - /// The tools' order: this Mac, your Macs, the network, then by name. + /// The tools' order: this Mac, your pair, your Macs, the network, then by name. static func ordered(_ models: [IntegrationModel]) -> [IntegrationModel] { models.sorted { ($0.location, $0.name.lowercased(), $0.id) < ($1.location, $1.name.lowercased(), $1.id) } } diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift b/provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift index 7e61b8241f..28b61b9dbb 100644 --- a/provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift +++ b/provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift @@ -4,14 +4,33 @@ import Foundation /// /// The edit is a byte splice of the JSONC file, never a re-serialisation: the owner's comments, order, other /// providers (a V1 `provider` map too) and default model stay exactly as they are. Only the provider's own value is -/// replaced, or the provider is appended; the top-level `model` is added only when the file has none. +/// replaced, or the provider is appended; the top-level `model` is added only when OpenCode has no default: no global +/// file sets one, and its TUI remembers no pick from `/models`. enum OpenCodeConfigPlan { static let schemaURL = "https://opencode.ai/config.json" /// OpenCode's package for an OpenAI-compatible endpoint. static let package = "@opencode/ai/providers/openai-compatible" - /// `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`: the last existing of `opencode.json` and - /// `opencode.jsonc` (OpenCode loads both, `.jsonc` last, and saves to the same one), else a new `opencode.jsonc`. + /// The default model OpenCode's global config files set (their top-level `model`). + enum GlobalDefault: Equatable, Sendable { + /// None of them sets one: OpenCode's TUI starts on the model it remembers from `/models`, else on the first it + /// lists, so Darkbloom's may become the default when it remembers none. + case none + /// The model they set, `provider/model`. + case model(String) + /// One of them sets `model` to something else than a model name, or can't be read: Darkbloom leaves the + /// default alone without naming it. + case unnamed + + /// What files read in OpenCode's load order (`globalFileNames`) set together: the default of the last one + /// that sets one. + static func merged(_ files: [GlobalDefault]) -> GlobalDefault { + files.last { $0 != .none } ?? .none + } + } + + /// `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`: the last of `globalFileNames` that exists there (the one + /// OpenCode saves to), else a new `opencode.jsonc`. static func configFile(home: URL, variables: [String: String]) -> URL { let base = variables["XDG_CONFIG_HOME"].flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0, isDirectory: true) } ?? home.appendingPathComponent(".config", isDirectory: true) @@ -21,10 +40,13 @@ enum OpenCodeConfigPlan { } /// The file's new bytes. A `.json` file stays strict JSON when it was: it gets no comment line. The top-level - /// `model` is added only when neither this file nor, by `defaultModelElsewhere`, another global file sets one. + /// `model` is added only when neither this file nor the global files it outranks (`defaultElsewhere`) set one, and + /// OpenCode's TUI remembers no pick (`rememberedPick`); otherwise the summary names the default that stays + /// (`keptDefault`), or notes the pick (`rememberedPick`). static func plan( existing: Data?, fileName: String, endpoint: IntegrationEndpoint, models listed: [IntegrationModel], - provider: IntegrationProvider, home: URL, defaultModelElsewhere: Bool = false + provider: IntegrationProvider, home: URL, defaultElsewhere: GlobalDefault = .none, + rememberedPick: String? = nil ) -> ToolConfigPlan { guard !listed.isEmpty else { return .refused(.models("Darkbloom's endpoint lists no chat models yet, so OpenCode has none to use.")) @@ -49,9 +71,13 @@ enum OpenCodeConfigPlan { withComment: fileName.hasSuffix(".jsonc"), unit: splice.unit) var rootMembers: [[String]] = fresh ? [["\"$schema\": \(jsonString(schemaURL))"]] : [] - let modelKeys = root.members(named: "model") - guard modelKeys.count < 2 else { return .refused(.file("it has two \"model\" keys")) } - let defaultModel = modelKeys.isEmpty && !defaultModelElsewhere ? "\(provider.id)/\(models[0].id)" : nil + guard root.members(named: "model").count < 2 else { return .refused(.file("it has two \"model\" keys")) } + // Darkbloom never sets a default over the owner's: OpenCode loads this file last of the global ones + // (`configFile`), so a `model` added here would win over the other one's, and, at every launch, over the + // model its TUI remembers from `/models` (`rememberedPick`). A run again finds the one it set here and leaves + // it. + let effective = GlobalDefault.merged([defaultElsewhere, globalDefault(in: document)]) + let defaultModel = effective == .none && rememberedPick == nil ? "\(provider.id)/\(models[0].id)" : nil if let defaultModel { rootMembers.append(["\"model\": \(jsonString(defaultModel))"]) } let change: ToolConfigSummary.ProviderChange @@ -78,9 +104,11 @@ enum OpenCodeConfigPlan { } if !rootMembers.isEmpty { splice.append(rootMembers, to: root) } - let summary = ToolConfigSummary( + var summary = ToolConfigSummary( provider: change, models: models.map(\.id), defaultModel: defaultModel, undescribed: models.filter { $0.fallback != nil && entries[$0.id] == nil }.map(\.id)) + if case .model(let kept) = effective { summary.keptDefault = kept } + if effective == .none { summary.rememberedPick = rememberedPick } guard splice.changesBytes else { return .unchanged(summary) } return verified(splice.result(), original: original, document: document, fileName: fileName, provider: provider, summary: summary) @@ -160,22 +188,75 @@ enum OpenCodeConfigPlan { keyFile: string("apiKey").flatMap { keyFile(inReference: $0, home: home) }) } - /// The global config files, in the order OpenCode loads them. + // MARK: - OpenCode's precedence + + /// OpenCode 2's global config files, in the order it loads them. All Darkbloom relies on about the order OpenCode + /// reads its configs in is here, from OpenCode's source (`anomalyco/opencode` at tag `v2.2.6`, `dc2ffcf8bf`): + /// + /// - It loads `opencode.json`, then `opencode.jsonc`, from its global folder + /// (`packages/core/src/config/discovery.ts`, `names`; `packages/core/src/config.ts`, `loadDirectory`), and not + /// OpenCode 1's `config.json` (`packages/core/test/config/config.test.ts`, "does not load legacy config.json + /// files"). With `OPENCODE_CONFIG_DIR` set, that folder is its global one (`packages/util/src/global.ts`); + /// `configFile` doesn't follow it. + /// - Its default model is the `model` of the last config it loads that sets one + /// (`packages/core/src/config/plugin/provider.ts`, `Config.latest(loaded.entries, "model")`): + /// `GlobalDefault.merged`. + /// - It saves to the last of these files that exists, else to a new `opencode.jsonc` + /// (`packages/core/src/config.ts`, `update`), and so does Darkbloom (`configFile`): the file Darkbloom edits is + /// the global one OpenCode loads last. + /// - It loads remote (`.well-known/opencode`) and integration configs before these files, and every other config + /// after them, whose `model` then wins (`packages/core/src/config.ts`, `load`): `OPENCODE_CONFIG`'s file, a + /// project's `opencode.json`, `opencode.jsonc` and `.opencode` folder, `OPENCODE_CONFIG_CONTENT`, and the + /// managed files. static let globalFileNames = ["opencode.json", "opencode.jsonc"] - /// Whether another global config file beside `file` sets a top-level `model`, or can't be read (so Darkbloom can't - /// tell). OpenCode loads `opencode.json`, then `opencode.jsonc`, and Darkbloom edits the last that exists, so a - /// `model` it added would override the owner's in the other file. Project, system and managed configs load after - /// the global ones and win over them, so a global `model` never replaces theirs. - static func otherGlobalConfigSetsModel(besides file: URL) -> Bool { + /// The model OpenCode's TUI remembers from `/models` (`provider/model`), which a new session starts on when no + /// config sets `model`; nil without one. From OpenCode 2's source at `v2.2.6`, `packages/`: + /// - a new session takes `--model`, else the config's `model`, else the first valid `recent` pick, else the first + /// model listed (`tui/src/context/local.tsx`, `fallbackModel`); + /// - `/models` adds its pick to `recent` (`tui/src/component/dialog-model.tsx` → `local.tsx` `set`; + /// `tui/src/model-preference.ts`, `addRecent`), kept in `model.json` in OpenCode's state folder + /// (`local.tsx`, `path.join(paths.state, "model.json")`): `$XDG_STATE_HOME/opencode`, else + /// `~/.local/state/opencode` (`util/src/global-roots.ts`); + /// - an entry counts with a non-empty `providerID` and `modelID`, and a file OpenCode can't read holds none + /// (`model-preference.ts`, `decodeModelPreference`). + static func rememberedPick(home: URL, variables: [String: String]) -> String? { + let state = variables["XDG_STATE_HOME"].flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0, isDirectory: true) } + ?? home.appendingPathComponent(".local/state", isDirectory: true) + let file = state.appendingPathComponent("opencode/model.json") + guard let data = try? Data(contentsOf: file, options: .mappedIfSafe), + data.count <= ToolConfigWriter.maximumFileBytes, + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let recent = root["recent"] as? [Any] else { return nil } + for entry in recent { + guard let pick = entry as? [String: Any], let provider = pick["providerID"] as? String, !provider.isEmpty, + let model = pick["modelID"] as? String, !model.isEmpty else { continue } + return "\(provider)/\(model)" + } + return nil + } + + /// The default model the global config files other than `file` set together (`GlobalDefault.merged`); one that + /// can't be read counts as setting a default Darkbloom can't name. Only `file`'s folder is read. + static func otherGlobalDefault(besides file: URL) -> GlobalDefault { let directory = file.deletingLastPathComponent() - return globalFileNames.filter { $0 != file.lastPathComponent }.contains { name in + return .merged(globalFileNames.filter { $0 != file.lastPathComponent }.map { name -> GlobalDefault in let other = directory.appendingPathComponent(name) - guard FileManager.default.fileExists(atPath: other.path) else { return false } + guard FileManager.default.fileExists(atPath: other.path) else { return .none } guard let data = try? Data(contentsOf: other), let document = try? JSONCDocument([UInt8](data)), - let root = document.root.object else { return true } - return !root.members(named: "model").isEmpty - } + document.root.object != nil else { return .unnamed } + return globalDefault(in: document) + }) + } + + /// The default model a config document's top-level `model` sets: a model name, or anything else (`""`, `null`, + /// two keys) as an unnamed default that stays. + static func globalDefault(in document: JSONCDocument) -> GlobalDefault { + guard let keys = document.root.object?.members(named: "model"), !keys.isEmpty else { return .none } + guard keys.count == 1, let name = try? JSONDecoder().decode( + String.self, from: Data(document.bytes[keys[0].value.start.. String { diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/ToolConfigPlan.swift b/provider-swift/Sources/darkbloom/ToolIntegration/ToolConfigPlan.swift index 2611b2b1da..2303e35109 100644 --- a/provider-swift/Sources/darkbloom/ToolIntegration/ToolConfigPlan.swift +++ b/provider-swift/Sources/darkbloom/ToolIntegration/ToolConfigPlan.swift @@ -23,6 +23,15 @@ struct ToolConfigSummary: Equatable, Sendable { var models: [String] /// The tool's default model as this edit sets it; nil when the edit leaves the default alone. var defaultModel: String? + /// The default model the edit leaves alone, as the tool's config names it (OpenCode: the `model` a global config + /// file sets, `exo/llama-3.3-70b`); nil when the edit sets one, or the config's default has no name. + var keptDefault: String? + /// The model OpenCode's TUI remembers from `/models` (`provider/model`), which new sessions start on when no config + /// sets `model`: the edit leaves the default to it. Nil when the edit sets one, or a config's default stays. + var rememberedPick: String? + /// The main model this edit replaced, in the tool's words (Hermes: `gpt-6-astra via opencodex`); nil when there + /// was none, or it was Darkbloom's already. + var replacedDefault: String? /// The endpoint's models the tool can't use, left out of its config (Hermes: under 64K context). var leftOut: [String] = [] /// Comments on the lines the edit replaced or removed. The backup keeps them. diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegration.swift b/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegration.swift index 7ff1764e53..f743afa0b1 100644 --- a/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegration.swift +++ b/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegration.swift @@ -26,13 +26,16 @@ enum IntegrationTool: String, CaseIterable, Sendable { func plan( existing: Data?, file: URL, endpoint: IntegrationEndpoint, models: [IntegrationModel], - provider: IntegrationProvider, home: URL + provider: IntegrationProvider, environment: ToolIntegrationEnvironment ) -> ToolConfigPlan { switch self { case .opencode: - OpenCodeConfigPlan.plan(existing: existing, fileName: file.lastPathComponent, endpoint: endpoint, - models: models, provider: provider, home: home, - defaultModelElsewhere: OpenCodeConfigPlan.otherGlobalConfigSetsModel(besides: file)) + OpenCodeConfigPlan.plan( + existing: existing, fileName: file.lastPathComponent, endpoint: endpoint, models: models, + provider: provider, home: environment.home, + defaultElsewhere: OpenCodeConfigPlan.otherGlobalDefault(besides: file), + rememberedPick: OpenCodeConfigPlan.rememberedPick(home: environment.home, + variables: environment.variables)) case .hermes: HermesConfigPlan.plan(existing: existing, endpoint: endpoint, models: models, provider: provider) } @@ -57,13 +60,21 @@ struct IntegrationEndpoint: Equatable, Sendable { /// `http://:/v1`, as `local.json` names the live server. let baseURL: String let keyFile: URL + /// The server is this Mac's part of a pair (of two Macs or more): the models it serves itself are the pair's. + var servesThePair = false /// The live local server `info`, by default the one in `local.json` (its own port, never an assumed one), with the - /// key file for that port; nil when no server runs, it serves without a key, or no key file holds its key. + /// key file for that port; nil when no server runs, it serves without a key, or no key file holds its key. It + /// serves the pair when its process is one of this Mac's running pair's (`pairProcesses`). Each default reads this + /// Mac's own state, so a test gives its own or points them elsewhere: `DARKBLOOM_LOCAL_DIR` for `local.json` and + /// the key files, `ClusterPairSummary.readerForTesting` for the cluster service. static func live(_ info: LocalEndpoint.Info? = LocalEndpoint.readLiveInfo(), - keyFile: (UInt16) -> URL? = { LocalEndpoint.keyFile(forPort: Int($0)) }) -> IntegrationEndpoint? { + keyFile: (UInt16) -> URL? = { LocalEndpoint.keyFile(forPort: Int($0)) }, + pairProcesses: () -> Set = { ClusterPairSummary.runningPairProcesses() }) + -> IntegrationEndpoint? { guard let info, !info.apiKey.isEmpty, let file = keyFile(info.port) else { return nil } - return IntegrationEndpoint(baseURL: info.baseURL, keyFile: file) + return IntegrationEndpoint(baseURL: info.baseURL, keyFile: file, + servesThePair: pairProcesses().contains(info.pid)) } } @@ -99,7 +110,7 @@ enum ToolIntegration { let writer = ToolConfigWriter(tool: tool, stateDirectory: environment.stateDirectory) return try writer.apply(to: file, newFileMode: tool.newFileMode, dryRun: dryRun) { existing in tool.plan(existing: existing, file: file, endpoint: endpoint, models: models, provider: provider, - home: environment.home) + environment: environment) } } diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift b/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift index eb5b2a36c4..93af1e0158 100644 --- a/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift +++ b/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift @@ -155,7 +155,8 @@ struct ToolIntegrationStep { return false } let listed = afterWait.listed - let models = IntegrationModels.resolve(listed, catalog: catalog) + let models = IntegrationModels.resolve(listed, catalog: catalog, + here: endpoint.servesThePair ? .yourPair : .thisMac) var ok = true var summaries: [ToolConfigSummary] = [] for (tool, executable) in ready { @@ -254,26 +255,20 @@ struct ToolIntegrationStep { case .refused(let file, let refusal): return (["✗ " + refusal.message(file: ToolIntegration.displayPath(file, home: home))], false) case .written(let file, let backup, let undo, let summary): - let path = ToolIntegration.displayPath(file, home: home) - let what = summary.provider == .updated ? "updated" : "added" - var lines: [String] + var lines = ["✓ \(tool.displayName) can use Darkbloom: \(count(summary.models.count)).", + " Changed: \(ToolIntegration.displayPath(file, home: home)) " + + "(\(changed(tool, summary, newFile: backup == nil, provider: provider)))"] + if let backup { lines.append(" Backup: \(ToolIntegration.displayPath(backup, home: home))") } switch tool { case .opencode: - let changed = backup == nil ? "a new file with the \"\(provider.id)\" provider" - : "\(what) the \"\(provider.id)\" provider; nothing else changed" - let useIt = summary.defaultModel.map { "in OpenCode, /models → \(provider.name); new sessions use \($0)." } - ?? "in OpenCode, /models → \(provider.name). Your default model is unchanged." - lines = ["✓ OpenCode can use Darkbloom: \(count(summary.models.count)).", - " Changed: \(path) (\(changed))"] - if let backup { lines.append(" Backup: \(ToolIntegration.displayPath(backup, home: home))") } - lines += [" Use it: \(useIt)", " Undo: \(undo)"] + lines += [" " + openCodeDefault(summary, models: models, provider: provider, + file: ToolIntegration.displayPath(file, home: home)), + " Undo: \(undo)"] case .hermes: - let model = summary.defaultModel.flatMap { id in models.first { $0.id == id }?.name ?? id } - lines = ["✓ Hermes uses Darkbloom: new Hermes chats run \(model ?? "a Darkbloom model")."] - lines.append(" Changed: \(path) (\(backup == nil ? "a new file with" : what) the \"\(provider.id)\" " - + "provider, made the main model)") - if let backup { lines.append(" Backup: \(ToolIntegration.displayPath(backup, home: home))") } - lines.append(" Switch back: hermes model · Undo: \(undo) · Chats already open keep their model.") + let main = summary.defaultModel.map { "Darkbloom's \(name(of: $0, in: models))" } ?? "Darkbloom" + let before = summary.replacedDefault.map { " (before: \($0))" } ?? "" + lines += [" New Hermes chats now use \(main)\(before). Switch back: hermes model", + " Undo: \(undo) · Chats already open keep their model."] if !summary.leftOut.isEmpty { lines.append(" Left out: \(summary.leftOut.joined(separator: ", ")) (Hermes needs 64K context)") } @@ -283,6 +278,60 @@ struct ToolIntegrationStep { } } + /// What a written config now holds of Darkbloom's, for the `Changed:` line: the provider, and the default model + /// when the edit set it. Hermes always makes Darkbloom its main model. + static func changed(_ tool: IntegrationTool, _ summary: ToolConfigSummary, newFile: Bool, + provider: IntegrationProvider) -> String { + let block = "the \"\(provider.id)\" provider" + switch tool { + case .opencode: + let andDefault = summary.defaultModel == nil ? "" : " and the default model" + if newFile { return "a new file with \(block)\(andDefault)" } + switch summary.provider { + case .added: return "added \(block)\(andDefault); nothing else changed" + case .updated: return "updated \(block)\(andDefault); nothing else changed" + case .unchanged: return "added the default model; nothing else changed" + } + case .hermes: + if newFile { return "a new file with \(block) as the main model" } + switch summary.provider { + case .added: return "added \(block) and made it the main model" + case .updated: return "updated \(block) and made it the main model" + case .unchanged: return "made \(block) the main model" + } + } + } + + /// OpenCode's default model after a written edit, on its own line: Darkbloom's when OpenCode had none, with the way + /// back that lasts (`/models` doesn't: a config's `model` comes first at every launch), `file` being the edited + /// one; else the default that stays, or the pick OpenCode remembers from `/models`, which Darkbloom's can be too. + static func openCodeDefault(_ summary: ToolConfigSummary, models: [IntegrationModel], + provider: IntegrationProvider, file: String) -> String { + let ours = provider.id + "/" + if let set = summary.defaultModel { + let id = set.hasPrefix(ours) ? String(set.dropFirst(ours.count)) : set + return "New OpenCode sessions now use Darkbloom's \(name(of: id, in: models)). To go back, remove \"model\" " + + "from \(file) or run the Undo below." + } + if let kept = summary.keptDefault { + return kept.hasPrefix(ours) ? "Your default stays \(kept) (the \"model\" in your OpenCode config)." + : "Your default stays \(kept); pick Darkbloom with /models." + } + if summary.rememberedPick != nil { return "Pick Darkbloom once with /models; OpenCode remembers it." } + return "Your default model stays as your config sets it; pick Darkbloom with /models." + } + + /// A model's name without where it runs (`Qwen 3.8 27B`), else its ID. + static func name(of id: String, in models: [IntegrationModel]) -> String { + models.first { $0.id == id }.map { IntegrationModel.displayName(in: $0.name) } ?? id + } + + /// The line beside a local API that already serves as the start would: the address the tools reach it at, never + /// the address it listens on (`0.0.0.0` for a pair's). + static func alreadyServes(_ live: LocalEndpoint.Info, tools: [IntegrationTool]) -> String { + "Darkbloom already serves at \(live.baseURL); setting up \(names(tools)) for it." + } + /// The line when this start has no local API for the tools. static func noLocalAPI(_ tools: [IntegrationTool]) -> String { "This Mac serves only the Darkbloom network, so \(names(tools)) \(tools.count == 1 ? "has" : "have") no local " diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/HermesConfigPlanTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/HermesConfigPlanTests.swift index 16c893aa22..72581a52a3 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/HermesConfigPlanTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/HermesConfigPlanTests.swift @@ -175,6 +175,36 @@ struct HermesConfigPlanTests { """ + added + block) } + @Test("the main model Darkbloom replaces is named with its provider; none, or Darkbloom's own, isn't") + func namesTheMainModelItReplaces() throws { + let cases: [(String?, String?)] = [ + ("model:\n default: gpt-6-astra\n provider: opencodex\n base_url: http://127.0.0.1:10100/v1\n", + "gpt-6-astra via opencodex"), + ("model:\n provider: \"custom:ollama-launch\"\n default: \"qwen3.6\"\n", "qwen3.6 via ollama-launch"), + ("model:\n model: openrouter/some-model\n", "openrouter/some-model"), + ("model: gpt-4o\n", "gpt-4o"), + ("model: \"\"\n", nil), + ("model: ~\n", nil), + ("model:\n provider: opencodex\n", nil), + (nil, nil), + ] + for (owner, before) in cases { + #expect(F.summary(plan(owner))?.replacedDefault == before, "\(owner ?? "no file")") + } + // Darkbloom's own main model, kept or switched to another of its models. + let created = try #require(F.newText(plan(nil))) + #expect(F.summary(plan(created, models: [F.glm]))?.replacedDefault == nil) + } + + @Test("a pair's model is the main one, as this Mac's would be") + func aPairsModelIsTheMainModel() { + let pair = IntegrationModel(id: "qwen3.8-27b", name: "Qwen 3.8 27B (your pair)", location: .yourPair, + contextLength: 262_144, outputLimit: 65_536, tools: true, imageInput: true, + reasoning: false) + #expect(F.summary(plan(nil, models: [F.glm, pair]))?.defaultModel == "qwen3.8-27b") + #expect(F.summary(plan(nil, models: [F.glm]))?.defaultModel == "glm-5.3-flash") + } + @Test("a Darkbloom default that is still listed with 64K or more is kept") func keepsTheCurrentDefault() throws { let created = try #require(F.newText(plan(nil))) diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/IntegrationModelsTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/IntegrationModelsTests.swift index 61fc09ee5c..28a03d7667 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/IntegrationModelsTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/IntegrationModelsTests.swift @@ -159,6 +159,67 @@ struct IntegrationModelsTests { ]) } + @Test("a pair's API: its own models are named (your pair); the others keep where they run") + func aPairsOwnModels() { + let models = IntegrationModels.resolve([ + EndpointModel(id: "z-net", ownedBy: "darkbloom"), + EndpointModel(id: "b-mine", ownedBy: "my-macs"), + EndpointModel(id: "q-pair", ownedBy: "this-mac"), + ], catalog: nil, here: .yourPair) + #expect(models.map(\.name) == ["q-pair (your pair)", "b-mine (your Macs)", "z-net (Darkbloom network, billed)"]) + #expect(models.first?.location == .yourPair) + // Read back from a tool's file without where it runs, so a run without the catalog keeps the name. + #expect(IntegrationModel.displayName(in: "Qwen 3.8 27B (your pair)") == "Qwen 3.8 27B") + #expect(IntegrationModel.Location.allCases.map(\.label) + == ["this Mac", "your pair", "your Macs", "Darkbloom network, billed"]) + } + + @Test("a pair's API serves its models here: the same limits and capabilities as this Mac's, online and offline") + func aPairsModelsAreServedHere() throws { + // Decoded as the endpoint lists them, so whatever the list says of a model served here (its engine's input + // modalities too) counts for the pair's as for this Mac's. + let listed = try JSONDecoder().decode([EndpointModel].self, from: Data(""" + [{"id": "q", "owned_by": "this-mac", "context_length": 262144, "max_output_length": 65536, + "input_modalities": ["text"]}, + {"id": "u", "owned_by": "this-mac", "input_modalities": ["text", "image"]}, + {"id": "m", "owned_by": "my-macs", "input_modalities": ["text", "image"]}] + """.utf8)) + func served(_ model: IntegrationModel) -> String { + "\(model.id) \(String(describing: model.contextLength)) \(String(describing: model.outputLimit)) " + + "\(model.tools) \(model.imageInput) \(model.reasoning) \(String(describing: model.fallback))" + } + let online = catalog([catalogModel("q", display: "Q", context: 131_072, capabilities: ["tools", "vision"])]) + for snapshot in [online, nil] as [CatalogSnapshot?] { + let here = IntegrationModels.resolve(listed, catalog: snapshot) + let pair = IntegrationModels.resolve(listed, catalog: snapshot, here: .yourPair) + #expect(pair.map(served) == here.map(served)) + #expect(pair.map(\.location) == [.yourPair, .yourPair, .yourMacs]) + } + } + + @Test("a pair's model keeps its engine's word on reasoning, a \"no\" too, online and offline, as this Mac's would") + func aPairsReasoningIsServedHere() throws { + // `supported_features: []` is the engine's "no": the catalog's reasoning can't add it, nor a tool's old entry. + let listed = try JSONDecoder().decode([EndpointModel].self, from: Data(""" + [{"id": "q", "owned_by": "this-mac", "context_length": 262144, "supported_features": []}, + {"id": "r", "owned_by": "this-mac", "context_length": 262144, "supported_features": ["reasoning"]}] + """.utf8)) + let online = catalog([catalogModel("q", display: "Q", context: 262_144, capabilities: ["tools", "reasoning"])]) + for snapshot in [online, nil] as [CatalogSnapshot?] { + let here = IntegrationModels.resolve(listed, catalog: snapshot) + let pair = IntegrationModels.resolve(listed, catalog: snapshot, here: .yourPair) + let mode = snapshot == nil ? "offline" : "online" + #expect(here.map(\.reasoning) == [false, true], "\(mode)") + #expect(pair.map(\.reasoning) == here.map(\.reasoning), "\(mode)") + #expect(pair.map(\.fallback) == here.map(\.fallback), "\(mode)") + } + } + + @Test("the endpoint's own process serves this Mac's models and its pair's, not your Macs' or the network's") + func whereAModelIsServedHere() { + #expect(IntegrationModel.Location.allCases.filter(\.servedHere) == [.thisMac, .yourPair]) + } + @Test("non-chat catalog models are left out; an alias ID takes the alias's name and its build's limits") func catalogKindsAndAliases() { let snapshot = catalog([ diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/OpenCodeConfigPlanTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/OpenCodeConfigPlanTests.swift index a2b933f52a..5cfbd144ac 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/OpenCodeConfigPlanTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/OpenCodeConfigPlanTests.swift @@ -69,7 +69,7 @@ struct OpenCodeConfigPlanTests { defaultModel: "darkbloom/gemma-4-26b-qat-4bit")) #expect(plan(text) == .unchanged(ToolConfigSummary( provider: .unchanged, models: ["gemma-4-26b-qat-4bit", "qwen3.8-27b", "glm-5.3-flash"], - defaultModel: nil))) + defaultModel: nil, keptDefault: "darkbloom/gemma-4-26b-qat-4bit"))) } @Test("an owner's file: only the providers block grows; comments, trailing commas, others and the model stay") @@ -100,12 +100,13 @@ struct OpenCodeConfigPlanTests { """ + suffix) #expect(F.summary(result)?.provider == .added) #expect(F.summary(result)?.defaultModel == nil) + #expect(F.summary(result)?.keptDefault == "anthropic/claude-sonnet-5-5") #expect(F.summary(result)?.droppedComments == 0) // The same run again changes nothing. #expect(plan(text) == .unchanged(ToolConfigSummary( provider: .unchanged, models: ["gemma-4-26b-qat-4bit", "qwen3.8-27b", "glm-5.3-flash"], - defaultModel: nil))) + defaultModel: nil, keptDefault: "anthropic/claude-sonnet-5-5"))) // A changed model list rewrites only the models member. let fewer = plan(text, models: [F.qwen]) @@ -117,7 +118,8 @@ struct OpenCodeConfigPlanTests { let tail = "\n }\n },\n" + suffix #expect(text.hasSuffix(tail) && rewritten.hasSuffix(tail)) #expect(rewritten.contains("\"qwen3.8-27b\"") && !rewritten.contains("gemma")) - #expect(F.summary(fewer) == ToolConfigSummary(provider: .updated, models: ["qwen3.8-27b"], defaultModel: nil)) + #expect(F.summary(fewer) == ToolConfigSummary(provider: .updated, models: ["qwen3.8-27b"], defaultModel: nil, + keptDefault: "anthropic/claude-sonnet-5-5")) } @Test("without the catalog, each model keeps its entry's name, capabilities and limits: nothing changes") @@ -130,7 +132,8 @@ struct OpenCodeConfigPlanTests { EndpointModel(id: "glm-5.3-flash", ownedBy: "my-macs"), ], catalog: nil) #expect(plan(online, models: offline) == .unchanged(ToolConfigSummary( - provider: .unchanged, models: ["gemma-4-26b-qat-4bit", "qwen3.8-27b", "glm-5.3-flash"], defaultModel: nil))) + provider: .unchanged, models: ["gemma-4-26b-qat-4bit", "qwen3.8-27b", "glm-5.3-flash"], defaultModel: nil, + keptDefault: "darkbloom/gemma-4-26b-qat-4bit"))) // A model the file has no entry for gets what is known; the others keep theirs. let more = offline + IntegrationModels.resolve( @@ -183,45 +186,127 @@ struct OpenCodeConfigPlanTests { #expect((parsed["providers"] as? [String: Any])?["darkbloom"] != nil) } - @Test("a default model the owner set is kept; none set means Darkbloom's first model") + @Test("a default model the owner set is kept, and named when it is a model; none set means Darkbloom's first model") func defaultModel() throws { - let kept = try #require(F.newText(plan("{\n \"model\": \"\"\n}\n"))) + let unnamed = plan("{\n \"model\": \"\"\n}\n") + let kept = try #require(F.newText(unnamed)) #expect(kept.hasPrefix("{\n \"model\": \"\",\n \"providers\": {")) + #expect(F.summary(unnamed)?.defaultModel == nil && F.summary(unnamed)?.keptDefault == nil) + let named = plan("{\n \"model\": \"omlx/qwen\"\n}\n") + #expect(F.summary(named)?.defaultModel == nil && F.summary(named)?.keptDefault == "omlx/qwen") let set = plan("{\n \"theme\": \"dark\"\n}\n") #expect(F.newText(set)?.contains(" \"model\": \"darkbloom/gemma-4-26b-qat-4bit\",\n") == true) #expect(F.summary(set)?.defaultModel == "darkbloom/gemma-4-26b-qat-4bit") + #expect(F.summary(set)?.keptDefault == nil) } - @Test("a default model set in another global file means none is added here, to a new file either") + @Test("a default model set in another global file means none is added here, to a new file either; it is named") func defaultModelSetElsewhere() throws { - let result = OpenCodeConfigPlan.plan( - existing: Data("{\n \"theme\": \"dark\"\n}\n".utf8), fileName: "opencode.jsonc", endpoint: F.endpoint, - models: F.models, provider: F.provider, home: F.home, defaultModelElsewhere: true) - let text = try #require(F.newText(result)) - #expect(!text.contains("\"model\"")) - #expect(F.summary(result)?.defaultModel == nil) - let created = OpenCodeConfigPlan.plan( - existing: nil, fileName: "opencode.jsonc", endpoint: F.endpoint, models: F.models, provider: F.provider, - home: F.home, defaultModelElsewhere: true) - #expect(F.newText(created)?.contains("\"model\"") == false) + for elsewhere in [OpenCodeConfigPlan.GlobalDefault.model("omlx/q"), .unnamed] { + let result = OpenCodeConfigPlan.plan( + existing: Data("{\n \"theme\": \"dark\"\n}\n".utf8), fileName: "opencode.jsonc", endpoint: F.endpoint, + models: F.models, provider: F.provider, home: F.home, defaultElsewhere: elsewhere) + let text = try #require(F.newText(result)) + #expect(!text.contains("\"model\"")) + #expect(F.summary(result)?.defaultModel == nil) + #expect(F.summary(result)?.keptDefault == (elsewhere == .unnamed ? nil : "omlx/q")) + let created = OpenCodeConfigPlan.plan( + existing: nil, fileName: "opencode.jsonc", endpoint: F.endpoint, models: F.models, provider: F.provider, + home: F.home, defaultElsewhere: elsewhere) + #expect(F.newText(created)?.contains("\"model\"") == false) + } + // This file's own default wins over the files it outranks. + let own = OpenCodeConfigPlan.plan( + existing: Data("{ \"model\": \"mine/m\" }".utf8), fileName: "opencode.jsonc", endpoint: F.endpoint, + models: F.models, provider: F.provider, home: F.home, defaultElsewhere: .model("omlx/q")) + #expect(F.summary(own)?.keptDefault == "mine/m") + } + + @Test("this file's own default beats the other global file's, named or not; two model keys there name none") + func thisFilesOwnDefaultWins() throws { + func summary(_ text: String, elsewhere: OpenCodeConfigPlan.GlobalDefault) -> ToolConfigSummary? { + F.summary(OpenCodeConfigPlan.plan( + existing: Data(text.utf8), fileName: "opencode.jsonc", endpoint: F.endpoint, models: F.models, + provider: F.provider, home: F.home, defaultElsewhere: elsewhere)) + } + // `""` here wins over a name there: the default stays, without a name, and none is written. + let unnamedHere = try #require(summary("{ \"model\": \"\" }", elsewhere: .model("omlx/q"))) + #expect(unnamedHere.defaultModel == nil && unnamedHere.keptDefault == nil) + // A name here wins over a default there that has none. + let namedHere = try #require(summary("{ \"model\": \"mine/m\" }", elsewhere: .unnamed)) + #expect(namedHere.defaultModel == nil && namedHere.keptDefault == "mine/m") + // The other file sets `model` twice: a default Darkbloom can't name. + let directory = try TemporaryDirectory() + try directory.write("{ \"model\": \"a/b\", \"model\": \"c/d\" }", to: "opencode/opencode.json") + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: directory.file("opencode/opencode.jsonc")) == .unnamed) + } + + @Test("a model OpenCode remembers from /models stands as its default: no model is added, and the pick is noted") + func aRememberedPickStands() throws { + func plan(_ existing: String, defaultElsewhere: OpenCodeConfigPlan.GlobalDefault = .none) -> ToolConfigPlan { + OpenCodeConfigPlan.plan(existing: Data(existing.utf8), fileName: "opencode.jsonc", endpoint: F.endpoint, + models: F.models, provider: F.provider, home: F.home, + defaultElsewhere: defaultElsewhere, rememberedPick: "omlx/qwen3.6") + } + let remembered = plan("{\n \"theme\": \"dark\"\n}\n") + #expect(F.newText(remembered)?.contains("\"model\"") == false) + #expect(F.summary(remembered)?.defaultModel == nil && F.summary(remembered)?.rememberedPick == "omlx/qwen3.6") + // A config's default comes before a remembered pick in OpenCode's TUI: it is the one that stays. + for (existing, elsewhere) in [("{ \"model\": \"mine/m\" }", OpenCodeConfigPlan.GlobalDefault.none), + ("{}", .model("mine/m"))] { + let configured = plan(existing, defaultElsewhere: elsewhere) + #expect(F.summary(configured)?.keptDefault == "mine/m", "\(existing)") + #expect(F.summary(configured)?.rememberedPick == nil, "\(existing)") + } + #expect(F.summary(plan("{ \"model\": \"\" }"))?.rememberedPick == nil, "a default without a name stays first") + } + + @Test("OpenCode's remembered pick: the first named entry of recent in model.json, in its state folder") + func rememberedPick() throws { + let directory = try TemporaryDirectory() + let home = directory.file("home") + let state = ["XDG_STATE_HOME": directory.file("state").path] + #expect(OpenCodeConfigPlan.rememberedPick(home: home, variables: [:]) == nil, "no file") + try directory.write(#"{ "recent": [{ "providerID": "", "modelID": "x" }, { "modelID": "y" }, "# + + #"{ "providerID": "omlx", "modelID": "qwen3.6" }, { "providerID": "exo", "modelID": "llama" }] }"#, + to: "home/.local/state/opencode/model.json") + #expect(OpenCodeConfigPlan.rememberedPick(home: home, variables: [:]) == "omlx/qwen3.6") + #expect(OpenCodeConfigPlan.rememberedPick(home: home, variables: ["XDG_STATE_HOME": ""]) == "omlx/qwen3.6", + "an empty XDG_STATE_HOME is no folder, as OpenCode reads it") + #expect(OpenCodeConfigPlan.rememberedPick(home: home, variables: state) == nil, "another state folder") + try directory.write(#"{ "recent": [{ "providerID": "exo", "modelID": "llama" }] }"#, + to: "state/opencode/model.json") + #expect(OpenCodeConfigPlan.rememberedPick(home: home, variables: state) == "exo/llama") + for text in [#"{ "recent": [], "favorite": [{ "providerID": "omlx", "modelID": "q" }] }"#, "{ \"recent\": ", + "[]", #"{ "recent": { "providerID": "omlx", "modelID": "q" } }"#] { + try directory.write(text, to: "state/opencode/model.json") + #expect(OpenCodeConfigPlan.rememberedPick(home: home, variables: state) == nil, "\(text)") + } } - @Test("another global file sets a default: its own top-level model key, or it can't be read") - func otherGlobalConfigSetsModel() throws { + @Test("the global files' default, merged as OpenCode 2 merges them: opencode.json, then opencode.jsonc") + func otherGlobalDefault() throws { let directory = try TemporaryDirectory() let folder = directory.file("opencode") let jsonc = folder.appendingPathComponent("opencode.jsonc") - #expect(!OpenCodeConfigPlan.otherGlobalConfigSetsModel(besides: jsonc)) + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: jsonc) == .none) try directory.write("{\n \"theme\": \"dark\"\n}\n", to: "opencode/opencode.json") - #expect(!OpenCodeConfigPlan.otherGlobalConfigSetsModel(besides: jsonc)) + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: jsonc) == .none) try directory.write("{ \"agent\": { \"build\": { \"model\": \"x/y\" } } }", to: "opencode/opencode.json") - #expect(!OpenCodeConfigPlan.otherGlobalConfigSetsModel(besides: jsonc)) + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: jsonc) == .none) try directory.write("{\n // mine\n \"model\": \"omlx/q\",\n}\n", to: "opencode/opencode.json") - #expect(OpenCodeConfigPlan.otherGlobalConfigSetsModel(besides: jsonc)) + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: jsonc) == .model("omlx/q")) + try directory.write("{ \"model\": null }", to: "opencode/opencode.json") + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: jsonc) == .unnamed) try directory.write("{ \"model\": ", to: "opencode/opencode.json") - #expect(OpenCodeConfigPlan.otherGlobalConfigSetsModel(besides: jsonc)) + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: jsonc) == .unnamed) // The file being edited isn't another one: its own model is the planner's to read. - #expect(!OpenCodeConfigPlan.otherGlobalConfigSetsModel(besides: folder.appendingPathComponent("opencode.json"))) + try directory.write("{ \"model\": \"omlx/q\" }", to: "opencode/opencode.json") + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: folder.appendingPathComponent("opencode.json")) == .none) + // OpenCode 1's config.json: OpenCode 2 doesn't load it ("does not load legacy config.json files"). + try directory.write("{ \"model\": \"legacy/m\" }", to: "opencode/config.json") + #expect(OpenCodeConfigPlan.otherGlobalDefault(besides: folder.appendingPathComponent("opencode.json")) == .none) + #expect(OpenCodeConfigPlan.globalFileNames == ["opencode.json", "opencode.jsonc"]) } @Test("an empty object and a one-line object get the provider on their own lines") diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/OpenCodeSmokeSetup.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/OpenCodeSmokeSetup.swift index 6abf7efedf..6571a0c59b 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/OpenCodeSmokeSetup.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/OpenCodeSmokeSetup.swift @@ -27,7 +27,9 @@ struct OpenCodeSmokeSetup { let localDirectory = try #require(ProcessInfo.processInfo.environment["DARKBLOOM_LOCAL_DIR"]) try #require(isInside(URL(fileURLWithPath: localDirectory))) - let endpoint = try #require(IntegrationEndpoint.live(), "no live endpoint in \(localDirectory)/local.json") + // The script's fake server is no pair's part: this Mac's own cluster service isn't read. + let endpoint = try #require(IntegrationEndpoint.live(pairProcesses: { [] }), + "no live endpoint in \(localDirectory)/local.json") try #require(isInside(endpoint.keyFile)) let models = IntegrationModels.resolve(try await IntegrationModels.fetch(endpoint), catalog: nil) let environment = ToolIntegrationEnvironment( diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/StartToolIntegrationTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/StartToolIntegrationTests.swift index 2cca914674..2a8b51bbfe 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/StartToolIntegrationTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/StartToolIntegrationTests.swift @@ -138,9 +138,12 @@ struct StartToolIntegrationTests { let keyFile = URL(fileURLWithPath: "/tmp/fixture/local_token") let live = LocalEndpoint.Info(host: "127.0.0.1", port: 8123, apiKey: "dk-local-fixture", version: "test", pid: 1, updatedAt: "") + // A test's pair, so `IntegrationEndpoint.live` never reads this Mac's own cluster service. func shortcut(_ arguments: [String], _ info: LocalEndpoint.Info? = live, keyFile file: URL? = keyFile) throws -> IntegrationEndpoint? { - try Start.parse(arguments).runningLocalAPI(info, keyFile: { _ in file }) + try ClusterPairSummary.$readerForTesting.withValue({ _ in .notPaired }) { + try Start.parse(arguments).runningLocalAPI(info, keyFile: { _ in file }) + } } let expected = IntegrationEndpoint(baseURL: "http://127.0.0.1:8123/v1", keyFile: keyFile) for arguments in [["--opencode"], ["--hermes", "--local"], ["--opencode", "--me-first"], @@ -168,9 +171,12 @@ struct StartToolIntegrationTests { version: "", pid: 1, updatedAt: ""), LocalEndpoint.Info(host: "0.0.0.0", port: 8123, apiKey: "k", version: "", pid: 1, updatedAt: "")] - let found = await Start.waitForLocalAPI(port: 8123, seconds: 30, - live: { answers.isEmpty ? nil : answers.removeFirst() }, - keyFile: { _ in keyFile }, pause: {}) + // A test's pair, so `IntegrationEndpoint.live` never reads this Mac's own cluster service. + let found = await ClusterPairSummary.$readerForTesting.withValue({ _ in .notPaired }) { + await Start.waitForLocalAPI(port: 8123, seconds: 30, + live: { answers.isEmpty ? nil : answers.removeFirst() }, + keyFile: { _ in keyFile }, pause: {}) + } #expect(found == .ready(IntegrationEndpoint(baseURL: "http://127.0.0.1:8123/v1", keyFile: keyFile))) let none = await Start.waitForLocalAPI(port: 8123, seconds: 0, live: { nil }, keyFile: { _ in keyFile }, pause: {}) @@ -350,13 +356,16 @@ struct StartToolIntegrationTests { #expect(ok) #expect(sandbox.said == [ "✓ OpenCode can use Darkbloom: 2 models.", - " Changed: ~/.config/opencode/opencode.jsonc (a new file with the \"darkbloom\" provider)", - " Use it: in OpenCode, /models → Darkbloom; new sessions use darkbloom/gemma-4-26b-qat-4bit.", + " Changed: ~/.config/opencode/opencode.jsonc (a new file with the \"darkbloom\" provider and the default " + + "model)", + " New OpenCode sessions now use Darkbloom's gemma-4-26b-qat-4bit. To go back, remove \"model\" from " + + "~/.config/opencode/opencode.jsonc or run the Undo below.", " Undo: rm \(ToolIntegration.shellQuoted(sandbox.openCodeFile.path))", - "✓ Hermes uses Darkbloom: new Hermes chats run qwen3.8-27b (this Mac).", - " Changed: ~/.hermes/config.yaml (a new file with the \"darkbloom\" provider, made the main model)", - " Switch back: hermes model · Undo: rm \(ToolIntegration.shellQuoted(sandbox.hermesFile.path)) · " - + "Chats already open keep their model.", + "✓ Hermes can use Darkbloom: 1 model.", + " Changed: ~/.hermes/config.yaml (a new file with the \"darkbloom\" provider as the main model)", + " New Hermes chats now use Darkbloom's qwen3.8-27b. Switch back: hermes model", + " Undo: rm \(ToolIntegration.shellQuoted(sandbox.hermesFile.path)) · Chats already open keep their " + + "model.", " Left out: gemma-4-26b-qat-4bit (Hermes needs 64K context)", " Darkbloom's catalog wasn't reachable: run `darkbloom --opencode --hermes` again online for the " + "models' names and image support.", @@ -383,7 +392,7 @@ struct StartToolIntegrationTests { "✓ OpenCode can use Darkbloom: 1 model.", " Changed: ~/.config/opencode/opencode.jsonc (updated the \"darkbloom\" provider; nothing else changed)", " Backup: ~/.darkbloom/integrations/backups/opencode/\(backup.lastPathComponent)", - " Use it: in OpenCode, /models → Darkbloom. Your default model is unchanged.", + " Your default stays darkbloom/gemma-4-26b-qat-4bit (the \"model\" in your OpenCode config).", " Undo: cp \(ToolIntegration.shellQuoted(backup.path)) \(ToolIntegration.shellQuoted(sandbox.openCodeFile.path))", ]) diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolIntegrationTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolIntegrationTests.swift index c280823b51..94c8eeee91 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolIntegrationTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolIntegrationTests.swift @@ -175,7 +175,7 @@ struct ToolIntegrationTests { } // The live endpoint reads the discovery folder through the process-wide DARKBLOOM_LOCAL_DIR, so it runs in a - // child process that alone points it at a temp folder. + // child process that alone points it at a temp folder, and keeps it off this Mac's cluster service. @Test("the live endpoint is local.json's address and port, with the key file that holds its key") func liveEndpoint() async { await #expect(processExitsWith: .success) { @@ -183,6 +183,7 @@ struct ToolIntegrationTests { .appendingPathComponent("tool-integration-live-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) setenv("DARKBLOOM_LOCAL_DIR", directory.path, 1) + keepCommandsOffThisMacsCluster() func publish(port: UInt16, key: String, pid: Int32 = getpid()) throws { try LocalEndpoint.writeInfo(LocalEndpoint.Info( host: "0.0.0.0", port: port, apiKey: key, version: "9.9.9", pid: pid, updatedAt: "t")) diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolSetupWordsTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolSetupWordsTests.swift new file mode 100644 index 0000000000..1184a24a96 --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolSetupWordsTests.swift @@ -0,0 +1,351 @@ +import Foundation +import Testing + +@testable import ProviderCore +@testable import darkbloom + +private typealias F = ToolIntegrationFixtures + +/// A temp home with Darkbloom's key file and the tools' configs as a user's Mac has them, and a recorder for what the +/// step says. No tool runs, no port is bound, and no real home, OpenCode or Hermes config is read. +private final class WordsSandbox: @unchecked Sendable { + let directory: TemporaryDirectory + let home: URL + let keyFile: URL + var said: [String] = [] + + init() throws { + directory = try TemporaryDirectory("tool-words") + home = directory.file("home") + keyFile = try directory.write(F.freshToken(), to: "home/.darkbloom/local_token", mode: 0o600) + } + + /// A pair's API on every address, as journey 2a found it on the leading Mac. + func endpoint(pair: Bool = false) -> IntegrationEndpoint { + IntegrationEndpoint(baseURL: "http://127.0.0.1:8001/v1", keyFile: keyFile, servesThePair: pair) + } + + var openCodeJSON: URL { home.appendingPathComponent(".config/opencode/opencode.json") } + var openCodeJSONC: URL { home.appendingPathComponent(".config/opencode/opencode.jsonc") } + var hermesFile: URL { home.appendingPathComponent(".hermes/config.yaml") } + + static let qwen = "EigenLabs/Qwen3.8-27B-4bit-mtp" + static let catalog = CatalogSnapshot(models: [ + CatalogModel(id: qwen, s3Name: qwen, displayName: "Qwen 3.8 27B", sizeGb: 1, maxContextLength: 262_144, + maxOutputLength: 65_536, capabilities: ["tools", "vision"]), + ], aliases: []) + + /// The start's environment variables (`XDG_STATE_HOME`, `XDG_CONFIG_HOME`). + var variables: [String: String] = [:] + + /// OpenCode's TUI's remembered `/models` picks, as OpenCode 2.2.6 writes them: `model.json` in its state folder. + func remember(_ picks: [(provider: String, model: String)], in state: String = "home/.local/state") throws { + let recent = picks.map { #"{ "providerID": "\#($0.provider)", "modelID": "\#($0.model)" }"# } + try directory.write(#"{ "recent": [\#(recent.joined(separator: ", "))], "favorite": [], "variant": {} }"#, + to: "\(state)/opencode/model.json") + } + + func step(_ tools: [IntegrationTool], catalog: CatalogSnapshot? = WordsSandbox.catalog) -> ToolIntegrationStep { + ToolIntegrationStep( + tools: tools, environment: ToolIntegrationEnvironment(home: home, variables: variables), provider: F.provider, + findTool: { .installed(URL(fileURLWithPath: "/fake/\($0.rawValue)")) }, + fetchModels: { _ in [EndpointModel(id: Self.qwen, ownedBy: "this-mac", contextLength: 262_144)] }, + fetchCatalog: { catalog }, say: { [self] in said.append($0) }) + } + + /// What the step says for `tools`, from its first line to the undo (or `Left out:`), without the backup's name. + func run(_ tools: [IntegrationTool], pair: Bool = false, + catalog: CatalogSnapshot? = WordsSandbox.catalog) async -> [String] { + said = [] + #expect(await step(tools, catalog: catalog).run(endpoint: endpoint(pair: pair), requests: "this Mac only")) + return said.filter { !$0.hasPrefix(" Requests:") && !$0.hasPrefix(" Other tools:") } + .map { $0.hasPrefix(" Backup:") ? " Backup: " : $0 } + .map { $0.replacingOccurrences(of: #"Undo: cp '[^']*' "#, with: "Undo: cp ", + options: .regularExpression) } + } +} + +/// His `opencode.json` in journey 2a: two providers of his own and no default model. +private let hisOpenCodeJSON = """ +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "exo": { "npm": "@ai-sdk/openai-compatible", "options": { "baseURL": "http://127.0.0.1:52415/v1" } }, + "omlx": { "npm": "@ai-sdk/openai-compatible", "options": { "baseURL": "http://127.0.0.1:8000/v1" } } + } +} + +""" + +/// His `~/.hermes/config.yaml` in journey 2a: the main model is another provider's. +private let hisHermes = """ +model: + default: gpt-6-astra + provider: opencodex + base_url: http://127.0.0.1:10100/v1 + api_mode: chat_completions + api_key: ${OPENCODEX_HERMES_API_KEY} +toolsets: + - hermes-cli + +""" + +@Suite("Start: --opencode and --hermes say what they did to your default, and where the models run", .serialized) +struct ToolSetupWordsTests { + // MARK: - OpenCode's default (J2-g) + + @Test("no global file sets a default: Darkbloom's becomes it, said on its own line, with the undo") + func noDefaultAnywhereSetsDarkbloomsAndSaysSo() async throws { + let sandbox = try WordsSandbox() + try sandbox.directory.write(hisOpenCodeJSON, to: "home/.config/opencode/opencode.json") + try sandbox.directory.write("{\n \"theme\": \"dark\"\n}\n", to: "home/.config/opencode/opencode.jsonc") + let json = try Data(contentsOf: sandbox.openCodeJSON) + #expect(await sandbox.run([.opencode]) == [ + "✓ OpenCode can use Darkbloom: 1 model.", + " Changed: ~/.config/opencode/opencode.jsonc (added the \"darkbloom\" provider and the default model; " + + "nothing else changed)", + " Backup: ", + " New OpenCode sessions now use Darkbloom's Qwen 3.8 27B. To go back, remove \"model\" from " + + "~/.config/opencode/opencode.jsonc or run the Undo below.", + " Undo: cp \(ToolIntegration.shellQuoted(sandbox.openCodeJSONC.path))", + ]) + #expect(F.utf8(try Data(contentsOf: sandbox.openCodeJSONC)) + .contains("\"model\": \"darkbloom/\(WordsSandbox.qwen)\"")) + #expect(try Data(contentsOf: sandbox.openCodeJSON) == json, "his opencode.json is never touched") + + // A new file says the same. + let fresh = try WordsSandbox() + let lines = await fresh.run([.opencode]) + #expect(lines.prefix(3) == [ + "✓ OpenCode can use Darkbloom: 1 model.", + " Changed: ~/.config/opencode/opencode.jsonc (a new file with the \"darkbloom\" provider and the default " + + "model)", + " New OpenCode sessions now use Darkbloom's Qwen 3.8 27B. To go back, remove \"model\" from " + + "~/.config/opencode/opencode.jsonc or run the Undo below.", + ]) + } + + @Test("a model picked with /models, which OpenCode remembers, stays its default: no model is written") + func aRememberedPickStays() async throws { + let sandbox = try WordsSandbox() + try sandbox.directory.write(hisOpenCodeJSON, to: "home/.config/opencode/opencode.json") + try sandbox.remember([("omlx", "qwen3.6"), ("exo", "llama-3.3-70b")]) + #expect(await sandbox.run([.opencode]) == [ + "✓ OpenCode can use Darkbloom: 1 model.", + " Changed: ~/.config/opencode/opencode.json (added the \"darkbloom\" provider; nothing else changed)", + " Backup: ", + " Pick Darkbloom once with /models; OpenCode remembers it.", + " Undo: cp \(ToolIntegration.shellQuoted(sandbox.openCodeJSON.path))", + ]) + let written = F.utf8(try Data(contentsOf: sandbox.openCodeJSON)) + #expect(!written.contains("\"model\""), "\(written)") + #expect(written.contains("\"omlx\": { \"npm\""), "his providers stay") + // A run again changes nothing. + #expect(await sandbox.run([.opencode]) == ["✓ OpenCode already lists Darkbloom's 1 model (nothing changed)."]) + + // OpenCode's state folder under XDG_STATE_HOME, as it finds it; then ~/.local/state isn't read. + let xdg = try WordsSandbox() + xdg.variables = ["XDG_STATE_HOME": xdg.directory.file("state").path] + try xdg.remember([("omlx", "qwen3.6")], in: "state") + #expect(await xdg.run([.opencode]).contains(" Pick Darkbloom once with /models; OpenCode remembers it.")) + let elsewhere = try WordsSandbox() + elsewhere.variables = ["XDG_STATE_HOME": elsewhere.directory.file("state").path] + try elsewhere.remember([("omlx", "qwen3.6")]) + _ = await elsewhere.run([.opencode]) + #expect(F.utf8(try Data(contentsOf: elsewhere.openCodeJSONC)).contains("\"model\": \"darkbloom/"), + "the pick is in another state folder than OpenCode's") + + // A config's default outranks a remembered pick in OpenCode, so it is the one named. + let both = try WordsSandbox() + try both.directory.write("{\n \"model\": \"exo/llama-3.3-70b\"\n}\n", to: "home/.config/opencode/opencode.json") + try both.remember([("omlx", "qwen3.6")]) + #expect(await both.run([.opencode]).contains(" Your default stays exo/llama-3.3-70b; pick Darkbloom with /models.")) + } + + @Test("no pick OpenCode would read (none, only favorites, malformed or unreadable): Darkbloom's becomes the default") + func noRememberedPickSetsDarkbloomsDefault() async throws { + let empty = #"{ "recent": [], "favorite": [{ "providerID": "omlx", "modelID": "qwen3.6" }], "variant": {} }"# + let unnamed = #"{ "recent": [{ "providerID": "", "modelID": "qwen3.6" }, { "providerID": "omlx" }] }"# + for text in [empty, unnamed, "{ \"recent\": ", "[]"] { + let sandbox = try WordsSandbox() + try sandbox.directory.write(text, to: "home/.local/state/opencode/model.json") + #expect(await sandbox.run([.opencode]).contains( + " New OpenCode sessions now use Darkbloom's Qwen 3.8 27B. To go back, remove \"model\" from " + + "~/.config/opencode/opencode.jsonc or run the Undo below."), "\(text)") + } + } + + @Test("a default in any global file stays, named; none is written, in either file") + func aDefaultElsewhereStays() async throws { + let sandbox = try WordsSandbox() + let mine = hisOpenCodeJSON.replacingOccurrences(of: "\"provider\": {", + with: "\"model\": \"exo/llama-3.3-70b\",\n \"provider\": {") + try sandbox.directory.write(mine, to: "home/.config/opencode/opencode.json") + try sandbox.directory.write("{\n \"theme\": \"dark\"\n}\n", to: "home/.config/opencode/opencode.jsonc") + #expect(await sandbox.run([.opencode]) == [ + "✓ OpenCode can use Darkbloom: 1 model.", + " Changed: ~/.config/opencode/opencode.jsonc (added the \"darkbloom\" provider; nothing else changed)", + " Backup: ", + " Your default stays exo/llama-3.3-70b; pick Darkbloom with /models.", + " Undo: cp \(ToolIntegration.shellQuoted(sandbox.openCodeJSONC.path))", + ]) + #expect(!F.utf8(try Data(contentsOf: sandbox.openCodeJSONC)).contains("\"model\"")) + + // The file Darkbloom edits sets it: it stays too. + let own = try WordsSandbox() + try own.directory.write("{\n \"model\": \"omlx/qwen\"\n}\n", to: "home/.config/opencode/opencode.json") + #expect(await own.run([.opencode]).contains(" Your default stays omlx/qwen; pick Darkbloom with /models.")) + } + + @Test("a default the global files set without a model's name stays, and the line says so without one") + func aDefaultWithoutANameStays() async throws { + for json in ["{ \"model\": \"\" }\n", "{ \"model\": null }\n", "{ \"model\": \n"] { + let sandbox = try WordsSandbox() + try sandbox.directory.write(json, to: "home/.config/opencode/opencode.json") + try sandbox.directory.write("{\n \"theme\": \"dark\"\n}\n", to: "home/.config/opencode/opencode.jsonc") + #expect(await sandbox.run([.opencode]) == [ + "✓ OpenCode can use Darkbloom: 1 model.", + " Changed: ~/.config/opencode/opencode.jsonc (added the \"darkbloom\" provider; nothing else changed)", + " Backup: ", + " Your default model stays as your config sets it; pick Darkbloom with /models.", + " Undo: cp \(ToolIntegration.shellQuoted(sandbox.openCodeJSONC.path))", + ], "\(json)") + #expect(!F.utf8(try Data(contentsOf: sandbox.openCodeJSONC)).contains("\"model\""), "\(json)") + } + } + + @Test("OpenCode 1's config.json is no global file of OpenCode 2's: a model there sets no default") + func legacyConfigJSONSetsNoDefault() async throws { + let sandbox = try WordsSandbox() + try sandbox.directory.write("{ \"model\": \"anthropic/claude-sonnet-4\" }\n", to: "home/.config/opencode/config.json") + #expect(await sandbox.run([.opencode]).contains( + " New OpenCode sessions now use Darkbloom's Qwen 3.8 27B. To go back, remove \"model\" from " + + "~/.config/opencode/opencode.jsonc or run the Undo below.")) + } + + // MARK: - Hermes' main model + + @Test("Hermes: Darkbloom becomes the main model, and the line names the one before and how to switch back") + func hermesNamesTheMainModelBefore() async throws { + let sandbox = try WordsSandbox() + try sandbox.directory.write(hisHermes, to: "home/.hermes/config.yaml") + #expect(await sandbox.run([.hermes]) == [ + "✓ Hermes can use Darkbloom: 1 model.", + " Changed: ~/.hermes/config.yaml (added the \"darkbloom\" provider and made it the main model)", + " Backup: ", + " New Hermes chats now use Darkbloom's Qwen 3.8 27B (before: gpt-6-astra via opencodex). Switch back: " + + "hermes model", + " Undo: cp \(ToolIntegration.shellQuoted(sandbox.hermesFile.path)) · Chats already open " + + "keep their model.", + ]) + // No main model before: nothing to name. + let fresh = try WordsSandbox() + #expect(await fresh.run([.hermes]).contains( + " New Hermes chats now use Darkbloom's Qwen 3.8 27B. Switch back: hermes model")) + } + + // MARK: - Where it serves (J2-e) and where the models run (J2-f) + + @Test("a running API is named by the address a tool uses, never its bind address") + func alreadyServesNamesTheURL() { + let everyAddress = LocalEndpoint.Info(host: "0.0.0.0", port: 8001, apiKey: "dk-local-fixture", version: "t", + pid: 41, updatedAt: "") + #expect(ToolIntegrationStep.alreadyServes(everyAddress, tools: [.opencode]) + == "Darkbloom already serves at http://127.0.0.1:8001/v1; setting up OpenCode for it.") + let loopback = LocalEndpoint.Info(host: "127.0.0.1", port: 8002, apiKey: "k", version: "t", pid: 41, + updatedAt: "") + #expect(ToolIntegrationStep.alreadyServes(loopback, tools: [.opencode, .hermes]) + == "Darkbloom already serves at http://127.0.0.1:8002/v1; setting up OpenCode and Hermes for it.") + } + + @Test("the pair's API: its models are named (your pair), and the names stay the same on every run") + func aPairsModelsAreThePairs() async throws { + let keyFile = URL(fileURLWithPath: "/tmp/fixture/local_token") + let info = LocalEndpoint.Info(host: "0.0.0.0", port: 8001, apiKey: "dk-local-fixture", version: "t", pid: 41, + updatedAt: "") + #expect(IntegrationEndpoint.live(info, keyFile: { _ in keyFile }, pairProcesses: { [41, 40] })?.servesThePair + == true, "this Mac's running part of the pair serves it") + #expect(IntegrationEndpoint.live(info, keyFile: { _ in keyFile }, pairProcesses: { [7] })?.servesThePair == false) + #expect(IntegrationEndpoint.live(info, keyFile: { _ in keyFile }, pairProcesses: { [] })?.servesThePair == false) + // A member's relay writes local.json with its cluster service's pid: the pair's API too. + let relay = LocalEndpoint.Info(host: "0.0.0.0", port: 8001, apiKey: "dk-local-fixture", version: "t", pid: 40, + updatedAt: "") + #expect(IntegrationEndpoint.live(relay, keyFile: { _ in keyFile }, pairProcesses: { [41, 40] })?.servesThePair + == true, "the relay serves the pair") + + let sandbox = try WordsSandbox() + let first = await sandbox.run([.opencode, .hermes], pair: true) + #expect(first.contains(" New Hermes chats now use Darkbloom's Qwen 3.8 27B. Switch back: hermes model")) + let openCode = try Data(contentsOf: sandbox.openCodeJSONC) + let hermes = try Data(contentsOf: sandbox.hermesFile) + #expect(F.utf8(openCode).contains("\"name\": \"Qwen 3.8 27B (your pair)\"")) + #expect(!F.utf8(openCode).contains("this Mac")) + #expect(F.utf8(hermes).contains(" default: \"\(WordsSandbox.qwen)\""), "the pair's model is the main one") + // Again, online and offline: nothing changes. + for catalog in [WordsSandbox.catalog, nil] as [CatalogSnapshot?] { + let again = await sandbox.run([.opencode, .hermes], pair: true, catalog: catalog) + #expect(again.prefix(2) == ["✓ OpenCode already lists Darkbloom's 1 model (nothing changed).", + "✓ Hermes already uses Darkbloom's current models (nothing changed)."]) + #expect(try Data(contentsOf: sandbox.openCodeJSONC) == openCode && Data(contentsOf: sandbox.hermesFile) == hermes) + } + } + + @Test("the pair's processes: its part's, and its cluster service's, whose relay serves a member's API") + func thePairsProcesses() { + var status = ClusterServiceStatus(role: "follower", serving: true, modelName: "m", sessionLeader: false, + localRank: 1, setup: nil, child: .init(running: true, starts: 1, pid: 41), + session: nil) + status.servicePID = 40 + #expect(ClusterPairSummary.pairProcesses(of: status) == [41, 40]) + status.child.running = false + #expect(ClusterPairSummary.pairProcesses(of: status).isEmpty, "no part runs: no pair serves here") + #expect(ClusterPairSummary.pairProcesses(of: nil).isEmpty, "no cluster service") + } + + // MARK: - Every line an edit can give + + @Test("each way an edit can go has its own Changed: words, and OpenCode's default its own line") + func everyChangedAndDefaultLine() { + func changed(_ tool: IntegrationTool, _ change: ToolConfigSummary.ProviderChange, setsDefault: Bool, + newFile: Bool = false) -> String { + let summary = ToolConfigSummary(provider: change, models: ["m"], + defaultModel: setsDefault ? "darkbloom/m" : nil) + return ToolIntegrationStep.changed(tool, summary, newFile: newFile, provider: F.provider) + } + let block = "the \"darkbloom\" provider" + #expect(changed(.opencode, .added, setsDefault: true, newFile: true) + == "a new file with \(block) and the default model") + #expect(changed(.opencode, .added, setsDefault: false, newFile: true) == "a new file with \(block)") + #expect(changed(.opencode, .added, setsDefault: true) + == "added \(block) and the default model; nothing else changed") + #expect(changed(.opencode, .added, setsDefault: false) == "added \(block); nothing else changed") + #expect(changed(.opencode, .updated, setsDefault: true) + == "updated \(block) and the default model; nothing else changed") + #expect(changed(.opencode, .updated, setsDefault: false) == "updated \(block); nothing else changed") + #expect(changed(.opencode, .unchanged, setsDefault: true) == "added the default model; nothing else changed") + #expect(changed(.hermes, .added, setsDefault: true, newFile: true) + == "a new file with \(block) as the main model") + #expect(changed(.hermes, .added, setsDefault: true) == "added \(block) and made it the main model") + #expect(changed(.hermes, .updated, setsDefault: true) == "updated \(block) and made it the main model") + #expect(changed(.hermes, .unchanged, setsDefault: true) == "made \(block) the main model") + + let pair = [IntegrationModel(id: "m", name: "Qwen 3.8 27B (your pair)", location: .yourPair, + contextLength: 262_144, outputLimit: 65_536, tools: true, imageInput: false, + reasoning: false)] + func line(_ defaultModel: String?, kept: String? = nil, remembered: String? = nil) -> String { + var summary = ToolConfigSummary(provider: .added, models: ["m"], defaultModel: defaultModel, + keptDefault: kept) + summary.rememberedPick = remembered + return ToolIntegrationStep.openCodeDefault(summary, models: pair, provider: F.provider, + file: "~/.config/opencode/opencode.json") + } + #expect(line("darkbloom/m") == "New OpenCode sessions now use Darkbloom's Qwen 3.8 27B. To go back, remove " + + "\"model\" from ~/.config/opencode/opencode.json or run the Undo below.") + #expect(line(nil, kept: "exo/llama-3.3-70b") + == "Your default stays exo/llama-3.3-70b; pick Darkbloom with /models.") + #expect(line(nil, kept: "darkbloom/m") + == "Your default stays darkbloom/m (the \"model\" in your OpenCode config).") + #expect(line(nil, remembered: "omlx/qwen3.6") == "Pick Darkbloom once with /models; OpenCode remembers it.") + #expect(line(nil) == "Your default model stays as your config sets it; pick Darkbloom with /models.") + } +}