diff --git a/changelog.d/tools-wait-for-the-model.md b/changelog.d/tools-wait-for-the-model.md
new file mode 100644
index 0000000000..ba1c592cec
--- /dev/null
+++ b/changelog.d/tools-wait-for-the-model.md
@@ -0,0 +1,5 @@
+### `darkbloom --opencode` and `--hermes` wait for your model, and starts say when a tool points elsewhere
+
+- Before it writes a tool's config, the start waits while this Mac still loads the models it started with, so OpenCode and Hermes get the limits this Mac gives each model instead of the catalog's. A terminal shows one live line, ``⠙ Loading Gemma 4 26B before setting up OpenCode… 42s``; without one, a line as it starts and one as it ends. It waits at most 10 minutes. A model still loading then, or one that didn't load, sets nothing up, and one line names the next step (`darkbloom status`, then `darkbloom --opencode` again). Ctrl-C stops the wait: nothing is written, and the start says so, also when the model finishes loading just then. Darkbloom keeps serving either way. On one Mac only for now: a pair's local API isn't waited for.
+- A model that isn't loading as the tools are set up (one unloaded when idle, or one that loads on a request) is named in one line: run `darkbloom --opencode` again once `darkbloom status` shows it loaded. That holds too when a route that dials out lists the catalog's limits for it.
+- A start without `--opencode` or `--hermes` never changes a tool's config. When OpenCode or Hermes is set up for another address than this Mac's local API (another port or `--bind`), or reads another key file, one line says so: ``OpenCode points at http://127.0.0.1:8001/v1, not this Mac's local API (http://127.0.0.1:8002/v1): `darkbloom --opencode` points it there.`` `localhost`, `127.0.0.1` and `::1` are this Mac, in any case, and so is its `.local` name for an API on every address. On one Mac only for now: a paired Mac's start doesn't say it.
diff --git a/docs/architecture/tool-integrations.md b/docs/architecture/tool-integrations.md
index 182758ac6e..77c14022de 100644
--- a/docs/architecture/tool-integrations.md
+++ b/docs/architecture/tool-integrations.md
@@ -24,6 +24,9 @@ flowchart LR
L["local.json
(live port)"] --> E["IntegrationEndpoint.live
base URL + key file"]
K["local_token /
cluster_local_token"] --> E
E --> M["IntegrationModels.fetch
GET /v1/models"]
+ S["the API process's
daemon state"] --> X["ModelLoadWait
(one live line)"]
+ M --> X
+ X -->|"loaded: read again"| M
C["catalog
(names, limits)"] --> R["IntegrationModels.resolve"]
M --> R
R --> P{"planner"}
@@ -59,6 +62,25 @@ flowchart LR
(65,536 for a 262,144-token window whose catalog row says 32,768). A pair's leader lists the pair's own context and
output instead (what its mode serves; it refuses a larger `max_tokens`), so a GLM pair's output stays 65,536.
+ Before the models are resolved, `ModelLoadWait.run` waits while the local API's own process still loads a model
+ this Mac lists for its start: this Mac's `/v1/models` gives a model's own limits (its window, above) only once it
+ is loaded, and the router may fill the catalog's in until then (on one Mac its `input_modalities` are listed loaded
+ or not). `ModelLoads.reported` believes only the daemon state that process wrote (its pid is `local.json`'s):
+ `startupPreloadPendingModels` and `warmModels`; the coordinator-less server (Only me) writes none of them and loads
+ before it listens. Where that state can't tell (there is none, it is another process's or another schema's, or the
+ API is a pair's, whose process preloads nothing or writes no state), nothing is waited for, as before the wait;
+ only a state that keeps naming a model as pending holds the start, for at most the deadline. An answer naming
+ nothing loaded and nothing to load is asked again `settleSeconds` (1 s) later, for a provider whose API answered
+ before it said what it loads. Then the list is read again. The wait draws one `LiveLine` on a terminal (else a
+ start and an end line), takes SIGINT only while it runs (`InterruptWatch`) and ends after `defaultTimeout`
+ (600 s); a timeout, a model that didn't load, or Ctrl-C writes nothing (`ToolIntegrationStep.waitForModels`).
+ Ctrl-C is asked for right after each look, before "nothing loading" can end the wait, and once more as the wait
+ returns, before the list is read again. The wait's `.ready` carries what the process has loaded by its own word
+ (`warmModels`; none from Only me's server or without a state of its own), and the "run again" line names this
+ Mac's models it hasn't (`ToolIntegrationStep.notLoaded`); without that word, those `/v1/models` lists without a
+ context. The word counts because a route that dials out lists the catalog's limits for a model that isn't loaded.
+ The wait is single-Mac for now: a pair's API can't tell (above), and a pair start without a terminal waits for the
+ pair to serve instead (`ClusterPairCommands`).
3. **OpenCode.** `OpenCodeConfigPlan.plan` reads the file into byte ranges with `JSONCDocument` and replaces only the
`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"`
@@ -76,6 +98,15 @@ flowchart LR
them (so oMLX's `omlx launch hermes`, and Hermes up to v0.17), are part of that key.
5. **Write.** `ToolConfigWriter.apply` makes the planned edit (invariants below) and returns the file, the backup
and the exact undo command.
+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
+ another file holding the same key. `ToolAddress.notice` says in one line which tools miss it and names
+ `darkbloom --opencode` / `--hermes`; it never writes (`Start.noteToolsPointingElsewhere`). Addresses compare by
+ `ToolAddress.sameAddress`: scheme, host and port in any case (the scheme's own port when none is given) and the
+ path without one `/` at its end; `localhost`, `127.0.0.1` and `::1` are one host, and so is this Mac's Bonjour name
+ (`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.
## Invariants
@@ -112,6 +143,7 @@ flowchart LR
| The endpoint lists no chat models | `.refused` (kind `.models`) for both tools |
| A dangling symlink, a folder or a file over 4 MiB (`maximumFileBytes = 4 << 20`) | `.refused` (kind `.file`) |
| Another Darkbloom run holds the lock for `lockTimeout = 10` s | `ToolConfigWriterError` |
+| A model is still loading after `ModelLoadWait.defaultTimeout`, didn't load, or Ctrl-C stops the wait | Nothing is written; one line names the next step |
## Hermes versions and limits
@@ -131,6 +163,8 @@ flowchart LR
| OpenCode | `provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift`, `provider-swift/Sources/darkbloom/ToolIntegration/JSONCDocument.swift` |
| 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`) |
+| Where a tool points, after a start without a tool flag | `provider-swift/Sources/darkbloom/ToolIntegration/ToolAddress.swift` (`ToolAddress.notice`), `provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift` (`Start.noteToolsPointingElsewhere`) |
| Safe edits | `provider-swift/Sources/darkbloom/ToolIntegration/ToolConfigWriter.swift` (`ToolConfigWriter.apply`) |
| Tests | `provider-swift/Tests/DarkbloomCLITests/ToolIntegration/`, `scripts/integrations/opencode-smoke.sh` |
diff --git a/docs/developer/test.md b/docs/developer/test.md
index 096343a263..89d23b0587 100644
--- a/docs/developer/test.md
+++ b/docs/developer/test.md
@@ -989,7 +989,7 @@ config.
```bash
swift test --skip-build --no-parallel \
- --filter 'OpenCodeConfigPlanTests|HermesConfigPlanTests|HermesVersionTests|ToolConfigWriterTests|IntegrationModelsTests|ToolIntegrationTests|AtomicFileTests|keyFileIsTheFileHoldingThePortsKey'
+ --filter 'OpenCodeConfigPlanTests|HermesConfigPlanTests|HermesVersionTests|ToolConfigWriterTests|IntegrationModelsTests|ToolIntegrationTests|ModelLoadWaitTests|ToolAddressTests|AtomicFileTests|keyFileIsTheFileHoldingThePortsKey'
```
| Coverage | Suites |
@@ -998,6 +998,7 @@ swift test --skip-build --no-parallel \
| 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` |
| 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` |
+| 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
written config. It runs the writer through the opt-in `OpenCodeSmokeSetup`
diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md
index a1cd35258c..bd90a39823 100644
--- a/docs/provider/cli-reference.md
+++ b/docs/provider/cli-reference.md
@@ -449,15 +449,59 @@ They run once, at `start`:
No line or file holds the key, and no start screen shows it
(`Start.localServerBanner`). The `--local` banner's `Your requests:` line
and the tool block come from one Keychain read, of whether an account key
- is saved. A model of this Mac's that isn't loaded yet has no context in
- `/v1/models`, so one line says to run the start again once it is loaded, to
- pick up its limits.
+ is saved.
+4. **Before it writes, it waits for this Mac's models** (`ModelLoadWait`,
+ `provider-swift/Sources/darkbloom/ToolIntegration/ModelLoadWait.swift`):
+ while the local API's own process (its daemon state, by the pid in
+ `local.json`) still loads a model this Mac lists for its start
+ (`startupPreloadPendingModels`), `/v1/models` gives none of that model's own
+ limits. On a terminal one live line is drawn in place
+ (`⠙ Loading Gemma 4 26B before setting up OpenCode… 42s`); without one, a
+ line as it starts (`Waiting up to 10m for Gemma 4 26B to load before setting
+ up OpenCode.`) and one as it ends (`Gemma 4 26B loaded after 42s.`). Then
+ `/v1/models` is read again and the tools get the limits this Mac gives. A
+ provider that names nothing loaded and nothing to load is asked once more a
+ second later (it may not have said yet); Only me's server loads before it
+ listens, so it isn't waited for. Nothing is written, and the start exits 1,
+ when the model is still loading after `ModelLoadWait.defaultTimeout` (10
+ minutes; ``✗ Gemma 4 26B is still loading after 10m, so OpenCode wasn't set
+ up. Run `darkbloom --opencode` again once `darkbloom status` shows it
+ loaded.``), when it didn't load (``… didn't load, so OpenCode wasn't set up:
+ `darkbloom status` says why.``), or on Ctrl-C, which the wait alone takes
+ (``Stopped waiting for Gemma 4 26B to load, so OpenCode wasn't set up;
+ nothing was written. …``). It asks for Ctrl-C at every look before anything
+ else, and once more as it ends, so one pressed as the model finishes loading
+ writes nothing either (``Stopped before setting up OpenCode; nothing was
+ written. Run `darkbloom --opencode` again.``). A model that isn't loading
+ (unloaded when idle, or one that loads on a request) isn't waited for: it
+ gets the catalog's limits, and one line says to run `darkbloom --opencode`
+ again once `darkbloom status` shows it loaded. Which models those are, the
+ process says (its `warmModels`), also when a route that dials out lists the
+ catalog's limits for them; without its word, `/v1/models` does (a model it
+ lists without a context). Single-Mac only for now: a pair's local API (its
+ leader's part, a relay or `cluster local`) can't tell, so it isn't waited
+ for.
A tool it can't set up prints `✗` and why, writes nothing and ends with
`Darkbloom keeps serving.`; the start then exits 1 (a background start keeps
running; `--local` keeps serving in the terminal). They are not single-Mac
options: on a paired Mac they apply to the pair's local API.
+A start without `--opencode` or `--hermes` that serves a local API (Only me, or
+Both, me first) reads the tools' configs and changes none: when Darkbloom's
+provider in OpenCode's or Hermes' config points at another address than this
+start's local API, or reads another key file than `local_token` (one that
+doesn't hold the same key), one line says so and names the command
+(`ToolAddress`, `provider-swift/Sources/darkbloom/ToolIntegration/ToolAddress.swift`):
+``OpenCode points at http://127.0.0.1:8001/v1, not this Mac's local API
+(http://127.0.0.1:8002/v1): `darkbloom --opencode` points it there.`` Two
+addresses are the same with the same scheme, host and port in any case (the
+scheme's own port when none is given) and path (one `/` at its end aside);
+`localhost`, `127.0.0.1` and `::1` are one host, and so is this Mac's `.local`
+name for an API on every address (`ToolAddress.sameAddress`). Single-Mac only
+for now: a paired Mac's `start` starts the pair and says nothing about the
+tools.
+
On a Mac in a two-Mac cluster (one that holds a pairing; a cluster service left
without one is a leftover, which `darkbloom cluster status` names), `start` starts the pair, as `darkbloom cluster` does
(`Start.pairStart`, `ClusterPairCommands`), whatever its state: running, stopped with `darkbloom stop`, or not running
diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md
index f23ecb56c7..b28bacba06 100644
--- a/docs/provider/direct-mode.md
+++ b/docs/provider/direct-mode.md
@@ -185,7 +185,7 @@ See [inference and logprob admission](../architecture/inference.md).
| API key | `~/.darkbloom/local_token`, mode `0600`; `dk-local-` + base64url of 32 random bytes; created once, reused across restarts | `provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift` (`loadOrCreateToken`, `tokenPrefix`) |
| Discovery record | `~/.darkbloom/local.json`, mode `0600`: `base_url`, `api_key`, `host`, `port`, `pid`, `version`, `updated_at`; removed on graceful shutdown | `LocalEndpoint.Info`, `writeInfo`, `removeInfo` |
| Directory | `~/.darkbloom`; a dev build (`darkbloom-dev`) uses `~/.darkbloom-dev`. `DARKBLOOM_LOCAL_DIR` replaces it for both files | `LocalEndpoint.directory`, `BuildEnvironment.installDirectory` |
-| Key file for tools | A tool that reads the key from a file instead of keeping a copy (OpenCode's `{file:}`, Hermes' `key_cmd`) uses the file holding exactly the key of the server on that port: `local_token`, or `cluster_local_token` for a pair's API. Both files hold only the key and are replaced atomically, never partly written. See the [config writers](../architecture/tool-integrations.md) | `LocalEndpoint.keyFile(forPort:)`, `provider-swift/Sources/ProviderCore/Service/AtomicFile.swift` (`AtomicFile.write`) |
+| Key file for tools | A tool that reads the key from a file instead of keeping a copy (OpenCode's `{file:}`, Hermes' `key_cmd`) uses the file holding exactly the key of the server on that port: `local_token`, or `cluster_local_token` for a pair's API. Both files hold only the key and are replaced atomically, never partly written. A start without `--opencode` / `--hermes` says in one line when a tool set up for Darkbloom reads another file than `local_token` (or points at another address), and changes nothing. See the [config writers](../architecture/tool-integrations.md) | `LocalEndpoint.keyFile(forPort:)`, `LocalEndpoint.tokenPath()`, `provider-swift/Sources/ProviderCore/Service/AtomicFile.swift` (`AtomicFile.write`) |
| `--bind 0.0.0.0` | Advertised `base_url` uses `127.0.0.1`; other hosts use the machine's address, and `darkbloom local` prints its Bonjour URL on a `network:` line. [`darkbloom cluster local`](./two-mac-cluster.md#serving-locally-only) binds the cluster's API this way by default | `LocalEndpoint.Info.init`, `Local.networkURL` |
| `--no-auth` | No token check; `api_key` is empty in the discovery record. The [local router](#when-this-mac-cant-take-a-request-the-local-router) then passes nothing on and never uses the account key | `LocalInferenceHTTPConfig.authToken == nil`; `LocalRouterConfig.localKeyRequired` |
@@ -558,7 +558,7 @@ writes too (`StandaloneServer.startLifecycleControl`).
| `401 Unauthorized` | Send `Authorization: Bearer $(cat ~/.darkbloom/local_token)`; the token in `local.json` is authoritative |
| `413` on a chat request with images | Body above `localInferenceMaxUploadBytes`; downscale or send fewer images |
| `darkbloom local` says no server is running but a process is listening | The listener is not a Darkbloom server (foreign process on the port) or a stale `local.json` was cleaned; restart with a free port |
-| ``the local API isn't up: port 8001 is in use (`darkbloom start --port 8002`)`` (`status`, `local`) | Another program listens on this Mac's local API port. Free it and run `darkbloom restart`, or run the command it names: the new port is saved, and tools set up for the old one need `darkbloom --opencode` or `--hermes` again |
+| ``the local API isn't up: port 8001 is in use (`darkbloom start --port 8002`)`` (`status`, `local`) | Another program listens on this Mac's local API port. Free it and run `darkbloom restart`, or run the command it names: the new port is saved, and the start names each tool still set up for the old one: `darkbloom --opencode` or `--hermes` points it at the new one |
| Model not in `/v1/models` | Only models with an engine-v2 adapter are advertised; `darkbloom models list` |
| Endpoint unreachable from another machine | Default bind is loopback; `--bind 0.0.0.0` and open the port, then set a reverse proxy with TLS |
| A DevNet build (`darkbloom-dev`) fails a request for a model it hasn't loaded with ``The production Darkbloom on this Mac holds this Mac's GPU: … no model of this build loads here until production stops serving`` | The production app serves on this Mac, and two models don't fit one Mac's memory: a DevNet build refuses each cold load at its start, before any eviction, weight hash or reservation (`StandaloneServer.ensureModelLoaded`, `ClusterGPUHold.productionServesHere`). A model it loaded before production started keeps serving. Retry once production stops serving here; production's own build never refuses this way |
diff --git a/docs/provider/local-first.md b/docs/provider/local-first.md
index 8cc92dec77..86cbe4ad76 100644
--- a/docs/provider/local-first.md
+++ b/docs/provider/local-first.md
@@ -241,13 +241,19 @@ model.
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/`).
-- **Run it again** when your models change, or when the port or the key
- changes; with nothing new, it changes nothing. Run it again too once a model
- you just started is loaded: until then this Mac doesn't know its limits, the
- tools get the catalog's, and the start says so.
-
- Once a model is loaded, the tools get its whole context window from this
- Mac, and a quarter of it as their output limit (65,536 tokens for a
+- **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,
+ one line as it starts and one as it ends). So the tools get the limits this
+ Mac gives each model, not the catalog's. It waits at most 10 minutes: a model
+ still loading then, or one that doesn't load, sets nothing up, and the line
+ names the next step. Ctrl-C stops the wait; nothing is written, and the start
+ says so, also when the model finishes loading just then. Darkbloom keeps
+ serving either way. On one Mac only for now: a pair's local API isn't waited
+ for (a pair started without a terminal already waits up to 10 minutes for the
+ pair to serve).
+- **What the tools get:** once a model is loaded, its whole context window from
+ this Mac, and a quarter of it as their output limit (65,536 tokens for a
262,144-token window), not the catalog's smaller one. On a pair, they get
the pair's own limits, which it serves. For a model this Mac or its pair
serves, they get image input exactly when it serves images, whatever
@@ -256,6 +262,19 @@ model.
alone, gets none. Your other Macs' models get the catalog's. Which models
reason still comes from the catalog.
+- **Run it again** when your models change; with nothing new, it changes
+ nothing. A model that isn't loading as it runs (one unloaded when idle, or
+ one that loads on a request) gets the catalog's limits, and one line says to
+ run it again once `darkbloom status` shows it loaded.
+- **If the address or the key changes** (another port, another `--bind`, or
+ another key file), the next `darkbloom start` says so in one line and names
+ the command that points the tools there again:
+ ``OpenCode points at http://127.0.0.1:8001/v1, not this Mac's local API
+ (http://127.0.0.1:8002/v1): `darkbloom --opencode` points it there.`` A
+ start without `--opencode` or `--hermes` never changes a tool's file.
+ `localhost`, `127.0.0.1` and `::1` are all this Mac, and so is its `.local`
+ name when the API listens on every address. On one Mac only for now: a
+ paired Mac's start doesn't say it.
- **Offline** (Darkbloom's catalog unreachable), a run again keeps the names,
image support and limits already set up, but image input for a model served
here follows this Mac. A model set up for the first time then gets its ID,
diff --git a/docs/provider/quickstart.md b/docs/provider/quickstart.md
index 4314b23784..8ffa6fced2 100644
--- a/docs/provider/quickstart.md
+++ b/docs/provider/quickstart.md
@@ -12,6 +12,7 @@ exec $SHELL -l # or open a new Terminal window
darkbloom --opencode # or --hermes
How should this Mac serve? 1 Only me · 2 Darkbloom network · 3 Both, me first [3]
Enter → your models (downloads offered) → memory when idle → serves in the background
+ ⠙ Loading Gemma 4 26B before setting up OpenCode… 42s
✓ OpenCode can use Darkbloom
opencode # then /models → Darkbloom
```
@@ -19,7 +20,6 @@ opencode # then /models → Darkbloom
Two Macs: run `darkbloom cluster` on each, then `darkbloom --opencode` on
the leading Mac.
-
## Prerequisites
@@ -107,12 +107,13 @@ Mac and goes on
`provider.auto_restart = true` (the default) it also arms the crash-recovery
watchdog `io.darkbloom.watchdog`
(`provider-swift/Sources/ProviderCore/Service/WatchdogAgent.swift`).
-5. **OpenCode:** once this Mac's local API answers (it waits up to 30 seconds),
- it adds a `darkbloom` provider to OpenCode's config, keeps a backup and
- prints the one-line undo. A model that is still loading gets its limits
- from Darkbloom's catalog, and the start says to run it again once the model
- is loaded. OpenCode's config never holds your key: OpenCode reads it from
- Darkbloom's key file
+5. **OpenCode:** once this Mac's local API answers (it waits up to 30 seconds)
+ and the models it started with are loaded (one live line,
+ `⠙ Loading Gemma 4 26B before setting up OpenCode… 42s`, for up to 10
+ minutes; Ctrl-C stops it and writes nothing), it adds a `darkbloom` provider
+ to OpenCode's config with the limits this Mac gives each model, keeps a
+ backup and prints the one-line undo. OpenCode's config never holds your key:
+ OpenCode reads it from Darkbloom's key file
([Use it from OpenCode or Hermes](./local-first.md#use-it-from-opencode-or-hermes)).
With **Only me**, the background service runs `darkbloom start --foreground
@@ -138,7 +139,9 @@ client: `darkbloom local` prints the address, the key and a `curl` to try
then goes on as above.
- **Two Macs:** run `darkbloom cluster` on each Mac to pair them and choose
how the pair serves, then `darkbloom --opencode` on the leading Mac
- ([Two Macs as one provider](./two-mac-cluster.md)).
+ ([Two Macs as one provider](./two-mac-cluster.md)). The wait for your model
+ and the line when a tool points elsewhere are for one Mac for now: on a pair
+ that is still loading, run it again once the pair serves.
diff --git a/provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift b/provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift
index 5f59ebad7e..fd094c1df0 100644
--- a/provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift
+++ b/provider-swift/Sources/ProviderCore/Server/LocalEndpoint.swift
@@ -28,7 +28,8 @@ public enum LocalEndpoint {
return BuildEnvironment.current.installDirectory()
}
- static func tokenPath() -> URL { directory().appendingPathComponent("local_token") }
+ /// This Mac's own key file: every local API it serves alone takes its key, and tools set up for it read it.
+ public static func tokenPath() -> URL { directory().appendingPathComponent("local_token") }
static func infoPath() -> URL { directory().appendingPathComponent("local.json") }
// MARK: - Token
diff --git a/provider-swift/Sources/darkbloom/LocalCommand.swift b/provider-swift/Sources/darkbloom/LocalCommand.swift
index 14f73a1f45..829397aada 100644
--- a/provider-swift/Sources/darkbloom/LocalCommand.swift
+++ b/provider-swift/Sources/darkbloom/LocalCommand.swift
@@ -140,8 +140,12 @@ struct Local: AsyncParsableCommand {
/// For a server listening on every interface: this Mac's Bonjour (`.local`) URL, which other computers on the
/// same network can dial; nil for a loopback or specific-address server, or when the Mac has no local host name.
static func networkURL(host: String, port: UInt16) -> String? {
- guard host == "0.0.0.0" || host == "::",
- let name = SCDynamicStoreCopyLocalHostName(nil) as String?, !name.isEmpty else { return nil }
+ guard host == "0.0.0.0" || host == "::", let name = localHostName() else { return nil }
return "http://\(name).local:\(port)/v1"
}
+
+ /// This Mac's Bonjour host name, without `.local`; nil when it has none.
+ static func localHostName() -> String? {
+ (SCDynamicStoreCopyLocalHostName(nil) as String?).flatMap { $0.isEmpty ? nil : $0 }
+ }
}
diff --git a/provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift b/provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift
index 27db70bd8d..2dbac58510 100644
--- a/provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift
+++ b/provider-swift/Sources/darkbloom/Start/StartCommand+Tools.swift
@@ -4,7 +4,8 @@ import ProviderCore
// `darkbloom --opencode` / `--hermes`: start Darkbloom only if no local API runs, then point the tools at it
// (ToolIntegrationStep). They run once, at start: never in the launchd child, never per request. A start without a
-// tool flag reads nothing here. No line, and no tool file, holds a key.
+// tool flag never writes a tool's config: it only reads the tools' configs, to say when one points elsewhere
+// (ToolAddress). No line, and no tool file, holds a key.
extension Start {
/// Why `--opencode` / `--hermes` can't go with these flags; nil when they can.
var toolFlagsRefusal: String? {
@@ -81,9 +82,14 @@ extension Start {
}
/// Beside the coordinator-less server, once it is bound, on a task of its own: the server keeps serving whatever
- /// happens there.
- func setUpToolsBesideLocalServer(_ info: LocalEndpoint.Info, serving: StartServing, coordinatorURL: String) {
- guard !requestedTools.isEmpty else { return }
+ /// happens there. Without a tool flag, it says when a tool points elsewhere (`noteTools`, by default
+ /// `noteToolsPointingElsewhere`), except in a service's child (`foreground`), whose lines go to a log.
+ func setUpToolsBesideLocalServer(_ info: LocalEndpoint.Info, serving: StartServing, coordinatorURL: String,
+ noteTools: ((StartServing) -> Void)? = nil) {
+ guard !requestedTools.isEmpty else {
+ if !foreground { (noteTools ?? { noteToolsPointingElsewhere($0) })(serving) }
+ return
+ }
guard let endpoint = IntegrationEndpoint.live(info) else {
print("✗ \(ToolIntegrationStep.names(requestedTools)) couldn't be set up: no key file holds this server's "
+ "key. \(ToolIntegrationStep.keepsServing)")
@@ -95,14 +101,19 @@ extension Start {
/// After the background provider started: once its local API is bound, which `local.json` says, waiting at most
/// `waitSeconds` (Only me listens only once its models are loaded, so it waits longer). A step that fails ends the
- /// start with exit 1; the provider keeps serving.
+ /// start with exit 1; the provider keeps serving. Without a tool flag, it says when a tool points elsewhere
+ /// (`noteTools`, by default `noteToolsPointingElsewhere`).
func setUpToolsBesideDaemon(serving: StartServing, coordinatorURL: String,
waitSeconds: Int = Start.toolWaitSeconds,
waitForAPI: (_ port: UInt16, _ seconds: Int) async -> LocalAPIWait = {
await Start.waitForLocalAPI(port: $0, seconds: $1)
},
- step: ToolIntegrationStep? = nil) async throws {
- guard !requestedTools.isEmpty else { return }
+ step: ToolIntegrationStep? = nil,
+ noteTools: ((StartServing) -> Void)? = nil) async throws {
+ guard !requestedTools.isEmpty else {
+ (noteTools ?? { noteToolsPointingElsewhere($0) })(serving)
+ return
+ }
let endpoint: IntegrationEndpoint
switch await waitForAPI(serving.port, waitSeconds) {
case .ready(let found):
@@ -121,6 +132,24 @@ extension Start {
coordinatorURL: coordinatorURL, step: step) else { throw ExitCode.failure }
}
+ /// A start without `--opencode` / `--hermes` that serves a local API never changes a tool's config: when a tool set
+ /// up for Darkbloom points elsewhere (another port or address, or another key file), one line says so and names
+ /// the command that points it here (`ToolAddress`). With a tool flag, nothing: that start points the tools here
+ /// itself. `keyFile`: the one this Mac's local API takes; `localHostName`: this Mac's Bonjour name.
+ func noteToolsPointingElsewhere(_ serving: StartServing, environment: ToolIntegrationEnvironment = .current,
+ provider: IntegrationProvider = .current, keyFile: URL = LocalEndpoint.tokenPath(),
+ localHostName: () -> String? = { Local.localHostName() },
+ say: (String) -> Void = { print($0) }) {
+ guard requestedTools.isEmpty, serving.hasLocalAPI,
+ let line = ToolAddress.notice(
+ baseURL: serving.baseURL, keyFile: serving.noAuth ? nil : keyFile, environment: environment,
+ provider: provider,
+ thisMac: ToolAddress.thisMacsNames(listeningOn: serving.bind, localHostName: localHostName))
+ else { return }
+ say("")
+ say(line)
+ }
+
/// For a local API this start didn't resolve (one already running, or the pair's): where your requests go comes
/// from the saved `[local] route`, and the catalog from `--coordinator-url`, else the config's, else the build's.
/// Reads the config once, without detecting hardware.
diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift b/provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift
index 8f9e0ace3f..f2b98a8538 100644
--- a/provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift
+++ b/provider-swift/Sources/darkbloom/ToolIntegration/HermesConfigPlan.swift
@@ -62,6 +62,12 @@ enum HermesConfigPlan {
}
}
+ /// Where the provider's block in a config's `bytes` points: its `api`, and the file its `key_cmd` reads
+ /// (`/bin/cat `, as `plan` writes it); nil when the file has no such block or can't be read.
+ static func pointer(in bytes: Data, provider: IntegrationProvider) -> ToolPointer? {
+ (try? HermesEdit(text: String(decoding: bytes, as: UTF8.self), provider: provider))?.pointer()
+ }
+
private static func floorReason(_ models: [IntegrationModel]) -> String {
guard let largest = models.compactMap(\.contextLength).max() else {
return """
@@ -229,7 +235,6 @@ private struct HermesEdit {
indent: String, endpoint: IntegrationEndpoint, models: [IntegrationModel], main: String
) -> [String] {
let (one, two, three) = (indent + unit, indent + unit + unit, indent + unit + unit + unit)
- let keyCommand = "/bin/cat " + ToolIntegration.shellQuoted(endpoint.keyFile.path, onlyIfNeeded: true)
// Hermes sends no output cap to a custom endpoint, and Darkbloom's default is 4096 tokens; the cap must suit
// every model Hermes can switch to on this provider.
let maxTokens = models.map { $0.outputLimit ?? min(IntegrationModels.defaultOutputCap, ($0.contextLength ?? 0) / 4) }
@@ -239,7 +244,7 @@ private struct HermesEdit {
one + "name: " + Self.quoted(provider.name),
one + "api: " + Self.quoted(endpoint.baseURL),
one + "transport: " + Self.quoted("chat_completions"),
- one + "key_cmd: " + Self.quoted(keyCommand),
+ one + "key_cmd: " + Self.quoted(Self.keyCommand(reading: endpoint.keyFile)),
one + "default_model: " + Self.quoted(main),
one + "extra_body:",
two + "max_tokens: \(maxTokens)",
@@ -256,14 +261,9 @@ private struct HermesEdit {
/// What Darkbloom's provider block says of each model now, by model ID: its context and vision, with the block's
/// output cap. A block it can't read holds nothing.
func modelEntries() -> [String: IntegrationModel.Entry] {
- guard let providers, providers.value.isEmpty,
- let mine = (try? children(of: providers))?.first(where: { $0.key == provider.id }),
- let fields = try? children(of: mine) else { return [:] }
- func value(_ key: String, in entries: [YAMLEntry]) -> String? {
- entries.first { $0.key == key }.flatMap { Self.scalar($0.value) }
- }
+ guard let fields = providerFields() else { return [:] }
let cap = fields.first { $0.key == "extra_body" }.flatMap { try? children(of: $0) }
- .flatMap { value("max_tokens", in: $0) }.flatMap { Int($0) }
+ .flatMap { Self.value("max_tokens", in: $0) }.flatMap { Int($0) }
guard let models = fields.first(where: { $0.key == "models" }), let listed = try? children(of: models) else {
return [:]
}
@@ -271,12 +271,52 @@ private struct HermesEdit {
for model in listed {
let values = (try? children(of: model)) ?? []
entries[model.key] = IntegrationModel.Entry(
- contextLength: value("context_length", in: values).flatMap { Int($0) }, outputLimit: cap,
- imageInput: value("supports_vision", in: values)?.lowercased() == "true")
+ contextLength: Self.value("context_length", in: values).flatMap { Int($0) }, outputLimit: cap,
+ imageInput: Self.value("supports_vision", in: values)?.lowercased() == "true")
}
return entries
}
+ /// Where Darkbloom's provider block points (`HermesConfigPlan.pointer`); nil without one it can read.
+ func pointer() -> ToolPointer? {
+ guard let fields = providerFields() else { return nil }
+ return ToolPointer(baseURL: Self.value("api", in: fields),
+ keyFile: Self.value("key_cmd", in: fields).flatMap(Self.keyFile(readBy:)))
+ }
+
+ /// The fields of Darkbloom's provider block; nil without one it can read.
+ private func providerFields() -> [YAMLEntry]? {
+ guard let providers, providers.value.isEmpty,
+ let mine = (try? children(of: providers))?.first(where: { $0.key == provider.id }) else { return nil }
+ return try? children(of: mine)
+ }
+
+ /// `key`'s scalar value among `entries`.
+ private static func value(_ key: String, in entries: [YAMLEntry]) -> String? {
+ entries.first { $0.key == key }.flatMap { scalar($0.value) }
+ }
+
+ // MARK: - The key command
+
+ /// The `key_cmd` Hermes runs for Darkbloom's key: `/bin/cat` and the key file's path as one shell word.
+ static func keyCommand(reading keyFile: URL) -> String {
+ keyReader + ToolIntegration.shellQuoted(keyFile.path, onlyIfNeeded: true)
+ }
+
+ /// The key file a `keyCommand` reads; nil for any other command, or a path that isn't absolute.
+ static func keyFile(readBy command: String) -> URL? {
+ guard command.hasPrefix(keyReader) else { return nil }
+ var path = String(command.dropFirst(keyReader.count))
+ // `ToolIntegration.shellQuoted`'s single quotes, each quote inside as '\''.
+ if path.hasPrefix("'") {
+ guard path.count >= 2, path.hasSuffix("'") else { return nil }
+ path = String(path.dropFirst().dropLast()).replacingOccurrences(of: "'\\''", with: "'")
+ }
+ return path.hasPrefix("/") ? URL(fileURLWithPath: path) : nil
+ }
+
+ private static let keyReader = "/bin/cat "
+
// MARK: - Result
/// Comments of the original that `text` no longer holds: those on the lines the edit replaced or removed.
diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift b/provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift
index fb632483fb..8b17ef1cdc 100644
--- a/provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift
+++ b/provider-swift/Sources/darkbloom/ToolIntegration/IntegrationModels.swift
@@ -270,4 +270,9 @@ enum IntegrationModels {
private static func positive(_ value: Int?) -> Int? {
value.flatMap { $0 > 0 ? $0 : nil }
}
+
+ /// An endpoint ID's name in the catalog (an alias's, else its build's), else the ID: `Gemma 4 26B`.
+ static func displayName(of id: String, in catalog: CatalogSnapshot?) -> String {
+ catalogDetails(id, in: catalog).name.flatMap { $0.isEmpty ? nil : $0 } ?? id
+ }
}
diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/ModelLoadWait.swift b/provider-swift/Sources/darkbloom/ToolIntegration/ModelLoadWait.swift
new file mode 100644
index 0000000000..8bd52e07d7
--- /dev/null
+++ b/provider-swift/Sources/darkbloom/ToolIntegration/ModelLoadWait.swift
@@ -0,0 +1,264 @@
+import Darwin
+import Foundation
+import ProviderCore
+
+/// What the local API's own process says about loading the models it serves: its daemon state (`DaemonStateFile`),
+/// read only when that process wrote it (its pid is the one in `local.json`).
+///
+/// When it can't tell, nothing is waited for and the tools are set up as before this wait: there is no state, it is
+/// another process's, this build can't read it (another schema), or an older provider's lacks the pending list. A
+/// pair's API can't tell either: its process preloads nothing (the pair's own processes load its model) or writes no
+/// state. Only a state that keeps naming a model as pending holds the start, and then for at most the wait's deadline,
+/// even when its process has stopped writing it.
+struct ModelLoads: Equatable, Sendable {
+ /// Loaded now (`DaemonState.warmModels`).
+ var loaded: Set = []
+ /// Its start's models still to load, the first loading now (`DaemonState.startupPreloadPendingModels`). A model
+ /// stays in the list until a later one starts or the preload ends, so through its warm-up too.
+ var pending: [String] = []
+ /// The coordinator-less server (Only me) loads its models before its API listens, and its state names none.
+ var loadsBeforeListening = false
+
+ /// What `state` says, when the process serving the local API (`apiPID`) wrote it; nil otherwise.
+ static func reported(by state: DaemonState?, apiPID: Int32?) -> ModelLoads? {
+ guard let state, let apiPID, state.pid == apiPID else { return nil }
+ if state.servesOnlyItsOwner { return ModelLoads(loadsBeforeListening: true) }
+ return ModelLoads(loaded: Set(state.warmModels), pending: state.startupPreloadPendingModels ?? [])
+ }
+
+ /// What this Mac's running local API's process says now.
+ static func live() -> ModelLoads? {
+ reported(by: DaemonStateFile.read(), apiPID: LocalEndpoint.readLiveInfo()?.pid)
+ }
+
+ /// Those of `thisMac` that its start still loads: pending and not loaded yet.
+ func loading(among thisMac: [String]) -> [String] {
+ pending.filter { thisMac.contains($0) && !loaded.contains($0) }
+ }
+}
+
+/// Ctrl-C while the start waits for a model (`ModelLoadWait`). Between `begin` and `end` the signal only presses this
+/// watch; before and after, it does what it did. `begin` and `end` run on the wait's own task; the signal's handler
+/// only presses.
+final class InterruptWatch: @unchecked Sendable {
+ private let lock = NSLock()
+ private let signalNumber: Int32?
+ private var pressed = false
+ private var source: DispatchSourceSignal?
+ private var previous = sigaction()
+
+ /// `signal` nil: only `press` presses it (tests).
+ init(signal: Int32? = nil) {
+ signalNumber = signal
+ }
+
+ /// The live watch, on SIGINT.
+ static func ctrlC() -> InterruptWatch { InterruptWatch(signal: SIGINT) }
+
+ var wasPressed: Bool { lock.withLock { pressed } }
+
+ func press() { lock.withLock { pressed = true } }
+
+ func begin() {
+ guard let signalNumber, source == nil else { return }
+ // The source first: a signal before it is set up still does what it did, and none after it is lost.
+ let source = DispatchSource.makeSignalSource(signal: signalNumber, queue: .global(qos: .userInitiated))
+ source.setEventHandler { [weak self] in self?.press() }
+ source.resume()
+ self.source = source
+ sigaction(signalNumber, nil, &previous)
+ signal(signalNumber, SIG_IGN)
+ }
+
+ func end() {
+ guard let signalNumber, let source else { return }
+ source.cancel()
+ self.source = nil
+ sigaction(signalNumber, &previous, nil)
+ }
+}
+
+/// The wait's one line on a terminal: drawn again in place (a carriage return, the line, erase to its end), never
+/// wider than the window, and erased when the wait ends.
+struct LiveLine {
+ var write: (String) -> Void
+ var columns: () -> Int = { 80 }
+
+ func show(_ text: String) {
+ let width = max(10, columns() - 1)
+ write("\r\u{1B}[2K" + (text.count <= width ? text : String(text.prefix(width - 1)) + "…"))
+ }
+
+ func erase() { write("\r\u{1B}[2K") }
+
+ /// Standard output, when it is a terminal that can draw a line again (not `TERM=dumb`); nil without one (a pipe or
+ /// a log), where nothing is drawn in place.
+ static func standardOutput(isTerminal: Bool = isatty(STDOUT_FILENO) != 0,
+ environment: [String: String] = ProcessInfo.processInfo.environment) -> LiveLine? {
+ guard isTerminal, environment["TERM"] != "dumb" else { return nil }
+ return LiveLine(write: DarkbloomCommandLook.writeToStandardOutput,
+ columns: { DarkbloomCommandLook.standardOutputColumns(fallback: 80) })
+ }
+}
+
+/// Before `darkbloom --opencode` / `--hermes` write a tool's config, they wait while the local API's process still loads
+/// this Mac's models at its start: until a model is loaded, this Mac's `/v1/models` gives none of its own limits, and
+/// the tools would get the catalog's. That list can't say which models are loading: it lists a model being loaded just
+/// as one that isn't loaded, and its router can fill in the catalog's limits for both. So the wait asks the process
+/// itself (`ModelLoads`). One live line on a terminal, else one line as it starts and one as it ends; at most
+/// `timeout`; Ctrl-C ends it. A model that isn't loading (one that unloads when idle, or loads on a request) isn't
+/// waited for.
+struct ModelLoadWait {
+ enum Outcome: Equatable, Sendable {
+ /// Nothing of this Mac's is loading now: set the tools up. `waited`: it waited for models that have loaded
+ /// since this Mac's list was read, so the list is read again for their limits. `loaded`: the models the
+ /// process has loaded, by its own word; nil when it gave none (no state of its own, or Only me's server, whose
+ /// state names none).
+ case ready(waited: Bool, loaded: Set? = nil)
+ /// The model it waited for didn't load.
+ case notLoaded(model: String)
+ /// The model is still loading at the deadline.
+ case timedOut(model: String)
+ /// Ctrl-C while it waited for the model.
+ case interrupted(model: String)
+ }
+
+ /// What the local API's process says, at each look.
+ var loads: () -> ModelLoads?
+ var timeout: TimeInterval = ModelLoadWait.defaultTimeout
+ /// Seconds on a monotonic clock.
+ var clock: () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }
+ /// Between two looks; the spinner turns once per look.
+ var pause: () async -> Void = { try? await Task.sleep(for: .milliseconds(250)) }
+ var interrupt = InterruptWatch()
+ /// Nil without a terminal: then nothing is drawn in place, and the wait says one line as it starts instead.
+ var liveLine: LiveLine?
+
+ /// The longest wait. A model's load takes from seconds to a few minutes; past this, something else is wrong.
+ static let defaultTimeout: TimeInterval = 600
+ /// Right after its local API answers, a provider may not have said yet what it loads: an answer that names nothing
+ /// loaded and nothing to load is asked once more, this long after.
+ static let settleSeconds: TimeInterval = 1
+ static let spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
+
+ /// As `start` waits: the local API's own process, the terminal's live line (`LiveLine.standardOutput`'s rule for
+ /// `isTerminal` and `environment`), and Ctrl-C.
+ static func live(isTerminal: Bool = isatty(STDOUT_FILENO) != 0,
+ environment: [String: String] = ProcessInfo.processInfo.environment) -> ModelLoadWait {
+ ModelLoadWait(loads: { ModelLoads.live() }, interrupt: .ctrlC(),
+ liveLine: .standardOutput(isTerminal: isTerminal, environment: environment))
+ }
+
+ /// Waits while the local API's process loads any of `thisMac` (this Mac's models as its `/v1/models` lists them)
+ /// for its start. `name` gives a model's name for the lines, `say` prints a whole line.
+ func run(thisMac: [String], tools: [IntegrationTool], name: (String) -> String,
+ say: (String) -> Void) async -> Outcome {
+ guard !thisMac.isEmpty else { return .ready(waited: false) }
+ interrupt.begin()
+ defer { interrupt.end() }
+ let start = clock()
+ var awaited: [String] = []
+ var emptySince: TimeInterval?
+ var frame = 0
+ while true {
+ let now = clock()
+ let report = loads()
+ let loading = report?.loading(among: thisMac) ?? []
+ let model = loading.first ?? awaited.first ?? thisMac[0]
+ // Ctrl-C first, whatever this look says: one pressed since the last look stops the wait even when the model
+ // has loaded since, so nothing is written.
+ if interrupt.wasPressed { return erasingLiveLine(.interrupted(model: model)) }
+ if loading.isEmpty {
+ // Nothing is loading. That stands at once after models this wait saw loading, or when the process
+ // names a model loaded or loads before it listens. Any other answer, or none, may come before the
+ // process has said what it loads: it stands once nothing has been loading for `settleSeconds`.
+ let settled = !awaited.isEmpty || report.map { $0.loadsBeforeListening || !$0.loaded.isEmpty } == true
+ if settled || emptySince.map({ now - $0 >= Self.settleSeconds }) == true {
+ return nothingLoading(awaited: awaited, report: report, elapsed: now - start, name: name, say: say)
+ }
+ if emptySince == nil { emptySince = now }
+ }
+ if !loading.isEmpty {
+ if now - start >= timeout { return erasingLiveLine(.timedOut(model: model)) }
+ if awaited.isEmpty, liveLine == nil { say(Self.startLine(name(model), tools: tools, timeout: timeout)) }
+ for id in loading where !awaited.contains(id) { awaited.append(id) }
+ emptySince = nil
+ liveLine?.show("\(Self.spinner[frame % Self.spinner.count]) "
+ + Self.loadingLine(name(model), tools: tools, elapsed: now - start))
+ frame += 1
+ }
+ await pause()
+ }
+ }
+
+ /// The wait ended with nothing loading, as the process's last `report` says: the models it waited for that loaded,
+ /// or the first that didn't (its process may have ended).
+ private func nothingLoading(awaited: [String], report: ModelLoads?, elapsed: TimeInterval,
+ name: (String) -> String, say: (String) -> Void) -> Outcome {
+ let loaded = report.flatMap { $0.loadsBeforeListening ? nil : $0.loaded }
+ guard !awaited.isEmpty else { return .ready(waited: false, loaded: loaded) }
+ let done = awaited.filter { loaded?.contains($0) == true }
+ guard !done.isEmpty else { return erasingLiveLine(.notLoaded(model: awaited[0])) }
+ liveLine?.erase()
+ say(Self.loadedLine(done.map(name), elapsed: elapsed))
+ return .ready(waited: true, loaded: loaded)
+ }
+
+ private func erasingLiveLine(_ outcome: Outcome) -> Outcome {
+ liveLine?.erase()
+ return outcome
+ }
+
+ // MARK: - Words
+
+ /// The live line, after its spinner: `Loading Gemma 4 26B before setting up OpenCode… 42s`.
+ static func loadingLine(_ model: String, tools: [IntegrationTool], elapsed: TimeInterval) -> String {
+ "Loading \(model) before setting up \(ToolIntegrationStep.names(tools))… \(duration(elapsed))"
+ }
+
+ /// Without a terminal, as the wait starts.
+ static func startLine(_ model: String, tools: [IntegrationTool], timeout: TimeInterval) -> String {
+ "Waiting up to \(DurationFormatting.compact(timeout)) for \(model) to load before setting up "
+ + "\(ToolIntegrationStep.names(tools))."
+ }
+
+ /// The models it waited for are loaded.
+ static func loadedLine(_ models: [String], elapsed: TimeInterval) -> String {
+ "\(list(models)) loaded after \(duration(elapsed))."
+ }
+
+ /// The model was still loading at the deadline; nothing was written.
+ static func stillLoading(_ model: String, tools: [IntegrationTool], after seconds: TimeInterval) -> String {
+ "✗ \(model) is still loading after \(DurationFormatting.compact(seconds)), so "
+ + "\(ToolIntegrationStep.notSetUp(tools)). Run `\(ToolIntegrationStep.command(tools))` again once "
+ + "`\(ToolIntegrationStep.cli) status` shows it loaded."
+ }
+
+ /// The model it waited for didn't load; nothing was written.
+ static func didNotLoad(_ model: String, tools: [IntegrationTool]) -> String {
+ "✗ \(model) didn't load, so \(ToolIntegrationStep.notSetUp(tools)): `\(ToolIntegrationStep.cli) status` says why."
+ }
+
+ /// Ctrl-C while it waited; nothing was written.
+ static func stopped(_ model: String, tools: [IntegrationTool]) -> String {
+ "Stopped waiting for \(model) to load, so \(ToolIntegrationStep.notSetUp(tools)); nothing was written. Run "
+ + "`\(ToolIntegrationStep.command(tools))` again once `\(ToolIntegrationStep.cli) status` shows it loaded."
+ }
+
+ /// Ctrl-C as the wait ended, after its last look; nothing was written.
+ static func stoppedBeforeWriting(_ tools: [IntegrationTool]) -> String {
+ "Stopped before setting up \(ToolIntegrationStep.names(tools)); nothing was written. Run "
+ + "`\(ToolIntegrationStep.command(tools))` again."
+ }
+
+ /// `42s`, `1m 12s`, `10m 0s`.
+ static func duration(_ seconds: TimeInterval) -> String {
+ DurationFormatting.compact(seconds, secondsInMinuteRange: true, elideZeroMinutesInHourRange: false)
+ }
+
+ /// `A`, `A and B`, `A, B and C`.
+ static func list(_ names: [String]) -> String {
+ names.count <= 2 ? names.joined(separator: " and ")
+ : names.dropLast().joined(separator: ", ") + " and " + names[names.count - 1]
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift b/provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift
index ad2804a207..7e61b8241f 100644
--- a/provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift
+++ b/provider-swift/Sources/darkbloom/ToolIntegration/OpenCodeConfigPlan.swift
@@ -136,6 +136,30 @@ enum OpenCodeConfigPlan {
"{file:\(ToolIntegration.displayPath(keyFile, home: home))}"
}
+ /// The key file a `keyReference` names; nil for a key given another way (`{env:…}`, the key itself), or a path
+ /// that isn't absolute or under `~`.
+ static func keyFile(inReference reference: String, home: URL) -> URL? {
+ guard reference.hasPrefix("{file:"), reference.hasSuffix("}") else { return nil }
+ let path = String(reference.dropFirst("{file:".count).dropLast())
+ if path == "~" || path.hasPrefix("~/") { return home.appendingPathComponent(String(path.dropFirst(2))) }
+ return path.hasPrefix("/") ? URL(fileURLWithPath: path) : nil
+ }
+
+ /// Where the provider's block in a config's `bytes` points: its `settings.baseURL`, and the file its `apiKey`
+ /// reads (`keyFile(inReference:home:)`); nil when the file has no such block or isn't JSONC.
+ static func pointer(in bytes: Data, provider: IntegrationProvider, home: URL) -> ToolPointer? {
+ guard let document = try? JSONCDocument([UInt8](bytes)), let root = document.root.object,
+ let block = root.members(named: "providers").first?.value.object?.members(named: provider.id).first?
+ .value.object else { return nil }
+ let settings = block.members(named: "settings").first?.value.object
+ func string(_ key: String) -> String? {
+ guard let value = settings?.members(named: key).first?.value else { return nil }
+ return try? JSONDecoder().decode(String.self, from: Data(document.bytes[value.start.. ToolPointer? {
+ guard let bytes = try? Data(contentsOf: tool.configFile(in: environment), options: .mappedIfSafe),
+ bytes.count <= ToolConfigWriter.maximumFileBytes else { return nil }
+ switch tool {
+ case .opencode: return OpenCodeConfigPlan.pointer(in: bytes, provider: provider, home: environment.home)
+ case .hermes: return HermesConfigPlan.pointer(in: bytes, provider: provider)
+ }
+ }
+
+ /// The names loopback answers to, as every local API on this Mac does.
+ static let loopbackNames: Set = ["localhost", "127.0.0.1", "::1"]
+
+ /// The names a tool on this Mac reaches its local API listening on `bind` by: loopback's, and this Mac's Bonjour
+ /// name (`localHostName`, with `.local`) when it listens on every address, as `darkbloom local` prints it then.
+ static func thisMacsNames(listeningOn bind: String, localHostName: () -> String?) -> Set {
+ guard bind == "0.0.0.0" || bind == "::", let name = localHostName() else { return loopbackNames }
+ return loopbackNames.union(["\(name.lowercased()).local"])
+ }
+
+ /// Whether two base URLs reach the same local API: the same scheme, port (the scheme's own when none is given) and
+ /// path (one `/` at its end aside), and the same host in any case, `thisMac`'s names counting as one.
+ static func sameAddress(_ one: String, _ other: String, thisMac: Set = loopbackNames) -> Bool {
+ guard let first = URLComponents(string: one), let second = URLComponents(string: other),
+ first.host != nil, second.host != nil else { return trimmed(one) == trimmed(other) }
+ func scheme(_ url: URLComponents) -> String? { url.scheme?.lowercased() }
+ func host(_ url: URLComponents) -> String {
+ let name = (url.host ?? "").lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
+ return thisMac.contains(name) ? "this Mac" : name
+ }
+ func port(_ url: URLComponents) -> Int? {
+ url.port ?? ["http": 80, "https": 443][scheme(url) ?? ""]
+ }
+ return scheme(first) == scheme(second) && host(first) == host(second) && port(first) == port(second)
+ && trimmed(first.path) == trimmed(second.path)
+ }
+
+ /// The tools set up for Darkbloom whose provider block misses the local API at `baseURL` that takes the key in
+ /// `keyFile` (nil: the API takes no key, so any file does), and how. `thisMac`: the names it answers to.
+ static func misses(baseURL: String, keyFile: URL?, environment: ToolIntegrationEnvironment,
+ provider: IntegrationProvider,
+ thisMac: Set = loopbackNames) -> [(tool: IntegrationTool, miss: Miss)] {
+ IntegrationTool.allCases.compactMap { tool in
+ guard let pointer = pointer(of: tool, environment: environment, provider: provider) else { return nil }
+ if let url = pointer.baseURL, !sameAddress(url, baseURL, thisMac: thisMac) { return (tool, .address(url)) }
+ if let keyFile, let theirs = pointer.keyFile, !sameKey(theirs, keyFile) {
+ return (tool, .key(theirs.standardizedFileURL.path))
+ }
+ return nil
+ }
+ }
+
+ /// The one line for `misses`, or nil when there are none: what the tools point at, and the command that points
+ /// them at the local API again.
+ static func notice(_ misses: [(tool: IntegrationTool, miss: Miss)], baseURL: String, keyFile: URL?,
+ home: URL) -> String? {
+ guard let first = misses.first?.miss else { return nil }
+ let tools = misses.map(\.tool)
+ let one = tools.count == 1
+ let names = ToolIntegrationStep.names(tools)
+ let fix = "`\(ToolIntegrationStep.command(tools))` points \(one ? "it" : "them") there."
+ // Tools that miss it in different ways share one line that names no address or file.
+ guard misses.allSatisfy({ $0.miss == first }) else {
+ return "\(names) \(one ? "doesn't" : "don't") point at this Mac's local API (\(baseURL)): \(fix)"
+ }
+ switch first {
+ case .address(let url):
+ return "\(names) \(one ? "points" : "point") at \(url), not this Mac's local API (\(baseURL)): \(fix)"
+ case .key(let path):
+ let theirs = ToolIntegration.displayPath(URL(fileURLWithPath: path), home: home)
+ let ours = keyFile.map { " (\(ToolIntegration.displayPath($0, home: home)))" } ?? ""
+ return "\(names) \(one ? "reads" : "read") the key in \(theirs), not the one this Mac's local API "
+ + "takes\(ours): \(fix)"
+ }
+ }
+
+ /// The line for a start that serves its local API at `baseURL`, with the key in `keyFile` (nil: no key).
+ /// `thisMac`: the names the API answers to.
+ static func notice(baseURL: String, keyFile: URL?, environment: ToolIntegrationEnvironment = .current,
+ provider: IntegrationProvider = .current, thisMac: Set = loopbackNames) -> String? {
+ notice(misses(baseURL: baseURL, keyFile: keyFile, environment: environment, provider: provider,
+ thisMac: thisMac),
+ baseURL: baseURL, keyFile: keyFile, home: environment.home)
+ }
+
+ private static func trimmed(_ url: String) -> String { url.hasSuffix("/") ? String(url.dropLast()) : url }
+
+ /// The same file, or two files that hold the same key.
+ private static func sameKey(_ one: URL, _ other: URL) -> Bool {
+ if one.standardizedFileURL.path == other.standardizedFileURL.path { return true }
+ func key(_ file: URL) -> String? {
+ (try? String(contentsOf: file, encoding: .utf8))?.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+ guard let ours = key(other), !ours.isEmpty else { return false }
+ return key(one) == ours
+ }
+}
diff --git a/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift b/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift
index 2276c41148..8029158e17 100644
--- a/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift
+++ b/provider-swift/Sources/darkbloom/ToolIntegration/ToolIntegrationStep.swift
@@ -74,8 +74,9 @@ enum ToolLocator {
}
/// `darkbloom --opencode` / `--hermes`: once, at start, points each tool at this Mac's live local API, with a
-/// backup and a one-line undo. It never prints or writes a key, and a tool it can't set up never stops Darkbloom
-/// serving.
+/// backup and a one-line undo. It first waits while the API's process still loads this Mac's models (`ModelLoadWait`),
+/// so the tools get each model's own limits. It never prints or writes a key, and a tool it can't set up never stops
+/// Darkbloom serving.
struct ToolIntegrationStep {
var tools: [IntegrationTool]
var environment: ToolIntegrationEnvironment = .current
@@ -87,13 +88,16 @@ struct ToolIntegrationStep {
var say: (String) -> Void
/// ` --version`'s first line; nil when it doesn't answer.
var versionOutput: (IntegrationTool, URL) -> String? = { _, _ in nil }
+ /// The wait, before anything is written, while the local API's process still loads this Mac's models; nil: none.
+ var modelLoadWait: ModelLoadWait?
/// How long the step waits for the local API's `/v1/models`. That list waits for the coordinator's up to the
/// router's own deadline (`LocalRouter.Timing.list`), so with an unreachable coordinator it answers late: the step
/// gives it well over that, once, at start.
static let modelListTimeout: TimeInterval = 15
- /// The step as `start` runs it: the tools found on this Mac, the endpoint's models and the coordinator's catalog.
+ /// The step as `start` runs it: the tools found on this Mac, the endpoint's models, the coordinator's catalog, and
+ /// the wait for this Mac's models to load.
static func live(tools: [IntegrationTool], coordinatorURL: String) -> ToolIntegrationStep {
let environment = ToolIntegrationEnvironment.current
return ToolIntegrationStep(
@@ -109,7 +113,8 @@ struct ToolIntegrationStep {
return try? await client.fetchCatalogSnapshot(includeAliases: true)
},
say: { print($0) },
- versionOutput: { _, executable in ToolLocator.version(of: executable) })
+ versionOutput: { _, executable in ToolLocator.version(of: executable) },
+ modelLoadWait: .live())
}
/// Sets each tool up for `endpoint`. `requests` says where the owner's requests go, in the start screen's words.
@@ -140,15 +145,16 @@ struct ToolIntegrationStep {
private func configure(_ ready: [(tool: IntegrationTool, executable: URL)], endpoint: IntegrationEndpoint,
requests: String) async -> Bool {
- let listed: [EndpointModel]
- do {
- listed = try await fetchModels(endpoint)
- } catch {
- say("✗ Couldn't read the models of this Mac's local API (\(Self.describe(error))), so "
- + "\(Self.notSetUp(ready.map(\.tool))).")
+ let tools = ready.map(\.tool)
+ guard let read = await readModels(endpoint, tools: tools) else { return false }
+ let catalog = await fetchCatalog()
+ // No tool's config is written while the local API's process still loads a model this Mac lists for its start:
+ // a wait that ends before it is loaded (the deadline, a model that didn't load, Ctrl-C) returns here, before
+ // any file is touched.
+ guard let afterWait = await waitForModels(read, endpoint: endpoint, tools: tools, catalog: catalog) else {
return false
}
- let catalog = await fetchCatalog()
+ let listed = afterWait.listed
let models = IntegrationModels.resolve(listed, catalog: catalog)
var ok = true
var summaries: [ToolConfigSummary] = []
@@ -175,16 +181,12 @@ struct ToolIntegrationStep {
}
if catalog == nil, !summaries.isEmpty {
say(summaries.allSatisfy(\.undescribed.isEmpty) ? Self.catalogUnreachableKept
- : Self.catalogUnreachable(ready.map(\.tool)))
- }
- // This Mac lists a model's context only while it is loaded, so the tools got the catalog's limits for the rest.
- let unloaded = listed.filter {
- $0.contextLength == nil && IntegrationModels.location(ownedBy: $0.ownedBy) == .thisMac
+ : Self.catalogUnreachable(tools))
}
+ let unloaded = Self.notLoaded(listed, loaded: afterWait.loaded)
if !unloaded.isEmpty {
- let one = unloaded.count == 1
- say(" Run `\(Self.command(ready.map(\.tool)))` again once the "
- + "\(one ? "model is" : "models are") loaded, to pick up \(one ? "its" : "their") limits.")
+ say(Self.runAgainOnceLoaded(unloaded.map { IntegrationModels.displayName(of: $0.id, in: catalog) },
+ tools: tools))
}
let keyFile = ToolIntegration.displayPath(endpoint.keyFile, home: environment.home)
say(" Requests: \(requests)")
@@ -192,6 +194,55 @@ struct ToolIntegrationStep {
return ok
}
+ /// The endpoint's models; nil, said in one line, when they can't be read.
+ private func readModels(_ endpoint: IntegrationEndpoint, tools: [IntegrationTool]) async -> [EndpointModel]? {
+ do {
+ return try await fetchModels(endpoint)
+ } catch {
+ say("✗ Couldn't read the models of this Mac's local API (\(Self.describe(error))), so "
+ + "\(Self.notSetUp(tools)).")
+ return nil
+ }
+ }
+
+ /// This Mac's models the tools got no limits of this Mac's for: those its process hasn't `loaded`, by its own word.
+ /// Without that word, those listed without a context, which this Mac lists only while a model is loaded (unless its
+ /// router fills the catalog's in, with an account key and a route that dials out).
+ static func notLoaded(_ listed: [EndpointModel], loaded: Set?) -> [EndpointModel] {
+ let thisMac = listed.filter { IntegrationModels.location(ownedBy: $0.ownedBy) == .thisMac }
+ guard let loaded else { return thisMac.filter { $0.contextLength == nil } }
+ return thisMac.filter { !loaded.contains($0.id) }
+ }
+
+ /// Waits (`modelLoadWait`; none without it) while the local API's process still loads this Mac's models in
+ /// `listed`, then gives what the endpoint lists now, their own limits included, and what the process has loaded
+ /// by its own word (nil without it); nil, said in one line, when nothing may be written: the model didn't load,
+ /// is still loading at the deadline, or Ctrl-C stopped the wait, even as it ended.
+ private func waitForModels(_ listed: [EndpointModel], endpoint: IntegrationEndpoint, tools: [IntegrationTool],
+ catalog: CatalogSnapshot?) async -> (listed: [EndpointModel], loaded: Set?)? {
+ guard let wait = modelLoadWait else { return (listed, nil) }
+ let thisMac = listed.filter { IntegrationModels.location(ownedBy: $0.ownedBy) == .thisMac }.map(\.id)
+ let name = { (id: String) in IntegrationModels.displayName(of: id, in: catalog) }
+ switch await wait.run(thisMac: thisMac, tools: tools, name: name, say: say) {
+ case .ready(let waited, let loaded):
+ // Ctrl-C after the wait's last look, as it ended: still nothing is written. Past the wait, Ctrl-C does
+ // what it did before it.
+ guard !wait.interrupt.wasPressed else {
+ say(ModelLoadWait.stoppedBeforeWriting(tools))
+ return nil
+ }
+ guard waited else { return (listed, loaded) }
+ return await readModels(endpoint, tools: tools).map { ($0, loaded) }
+ case .notLoaded(let model):
+ say(ModelLoadWait.didNotLoad(name(model), tools: tools))
+ case .timedOut(let model):
+ say(ModelLoadWait.stillLoading(name(model), tools: tools, after: wait.timeout))
+ case .interrupted(let model):
+ say(ModelLoadWait.stopped(name(model), tools: tools))
+ }
+ return nil
+ }
+
/// The lines for one tool's outcome, and whether the tool is set up. Never a key.
static func lines(_ tool: IntegrationTool, _ outcome: ToolConfigWriter.Outcome, models: [IntegrationModel],
provider: IntegrationProvider, home: URL) -> (lines: [String], done: Bool) {
@@ -239,6 +290,13 @@ struct ToolIntegrationStep {
+ "(`\(command(tools)) --local`)."
}
+ /// The line for this Mac's models that were neither loaded nor loading as the tools were set up (unloaded when
+ /// idle, or loaded only on a request), so the tools got no limits of this Mac's for them.
+ static func runAgainOnceLoaded(_ models: [String], tools: [IntegrationTool]) -> String {
+ " Run `\(command(tools))` again once `\(cli) status` shows \(ModelLoadWait.list(models)) loaded, to pick up "
+ + "\(models.count == 1 ? "its" : "their") limits."
+ }
+
/// The line when the local API didn't come up in time after a background start.
static func notUp(_ tools: [IntegrationTool], seconds: Int) -> String {
"✗ This Mac's local API didn't answer within \(seconds) seconds, so \(notSetUp(tools)). Run "
diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ModelLoadWaitTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ModelLoadWaitTests.swift
new file mode 100644
index 0000000000..0f00e3f00c
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ModelLoadWaitTests.swift
@@ -0,0 +1,417 @@
+import Darwin
+import Foundation
+import Testing
+
+@testable import ProviderCore
+@testable import darkbloom
+
+private typealias F = ToolIntegrationFixtures
+
+/// A wait that never ends is a failure, not a hang: a fake local API process answers at most this many looks (2,500 s
+/// on the fake clock, past any deadline), then records an issue, presses Ctrl-C and runs the clock out, so a wait ends
+/// even if it ignores one of the two.
+private let maximumLooks = 10_000
+
+/// A fake local API process and clock for a wait built by hand: `answer` gets each look's number (from 1).
+private final class FakeProcess: @unchecked Sendable {
+ let interrupt: InterruptWatch
+ let limit: Int
+ var looks = 0
+ var now: TimeInterval = 0
+
+ init(interrupt: InterruptWatch = InterruptWatch(), limit: Int = maximumLooks) {
+ self.interrupt = interrupt
+ self.limit = limit
+ }
+
+ func look(_ answer: (Int) -> ModelLoads?) -> ModelLoads? {
+ looks += 1
+ if looks == limit {
+ Issue.record("the wait never ended")
+ interrupt.press()
+ now += 1_000_000
+ }
+ return answer(looks)
+ }
+}
+
+/// A temp home with Darkbloom's key file, a clock that moves only between looks, a local API process that answers as
+/// scripted, and recorders for what the step says and what its live line draws. No tool runs, no port is bound, no
+/// state file is read and no signal is taken.
+private final class WaitSandbox: @unchecked Sendable {
+ static let gemma = "gemma-4-26b-qat-4bit"
+ static let loading = ModelLoads(pending: [gemma])
+ static let loaded = ModelLoads(loaded: [gemma])
+
+ let directory: TemporaryDirectory
+ let home: URL
+ let keyFile: URL
+ let interrupt = InterruptWatch()
+ var said: [String] = []
+ var drawn: [String] = []
+ var now: TimeInterval = 1_000
+ var looks = 0
+ /// Reads of this Mac's `/v1/models`.
+ var reads = 0
+ /// Ctrl-C as the step says a line this returns true for.
+ var pressWhenSaid: (String) -> Bool = { _ in false }
+
+ init() throws {
+ directory = try TemporaryDirectory("tools-wait")
+ home = directory.file("home")
+ keyFile = try directory.write(F.freshToken(), to: "home/.darkbloom/local_token", mode: 0o600)
+ }
+
+ var endpoint: IntegrationEndpoint { IntegrationEndpoint(baseURL: "http://127.0.0.1:8123/v1", keyFile: keyFile) }
+ var openCodeFile: URL { home.appendingPathComponent(".config/opencode/opencode.jsonc") }
+
+ /// The catalog says 131,072 tokens for Gemma; this Mac serves its whole window, 262,144.
+ static let catalog = CatalogSnapshot(models: [
+ CatalogModel(id: gemma, s3Name: gemma, displayName: "Gemma 4 26B", sizeGb: 1, maxContextLength: 131_072,
+ maxOutputLength: 32_768, capabilities: ["tools", "vision", "reasoning"]),
+ ], aliases: [])
+
+ /// The local API's process answers `answers` in turn, the last again and again; Ctrl-C at look `pressAt`.
+ func wait(_ answers: [ModelLoads?], timeout: TimeInterval = ModelLoadWait.defaultTimeout, terminal: Bool = false,
+ pressAt: Int? = nil) -> ModelLoadWait {
+ ModelLoadWait(
+ loads: { [self] in
+ defer { looks += 1 }
+ if looks == pressAt { interrupt.press() }
+ if looks == maximumLooks {
+ Issue.record("the wait never ended")
+ interrupt.press()
+ now += 1_000_000
+ }
+ return answers[min(looks, answers.count - 1)]
+ },
+ timeout: timeout, clock: { [self] in now }, pause: { [self] in now += 0.25 }, interrupt: interrupt,
+ liveLine: terminal ? LiveLine(write: { [self] in drawn.append($0) }, columns: { 120 }) : nil)
+ }
+
+ /// The step, with OpenCode and Hermes installed; this Mac lists Gemma with its window once the process says it is
+ /// loaded (`loadedFromRead`: the read of `/v1/models` from which it does). `routerFills`: before that, the router
+ /// fills the catalog's limits in, as it does with an account key and a route that dials out.
+ func step(_ tools: [IntegrationTool], wait: ModelLoadWait?, loadedFromRead: Int = 2,
+ routerFills: Bool = false) -> ToolIntegrationStep {
+ ToolIntegrationStep(
+ tools: tools, environment: ToolIntegrationEnvironment(home: home, variables: [:]), provider: F.provider,
+ findTool: { .installed(URL(fileURLWithPath: "/fake/\($0.rawValue)")) },
+ fetchModels: { [self] _ in
+ reads += 1
+ return [EndpointModel(id: Self.gemma, ownedBy: "this-mac",
+ contextLength: reads >= loadedFromRead ? 262_144 : routerFills ? 131_072 : nil)]
+ },
+ fetchCatalog: { Self.catalog },
+ say: { [self] line in
+ said.append(line)
+ if pressWhenSaid(line) { interrupt.press() }
+ },
+ modelLoadWait: wait)
+ }
+
+ /// Every file but the key file.
+ func filesOtherThanTheKey() -> [URL] {
+ directory.allFiles().filter { $0.resolvingSymlinksInPath().path != keyFile.resolvingSymlinksInPath().path }
+ }
+}
+
+@Suite("Start: --opencode and --hermes wait for this Mac's models to load", .serialized, .timeLimit(.minutes(1)))
+struct ModelLoadWaitTests {
+ // MARK: - Wait, then write
+
+ @Test("a model still loading: the step waits for it, then writes the limits this Mac gives it")
+ func waitsThenWritesTheModelsOwnLimits() async throws {
+ let sandbox = try WaitSandbox()
+ let loading = WaitSandbox.loading
+ let wait = sandbox.wait([loading, loading, loading, loading, WaitSandbox.loaded])
+ #expect(await sandbox.step([.opencode], wait: wait).run(endpoint: sandbox.endpoint, requests: "this Mac only"))
+ #expect(sandbox.reads == 2, "the list is read again once the model is loaded")
+ let written = F.utf8(try Data(contentsOf: sandbox.openCodeFile))
+ #expect(written.contains("\"limit\": { \"context\": 262144, \"output\": 32768 }"),
+ "this Mac's window, not the catalog's 131,072")
+ #expect(Array(sandbox.said.prefix(3)) == [
+ "Waiting up to 10m for Gemma 4 26B to load before setting up OpenCode.",
+ "Gemma 4 26B loaded after 1s.",
+ "✓ OpenCode can use Darkbloom: 1 model.",
+ ])
+ #expect(!sandbox.said.contains { $0.contains("again once") }, "nothing to run again")
+ }
+
+ @Test("nothing loading: the tools are set up at once, without a wait or a line about it")
+ func nothingLoadingNoWait() async throws {
+ let sandbox = try WaitSandbox()
+ #expect(await sandbox.step([.opencode], wait: sandbox.wait([WaitSandbox.loaded]), loadedFromRead: 1)
+ .run(endpoint: sandbox.endpoint, requests: "this Mac only"))
+ #expect(sandbox.looks == 1 && sandbox.reads == 1 && sandbox.now == 1_000)
+ #expect(sandbox.said.first == "✓ OpenCode can use Darkbloom: 1 model.")
+
+ // The coordinator-less server (Only me) loads its models before it listens: once it answers, nothing is left.
+ let onlyMe = try WaitSandbox()
+ #expect(await onlyMe.step([.opencode], wait: onlyMe.wait([ModelLoads(loadsBeforeListening: true)]),
+ loadedFromRead: 1).run(endpoint: onlyMe.endpoint, requests: "this Mac only"))
+ #expect(onlyMe.looks == 1 && onlyMe.said.first == "✓ OpenCode can use Darkbloom: 1 model.")
+ }
+
+ @Test("a provider that hasn't said what it loads yet is asked again a second later, then waited for")
+ func anEmptyAnswerIsAskedAgain() async throws {
+ // Right after its API answers: no state of its own yet, then its start's plan.
+ let sandbox = try WaitSandbox()
+ let wait = sandbox.wait([nil, WaitSandbox.loading, WaitSandbox.loading, WaitSandbox.loaded])
+ #expect(await sandbox.step([.opencode], wait: wait).run(endpoint: sandbox.endpoint, requests: "x"))
+ #expect(sandbox.said.prefix(2) == ["Waiting up to 10m for Gemma 4 26B to load before setting up OpenCode.",
+ "Gemma 4 26B loaded after 0s."])
+
+ // No word at all, or nothing loaded and nothing to load (it unloads when idle): set up after the second look.
+ for answer in [nil, ModelLoads()] as [ModelLoads?] {
+ let quiet = try WaitSandbox()
+ #expect(await quiet.step([.opencode], wait: quiet.wait([answer]), loadedFromRead: 1)
+ .run(endpoint: quiet.endpoint, requests: "x"))
+ #expect(quiet.now - 1_000 >= ModelLoadWait.settleSeconds && quiet.now - 1_000 < 2, "\(String(describing: answer))")
+ #expect(quiet.reads == 1 && quiet.said.first == "✓ OpenCode can use Darkbloom: 1 model.")
+ }
+ #expect(ModelLoadWait.settleSeconds == 1, "a second, as the docs say")
+ }
+
+ // MARK: - Nothing written
+
+ @Test("still loading at the deadline: the message names the next step, and nothing is written")
+ func timeoutSaysSoAndWritesNothing() async throws {
+ let sandbox = try WaitSandbox()
+ let wait = sandbox.wait([WaitSandbox.loading], timeout: 5)
+ #expect(await !sandbox.step([.opencode, .hermes], wait: wait).run(endpoint: sandbox.endpoint, requests: "x"))
+ #expect(sandbox.said == [
+ "Waiting up to 5s for Gemma 4 26B to load before setting up OpenCode and Hermes.",
+ "✗ Gemma 4 26B is still loading after 5s, so OpenCode and Hermes weren't set up. Run "
+ + "`darkbloom --opencode --hermes` again once `darkbloom status` shows it loaded.",
+ "Darkbloom keeps serving.",
+ ])
+ #expect(sandbox.now - 1_000 == 5)
+ #expect(sandbox.filesOtherThanTheKey().isEmpty)
+ #expect(ModelLoadWait.defaultTimeout == 600)
+ }
+
+ @Test("Ctrl-C while it waits: nothing is written, and the start says so")
+ func ctrlCWritesNothing() async throws {
+ let sandbox = try WaitSandbox()
+ let wait = sandbox.wait([WaitSandbox.loading], terminal: true, pressAt: 3)
+ #expect(await !sandbox.step([.opencode], wait: wait).run(endpoint: sandbox.endpoint, requests: "x"))
+ #expect(sandbox.said == [
+ "Stopped waiting for Gemma 4 26B to load, so OpenCode wasn't set up; nothing was written. Run "
+ + "`darkbloom --opencode` again once `darkbloom status` shows it loaded.",
+ "Darkbloom keeps serving.",
+ ])
+ #expect(sandbox.drawn.last == "\r\u{1B}[2K", "the live line is erased")
+ #expect(sandbox.filesOtherThanTheKey().isEmpty)
+ }
+
+ @Test("Ctrl-C as the model finishes loading, or as the wait ends: nothing is written all the same")
+ func ctrlCAsTheModelLoadsWritesNothing() async throws {
+ // Pressed in the pause before the look that sees the model loaded.
+ let sandbox = try WaitSandbox()
+ let wait = sandbox.wait([WaitSandbox.loading, WaitSandbox.loading, WaitSandbox.loaded], pressAt: 2)
+ #expect(await !sandbox.step([.opencode], wait: wait).run(endpoint: sandbox.endpoint, requests: "x"))
+ #expect(sandbox.said == [
+ "Waiting up to 10m for Gemma 4 26B to load before setting up OpenCode.",
+ "Stopped waiting for Gemma 4 26B to load, so OpenCode wasn't set up; nothing was written. Run "
+ + "`darkbloom --opencode` again once `darkbloom status` shows it loaded.",
+ "Darkbloom keeps serving.",
+ ])
+ #expect(sandbox.filesOtherThanTheKey().isEmpty)
+
+ // Pressed after the wait's last look, as it ends: checked again before anything is written.
+ let late = try WaitSandbox()
+ late.pressWhenSaid = { $0 == "Gemma 4 26B loaded after 0s." }
+ #expect(await !late.step([.opencode], wait: late.wait([WaitSandbox.loading, WaitSandbox.loaded]))
+ .run(endpoint: late.endpoint, requests: "x"))
+ #expect(late.said == [
+ "Waiting up to 10m for Gemma 4 26B to load before setting up OpenCode.",
+ "Gemma 4 26B loaded after 0s.",
+ "Stopped before setting up OpenCode; nothing was written. Run `darkbloom --opencode` again.",
+ "Darkbloom keeps serving.",
+ ])
+ #expect(late.filesOtherThanTheKey().isEmpty)
+ }
+
+ @Test("a model it waited for that didn't load: nothing is written, and `status` says why")
+ func notLoadedWritesNothing() async throws {
+ let sandbox = try WaitSandbox()
+ let wait = sandbox.wait([WaitSandbox.loading, WaitSandbox.loading, ModelLoads()])
+ #expect(await !sandbox.step([.opencode], wait: wait).run(endpoint: sandbox.endpoint, requests: "x"))
+ #expect(sandbox.said == [
+ "Waiting up to 10m for Gemma 4 26B to load before setting up OpenCode.",
+ "✗ Gemma 4 26B didn't load, so OpenCode wasn't set up: `darkbloom status` says why.",
+ "Darkbloom keeps serving.",
+ ])
+ #expect(sandbox.filesOtherThanTheKey().isEmpty)
+ }
+
+ // MARK: - Run it again
+
+ @Test("a model its process hasn't loaded gets the run-again line, also when the router lists the catalog's limits")
+ func notLoadedByItsProcessSaysRunAgain() async throws {
+ let line = " Run `darkbloom --opencode` again once `darkbloom status` shows Gemma 4 26B loaded, to pick up its "
+ + "limits."
+ // An account key and a route that dials out: the router lists the catalog's 131,072 for a model not loaded.
+ let dialsOut = try WaitSandbox()
+ #expect(await dialsOut.step([.opencode], wait: dialsOut.wait([ModelLoads()]), loadedFromRead: 99,
+ routerFills: true).run(endpoint: dialsOut.endpoint, requests: "x"))
+ #expect(F.utf8(try Data(contentsOf: dialsOut.openCodeFile)).contains("\"context\": 131072"), "the catalog's")
+ #expect(dialsOut.said.filter { $0 == line }.count == 1, "\(dialsOut.said)")
+ // Loaded, by its process's word: no line.
+ let loaded = try WaitSandbox()
+ #expect(await loaded.step([.opencode], wait: loaded.wait([WaitSandbox.loaded]), loadedFromRead: 99,
+ routerFills: true).run(endpoint: loaded.endpoint, requests: "x"))
+ #expect(!loaded.said.contains { $0.hasPrefix(" Run `") }, "\(loaded.said)")
+ // No word from its process (no state of its own, or Only me's server): a model listed without its context.
+ for answer in [nil, ModelLoads(loadsBeforeListening: true)] as [ModelLoads?] {
+ let silent = try WaitSandbox()
+ #expect(await silent.step([.opencode], wait: silent.wait([answer]), loadedFromRead: 99)
+ .run(endpoint: silent.endpoint, requests: "x"))
+ #expect(silent.said.filter { $0 == line }.count == 1, "\(String(describing: answer)): \(silent.said)")
+ let filled = try WaitSandbox()
+ #expect(await filled.step([.opencode], wait: filled.wait([answer]), loadedFromRead: 99, routerFills: true)
+ .run(endpoint: filled.endpoint, requests: "x"))
+ #expect(!filled.said.contains { $0.hasPrefix(" Run `") }, "\(String(describing: answer)): \(filled.said)")
+ }
+ }
+
+ // MARK: - The line
+
+ @Test("on a terminal one live line, drawn in place; without one, a line as it starts and one as it ends")
+ func oneLiveLineOnlyOnATerminal() async throws {
+ let answers = [WaitSandbox.loading, WaitSandbox.loading, WaitSandbox.loading, WaitSandbox.loaded]
+ let plain = try WaitSandbox()
+ #expect(await plain.step([.opencode], wait: plain.wait(answers)).run(endpoint: plain.endpoint, requests: "x"))
+ #expect(plain.drawn.isEmpty)
+ #expect(Array(plain.said.prefix(2)) == ["Waiting up to 10m for Gemma 4 26B to load before setting up OpenCode.",
+ "Gemma 4 26B loaded after 0s."])
+ #expect(!plain.said.joined().contains("\r") && !plain.said.joined().contains("\u{1B}"))
+
+ let terminal = try WaitSandbox()
+ #expect(await terminal.step([.opencode], wait: terminal.wait(answers, terminal: true))
+ .run(endpoint: terminal.endpoint, requests: "x"))
+ let line = "Loading Gemma 4 26B before setting up OpenCode… 0s"
+ #expect(terminal.drawn == ["\r\u{1B}[2K⠋ " + line, "\r\u{1B}[2K⠙ " + line, "\r\u{1B}[2K⠹ " + line,
+ "\r\u{1B}[2K"])
+ #expect(terminal.said.first == "Gemma 4 26B loaded after 0s.", "no start line beside the live one")
+ }
+
+ @Test("the live line says how long it has waited, and never runs past the window")
+ func liveLineWords() {
+ #expect(ModelLoadWait.loadingLine("Gemma 4 26B", tools: [.opencode, .hermes], elapsed: 72)
+ == "Loading Gemma 4 26B before setting up OpenCode and Hermes… 1m 12s")
+ var drawn: [String] = []
+ LiveLine(write: { drawn.append($0) }, columns: { 21 }).show("Loading Gemma 4 26B before setting up OpenCode")
+ #expect(drawn == ["\r\u{1B}[2KLoading Gemma 4 26B…"])
+ #expect(ModelLoadWait.loadedLine(["Gemma 4 26B", "Qwen 3.8 27B", "GLM-5.3-Flash"], elapsed: 125)
+ == "Gemma 4 26B, Qwen 3.8 27B and GLM-5.3-Flash loaded after 2m 5s.")
+ }
+
+ @Test("no terminal, no live line: a pipe, a log or a dumb terminal gets whole lines only")
+ func noLiveLineWithoutATerminal() {
+ #expect(LiveLine.standardOutput(isTerminal: false, environment: ["TERM": "xterm-256color"]) == nil)
+ #expect(LiveLine.standardOutput(isTerminal: true, environment: ["TERM": "dumb"]) == nil)
+ #expect(LiveLine.standardOutput(isTerminal: true, environment: ["TERM": "xterm-256color"]) != nil)
+ #expect(LiveLine.standardOutput(isTerminal: true, environment: [:]) != nil, "a terminal that names no TERM")
+ }
+
+ @Test("the wait start runs draws its live line exactly where a terminal can draw one")
+ func theLiveWaitDrawsOnlyOnATerminal() {
+ #expect(ModelLoadWait.live(isTerminal: false, environment: ["TERM": "xterm-256color"]).liveLine == nil)
+ #expect(ModelLoadWait.live(isTerminal: true, environment: ["TERM": "dumb"]).liveLine == nil)
+ #expect(ModelLoadWait.live(isTerminal: true, environment: ["TERM": "xterm-256color"]).liveLine != nil)
+ #expect((ModelLoadWait.live().liveLine == nil) == (LiveLine.standardOutput() == nil), "this process's own")
+ }
+
+ // MARK: - What the local API's process says
+
+ @Test("only the local API's own process is believed, and Only me's server has loaded before it listens")
+ func theAPIsOwnProcessSays() {
+ let loop = DaemonState(pid: 42, version: "test", writtenAt: 0, startedAt: 0, warmModels: ["a"],
+ startupPreloadPendingModels: ["b", "c"], runtimeCapabilities: [])
+ #expect(ModelLoads.reported(by: loop, apiPID: 42) == ModelLoads(loaded: ["a"], pending: ["b", "c"]))
+ #expect(ModelLoads.reported(by: loop, apiPID: 7) == nil, "another process's state")
+ #expect(ModelLoads.reported(by: loop, apiPID: nil) == nil, "no local API")
+ #expect(ModelLoads.reported(by: nil, apiPID: 42) == nil)
+ let onlyMe = DaemonState(pid: 42, version: "test", writtenAt: 0, startedAt: 0)
+ #expect(ModelLoads.reported(by: onlyMe, apiPID: 42) == ModelLoads(loadsBeforeListening: true))
+ }
+
+ @Test("still loading: pending, listed by this Mac and not loaded yet, in the order the process loads them")
+ func whatStillLoads() {
+ // The process keeps a model pending through its warm-up, after it is loaded.
+ #expect(ModelLoads(loaded: ["a"], pending: ["a", "b", "c"]).loading(among: ["a", "b", "d"]) == ["b"])
+ #expect(ModelLoads(pending: ["b", "a"]).loading(among: ["a", "b"]) == ["b", "a"])
+ #expect(ModelLoads(loaded: ["a"]).loading(among: ["a"]).isEmpty)
+ #expect(ModelLoads(loadsBeforeListening: true).loading(among: ["a"]).isEmpty)
+ }
+
+ @Test("the step `start` runs waits")
+ func startsStepWaits() {
+ #expect(ToolIntegrationStep.live(tools: [.opencode], coordinatorURL: "wss://coordinator.invalid/ws/provider")
+ .modelLoadWait != nil)
+ }
+
+ @Test("a model this Mac doesn't list, or one already loaded, isn't waited for")
+ func onlyThisMacsLoadingModelsAreWaitedFor() async {
+ let process = FakeProcess()
+ let answer = ModelLoads(loaded: ["warm"], pending: ["warm", "elsewhere"])
+ let wait = ModelLoadWait(loads: { process.look { _ in answer } }, clock: { process.now }, pause: {},
+ interrupt: process.interrupt)
+ let outcome = await wait.run(thisMac: ["warm", "listed"], tools: [.opencode], name: { $0 }, say: { _ in })
+ #expect(outcome == .ready(waited: false, loaded: ["warm"]) && process.looks == 1)
+ // This Mac lists none of its own (a relay): nothing to ask.
+ #expect(await ModelLoadWait(loads: { Issue.record("asked"); return nil }).run(
+ thisMac: [], tools: [.opencode], name: { $0 }, say: { _ in }) == .ready(waited: false))
+ }
+
+ @Test("the live watch takes the signal only while it waits, then gives it back as it was")
+ func theWatchTakesTheSignalOnlyWhileItWaits() async throws {
+ // SIGUSR2 stands in for SIGINT, so no other test's handler sees it.
+ let before = signal(SIGUSR2, SIG_DFL)
+ defer { signal(SIGUSR2, before) }
+ let watch = InterruptWatch(signal: SIGUSR2)
+ watch.begin()
+ // Raised only once the watch has it: the signal's default action would end the test process.
+ try #require(ProviderStopSignals.isIgnored(SIGUSR2), "the default action can't end the process while it waits")
+ raise(SIGUSR2)
+ for _ in 0..<200 where !watch.wasPressed { try await Task.sleep(for: .milliseconds(10)) }
+ #expect(watch.wasPressed)
+ watch.end()
+ #expect(!ProviderStopSignals.isIgnored(SIGUSR2), "the default action is back")
+ }
+
+ @Test("the wait itself takes the signal at every look, stops on it, and gives it back as it was")
+ func theWaitTakesTheSignalOnlyWhileItRuns() async throws {
+ // SIGUSR2 stands in for SIGINT, as above.
+ let before = signal(SIGUSR2, SIG_DFL)
+ defer { signal(SIGUSR2, before) }
+ let process = FakeProcess(interrupt: InterruptWatch(signal: SIGUSR2))
+ var held: [Bool] = []
+ let wait = ModelLoadWait(loads: {
+ process.look { look in
+ held.append(ProviderStopSignals.isIgnored(SIGUSR2))
+ return look < 3 ? ModelLoads(pending: ["a"]) : ModelLoads(loaded: ["a"])
+ }
+ }, clock: { process.now }, pause: {}, interrupt: process.interrupt)
+ #expect(await wait.run(thisMac: ["a"], tools: [.opencode], name: { $0 }, say: { _ in })
+ == .ready(waited: true, loaded: ["a"]))
+ #expect(held == [true, true, true], "the wait has the signal at every look")
+ #expect(!ProviderStopSignals.isIgnored(SIGUSR2), "and gives it back")
+
+ // The signal stops the wait. Raised only once the wait has it: the default action would end the test process.
+ let raised = FakeProcess(interrupt: InterruptWatch(signal: SIGUSR2), limit: 2_000)
+ let stopped = ModelLoadWait(loads: {
+ raised.look { look in
+ if look == 2 {
+ if ProviderStopSignals.isIgnored(SIGUSR2) { raise(SIGUSR2) } else { Issue.record("the wait hasn't it") }
+ }
+ return ModelLoads(pending: ["a"])
+ }
+ }, clock: { raised.now }, pause: { try? await Task.sleep(for: .milliseconds(5)) }, interrupt: raised.interrupt)
+ #expect(await stopped.run(thisMac: ["a"], tools: [.opencode], name: { $0 }, say: { _ in })
+ == .interrupted(model: "a"))
+ #expect(!ProviderStopSignals.isIgnored(SIGUSR2), "given back after a stop too")
+ }
+}
diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/StartToolIntegrationTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/StartToolIntegrationTests.swift
index 89dd3b27b6..2cca914674 100644
--- a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/StartToolIntegrationTests.swift
+++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/StartToolIntegrationTests.swift
@@ -295,7 +295,8 @@ struct StartToolIntegrationTests {
@Test("a model this Mac hasn't loaded yet gets one line: run the start again once it is loaded")
func unloadedModelsSayRunAgain() async throws {
- let line = " Run `darkbloom --opencode` again once the model is loaded, to pick up its limits."
+ let line = " Run `darkbloom --opencode` again once `darkbloom status` shows gpt-oss-120b loaded, to pick up "
+ + "its limits."
let sandbox = try StepSandbox()
let unloaded = StepSandbox.listed + [EndpointModel(id: "gpt-oss-120b", ownedBy: "this-mac")]
#expect(await sandbox.step([.opencode], listed: unloaded).run(endpoint: sandbox.endpoint, requests: "x"))
@@ -306,6 +307,9 @@ struct StartToolIntegrationTests {
_ = await quiet.step([.opencode], listed: listed).run(endpoint: quiet.endpoint, requests: "x")
#expect(!quiet.said.contains { $0.hasPrefix(" Run `") })
}
+ #expect(ToolIntegrationStep.runAgainOnceLoaded(["Gemma 4 26B", "Qwen 3.8 27B"], tools: [.opencode, .hermes])
+ == " Run `darkbloom --opencode --hermes` again once `darkbloom status` shows Gemma 4 26B and Qwen 3.8 27B "
+ + "loaded, to pick up their limits.")
}
// MARK: - Finding the tools
diff --git a/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolAddressTests.swift b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolAddressTests.swift
new file mode 100644
index 0000000000..b311a373df
--- /dev/null
+++ b/provider-swift/Tests/DarkbloomCLITests/ToolIntegration/ToolAddressTests.swift
@@ -0,0 +1,239 @@
+import Foundation
+import Testing
+
+@testable import ProviderCore
+@testable import darkbloom
+
+private typealias F = ToolIntegrationFixtures
+
+/// A temp home with this Mac's key file and the pair's, where the tools are set up as `darkbloom --opencode --hermes`
+/// sets them up. No tool runs, no port is bound, and no real home, OpenCode or Hermes config is read.
+private final class AddressSandbox: @unchecked Sendable {
+ let directory: TemporaryDirectory
+ let home: URL
+ let keyFile: URL
+ let pairKeyFile: URL
+ var said: [String] = []
+
+ init() throws {
+ directory = try TemporaryDirectory("tools-address")
+ home = directory.file("home")
+ keyFile = try directory.write(F.freshToken(), to: "home/.darkbloom/local_token", mode: 0o600)
+ pairKeyFile = try directory.write(F.freshToken(), to: "home/.darkbloom/cluster_local_token", mode: 0o600)
+ }
+
+ var environment: ToolIntegrationEnvironment { ToolIntegrationEnvironment(home: home, variables: [:]) }
+ var openCodeFile: URL { home.appendingPathComponent(".config/opencode/opencode.jsonc") }
+ var hermesFile: URL { home.appendingPathComponent(".hermes/config.yaml") }
+
+ /// Sets `tools` up for the local API on `port` with the key in `keyFile` (this Mac's by default).
+ func setUp(_ tools: [IntegrationTool], port: UInt16, keyFile: URL? = nil) async {
+ let step = ToolIntegrationStep(
+ tools: tools, environment: environment, provider: F.provider,
+ findTool: { .installed(URL(fileURLWithPath: "/fake/\($0.rawValue)")) },
+ fetchModels: { _ in [EndpointModel(id: "qwen3.8-27b", ownedBy: "this-mac", contextLength: 262_144)] },
+ fetchCatalog: { nil }, say: { _ in })
+ let endpoint = IntegrationEndpoint(baseURL: "http://127.0.0.1:\(port)/v1", keyFile: keyFile ?? self.keyFile)
+ #expect(await step.run(endpoint: endpoint, requests: "this Mac only"))
+ }
+
+ /// A start serving `mode` on `port`, at `bind`.
+ func serving(mode: LocalSettings.Mode = .both, port: UInt16, bind: String = "127.0.0.1",
+ noAuth: Bool = false) -> StartServing {
+ StartServing(mode: mode, source: .saved, meFirst: mode == .both, meFirstIdleMinutes: 2, route: nil,
+ accountKeySaved: false, port: port, bind: bind, noAuth: noAuth)
+ }
+
+ /// What a start with `arguments` says after serving `mode` on `port`, on a Mac whose Bonjour name is
+ /// `localHostName`.
+ func notice(_ arguments: [String] = [], mode: LocalSettings.Mode = .both, port: UInt16, bind: String = "127.0.0.1",
+ noAuth: Bool = false, localHostName: String? = "tester-mac") throws -> [String] {
+ said = []
+ try Start.parse(arguments).noteToolsPointingElsewhere(
+ serving(mode: mode, port: port, bind: bind, noAuth: noAuth), environment: environment, provider: F.provider,
+ keyFile: keyFile, localHostName: { localHostName }, say: { self.said.append($0) })
+ return said
+ }
+
+ /// Points OpenCode's Darkbloom block at `url`, with this Mac's key file.
+ func pointOpenCode(at url: String) throws {
+ let settings = #"{ "baseURL": "\#(url)", "apiKey": "{file:~/.darkbloom/local_token}" }"#
+ try directory.write(#"{ "providers": { "darkbloom": { "settings": \#(settings) } } }"#,
+ to: "home/.config/opencode/opencode.jsonc")
+ }
+
+ /// The tools' configs, byte for byte, and every backup.
+ func snapshot() throws -> [Data?] {
+ [try? Data(contentsOf: openCodeFile), try? Data(contentsOf: hermesFile)]
+ + directory.allFiles().filter { $0.path.contains("/integrations/backups/") }.map { try? Data(contentsOf: $0) }
+ }
+}
+
+@Suite("Start: the tools follow this Mac's local API", .serialized, .timeLimit(.minutes(1)))
+struct ToolAddressTests {
+ @Test("a later start on another port says so in one line, names the command, and changes no file")
+ func aChangedPortIsSaidInOneLine() async throws {
+ let sandbox = try AddressSandbox()
+ await sandbox.setUp([.opencode, .hermes], port: 8123)
+ let before = try sandbox.snapshot()
+ #expect(try sandbox.notice(port: 8123).isEmpty, "the tools point at this Mac's local API")
+ #expect(try sandbox.notice(port: 8124) == ["", "OpenCode and Hermes point at http://127.0.0.1:8123/v1, not "
+ + "this Mac's local API (http://127.0.0.1:8124/v1): `darkbloom --opencode --hermes` points them there."])
+ #expect(try sandbox.notice(mode: .local, port: 8124).count == 2, "Only me too")
+ #expect(try sandbox.snapshot() == before, "a plain start never writes a tool's config")
+ }
+
+ @Test("only the tools set up for Darkbloom are named")
+ func onlyToolsSetUpAreNamed() async throws {
+ let sandbox = try AddressSandbox()
+ #expect(try sandbox.notice(port: 8124).isEmpty, "no tool set up")
+ await sandbox.setUp([.opencode], port: 8123)
+ #expect(try sandbox.notice(port: 8124).last == "OpenCode points at http://127.0.0.1:8123/v1, not this Mac's "
+ + "local API (http://127.0.0.1:8124/v1): `darkbloom --opencode` points it there.")
+ }
+
+ @Test("a tool reading another key file is named; the same key in another file is fine")
+ func anotherKeyFileIsNamed() async throws {
+ let sandbox = try AddressSandbox()
+ await sandbox.setUp([.opencode, .hermes], port: 8123, keyFile: sandbox.pairKeyFile)
+ #expect(try sandbox.notice(port: 8123).last == "OpenCode and Hermes read the key in "
+ + "~/.darkbloom/cluster_local_token, not the one this Mac's local API takes (~/.darkbloom/local_token): "
+ + "`darkbloom --opencode --hermes` points them there.")
+ // Without a key (--no-auth) any file does.
+ #expect(try sandbox.notice(port: 8123, noAuth: true).isEmpty)
+ try Data(contentsOf: sandbox.keyFile).write(to: sandbox.pairKeyFile)
+ #expect(try sandbox.notice(port: 8123).isEmpty, "the file holds this Mac's key")
+ }
+
+ @Test("tools that miss it in different ways get one line for both")
+ func differentMissesGetOneLine() async throws {
+ let sandbox = try AddressSandbox()
+ await sandbox.setUp([.opencode], port: 8124)
+ await sandbox.setUp([.hermes], port: 8123)
+ #expect(try sandbox.notice(port: 8123).last == "OpenCode points at http://127.0.0.1:8124/v1, not this Mac's "
+ + "local API (http://127.0.0.1:8123/v1): `darkbloom --opencode` points it there.")
+ await sandbox.setUp([.hermes], port: 8123, keyFile: sandbox.pairKeyFile)
+ #expect(try sandbox.notice(port: 8123).last == "OpenCode and Hermes don't point at this Mac's local API "
+ + "(http://127.0.0.1:8123/v1): `darkbloom --opencode --hermes` points them there.")
+ }
+
+ @Test("a base URL with a slash at its end is the same address")
+ func aTrailingSlashIsTheSameAddress() throws {
+ let sandbox = try AddressSandbox()
+ let settings = #"{ "baseURL": "http://127.0.0.1:8123/v1/", "apiKey": "{file:~/.darkbloom/local_token}" }"#
+ try sandbox.directory.write(#"{ "providers": { "darkbloom": { "settings": \#(settings) } } }"#,
+ to: "home/.config/opencode/opencode.jsonc")
+ try sandbox.directory.write("providers:\n darkbloom:\n api: \"http://127.0.0.1:8123/v1/\"\n"
+ + " key_cmd: \"/bin/cat \(sandbox.keyFile.path)\"\n", to: "home/.hermes/config.yaml")
+ #expect(try sandbox.notice(port: 8123).isEmpty)
+ #expect(try sandbox.notice(port: 8124).last?.hasPrefix("OpenCode and Hermes point at "
+ + "http://127.0.0.1:8123/v1/, not this Mac's local API") == true, "another port still is another address")
+ }
+
+ @Test("localhost, 127.0.0.1 and ::1 are this Mac, in any case; so is its .local name for an API on every address")
+ func thisMacsNamesAreThisMac() throws {
+ let sandbox = try AddressSandbox()
+ for url in ["http://localhost:8123/v1", "http://[::1]:8123/v1", "HTTP://LocalHost:8123/v1/",
+ "http://127.0.0.1:8123/v1"] {
+ try sandbox.pointOpenCode(at: url)
+ #expect(try sandbox.notice(port: 8123).isEmpty, "\(url)")
+ #expect(try sandbox.notice(port: 8124).last == "OpenCode points at \(url), not this Mac's local API "
+ + "(http://127.0.0.1:8124/v1): `darkbloom --opencode` points it there.", "another port: \(url)")
+ }
+ // This Mac's Bonjour name, which `darkbloom local` prints for an API on every address.
+ try sandbox.pointOpenCode(at: "http://Tester-Mac.local:8123/v1")
+ #expect(try sandbox.notice(port: 8123, bind: "0.0.0.0").isEmpty)
+ #expect(try sandbox.notice(port: 8123, bind: "127.0.0.1").count == 2, "an API on loopback alone isn't there")
+ #expect(try sandbox.notice(port: 8123, bind: "0.0.0.0", localHostName: "other-mac").count == 2, "another Mac")
+ #expect(try sandbox.notice(port: 8123, bind: "0.0.0.0", localHostName: nil).count == 2, "no name to know")
+ // Another path, scheme or port is another address; the scheme's own port is its port.
+ for url in ["http://localhost:8123/v2", "https://localhost:8123/v1", "http://localhost/v1"] {
+ try sandbox.pointOpenCode(at: url)
+ #expect(try sandbox.notice(port: 8123).count == 2, "\(url)")
+ }
+ #expect(ToolAddress.sameAddress("http://localhost/v1", "http://127.0.0.1:80/v1"))
+ #expect(!ToolAddress.sameAddress("http://192.168.1.5:8123/v1", "http://127.0.0.1:8123/v1"))
+ }
+
+ @Test("a plain start says it beside its background provider and its Only me server; a service's child never does")
+ func theStartsHooksSayIt() async throws {
+ let sandbox = try AddressSandbox()
+ await sandbox.setUp([.opencode], port: 8123)
+ let serving = sandbox.serving(port: 8124)
+ let line = ["", "OpenCode points at http://127.0.0.1:8123/v1, not this Mac's local API (http://127.0.0.1:8124/v1): "
+ + "`darkbloom --opencode` points it there."]
+ func note(_ start: Start) -> (StartServing) -> Void {
+ { start.noteToolsPointingElsewhere($0, environment: sandbox.environment, provider: F.provider,
+ keyFile: sandbox.keyFile, localHostName: { nil },
+ say: { sandbox.said.append($0) }) }
+ }
+ let coordinator = "wss://coordinator.invalid/ws/provider"
+ // Beside the background provider: the line, and no wait for an API it has no tool to set up for.
+ sandbox.said = []
+ let start = try Start.parse([])
+ try await start.setUpToolsBesideDaemon(serving: serving, coordinatorURL: coordinator, waitForAPI: { _, _ in
+ Issue.record("a start without a tool flag waits for no API")
+ return .notUp
+ }, noteTools: note(start))
+ #expect(sandbox.said == line)
+ // Beside the Only me server: the line in a terminal; none in a service's child, whose lines go to a log.
+ let info = LocalEndpoint.Info(host: "127.0.0.1", port: 8124, apiKey: "dk-local-fixture", version: "test", pid: 1,
+ updatedAt: "")
+ for (arguments, expected) in [([String](), line), (["--foreground"], [])] {
+ sandbox.said = []
+ let start = try Start.parse(arguments)
+ start.setUpToolsBesideLocalServer(info, serving: serving, coordinatorURL: coordinator, noteTools: note(start))
+ #expect(sandbox.said == expected, "\(arguments)")
+ }
+ }
+
+ @Test("no line with a tool flag (the start points the tools there itself) or without a local API")
+ func noLineWhenTheStartSetsToolsUpOrServesNoAPI() async throws {
+ let sandbox = try AddressSandbox()
+ await sandbox.setUp([.opencode, .hermes], port: 8123)
+ #expect(try sandbox.notice(["--opencode"], port: 8124).isEmpty)
+ #expect(try sandbox.notice(mode: .network, port: 8124).isEmpty)
+ }
+
+ @Test("the tools' files are read back as Darkbloom writes them, a key file under ~ or with quotes in its path")
+ func pointersReadBack() throws {
+ for keyFile in ["/Users/tester/.darkbloom/local_token", "/Users/o'neil/My Keys/local_token"] {
+ let endpoint = IntegrationEndpoint(baseURL: "http://127.0.0.1:8001/v1",
+ keyFile: URL(fileURLWithPath: keyFile))
+ let openCode = try #require(F.newText(OpenCodeConfigPlan.plan(
+ existing: nil, fileName: "opencode.jsonc", endpoint: endpoint, models: [F.qwen], provider: F.provider,
+ home: F.home)))
+ let hermes = try #require(F.newText(HermesConfigPlan.plan(
+ existing: nil, endpoint: endpoint, models: [F.qwen], provider: F.provider)))
+ for pointer in [OpenCodeConfigPlan.pointer(in: Data(openCode.utf8), provider: F.provider, home: F.home),
+ HermesConfigPlan.pointer(in: Data(hermes.utf8), provider: F.provider)] {
+ #expect(pointer?.baseURL == "http://127.0.0.1:8001/v1" && pointer?.keyFile?.path == keyFile,
+ "\(String(describing: pointer))")
+ }
+ }
+ // A key the owner gives some other way, and a file without Darkbloom's block.
+ let envKey = #"{ "providers": { "darkbloom": { "settings": { "apiKey": "{env:KEY}" } } } }"#
+ #expect(OpenCodeConfigPlan.pointer(in: Data(envKey.utf8), provider: F.provider, home: F.home)
+ == ToolPointer(baseURL: nil, keyFile: nil))
+ #expect(OpenCodeConfigPlan.pointer(in: Data(#"{ "providers": {} }"#.utf8), provider: F.provider,
+ home: F.home) == nil)
+ #expect(HermesConfigPlan.pointer(in: Data("providers:\n other:\n api: x\n".utf8), provider: F.provider)
+ == nil)
+ }
+
+ @Test("a key command or file reference Darkbloom doesn't write names no key file")
+ func otherKeyFormsNameNoFile() {
+ let api = "http://127.0.0.1:8001/v1"
+ for command in ["pass show darkbloom", "/bin/cat .darkbloom/local_token", "/bin/cat '/Users/tester/unclosed"] {
+ let text = "providers:\n darkbloom:\n api: \"\(api)\"\n key_cmd: \"\(command)\"\n"
+ #expect(HermesConfigPlan.pointer(in: Data(text.utf8), provider: F.provider)
+ == ToolPointer(baseURL: api, keyFile: nil), "\(command)")
+ }
+ for reference in ["{file:.darkbloom/local_token}", "dk-local-written-in-the-file"] {
+ let settings = #"{ "baseURL": "\#(api)", "apiKey": "\#(reference)" }"#
+ let text = #"{ "providers": { "darkbloom": { "settings": \#(settings) } } }"#
+ #expect(OpenCodeConfigPlan.pointer(in: Data(text.utf8), provider: F.provider, home: F.home)
+ == ToolPointer(baseURL: api, keyFile: nil), "\(reference)")
+ }
+ }
+}