diff --git a/docs/reference.md b/docs/reference.md index 5370be09c..8c9c2f4e6 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -156,6 +156,7 @@ line; agents connected to magpie lose it when it quits. | OpenPencil | `openpencil/settings.json` in the config folder: `~/Library/Application Support` (macOS), `$XDG_CONFIG_HOME` or `~/.config` (Linux), `%APPDATA%` (Windows) | provider (a `magpie` entry in its `builtin_agents`, magpie's models in its chat's model picker; the user's entries and settings kept; refused while OpenPencil runs, as it writes the file back when it quits) | | OpenBot | `OpenBot/openbot-custom-providers-v1.json` in the app data folder: `~/Library/Application Support` (macOS), `%APPDATA%` (Windows), `$XDG_CONFIG_HOME` or `~/.config` (Linux) | provider (a keyless `magpie` endpoint at `/agent/openbot/v1`, magpie's models in its model picker; the user's endpoints kept; OpenBot reads it at start, so restart it) | | Craft Agents | `~/.craft-agent/config.json` (or `$CRAFT_CONFIG_DIR`) | model (a keyless `pi_compat` connection `magpie` at `/agent/craft-agents/v1`, made the default; the user's connections and default kept and put back on off; new sessions use it) | +| Obsidian | Copilot for Obsidian 4+'s `.obsidian/plugins/copilot/data.json` in each vault `obsidian.json` lists (`~/Library/Application Support/obsidian`, `%APPDATA%\obsidian`, `$XDG_CONFIG_HOME/obsidian`, Flatpak, Snap) | provider (a keyless `magpie` provider at `/agent/obsidian/v1`, magpie's models in Copilot's chat picker and the default; the user's settings kept; reload Copilot or restart Obsidian) | | NewMax | `newmax.db` (SQLite, the row `app` of its `settings` table) in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` (every OS) | provider (a `magpie-gateway` entry in its `providers` and `providerOrder`, magpie's models in its model picker; the rest of the row kept byte for byte; refused while NewMax runs, as it writes its settings back whenever one changes) | | LiveAgent | `config.json` (JSONC, K-brain's) in `$LIVEAGENT_HOME`, else `$K_BRAIN_HOME`, else the folder `~/.liveagent/data-dir.json` points to, else `~/.liveagent` (every OS) | provider (`magpie`, `magpie-responses` and `magpie-anthropic` entries in its `providers`, each model on the one of the API it is served on natively: Chat Completions and Responses at the gateway's `/v1` as OpenAI providers whose request format the user can switch in LiveAgent and magpie keeps, Anthropic Messages at its root; magpie's models in its model picker; a model or provider of magpie's deleted in LiveAgent stays out; a default still K-brain's own demo model becomes magpie's first; refused while LiveAgent or its `k-brain` backend runs, as it writes its settings back whenever one changes) | | T3 Code | `~/.t3/userdata/settings.json` (`$T3CODE_HOME/userdata`) | provider (a `magpie` provider instance on Claude Code, magpie's models as its custom models; a `magpie-codex` instance on Codex, whose `launchArgs` are Codex's own `-c` overrides to magpie and a `magpie-codex-models.json` catalog beside the settings. The harness is picked in T3's model picker) | diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 008c6c93d..8b7842ae8 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -99,6 +99,7 @@ something else shows up as drift. - OpenPencil (ZSeven-W/openpencil, the `openpencil-desktop` app) keeps the builtin agents its chat runs on in `settings.json` in Rust's `dirs::config_dir()` joined with `openpencil`: `~/Library/Application Support/openpencil` on a Mac, `$XDG_CONFIG_HOME` or `~/.config` on Linux, `%APPDATA%` on Windows (`openPencil` in [`openpencil.go`](../../internal/agent/openpencil.go); its `settings_io.rs` and `settings_payload.rs`). magpie adds one entry to `builtin_agents`, `id: magpie`, `kind: openai-compat` at the gateway's `/v1` with a key naming OpenPencil (its User-Agent isn't known), `preset: custom`, the picked models as OpenPencil writes a list: the first as `model`, `models` only for two or more, at most 64 (v0.8.4 reads `model` alone). The user's other entries and settings stay, and so do the `display_name` and `enabled` they give magpie's entry; a sync with nothing to change doesn't write. OpenPencil needs `"version": 1` (a file without it is set aside as corrupt and saving stops), so magpie writes it in a file it makes and leaves a file with any other version, or none, alone. Disconnect takes the entry out, and the file when only the version and an empty list are left. OpenPencil reads the file once at start and writes it back whole when it quits, so a change is refused while `openpencil-desktop` runs (Windows can't be asked, so the notice says to quit it first). The model is picked in OpenPencil's chat, so the field is whether magpie is in its picker (`ListsModels`). Detected by its settings folder, `~/.openpencil` (its CLI's), `OpenPencil.app` (`com.zseven-w.openpencil`), or `%ProgramFiles%\OpenPencil`. open-pencil/open-pencil, the other app of the name, keeps its providers in its webview's localStorage, so it is not a row: it reaches magpie through Pi or an ACP agent magpie wires. - OpenBot (nightly-labs/openbot, openbot.run; jiezhengj on Discord) keeps the OpenAI-compatible endpoints its model picker lists in `openbot-custom-providers-v1.json` in Electron's userData folder, app data joined with `OpenBot`: `~/Library/Application Support/OpenBot` on a Mac, `%APPDATA%\OpenBot` on Windows, `$XDG_CONFIG_HOME/OpenBot` or `~/.config/OpenBot` on Linux (`openBot` in [`openbot.go`](../../internal/agent/openbot.go); its `custom-provider-store.ts` and `opencode-config.ts`, v0.58.0). magpie adds one entry to `providers`, `id: magpie` at the gateway's `/agent/openbot/v1` with `secret: null`: an entry's key and headers are one safeStorage ciphertext (the Keychain, DPAPI) that magpie doesn't open, so OpenBot hands the entry to OpenCode keyless, the gateway takes it as a request from this computer, and the address, not OpenCode's User-Agent, names it OpenBot's (`gateway.AgentURL`; before, it counted as OpenCode's, SSNQT on X). An entry written at `/v1` is rewritten at the next sync, and OpenBot reads it after a restart. OpenBot's list decoders fail closed (one entry or model it wouldn't take empties the list), so the models are the picked ones whose `magpie/` OpenBot accepts (ASCII letters, digits and `._:/[],=-`, at most 160), at most 64, with a context window only inside 1,024 to 100,000,000. The user's other entries stay, and so do the `name`, `harness` and `secret` they give magpie's entry; a sync with nothing to change doesn't write. A file whose `version` isn't the number 1, or whose `providers` isn't a list, is one OpenBot itself refuses, so magpie leaves it alone. Disconnect takes the entry out, and the file when only the version and an empty list are left. OpenBot reads the file once at start and writes it whole only when an endpoint is saved, edited or removed there, so the notice (while it runs) says to restart it before doing that. The model is picked in OpenBot's picker (`ListsModels`). Detected by its userData folder, `OpenBot.app` (`app.openbot.desktop`), or `OpenBot.exe` under `%LOCALAPPDATA%\Programs` or `%ProgramFiles%`. In the Library it takes skills, in `~/.agents/skills`, the only folder it reads (`home-skills.ts`). Its MCP servers live in its SQLite database, which magpie doesn't write (#5896), so it isn't in the MCP picker: magpie's `/mcp/magpie/…` servers are added there by hand as HTTP servers. - Craft Agents (lukilabs/craft-agents-oss, thecraftagents.com; springg1998 on X) keeps its connections in `config.json` under `$CRAFT_CONFIG_DIR` or `~/.craft-agent` (`craftAgents` in [`craftagents.go`](../../internal/agent/craftagents.go); its `config/paths.ts`, `config/storage.ts` and `config/llm-connections.ts`, v0.15.8). magpie adds one entry to `llmConnections`, slug `magpie`, `providerType: pi_compat` and `authType: none` at the gateway's `/agent/craft-agents/v1` with `customEndpoint.api: openai-completions`: Pi sends a keyless loopback request, which the gateway takes as this computer's, and the address names it Craft's. Its `models` are magpie's picked ones as objects, and `defaultModel` is always one of them, since Craft resets a default its list hasn't to the first. magpie makes it `defaultLlmConnection`; the user's default is stashed (as JSON, `""` for none) and put back on off when that connection is still there, and the `name` they give magpie's entry stays. A session keeps the connection it started on, and a workspace default goes over the global one, so the notice says new sessions use it. A `config.json` with no `workspaces` list is one Craft doesn't load, so magpie never makes one: Craft is opened once first. Picking one of the user's own models takes magpie's entry out and sets that model as their default connection's `defaultModel`. Craft re-reads the file on each lookup. Detected by `~/.craft-agent` or `Craft Agents.app` (`com.lukilabs.craft-agent`), or `Craft Agents.exe` under `%LOCALAPPDATA%\Programs\@craft-agentelectron`. In the Library it takes skills, in `~/.agents/skills`. +- Obsidian (`obsidian` in [`obsidian.go`](../../internal/agent/obsidian.go); shirotokiren on X) has no AI of its own; magpie wires its plugin Copilot for Obsidian (logancyang/obsidian-copilot, plugin id `copilot`, 4.0 and later) in every vault that has it. The vaults come from Obsidian's `obsidian.json` (`vaults..path`) in `~/Library/Application Support/obsidian` (macOS), `%APPDATA%\obsidian` (Windows), or on Linux `$XDG_CONFIG_HOME/obsidian`, the Flatpak's `~/.var/app/md.obsidian.Obsidian/config/obsidian` and the Snap's `~/snap/obsidian/current/.config/obsidian`; a vault has Copilot when `.obsidian/plugins/copilot/manifest.json` is there. In its `data.json` magpie adds `providers.magpie` (`openai-compatible`, `baseUrl` the gateway's `/agent/obsidian/v1`, `requiresApiKey: false` and no keychain id, `enableCors: false` so Copilot streams through the window's fetch, answered by the gateway's CORS for `app://obsidian.md`), one `configuredModels` entry per magpie model (provider `magpie`, ids made from the model's, uuid v5, so a sync finds them again; limits, image input and reasoning efforts from the catalog), each new one in `backends.chat.enabledModels`, and on the first wire `defaultModelKey` (the old one kept in the stash). A sync keeps a model the user turned off off, their default, and the name and key they give the provider; it writes only the keys that change, through a temp file renamed over the old (`edit.PatchJSON`, `edit.WriteAtomic`), and nothing when nothing does. Disconnect takes out the provider, its models and their ids in every backend, and puts the default back when magpie's is still it. Copilot 3 (`activeModels`) is refused with a message to update it, and so is no vault with Copilot. Obsidian holds the settings in memory, so the notice (while it runs) says to reload Copilot or restart Obsidian. Smart Connections is not wired: its free plugin embeds with a local model only, and its API providers are in the closed Pro plugin, with keys in the keychain. - Antigravity, Google's desktop app (not Antigravity IDE, `com.google.antigravity-ide`), takes a gateway from `~/.antigravity/settings.json` from 2.15 on, and from `~/.gemini/config/config.json` (beside its `userSettings` and `plugins`) from 2.30 on, which reads only that file (YujunT46308 on X). magpie writes the same block into both, and a wiring made before 2.30 is carried into the new file at magpie's next start: Google's Antigravity Enterprise Gateway (docs.cloud.google.com/gemini/enterprise/docs/ai-developer-tools/connect-enterprise-gateway; `antigravity` in [`antigravity.go`](../../internal/agent/antigravity.go), ryougi_hachi on X). magpie writes `gateway` as `{enabled: true, url: , apiKey: , wireProtocol: openai}` and the model it starts on as `models.defaultModelId`, and takes out `models.list`, which would narrow the picker to the user's own. It also points `models.listSource`, the app's remote model catalog, at `/v1/models?format=antigravity` (`gateway.antigravityModels`): `{"list": [{modelId, displayName, maxTokens, maxOutputTokens, supportsImages, supportsThinking}]}`, the models the key may use. The backend (2.29.0) resolves models from `models.list`, then `listSource` (fetched with the gateway key), then `/v1/models`, then its built-in catalog. From `/v1/models` it reads the id alone, and a model its catalog doesn't know gets its family's defaults, a 200K window whatever the model's, so every magpie model had 200K (YujunT46308 on X); `context_window`, `context_length` and `max_input_tokens` there are not read. A bare array or `{"list": …}` is read; `{"models": …}` is not. A field magpie doesn't know is left out and the app's default stands. The picker shows `displayName`, so the names follow magpie's (`ListsModels`, not `NoNames`). The app's picker (its `main.js`, 2.29.0) offers effort only by grouping entries named ` (Low)`, `(Medium)`, `(High)`, `(XHigh)` or `(Max)` (its regex also takes `(Low thinking)`) under one row with an effort menu, two levels or more, starting on medium when a group has it, else the lowest; a model listed once had no effort control at all (YujunT46308 on X). So a model with two or more of those levels is listed once a level, `:` named ` ()` (`antigravityLevels`), and the request goes out under the chosen entry's id, whose `:level` suffix the gateway sends upstream ahead of the row's pick; the app's own `reasoning_effort` (`low` whatever was chosen, in a 2.29.0 run) loses to it. `models.defaultModelId` names one of those entries, since an id the catalog doesn't list starts the app on its first model: `gateway.AntigravityModel` adds the row's effort, fitted, else medium, else the lowest. The row's effort sets that start level (and is what a model with fewer than two levels is asked for); `Sync` moves a file written before onto a level, keeping a level already there. The model field shows the id without the level.`Sync` adds `listSource` to a file wired before, at the gateway's current address, stashing one of the user's. On the openai protocol the backend streams `/v1/chat/completions` with the key as a bearer token and a User-Agent of `antigravity/hub/`. The user's gateway, default model, list and `listSource` are stashed and put back on disconnect, or when a model of their own is picked; `caCertPath` and the rest of the file are never touched, and a `Sync` keeps what the user added to magpie's block (`customHeaders`). On a gateway the app uses no Google sign-in, and its backend asks Google for nothing (no `cloud_code_endpoint` or `api_server_url` call in a headless run): Google's docs say a gateway and a Google Account can't be used at once. What Google's servers turn on for a signed-in account, its experiments and the commands behind them (`/boost`, `/teamwork`, `/plugin`, `/generative_ui`, YujunT46308), is off while it is on magpie. No key in the file keeps both (`proxy` only routes the app's own HTTP), so the notice shown on connecting names what is lost and that turning it off gives it back. An organisation's `admin_settings.json` and the `AGY_LLM_GATEWAY_*` variables win over the file, so `Check` says when either sets a gateway. agy reads the same file below its own settings: an agy connected on its own row keeps its route, one that isn't follows the app's gateway, as the notice says. `~/.antigravity` is Antigravity IDE's and agy's too, so the app is found by its bundle at 2.15 or later (`desktopApps`) or `~/.gemini/antigravity/agyhub_summaries_proto.pb`, which only its backend writes. The app reads the file at start, so the notice asks for a restart. The Antigravity accounts magpie signs in (provider `antigravity`) are a separate thing: those send magpie's requests to Google. - NewMax (newmax.cc, an Electron app on the Claude Agent SDK) keeps its settings as JSON in the row `app` of the `settings` table of `newmax.db`, a SQLite database in WAL mode in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` on every system (`newMax` in [`newmax.go`](../../internal/agent/newmax.go); its main bundle's `configureAppDataPaths`, `loadPersistedAppSettings` and the renderer's `mergeProviders`, v1.1.22). magpie adds one entry to `providers` in the shape NewMax's own import writes, `id: magpie-gateway` (its own preset is `magpie`, its import's ids hold `%3A`), `apiFormat: anthropic` at the gateway's root (NewMax appends `/v1/messages`) with `ANTHROPIC_AUTH_TOKEN` and a key naming NewMax, at most 20 models (`MAX_MODELS`) as `models` and `enabledModels` with their context windows, and its id at the end of `providerOrder`. The row is edited in place in one immediate transaction, so every other byte stays; the user's `name` and `enabled` for magpie's entry and the fields NewMax adds to it stay through a sync, and a sync with nothing to change doesn't write. A row that isn't a JSON object, or whose `providers` or `providerOrder` isn't a list, is left alone. With no row (NewMax at its defaults), magpie writes one with its entry alone, as NewMax lays its defaults and presets under the row; with no database yet, it asks to open NewMax once. Disconnect takes the entry and the id out, sets a pick of it back to `default`, and takes the row out when only what magpie made is left. NewMax holds its settings in memory and writes the whole row back whenever one changes, so a change is refused while `NewMax` (`newmax` on Linux) runs (Windows can't be asked, so the notice says to quit it first). The model is picked in NewMax's model picker, so the field is whether magpie is in it (`ListsModels`). Detected by its data folder or `NewMax.app` (`cc.newmax.desktop`). - LiveAgent (Stack-Cairn/LiveAgent v2, a Tauri app) runs its models through K-brain, a Go backend it starts with its data folder, which keeps every provider in `config.json` there: `$LIVEAGENT_HOME`, else `$K_BRAIN_HOME`, else the folder `~/.liveagent/data-dir.json` points to (`{"path": …}`, set when the user moves LiveAgent's data), else `~/.liveagent` on every system (`liveAgent` in [`liveagent.go`](../../internal/agent/liveagent.go); LiveAgent's `data_home.rs` and `kbrain_backend.rs`, K-brain v0.107.12's `internal/config`). The file is JSONC in Pi's provider shape, decoded with unknown fields refused, so magpie writes only K-brain's fields. K-brain asks all of a provider's models on its one API, so magpie writes up to three providers and puts each model on the one of the API it is served on natively (`catalog.Model.APIs`, as dsh's routes): `providers.magpie-responses` for Responses and `providers.magpie` for every other OpenAI-side model (Chat Completions), each `type: codex` with `api` and `requestFormat` as LiveAgent's own settings write an OpenAI-compatible provider, `baseUrl` the gateway's `/v1` (K-brain appends only `/chat/completions` or `/responses`); `providers.magpie-anthropic` for Messages, `type: claude_code` and `api: anthropic-messages`, `baseUrl` the gateway's root (K-brain appends `/v1` and posts to `/messages` with `X-Api-Key`). LiveAgent's settings lock an Anthropic provider's API and let the user switch an OpenAI one between Chat Completions and Responses; a sync keeps the format they picked (Discord, xiaoxiaofei). A provider left with no model is taken out. Each has a key naming LiveAgent, `activeModels: null` (every model on), magpie's order as `modelOrder`, and `models` sorted by id as K-brain writes them, with each one's display name, context window, output limit and `input: [text, image]` when it takes images. Comments and every other key stay. Through a sync the user's name for each entry, the models they turned off (`activeModels`), their order and the fields K-brain adds (its `metadata`) stay; a model that moves to another of magpie's providers (a `config.json` from before, with every model on one Anthropic `magpie`) brings its name and off with it, and a pick of it follows; a model new to magpie's list is on and goes last, and a sync with nothing to change doesn't write. A model of magpie's the user deleted in LiveAgent, or a whole provider of magpie's, stays out until they put it back or magpie is turned off and on for LiveAgent (zero2sin on Discord: every sync, so every restart, wrote magpie's twenty or thirty models back): magpie keeps, per `config.json`, which of its models and providers LiveAgent has had (`liveAgentKept`, in the stash). One magpie added while LiveAgent ran is pending under the processes then (`liveAgentPIDs`), since LiveAgent's next save drops a model it never read: missing under those processes, or after they quit, it is written again; once other processes run it counts as had. On Windows, which can't be asked what runs, each counts as had at once. A default (or compact) model still K-brain's own, `model1` of its endpoint-less `demo` provider, becomes magpie's first; one the user picked stays. A file K-brain wouldn't read as providers (not an object, `providers` not an object, a top-level `models`, one provider written bare) is left alone. Disconnect takes magpie's entries out and a pick of them back to K-brain's default; a file left with no provider gets K-brain's `demo` back, since K-brain takes one with none as written over and restores `config.json.bak`, which can still hold magpie's; a file with nothing but what magpie made goes. LiveAgent's backend makes the file as `{}` when there is none (so a disconnect that takes the file away is undone the next start, harmlessly), reads it when it starts and writes it whole whenever a setting changes, so a change is refused while `liveagent` or `k-brain` runs (Windows can't be asked, so the notice says to quit it first). A model id another provider of the user's lists too has its metadata shared by K-brain, so a sync may write that model's limits back each time. The model is picked in LiveAgent's model picker, so the field is whether magpie is in it (`ListsModels`). Detected by its data folder, `LiveAgent.app` (`com.xiaofei.liveagent`) or its Windows install. Its logo is the app's own 64px icon (`src-tauri/icons/64x64.png`, MIT) in an SVG. @@ -223,6 +224,7 @@ go test -tags nogui ./internal/agent -run '^TestRaycast' go test -tags nogui ./internal/agent -run '^TestKiroCrew' go test -tags nogui ./internal/agent -run '^TestOpenPencil' go test -tags nogui ./internal/agent -run '^TestOpenBot' +go test -tags nogui ./internal/agent -run '^TestObsidian' go test -tags nogui ./internal/agent -run '^TestAntigravity' go test -tags nogui ./internal/gateway -run '^TestAntigravityCatalog' go test -tags nogui ./internal/agent -run '^TestNewMax' diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f04a2451f..7c345056e 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -30,7 +30,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | WSL under NAT | On Windows, while the gateway listens on loopback alone, `serveWSL` also serves it, in plain HTTP, at each address Windows has on a WSL network (`WSLNets`: the `vEthernet (WSL…)` adapters, looked for every 10s, since WSL's VM brings its adapter up and down). That is where a distro in NAT networking reaches Windows, and what `place` writes into its agents (zaidu259434 on X: Codex in WSL failed with sharing off). A distro in bridged networking is a peer on the LAN, and its default route is the LAN's router, not Windows: `wslrun.HostAt` takes Windows' address on the bridge's adapter (`vEthernet (WSL_Bridge_Switch)`), the one whose network holds that route (ecalpal_ on Discord). `lanGuard` takes a request there as this computer's (`fromWSL`) only when it arrives at that address, from inside that network, with the WSL key: `WSLKey`, a `wsl-` secret in magpie's folder (`wsl-key`, 0600), optionally followed by `-`. It becomes a loopback request carrying `magpie` or `magpie-` (`asFromLoopback`). A client that can only send its own key (Claude Science in WSL, which sends its Claude sign-in) puts the WSL key first in the path instead, `//v1/…`: `takeWSLPathKey` takes it off before `fromWSL` judges the request, and the request goes on without it. Anything else there, a Docker Desktop container on the same network included, is judged as another machine's. Windows' firewall still decides whether WSL gets in: WSL's network is a Public one. | [`wsl.go`](../../internal/gateway/wsl.go) | | TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) | | mTLS | With Settings → Network and sharing → Require a client certificate on (settings `MTLS`, `magpie mtls on`; hhdaxia on X, #5596), other computers reach the gateway and `magpie web`'s page only over TLS with a client certificate magpie's own CA (`internal/mtls`, `MTLSStore`: `ca.pem`, `ca-key.pem`, `clients.json` under the settings folder) issued and hasn't revoked. `tlsServer.config(strict)` is asked per connection, so the switch needs no relisten: without `--tls-cert` it serves a certificate the CA signs in memory for this computer's names, addresses and the SNI name (`ownServerCert`, made again when they or the CA change, or after a day), and with mTLS on even without `--tls-cert` the listener serves TLS. A peer that isn't this computer or a WSL distro (`fromWSLNet`) is asked `RequireAndVerifyClientCert` and its handshake ended when `VerifyConnection`'s `Admits` fails. The guards (`lanGuard`, and `ClientCertGuard` on the page) then refuse 403 every request `NeedsClientCert` names: plain HTTP, a proxy's or tunnel's on loopback (`proxied`, unless `MAGPIE_TRUST_PROXY=1` says the proxy checks certificates itself), the page port (`viaPagePort`), a connection made before the switch, a certificate revoked since its handshake. This computer (`local`, `ownAddress`) and a WSL agent with the WSL key (`fromWSL`) are answered as before. The Settings routes (`internal/gui/mtls.go`) never let a page from another computer shut itself out: without a certificate it can't turn mTLS on, and it can't revoke or issue again the certificate it came with (`pageCert`, `errOwnCert`). Not handled: a `.p12` for browsers, and a proxy that can't check certificates itself. `TestMTLSOtherComputerHandshake`, `TestMTLSGuardEveryRoute`, `TestMTLSThisComputerAndProxies`, `TestMTLSToggleWithoutRelisten`, `TestMTLSRevokeMidConnection`, `TestClientCertGuardPage`, `TestSettingsMTLSPageLockout`. | [`mtls.go`](../../internal/gateway/mtls.go), [`tls.go`](../../internal/gateway/tls.go), [`internal/mtls`](../../internal/mtls/mtls.go) | -| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/mcp/{name}`, `/mcp/magpie/web-search`, `/mcp/magpie/vision` and `/mcp/magpie/image` with its `/mcp/magpie/image/files/{name}` (magpie's own web search, image recognition and image generation as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`, and is answered ahead of everything below (`dumpFirst`, around `Handler`'s wrappers and around `lanGuard` in `Front`), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and `holdCatalog` takes `provider.Hold`'s and `filememo`'s, so a stuck holder of any of them would hold the dump too; a caller `goroutinesRefused` lets in is one those let in anyway, and any other goes through them as before (`TestGoroutineDumpAnswersWhileRequestsWait`). `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, in the mode its `settings.external_web_access` says (#5018; a ChatGPT account then searches by the same backend search, see [Which providers search for another model](#which-providers-search-for-another-model)), and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A WebSocket upgrade on `/v1/responses`, `/responses` or the Codex backend's `/responses` is Responses over a WebSocket, as Codex speaks it (below, [A Responses WebSocket](#a-responses-websocket)); one on another Codex backend path is answered 426, and a plain GET on `/v1/responses` 405. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. A browser sends a preflight without credentials, so a listed origin's preflight from another computer is let past `lanGuard`'s key check to be answered here (#4931, ggbdpq: a page on another machine got 401 to its preflight and never sent the keyed request); `lanGuard` hands on only an `OPTIONS` with `Access-Control-Request-Method` whose origin is listed (`corsAllowed`). Any other origin's preflight still meets the key check: `corsGuard` passes some unlisted origins on (loopback names, the request's own origin, other schemes), and Codex's backend relay would serve their `OPTIONS` on the user's sign-in (`TestCORSPreflightFromLANReachesNothing`). It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, each marked by `FromPagePort` so `local` is false for it (`viaPagePort`; `lanGuard` refuses it 403 while magpie isn't shared, saying to call the gateway's own address, and asks a gateway key otherwise): a raw TCP forward or a proxy with no forwarding header reaches that port from loopback, so no request there counts as an agent here (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | +| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), Ollama's `GET /api/version`, `GET /api/tags` and `POST /api/show` (`ollama.go`, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is `catalogFor`'s, so a key's models alone, `/api/show` tells `capabilities` (`completion`, `tools`, `vision` from `Images`, `thinking` from `Thinks`) and `model_info` with `general.architecture` `magpie`, `general.basename`, `magpie.context_length` (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the `general.parameter_count` and `magpie.embedding_length` the ollama CLI before 0.7 reads unchecked; a name ending `:latest`, as the ollama CLI asks, is the bare id unless a model is really called that (`ollamaName`); the client then chats on `/v1/chat/completions`, or on Ollama's own `POST /api/chat` and `POST /api/generate` (`ollama_chat.go`, Zed's Ollama provider, super_lalalalala on Discord), which `ollamaChatBody` turns into a `/v1/chat/completions` body handed to the same `handle(provider.Chat)` on a clone of the request, so they are routed, held to a key's models and counted as it is: `messages` with `images` (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's `thinking` as `reasoning_content` and its `tool_calls` given ids where Ollama sent none, a tool result matched to its call by `tool_call_id`, else `tool_name`, else in order (one with no call is a 400), `tools`, `format` (`json` or a schema), `think` (a level is `reasoning_effort`), and `options`' `temperature`, `top_p`, `seed`, `stop`, the two penalties and a positive `num_predict` as `max_tokens` (`num_ctx`, `top_k` and the rest of Ollama's own are dropped); `ollamaWriter` turns the reply into Ollama's NDJSON lines (streamed unless `stream:false`, then one object), tool calls with their `arguments` as an object and an `id`, and a last `done` line with `done_reason` and the token counts, and an error into `{"error":"…"}` with the status `/v1` would give; a request with no messages or prompt is answered `done_reason:"load"`, as Ollama does to warm a model), `/mcp/{name}`, `/mcp/magpie/web-search`, `/mcp/magpie/vision` and `/mcp/magpie/image` with its `/mcp/magpie/image/files/{name}` (magpie's own web search, image recognition and image generation as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/magpie/heap` (`heapProfile`, [`heap.go`](../../internal/gateway/heap.go), for `magpie heap`) is held tighter than the rest by `heapRefused` in the handler itself, so it holds where `Handler` is served without `lanGuard` too: only a loopback caller that isn't proxied (`local`), carries no browser mark (`fromBrowser`) and names a loopback `Host` (`loopbackHost`) gets the profile; a gateway key never lets anything else in. `/v1/magpie/cpu` (`cpuProfile`, [`cpu.go`](../../internal/gateway/cpu.go), for `magpie cpu`) records a CPU profile for `?seconds=` (30, from 5 to 120) and is held to the same callers by `cpuRefused`, which shares `profileRefused` with `heapRefused`; one profile records at a time (`cpuRecording`), a second is answered 409, and a caller that hangs up stops it. `/v1/magpie/goroutines` (`goroutineDump`, [`goroutines.go`](../../internal/gateway/goroutines.go), for `magpie goroutines`, #3362) answers every goroutine's stack and wait as text (`runtime/pprof`'s `goroutine` profile at debug 2) to the same callers, through `goroutinesRefused`, and is answered ahead of everything below (`dumpFirst`, around `Handler`'s wrappers and around `lanGuard` in `Front`), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and `holdCatalog` takes `provider.Hold`'s and `filememo`'s, so a stuck holder of any of them would hold the dump too; a caller `goroutinesRefused` lets in is one those let in anyway, and any other goes through them as before (`TestGoroutineDumpAnswersWhileRequestsWait`). `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, in the mode its `settings.external_web_access` says (#5018; a ChatGPT account then searches by the same backend search, see [Which providers search for another model](#which-providers-search-for-another-model)), and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A WebSocket upgrade on `/v1/responses`, `/responses` or the Codex backend's `/responses` is Responses over a WebSocket, as Codex speaks it (below, [A Responses WebSocket](#a-responses-websocket)); one on another Codex backend path is answered 426, and a plain GET on `/v1/responses` 405. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. A browser sends a preflight without credentials, so a listed origin's preflight from another computer is let past `lanGuard`'s key check to be answered here (#4931, ggbdpq: a page on another machine got 401 to its preflight and never sent the keyed request); `lanGuard` hands on only an `OPTIONS` with `Access-Control-Request-Method` whose origin is listed (`corsAllowed`). Any other origin's preflight still meets the key check: `corsGuard` passes some unlisted origins on (loopback names, the request's own origin, other schemes), and Codex's backend relay would serve their `OPTIONS` on the user's sign-in (`TestCORSPreflightFromLANReachesNothing`). It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before. Obsidian's `app://obsidian.md` (`appOrigin`) is also answered with CORS headers, keyless: Copilot for Obsidian streams through its window's fetch, which reads no reply without them, and the origin is one only Obsidian's own window sends, so it gets no more than its calls without an Origin get, and from the network it still needs a key (`TestCORSObsidian`, shirotokiren on X); `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`, this computer's own, never brought by a sync or restore: see [sync and backup](sync-backup.md#what-stays-on-each-computer); the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`), and its port hands the gateway's client routes (`ClientPath`) to `Server.Front`, the same lanGuard-over-Handler the gateway's listener serves, each marked by `FromPagePort` so `local` is false for it (`viaPagePort`; `lanGuard` refuses it 403 while magpie isn't shared, saying to call the gateway's own address, and asks a gateway key otherwise): a raw TCP forward or a proxy with no forwarding header reaches that port from loopback, so no request there counts as an agent here (`TestClientPathCoversHandler` fails when a route Handler adds is in neither `ClientPath` nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`ollama.go`](../../internal/gateway/ollama.go), [`ollama_chat.go`](../../internal/gateway/ollama_chat.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider — in a WSL distro, the distro's own, of the ones running now — for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key; a memory call first waits beside the turn it was started with, through `codexLeads`, see the side turns below), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id the asking agent's own subscription in magpie serves (a provider whose `Account.Agent` is the agent: Codex's ChatGPT accounts for Codex, Claude's for Claude Code) goes to that subscription first, found groups on or off (`ownFirst`, `provider.OwnRoute`; freefcw on X: Codex's bare `gpt-6-astra` went to Devin through `auto-gpt-6-astra`, whose soonest-renewing member came first, and with found groups off to the first provider in the order). Not for a group the user made or changed by that name, a found group magpie set one of the agent's fields to (`SetToGroup`, `agent.SetToGroup` over the agent's applied record, #750's bare spelling included), a gateway key held to some models, or a client magpie doesn't know as an agent; an auto stand-in and `agent.Reseat` prefer the agent's own subscription the same way (`AutoStandInFor`, `sameModel`). Otherwise a bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api): with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, an agent with a subscription of its own in magpie is refused it with a 400 naming the providers' ids and `magpie group auto on` (`provider.OffSpread`, `offSpreadRefused`): off, magpie picks no vendor for it. Any other client still gets the first provider in the Providers order that exposes it (`Resolve`), with no fallback. A provider the user keeps out of found groups (Routing's "Leave out a provider", `provider.SetAutoGroupSkip`, `autoGroupSkip` in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (`AutoStandIn`), and an agent set to it is moved there (`agent.Reseat`). magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (`catalog.Spelling`, its `normal` index: `glm-5.3-flash` whether the members serve `glm-5-3-flash`, Ark's dated id or `glm-5.3-flash`), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (`autoGroups`): the name models.dev gives that spelling (`catalog.NameOf`), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of `glm-5-3-flash` beside `auto/glm-5.3-flash` (XYenon on Discord, `TestFoundGroupIDAndNameAreOneSpelling`). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (`CanonicalRef`), and `PublicRef` takes one to the spelling now. Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-`, or to an `auto/` spelt otherwise than the group is listed now, moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`, `TestFoundGroupMovedOffAnOldSpelling`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | | A model's own id at a provider | A model the user lists by an id of theirs at a provider (a signed-in account's and a plugin's too; settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log, recent calls and the Routing page keep as `served`; the agent gets the id it asked for back in the reply, in every protocol, streamed or whole (`memberWriter` in [`member.go`](../../internal/gateway/member.go), `replyNamingOf`: the reply's `model`, Responses' `response.model`, Anthropic's `message.model`, Gemini's `modelVersion`; issennknight on Discord, whose agent warned that `deepseek-v4.1-flash` came back as `deepseek-v4.1-flash-1017`). The same holds for a group or a `provider/model` id the vendor knows by another name. A reply whose vendor sent the wire name as asked keeps the vendor's name (a dated `-20261017` included). Settings' `replyModel` (Settings › Models › Replies › Model name in replies) picks for every request: `""` the model asked for, `member` the group's member, `vendor` the vendor's own name, as before the asked-for name, each for every agent, Claude Code, Claude Desktop and Codex included (ZoeCats on Discord: in v0.1.2760 `member` still gave those three the model asked for; `TestPluginReplyNamesMember` holds it on a plugin too). A file from before it with `memberModel` on reads as `member`, and `memberModel` is written beside `replyModel` for an older magpie (`normal` in settings.go; `Merge` in settingsapi takes an older page's `memberModel` only when its switch moved). A request's `X-Magpie-Response-Model` (`asked`, `member` or `vendor`) overrides the setting for that request, for every agent (`TestReplyNamesAskedModel`, `TestGeminiReplyNamesAskedModel`, `TestReplyNamesMember`, `TestReplyModelFoldsMemberModel`, `TestReplyModelSaves`). A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's `--model`, Antigravity's variant, and which accounts list it and at what levels (`TestLocalModelIDAtAPlugin`, `TestLocalModelIDAtAClaudeAccount`, `TestLocalModelIDAtAnAntigravityAccount`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 7253c4355..6a119d6fb 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -317,6 +317,7 @@ func onMachine(home, cfg string) []*Agent { openPencil(home, cfg), openBot(home, cfg), craftAgents(home), + obsidian(home, cfg), newMax(home), liveAgent(home), raycast(home), diff --git a/internal/agent/obsidian.go b/internal/agent/obsidian.go new file mode 100644 index 000000000..41f94bed0 --- /dev/null +++ b/internal/agent/obsidian.go @@ -0,0 +1,594 @@ +package agent + +// Obsidian (obsidian.md) has no AI of its own: its community plugins bring +// it. magpie wires the one that takes an OpenAI-compatible endpoint the +// user names, Copilot for Obsidian (logancyang/obsidian-copilot, plugin id +// "copilot"), in every vault that has it (shirotokiren on X). +// +// Obsidian lists its vaults in obsidian.json in its config folder: +// ~/Library/Application Support/obsidian on a Mac, %APPDATA%\obsidian on +// Windows, $XDG_CONFIG_HOME/obsidian on Linux, or the Flatpak's and the +// Snap's own config folders. The file is {"vaults": {"": {"path": +// "", "ts": …, "open": true}}}. A plugin keeps its settings +// in /.obsidian/plugins//data.json, which Obsidian reads when +// the plugin loads and writes whole from what the plugin holds whenever it +// saves. +// +// Copilot 4 (settingsVersion 4 and on; 4.0.19's src/settings/model.ts and +// src/modelManagement/types/persisted.ts) keeps its endpoints there as +// +// "providers": {"": {"providerId", "providerType": "openai-compatible", +// "displayName", "baseUrl", "enableCors", "apiKeyKeychainId", +// "requiresApiKey", "origin": {"kind": "byok"}, "addedAt"}}, +// "configuredModels": [{"configuredModelId", "providerId", +// "info": {"id", "displayName", "limits", "modalities", "reasoning", …}, +// "configuredAt"}], +// "backends": {"chat": {"enabledModels": ["", …]}}, +// "defaultModelKey": "" +// +// A key lives in Obsidian's keychain (apiKeyKeychainId), which magpie +// doesn't write, so magpie's provider has none: requiresApiKey false is +// Copilot's keyless custom endpoint (optionalCustomProviderAuthMigration), +// whose requests carry no Authorization, and the gateway takes a call +// with no key from this computer. Copilot calls it from Obsidian's window +// with its fetch, so the reply streams; the gateway answers that window's +// CORS (appOrigin). The address names Obsidian, /agent/obsidian, since the +// window's User-Agent is a browser's. +// +// magpie's provider is "magpie", its models' ids are made from theirs, so +// a sync finds them again: a model the user turned off in Copilot stays +// off, a new one comes on, one gone goes with its place in every backend. +// The first time, Copilot's default model becomes magpie's first, and +// what it was is kept in the stash to put back when magpie is turned off. +// Everything else in the file stays as written. +// +// Copilot 3 kept models in activeModels, which Copilot 4 moves to +// providers when it first loads; magpie writes only Copilot 4's, so a +// vault with Copilot 3 is left alone and named in the error. +// +// Smart Connections (brianpetro) is not wired: its free plugin embeds +// with a local model only (obsidian-smart-env's embedding_models.js), and +// its API providers are in the closed Pro plugin, keys in the keychain. + +import ( + "crypto/sha1" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "slices" + "sort" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/gateway" +) + +// obsidianApp is Obsidian's macOS bundle. +var obsidianApp = desktopApp{id: "md.obsidian", names: []string{"Obsidian.app"}} + +// obsidianProc is Obsidian's process: the .app's Obsidian, the .exe's, the +// AppImage's and the packages' obsidian. +var obsidianProc = []string{`(^|/)(Obsidian|obsidian)( |$)`} + +// obsCopilotPlugin is Copilot for Obsidian's plugin id (its manifest.json). +const obsCopilotPlugin = "copilot" + +// obsCopilotMagpie is magpie's provider id in Copilot's providers. +const obsCopilotMagpie = magpieID + +// obsCopilotModelSpace makes magpie's configured model ids in Copilot, one +// per model id, the same on every sync (uuid v5 of "magpie/"). +var obsCopilotModelSpace = uuid.NewSHA1(uuid.NameSpaceURL, []byte("https://usemagpie.ai/obsidian/copilot")) + +var noticeObsidian = newNotice("Obsidian holds Copilot's settings while it runs — reload Copilot in Settings › Community plugins (or restart Obsidian) to see magpie's models, before changing Copilot's settings there.") + +func obsidian(home, cfg string) *Agent { + dirs := obsidianDirs(home, cfg) + dir := dirs[0] + for _, d := range dirs { + if isFile(filepath.Join(d, "obsidian.json")) { + dir = d + break + } + } + vaults := obsidianVaults(dirs) + var paths []string + for _, v := range vaults { + paths = append(paths, obsCopilotData(v)) + } + wired := func() bool { + return slices.ContainsFunc(vaults, func(v string) bool { return obsCopilotWired(obsCopilotData(v)) }) + } + write := func(on bool) error { + var errs []error + n := 0 + for _, v := range vaults { + if !obsCopilotHere(v) { + continue + } + p := obsCopilotData(v) + var err error + if on { + err = obsCopilotWire(p, gateway.URL()) + } else { + err = obsCopilotUnwire(p) + } + if err != nil { + errs = append(errs, err) + continue + } + n++ + } + if on && n == 0 && len(errs) == 0 { + return errors.New("no Obsidian vault here has Copilot for Obsidian: install Copilot from Obsidian's Settings › Community plugins first") + } + return errors.Join(errs...) + } + return atomic(&Agent{ + ID: "obsidian", Name: "Obsidian", Icon: "obsidian", Aliases: []string{"obsidian-copilot"}, + Dir: dir, Path: filepath.Join(dir, "obsidian.json"), + detect: func() bool { + return slices.ContainsFunc(dirs, isDir) || macBundle(obsidianApp) + }, + Notice: func() string { + if wired() && Running(obsidianProc...) { + return noticeObsidian.String() + } + return "" + }, + // a sync brings magpie's models up to date in each vault it is in, + // and wires no vault the user hasn't asked for + Sync: func() error { + var errs []error + for _, v := range vaults { + if p := obsCopilotData(v); obsCopilotWired(p) { + errs = append(errs, obsCopilotWire(p, gateway.URL())) + } + } + return errors.Join(errs...) + }, + ListsModels: true, + Fields: []Field{{ + Key: "provider", Label: "provider", + Get: func() string { + if wired() { + return magpieID + } + return "" + }, + Set: func(v string) error { return write(v != "") }, + Options: func(map[string]string) []Option { + return []Option{{Value: magpieID, Label: "magpie", Icon: "magpie", Note: "every magpie model in Copilot for Obsidian, in each vault that has it"}} + }, + }}, + }, paths...) +} + +// obsidianDirs are the folders Obsidian may keep obsidian.json in here, +// the one it uses on this system first. +func obsidianDirs(home, cfg string) []string { + return obsidianDirsOn(runtime.GOOS, home, cfg, appdir.Getenv("APPDATA")) +} + +// obsidianDirsOn is obsidianDirs on the system goos, with the +// XDG_CONFIG_HOME folder cfg and %APPDATA% appData. +func obsidianDirsOn(goos, home, cfg, appData string) []string { + switch goos { + case "darwin": + return []string{filepath.Join(home, "Library", "Application Support", "obsidian")} + case "windows": + d := appData + if d == "" { + d = filepath.Join(home, "AppData", "Roaming") + } + return []string{filepath.Join(d, "obsidian")} + } + return []string{ + filepath.Join(cfg, "obsidian"), + filepath.Join(home, ".var", "app", "md.obsidian.Obsidian", "config", "obsidian"), + filepath.Join(home, "snap", "obsidian", "current", ".config", "obsidian"), + } +} + +// obsidianVaults are the vault folders obsidian.json in dirs lists that +// are still there, each once, in the order of their ids. +func obsidianVaults(dirs []string) []string { + var out []string + for _, d := range dirs { + b, err := edit.Read(filepath.Join(d, "obsidian.json")) + if err != nil || len(b) == 0 { + continue + } + var doc struct { + Vaults map[string]struct { + Path string `json:"path"` + } `json:"vaults"` + } + if json.Unmarshal(b, &doc) != nil { + continue + } + ids := make([]string, 0, len(doc.Vaults)) + for id := range doc.Vaults { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + p := doc.Vaults[id].Path + if p == "" || !isDir(p) || slices.Contains(out, filepath.Clean(p)) { + continue + } + out = append(out, filepath.Clean(p)) + } + } + return out +} + +// obsCopilotDir is Copilot's plugin folder in vault. +func obsCopilotDir(vault string) string { + return filepath.Join(vault, ".obsidian", "plugins", obsCopilotPlugin) +} + +// obsCopilotData is Copilot's settings file in vault. +func obsCopilotData(vault string) string { return filepath.Join(obsCopilotDir(vault), "data.json") } + +// obsCopilotHere says vault has Copilot installed. +func obsCopilotHere(vault string) bool { + return isFile(filepath.Join(obsCopilotDir(vault), "manifest.json")) +} + +// obsCopilotWired says the settings file at path has magpie's provider. +func obsCopilotWired(path string) bool { + b, err := edit.Read(path) + return err == nil && obsCopilotOurs(gjson.GetBytes(b, "providers."+obsCopilotMagpie)) +} + +// obsCopilotOurs says a provider named magpie in Copilot's settings is the +// one magpie wrote: its baseUrl is magpie's Obsidian route, on whatever +// port. One the user added by hand under that name is theirs, and magpie +// neither counts it as connected nor takes it out. +func obsCopilotOurs(p gjson.Result) bool { + return p.IsObject() && strings.HasSuffix(strings.TrimRight(p.Get("baseUrl").String(), "/"), "/agent/obsidian/v1") +} + +// obsCopilotRead is the settings file at path as a map, with the version of +// the Copilot installed beside it; a file that isn't there or holds +// nothing is an empty one. A file Copilot wouldn't read, or one Copilot 3 +// writes, is an error, and magpie leaves it alone. +func obsCopilotRead(path string) (map[string]json.RawMessage, []byte, error) { + dir := filepath.Dir(path) + if v := obsCopilotMajor(filepath.Join(dir, "manifest.json")); v > 0 && v < 4 { + return nil, nil, fmt.Errorf("%s is Copilot %d: magpie sets Copilot for Obsidian 4 and later — update it in Obsidian's Settings › Community plugins", dir, v) + } + b, err := edit.Read(path) + if err != nil { + return nil, nil, err + } + doc := map[string]json.RawMessage{} + if strings.TrimSpace(string(b)) == "" { + return doc, b, nil + } + if err := json.Unmarshal(b, &doc); err != nil || doc == nil { + return nil, nil, fmt.Errorf("%s isn't JSON Copilot reads, so magpie leaves it alone", path) + } + return doc, b, nil +} + +// obsCopilotMajor is the major version manifest.json at path says, 0 when it +// says none. +func obsCopilotMajor(path string) int { + b, err := edit.Read(path) + if err != nil { + return 0 + } + v := gjson.GetBytes(b, "version").String() + major, _, _ := strings.Cut(v, ".") + n, _ := strconv.Atoi(major) + return n +} + +// obsCopilotProvider is magpie's entry of providers, for a gateway at gw. +type obsCopilotProvider struct { + ProviderID string `json:"providerId"` + ProviderType string `json:"providerType"` + DisplayName string `json:"displayName"` + BaseURL string `json:"baseUrl"` + EnableCors bool `json:"enableCors"` + APIKeyKeychainID *string `json:"apiKeyKeychainId"` + RequiresAPIKey bool `json:"requiresApiKey"` + Origin json.RawMessage `json:"origin"` + AddedAt int64 `json:"addedAt"` +} + +// obsCopilotModelInfo is a configured model's info (ModelInfo, catalog.ts). +type obsCopilotModelInfo struct { + ID string `json:"id"` + DisplayName string `json:"displayName"` + Modalities *obsMods `json:"modalities,omitempty"` + Limits *obsLimits `json:"limits,omitempty"` + Reasoning bool `json:"reasoning,omitempty"` + ReasoningEfforts []string `json:"reasoningEfforts,omitempty"` +} + +type obsMods struct { + Input []string `json:"input,omitempty"` + Output []string `json:"output,omitempty"` +} + +type obsLimits struct { + Context int `json:"context,omitempty"` + Output int `json:"output,omitempty"` +} + +// obsCopilotModel is an entry of configuredModels. +type obsCopilotModel struct { + ConfiguredModelID string `json:"configuredModelId"` + ProviderID string `json:"providerId"` + Info obsCopilotModelInfo `json:"info"` + ConfiguredAt int64 `json:"configuredAt"` +} + +// obsCopilotModelID is magpie's configured model id in Copilot for the model +// id. +func obsCopilotModelID(id string) string { + return uuid.NewHash(sha1.New(), obsCopilotModelSpace, []byte("magpie/"+id), 5).String() +} + +// obsCopilotModels are magpie's models as Copilot's configured models. +func obsCopilotModels(now int64) []obsCopilotModel { + var out []obsCopilotModel + seen := map[string]bool{} + for _, m := range sharedModels("obsidian") { + if m.ID == "" || seen[m.ID] { + continue + } + seen[m.ID] = true + info := obsCopilotModelInfo{ID: m.ID, DisplayName: m.Name} + if info.DisplayName == "" { + info.DisplayName = m.ID + } + in := []string{"text"} + if m.Images { + in = append(in, "image") + } + info.Modalities = &obsMods{Input: in, Output: []string{"text"}} + if m.Context > 0 || m.Output > 0 { + info.Limits = &obsLimits{Context: m.Context, Output: m.Output} + } + if len(m.Efforts) > 0 { + info.Reasoning = true + info.ReasoningEfforts = slices.Clone(m.Efforts) + } + out = append(out, obsCopilotModel{ConfiguredModelID: obsCopilotModelID(m.ID), ProviderID: obsCopilotMagpie, Info: info, ConfiguredAt: now}) + } + return out +} + +// stashKey is where the default model Copilot had in the vault of the +// settings file at path is kept while magpie's is. +func obsCopilotStashKey(path string) string { return "obsidian.copilot.default:" + path } + +// obsCopilotWire puts magpie's provider and models into the settings file at +// path for a gateway at gw, and writes it only when that changes it. +func obsCopilotWire(path, gw string) error { + doc, raw, err := obsCopilotRead(path) + if err != nil { + return err + } + now := time.Now().UnixMilli() + + providers := map[string]json.RawMessage{} + if raw, ok := doc["providers"]; ok && json.Unmarshal(raw, &providers) != nil { + return fmt.Errorf("%s: providers is not an object", path) + } + first := providers[obsCopilotMagpie] == nil + if !first && !obsCopilotOurs(gjson.ParseBytes(providers[obsCopilotMagpie])) { + return fmt.Errorf("%s: Copilot has a provider of its own named magpie, at another address — rename it in Copilot's settings, and magpie adds its own", path) + } + want := obsCopilotProvider{ + ProviderID: obsCopilotMagpie, ProviderType: "openai-compatible", DisplayName: "magpie", + BaseURL: gateway.AgentURL(gw, "obsidian") + "/v1", RequiresAPIKey: false, + Origin: json.RawMessage(`{"kind":"byok"}`), AddedAt: now, + } + if !first { + old := gjson.ParseBytes(providers[obsCopilotMagpie]) + if n := old.Get("displayName").String(); n != "" { + want.DisplayName = n + } + if a := old.Get("addedAt"); a.Type == gjson.Number { + want.AddedAt = a.Int() + } + if k := old.Get("apiKeyKeychainId"); k.Type == gjson.String { + s := k.String() + want.APIKeyKeychainID = &s + } + } + + // the user's models as written, magpie's made again + var list []json.RawMessage + if raw, ok := doc["configuredModels"]; ok && json.Unmarshal(raw, &list) != nil { + return fmt.Errorf("%s: configuredModels is not a list", path) + } + had := map[string]gjson.Result{} + var kept []json.RawMessage + for _, e := range list { + if gjson.GetBytes(e, "providerId").String() == obsCopilotMagpie { + had[gjson.GetBytes(e, "configuredModelId").String()] = gjson.ParseBytes(e) + continue + } + kept = append(kept, e) + } + ms := obsCopilotModels(now) + ours := map[string]bool{} + for i, m := range ms { + ours[m.ConfiguredModelID] = true + if h, ok := had[m.ConfiguredModelID]; ok { + if a := h.Get("configuredAt"); a.Type == gjson.Number { + ms[i].ConfiguredAt = a.Int() + } + } + b, _ := json.Marshal(ms[i]) + kept = append(kept, b) + } + if len(ms) == 0 { + return errors.New("magpie has no models to give Copilot for Obsidian: add a provider in magpie first") + } + + // each backend's enabled models: the user's as they were, magpie's that + // were on still on, magpie's gone out, and in chat magpie's new ones on + sets := []edit.KV{ + {Path: "providers." + obsCopilotMagpie, Value: want}, + {Path: "configuredModels", Value: kept}, + } + backends := map[string]json.RawMessage{} + if b, ok := doc["backends"]; ok && json.Unmarshal(b, &backends) != nil { + return fmt.Errorf("%s: backends is not an object", path) + } + for name, b := range backends { + ids, ok, err := obsCopilotEnabled(b) + if err != nil { + return fmt.Errorf("%s: backends.%s: %w", path, name, err) + } + if !ok && name != "chat" { + continue + } + var next []string + for _, id := range ids { + if _, mine := had[id]; mine && !ours[id] { + continue + } + next = append(next, id) + } + if name == "chat" { + for _, m := range ms { + if _, before := had[m.ConfiguredModelID]; !before && !slices.Contains(next, m.ConfiguredModelID) { + next = append(next, m.ConfiguredModelID) + } + } + } + if next == nil { + next = []string{} + } + sets = append(sets, edit.KV{Path: "backends." + obsJSONKey(name) + ".enabledModels", Value: next}) + } + if _, ok := backends["chat"]; !ok { + var ids []string + for _, m := range ms { + ids = append(ids, m.ConfiguredModelID) + } + sets = append(sets, edit.KV{Path: "backends.chat.enabledModels", Value: ids}) + } + + def := gjson.GetBytes(doc["defaultModelKey"], "@this").String() + switch { + case first: + stash(map[string]string{obsCopilotStashKey(path): def}) + sets = append(sets, edit.KV{Path: "defaultModelKey", Value: ms[0].ConfiguredModelID}) + case def != "" && !ours[def]: + if _, mine := had[def]; mine { + // the default was a magpie model that is gone + sets = append(sets, edit.KV{Path: "defaultModelKey", Value: ms[0].ConfiguredModelID}) + } + } + return obsCopilotPatch(path, raw, sets, nil) +} + +// obsCopilotEnabled is a backend's enabledModels, and whether it has them. +func obsCopilotEnabled(raw json.RawMessage) ([]string, bool, error) { + e := gjson.GetBytes(raw, "enabledModels") + if !e.Exists() { + return nil, false, nil + } + var ids []string + if err := json.Unmarshal([]byte(e.Raw), &ids); err != nil { + return nil, false, errors.New("enabledModels is not a list of ids") + } + return ids, true, nil +} + +// obsCopilotPatch sets set and deletes del in the settings file at path, read +// before as raw, and writes it, through a temp file renamed over it, only +// when that changes something: each key the user wrote stays as written. +func obsCopilotPatch(path string, raw []byte, set []edit.KV, del []string) error { + var change []edit.KV + for _, kv := range set { + cur := gjson.GetBytes(raw, kv.Path) + if cur.Exists() && sameJSON(cur.Raw, kv.Value) { + continue + } + change = append(change, kv) + } + var gone []string + for _, k := range del { + if gjson.GetBytes(raw, k).Exists() { + gone = append(gone, k) + } + } + if len(change) == 0 && len(gone) == 0 { + return nil + } + out, err := edit.PatchJSON(raw, change, gone) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + return edit.WriteAtomic(path, out) +} + +// obsCopilotUnwire takes magpie's provider, its models and their places out +// of the settings file at path, and puts back the default model Copilot +// had before when magpie's is still it. +func obsCopilotUnwire(path string) error { + if !obsCopilotWired(path) { + return nil + } + doc, raw, err := obsCopilotRead(path) + if err != nil { + return err + } + var list, kept []json.RawMessage + json.Unmarshal(doc["configuredModels"], &list) + mine := map[string]bool{} + for _, e := range list { + if gjson.GetBytes(e, "providerId").String() == obsCopilotMagpie { + mine[gjson.GetBytes(e, "configuredModelId").String()] = true + continue + } + kept = append(kept, e) + } + if kept == nil { + kept = []json.RawMessage{} + } + sets := []edit.KV{{Path: "configuredModels", Value: kept}} + backends := map[string]json.RawMessage{} + json.Unmarshal(doc["backends"], &backends) + for name, b := range backends { + ids, ok, err := obsCopilotEnabled(b) + if err != nil || !ok { + continue + } + next := slices.DeleteFunc(slices.Clone(ids), func(id string) bool { return mine[id] }) + if next == nil { + next = []string{} + } + sets = append(sets, edit.KV{Path: "backends." + obsJSONKey(name) + ".enabledModels", Value: next}) + } + before := unstash(obsCopilotStashKey(path)) + if def := gjson.GetBytes(doc["defaultModelKey"], "@this").String(); mine[def] { + sets = append(sets, edit.KV{Path: "defaultModelKey", Value: before}) + } + return obsCopilotPatch(path, raw, sets, []string{"providers." + obsCopilotMagpie}) +} + +// obsJSONKey is name as one key of a JSON key path. +func obsJSONKey(name string) string { return strings.ReplaceAll(name, ".", `\.`) } diff --git a/internal/agent/obsidian_test.go b/internal/agent/obsidian_test.go new file mode 100644 index 000000000..ab582912e --- /dev/null +++ b/internal/agent/obsidian_test.go @@ -0,0 +1,466 @@ +package agent + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" +) + +// obsCopilotUser is a vault's .obsidian/plugins/copilot/data.json as Copilot +// for Obsidian 4.0.19 saves it (src/settings/model.ts, CopilotSettings, and +// src/modelManagement/types/persisted.ts): an OpenAI key in the keychain, +// an Ollama endpoint with no key, models of both, the chat backend's +// picker and an agent backend's, and settings magpie has no business with. +const obsCopilotUser = `{ + "userId": "8f1c2d3e-0000-4000-8000-000000000001", + "isPlusUser": false, + "defaultChainType": "llm_chain", + "defaultModelKey": "1b7c5a52-6d0e-4c1d-9b0e-3f6c2a1d0e01", + "embeddingModelKey": "text-embedding-3-small|openai", + "temperature": 0.1, + "maxTokens": 6000, + "contextTurns": 15, + "defaultSaveFolder": "copilot/copilot-conversations", + "enableEncryption": false, + "debug": false, + "settingsVersion": 16, + "_keychainVaultId": "vault-9a8b7c", + "agentMode": { + "byok": {}, + "activeBackend": "opencode", + "backends": {"opencode": {"defaultModel": null}}, + "debugFullFrames": false, + "offerFeedbackCards": true, + "notificationSound": false, + "notificationSoundId": "chime", + "skills": {"folder": "copilot/skills"} + }, + "providers": { + "openai": { + "providerId": "openai", + "providerType": "openai", + "displayName": "OpenAI", + "apiKeyKeychainId": "copilot-provider-openai", + "origin": {"kind": "byok", "catalogProviderId": "openai"}, + "addedAt": 1781000000000 + }, + "6d1e2f3a-4b5c-4d6e-8f70-819203a4b5c6": { + "providerId": "6d1e2f3a-4b5c-4d6e-8f70-819203a4b5c6", + "providerType": "openai-compatible", + "displayName": "Ollama", + "baseUrl": "http://localhost:11434/v1", + "enableCors": true, + "apiKeyKeychainId": null, + "requiresApiKey": false, + "origin": {"kind": "byok"}, + "addedAt": 1781000001000 + } + }, + "configuredModels": [ + { + "configuredModelId": "1b7c5a52-6d0e-4c1d-9b0e-3f6c2a1d0e01", + "providerId": "openai", + "info": {"id": "gpt-5.1", "displayName": "GPT-5.1", "limits": {"context": 400000, "output": 128000}, "reasoning": true}, + "configuredAt": 1781000000500 + }, + { + "configuredModelId": "2c8d6b63-7e1f-4d2e-8c1f-4a7d3b2e1f02", + "providerId": "6d1e2f3a-4b5c-4d6e-8f70-819203a4b5c6", + "info": {"id": "qwen3:8b", "displayName": "qwen3:8b"}, + "configuredAt": 1781000001500 + } + ], + "backends": { + "chat": {"enabledModels": ["1b7c5a52-6d0e-4c1d-9b0e-3f6c2a1d0e01", "2c8d6b63-7e1f-4d2e-8c1f-4a7d3b2e1f02"]}, + "opencode": {"enabledModels": ["2c8d6b63-7e1f-4d2e-8c1f-4a7d3b2e1f02"]} + }, + "copilotPlusCatalog": {"models": [], "defaultEnabledIds": []}, + "connectors": [], + "customConnectors": [] +} +` + +// obsCopilotManifest is Copilot's manifest.json at version v. +func obsCopilotManifest(v string) string { + return `{"id": "copilot", "name": "Copilot", "version": "` + v + `", "minAppVersion": "1.7.2", "author": "Logan Yang"}` +} + +// obsidianVault makes a vault at dir listed in the obsidian.json in cfgDir, +// with Copilot at version v (none when v is "") and its data.json data +// (none when data is ""). +func obsidianVault(t *testing.T, cfgDir, id, dir, v, data string) string { + t.Helper() + os.MkdirAll(filepath.Join(dir, ".obsidian"), 0o755) + if v != "" { + os.MkdirAll(obsCopilotDir(dir), 0o755) + os.WriteFile(filepath.Join(obsCopilotDir(dir), "manifest.json"), []byte(obsCopilotManifest(v)), 0o644) + if data != "" { + os.WriteFile(obsCopilotData(dir), []byte(data), 0o644) + } + } + os.MkdirAll(cfgDir, 0o755) + p := filepath.Join(cfgDir, "obsidian.json") + doc := map[string]any{} + if b, err := os.ReadFile(p); err == nil { + json.Unmarshal(b, &doc) + } + vs, _ := doc["vaults"].(map[string]any) + if vs == nil { + vs = map[string]any{} + } + vs[id] = map[string]any{"path": dir, "ts": 1781000000000, "open": true} + doc["vaults"] = vs + b, _ := json.Marshal(doc) + os.WriteFile(p, b, 0o644) + return obsCopilotData(dir) +} + +// obsCopilotDoc is the settings file at path, read as Copilot reads it. +type obsCopilotDoc struct { + DefaultModelKey string `json:"defaultModelKey"` + Providers map[string]json.RawMessage `json:"providers"` + ConfiguredModels []obsCopilotModel `json:"configuredModels"` + Backends map[string]struct { + EnabledModels []string `json:"enabledModels"` + } `json:"backends"` +} + +func obsReadCopilot(t *testing.T, path string) (obsCopilotDoc, map[string]json.RawMessage) { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var d obsCopilotDoc + var top map[string]json.RawMessage + if err := json.Unmarshal(b, &d); err != nil { + t.Fatalf("not JSON Copilot reads: %v\n%s", err, b) + } + json.Unmarshal(b, &top) + return d, top +} + +// Copilot for Obsidian takes an OpenAI-compatible endpoint the user names. +// magpie adds itself as the provider "magpie", keyless, on the gateway's +// Chat Completions under /agent/obsidian, with every magpie model in the +// chat picker and the first as the default, in each vault with Copilot; +// it keeps every other setting as written, writes nothing when nothing +// changed, keeps what the user changes in Copilot, and off puts the +// default back and takes out only what is magpie's (shirotokiren on X). +func TestObsidianCopilot(t *testing.T) { + home := syncHome(t) + cfg := filepath.Join(home, ".config") + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil { + t.Fatal(err) + } + if !slices.ContainsFunc(All(), func(x *Agent) bool { return x.ID == "obsidian" && x.Name == "Obsidian" }) { + t.Fatal("Obsidian is not among the agents") + } + if a := obsidian(home, cfg); a.Detected() { + t.Fatal("found with nothing of it here") + } + odir := obsidianDirs(home, cfg)[0] + notes := filepath.Join(home, "Documents", "Notes") + path := obsidianVault(t, odir, "a1b2c3d4e5f60718", notes, "4.0.19", obsCopilotUser) + // a second vault without Copilot, and one listed that is gone + obsidianVault(t, odir, "b2c3d4e5f6071829", filepath.Join(home, "Plain"), "", "") + obsidianVault(t, odir, "c3d4e5f60718293a", filepath.Join(home, "Gone"), "", "") + os.RemoveAll(filepath.Join(home, "Gone")) + + a := obsidian(home, cfg) + if !a.Detected() { + t.Fatal("not found with its config folder") + } + if a.Path != filepath.Join(odir, "obsidian.json") { + t.Fatalf("path %s", a.Path) + } + f := a.Field("provider") + if f.Get() != "" { + t.Fatalf("get: %q", f.Get()) + } + if err := f.Set(magpieID); err != nil { + t.Fatal(err) + } + if f.Get() != magpieID { + t.Fatalf("get after set: %q", f.Get()) + } + if _, err := os.Stat(obsCopilotData(filepath.Join(home, "Plain"))); !os.IsNotExist(err) { + t.Errorf("a vault without Copilot got its settings: %v", err) + } + + running := Running + t.Cleanup(func() { Running = running }) + Running = func(...string) bool { return true } + if a.Notice() != noticeObsidian.String() { + t.Errorf("notice while it runs: %q", a.Notice()) + } + Running = func(...string) bool { return false } + if a.Notice() != "" { + t.Errorf("notice while it doesn't: %q", a.Notice()) + } + + d, top := obsReadCopilot(t, path) + var p obsCopilotProvider + if err := json.Unmarshal(d.Providers[magpieID], &p); err != nil { + t.Fatalf("magpie's provider: %v %s", err, d.Providers[magpieID]) + } + if p.ProviderID != magpieID || p.ProviderType != "openai-compatible" || p.BaseURL != gateway.URL()+"/agent/obsidian/v1" || + p.RequiresAPIKey || p.APIKeyKeychainID != nil || p.EnableCors || p.AddedAt == 0 || !sameJSON(string(p.Origin), map[string]string{"kind": "byok"}) { + t.Errorf("provider: %+v", p) + } + var want, got, mine []string + for _, m := range magpieModels("obsidian") { + want = append(want, m.ID) + } + for _, m := range d.ConfiguredModels { + if m.ProviderID == magpieID { + got = append(got, m.Info.ID) + mine = append(mine, m.ConfiguredModelID) + if strings.Contains(m.ConfiguredModelID, "|") || m.Info.DisplayName == "" || m.ConfiguredAt == 0 { + t.Errorf("model %+v", m) + } + } + } + if len(want) < 2 || !slices.Equal(got, want) { + t.Errorf("models %v, want %v", got, want) + } + if d.DefaultModelKey != mine[0] { + t.Errorf("default %q, want magpie's first %q", d.DefaultModelKey, mine[0]) + } + chat := d.Backends["chat"].EnabledModels + if !slices.Equal(chat, append([]string{"1b7c5a52-6d0e-4c1d-9b0e-3f6c2a1d0e01", "2c8d6b63-7e1f-4d2e-8c1f-4a7d3b2e1f02"}, mine...)) { + t.Errorf("chat's picker: %v", chat) + } + if oc := d.Backends["opencode"].EnabledModels; !slices.Equal(oc, []string{"2c8d6b63-7e1f-4d2e-8c1f-4a7d3b2e1f02"}) { + t.Errorf("an agent backend's picker: %v", oc) + } + // every other setting, and the user's providers and models, as written + var user map[string]json.RawMessage + json.Unmarshal([]byte(obsCopilotUser), &user) + for k, v := range user { + switch k { + case "defaultModelKey", "providers", "configuredModels", "backends": + continue + } + if !sameJSON(string(top[k]), v) { + t.Errorf("%s: %s, was %s", k, top[k], v) + } + } + var userProv map[string]json.RawMessage + json.Unmarshal(user["providers"], &userProv) + for k, v := range userProv { + if !sameJSON(string(d.Providers[k]), v) { + t.Errorf("the user's provider %s: %s", k, d.Providers[k]) + } + } + var userModels []json.RawMessage + json.Unmarshal(user["configuredModels"], &userModels) + var all []json.RawMessage + json.Unmarshal(top["configuredModels"], &all) + for i, m := range userModels { + if !sameJSON(string(all[i]), m) { + t.Errorf("the user's model %d: %s", i, all[i]) + } + } + + // nothing changed: nothing written + b, _ := os.ReadFile(path) + st, _ := os.Stat(path) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if err := f.Set(magpieID); err != nil { + t.Fatal(err) + } + if b2, _ := os.ReadFile(path); !bytes.Equal(b, b2) { + t.Errorf("rewritten with nothing changed:\n%s\n%s", b, b2) + } + if st2, _ := os.Stat(path); !st2.ModTime().Equal(st.ModTime()) { + t.Error("written with nothing changed") + } + + // in Copilot the user renames magpie, turns its second model off in + // the picker and picks their own default; magpie gets a model more. + // A sync keeps all three and turns the new model on. + var doc map[string]any + json.Unmarshal(b, &doc) + doc["providers"].(map[string]any)[magpieID].(map[string]any)["displayName"] = "My magpie" + doc["defaultModelKey"] = "2c8d6b63-7e1f-4d2e-8c1f-4a7d3b2e1f02" + bk := doc["backends"].(map[string]any)["chat"].(map[string]any) + bk["enabledModels"] = slices.DeleteFunc(bk["enabledModels"].([]any), func(x any) bool { return x == mine[1] }) + edited, _ := json.MarshalIndent(doc, "", " ") + os.WriteFile(path, edited, 0o644) + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash", "max"}}); err != nil { + t.Fatal(err) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + d, _ = obsReadCopilot(t, path) + json.Unmarshal(d.Providers[magpieID], &p) + if p.DisplayName != "My magpie" { + t.Errorf("the user's name not kept: %q", p.DisplayName) + } + if d.DefaultModelKey != "2c8d6b63-7e1f-4d2e-8c1f-4a7d3b2e1f02" { + t.Errorf("the user's default not kept: %q", d.DefaultModelKey) + } + var now []string + for _, m := range d.ConfiguredModels { + if m.ProviderID == magpieID { + now = append(now, m.ConfiguredModelID) + } + } + if len(now) != len(mine)+1 { + t.Fatalf("models after sync: %d, want %d", len(now), len(mine)+1) + } + chat = d.Backends["chat"].EnabledModels + if slices.Contains(chat, mine[1]) { + t.Errorf("a model the user turned off came back on: %v", chat) + } + if !slices.Contains(chat, now[len(now)-1]) || !slices.Contains(chat, mine[0]) { + t.Errorf("the new model, or one left on, isn't on: %v", chat) + } + + // off, with the default magpie's again: the old default comes back, + // and only magpie's provider, models and their places go + doc = nil + b, _ = os.ReadFile(path) + json.Unmarshal(b, &doc) + doc["defaultModelKey"] = mine[0] + edited, _ = json.MarshalIndent(doc, "", " ") + os.WriteFile(path, edited, 0o644) + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if f.Get() != "" { + t.Fatalf("get after off: %q", f.Get()) + } + d, top = obsReadCopilot(t, path) + if d.DefaultModelKey != "1b7c5a52-6d0e-4c1d-9b0e-3f6c2a1d0e01" { + t.Errorf("default after off: %q", d.DefaultModelKey) + } + if !sameJSON(string(top["providers"]), user["providers"]) || !sameJSON(string(top["configuredModels"]), user["configuredModels"]) { + t.Errorf("after off:\n%s\n%s", top["providers"], top["configuredModels"]) + } + if c := d.Backends["chat"].EnabledModels; !slices.Equal(c, []string{"1b7c5a52-6d0e-4c1d-9b0e-3f6c2a1d0e01", "2c8d6b63-7e1f-4d2e-8c1f-4a7d3b2e1f02"}) { + t.Errorf("chat's picker after off: %v", c) + } + // a sync with magpie off writes nothing + b, _ = os.ReadFile(path) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if b2, _ := os.ReadFile(path); !bytes.Equal(b, b2) { + t.Errorf("a sync off wrote:\n%s", b2) + } +} + +// A vault whose Copilot has never saved has no data.json yet: magpie makes +// one Copilot reads, with magpie's provider, models and chat picker. +func TestObsidianCopilotNoSettingsYet(t *testing.T) { + home := syncHome(t) + cfg := filepath.Join(home, ".config") + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil { + t.Fatal(err) + } + path := obsidianVault(t, obsidianDirs(home, cfg)[0], "v1", filepath.Join(home, "V"), "4.1.0", "") + if err := obsidian(home, cfg).Field("provider").Set(magpieID); err != nil { + t.Fatal(err) + } + d, _ := obsReadCopilot(t, path) + if len(d.ConfiguredModels) == 0 || d.DefaultModelKey != d.ConfiguredModels[0].ConfiguredModelID || len(d.Backends["chat"].EnabledModels) != len(d.ConfiguredModels) { + t.Errorf("made: %+v", d) + } +} + +// A provider the user added by hand under the name magpie is theirs (the +// HandWired rule): it doesn't read as connected, Disconnect leaves it, and +// Connect says so and writes nothing. +func TestObsidianCopilotHandWiredMagpieIsTheirs(t *testing.T) { + home := syncHome(t) + cfg := filepath.Join(home, ".config") + provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}) + own := `{"providers": {"magpie": {"providerId": "magpie", "providerType": "openai-compatible", "displayName": "magpie", "baseUrl": "https://magpie.example.com/v1", "enableCors": true, "apiKeyKeychainId": "k1", "requiresApiKey": true, "origin": {"kind": "byok"}, "addedAt": 1}}, "configuredModels": [{"configuredModelId": "m1", "providerId": "magpie", "info": {"id": "x"}, "configuredAt": 1}], "defaultModelKey": "m1"}` + path := obsidianVault(t, obsidianDirs(home, cfg)[0], "v", filepath.Join(home, "V"), "4.0.19", own) + a := obsidian(home, cfg) + if a.Wired() { + t.Error("the user's own provider named magpie reads as connected") + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(path); string(b) != own { + t.Errorf("Disconnect wrote the user's provider: %s", b) + } + if err := a.Field("provider").Set(magpieID); err == nil || !strings.Contains(err.Error(), "of its own named magpie") { + t.Errorf("Connect over the user's provider: %v", err) + } + if b, _ := os.ReadFile(path); string(b) != own { + t.Errorf("Connect wrote the user's provider: %s", b) + } +} + +// Copilot 3 keeps its models in activeModels, which magpie doesn't write, +// and no vault with Copilot is no place to put magpie: each is an error +// that says what to do, and nothing is written. +func TestObsidianCopilotRefuses(t *testing.T) { + home := syncHome(t) + cfg := filepath.Join(home, ".config") + provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}) + odir := obsidianDirs(home, cfg)[0] + obsidianVault(t, odir, "p", filepath.Join(home, "P"), "", "") + if err := obsidian(home, cfg).Field("provider").Set(magpieID); err == nil || !strings.Contains(err.Error(), "install Copilot") { + t.Errorf("no Copilot: %v", err) + } + old := `{"activeModels": [], "defaultModelKey": "gpt-4o|openai"}` + path := obsidianVault(t, odir, "q", filepath.Join(home, "Q"), "2.9.5", old) + if err := obsidian(home, cfg).Field("provider").Set(magpieID); err == nil || !strings.Contains(err.Error(), "update it") { + t.Errorf("Copilot 2: %v", err) + } + if b, _ := os.ReadFile(path); string(b) != old { + t.Errorf("Copilot 2's settings written: %s", b) + } + os.WriteFile(filepath.Join(obsCopilotDir(filepath.Join(home, "Q")), "manifest.json"), []byte(obsCopilotManifest("4.0.19")), 0o644) + os.WriteFile(path, []byte(`{"providers": [`), 0o644) + if err := obsidian(home, cfg).Field("provider").Set(magpieID); err == nil { + t.Error("a file Copilot can't read: set") + } + if b, _ := os.ReadFile(path); string(b) != `{"providers": [` { + t.Errorf("written: %s", b) + } +} + +// obsidian.json is where Obsidian keeps it on each system: its Electron +// userData folder, and on Linux the Flatpak's and the Snap's too. +func TestObsidianDirsPerOS(t *testing.T) { + home := filepath.Join("h", "me") + cfg := filepath.Join(home, ".cfg") + for _, c := range []struct { + goos, appData string + want []string + }{ + {"darwin", "", []string{filepath.Join(home, "Library", "Application Support", "obsidian")}}, + {"windows", filepath.Join("R", "Roaming"), []string{filepath.Join("R", "Roaming", "obsidian")}}, + {"windows", "", []string{filepath.Join(home, "AppData", "Roaming", "obsidian")}}, + {"linux", "", []string{ + filepath.Join(cfg, "obsidian"), + filepath.Join(home, ".var", "app", "md.obsidian.Obsidian", "config", "obsidian"), + filepath.Join(home, "snap", "obsidian", "current", ".config", "obsidian"), + }}, + } { + if got := obsidianDirsOn(c.goos, home, cfg, c.appData); !slices.Equal(got, c.want) { + t.Errorf("%s (APPDATA %q): %v, want %v", c.goos, c.appData, got, c.want) + } + } + if got := obsidianDirs(home, cfg); !slices.Equal(got, obsidianDirsOn(runtime.GOOS, home, cfg, os.Getenv("APPDATA"))) { + t.Errorf("here: %v", got) + } +} diff --git a/internal/gateway/cors.go b/internal/gateway/cors.go index 94bbccbd1..693324c74 100644 --- a/internal/gateway/cors.go +++ b/internal/gateway/cors.go @@ -41,10 +41,17 @@ import ( // So is a page at a subdomain of localhost (localhostSubdomain, #2256): // Safari and other WebKit views ask the DNS for such a name, and a // resolver that answers it serves the page from anywhere. +// +// Obsidian (appOrigin) gets the headers without being listed and without a +// key: its plugins call from app://obsidian.md, which only Obsidian's own +// window sends, and Copilot for Obsidian's streaming chat goes through +// the window's fetch, which reads no reply without them (the agent +// "obsidian" wires it keyless, shirotokiren on X). func corsGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") - if origin == "" || !corsAllowed(origin) { + app := appOrigin(origin) + if origin == "" || !app && !corsAllowed(origin) { if foreignPage(r, origin) { log.Printf("refused %s %s from the web page %s: not one listed in Settings", r.Method, r.URL.Path, origin) writeError(w, provider.Chat, http.StatusForbidden, "magpie doesn't answer the web page "+origin+": list it in Settings → Network and sharing → Web pages to let it call magpie with a gateway key") @@ -81,8 +88,10 @@ func corsGuard(next http.Handler) http.Handler { return } // lanGuard, in front of Handler on the real server, has already - // taken the key and put magpie's own token in its place - if !keyedCaller(r) { + // taken the key and put magpie's own token in its place. An app's + // window is no page: it is held to the network's rules alone, as + // the app's own requests without an Origin are. + if !app && !keyedCaller(r) { writeError(w, provider.Chat, http.StatusUnauthorized, "a web page or browser extension calls magpie with a gateway key: create one in magpie's Gateway page and send it as Authorization: Bearer (or x-api-key)") return } @@ -195,6 +204,19 @@ func hostPort(hp, scheme string) string { return net.JoinHostPort(strings.Trim(hp, "[]"), port) } +// appOrigins are the origins of desktop apps whose plugins call the +// gateway from the app's own window, under its CORS: Obsidian's +// (app://obsidian.md, the origin Copilot for Obsidian's docs give Ollama's +// OLLAMA_ORIGINS). No web page and no browser extension can send one, so +// a call that carries it is the app's, and is answered as the app's calls +// without an Origin are. +var appOrigins = []string{"app://obsidian.md"} + +// appOrigin: origin is one of appOrigins. +func appOrigin(origin string) bool { + return slices.Contains(appOrigins, strings.ToLower(strings.TrimRight(origin, "/"))) +} + // corsAllowed: origin is one the user listed. func corsAllowed(origin string) bool { saved := settings.Load().CORSOrigins diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index bbe68ccd3..ecae92918 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -770,3 +770,83 @@ func TestCORSPreflightFromLANReachesNothing(t *testing.T) { } } } + +// Copilot for Obsidian streams its chat through the window's fetch, from +// Origin app://obsidian.md, and the agent "obsidian" wires it with no key +// (shirotokiren on X): its preflight is answered and its calls read their +// replies without being listed in Settings or carrying a key. Another +// app:// origin is still neither answered nor refused, as before, and from +// another machine the call needs the key as every other call does. +func TestCORSObsidian(t *testing.T) { + fresh(t) + var hits atomic.Int64 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`) + })) + defer up.Close() + if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil { + t.Fatal(err) + } + s := settings.Load() + s.LAN = true + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + const obsidian = "app://obsidian.md" + srv := lanGuard(New().Handler()) + do := func(remote, method, path, origin string) *httptest.ResponseRecorder { + t.Helper() + var body io.Reader + if method == "POST" { + body = strings.NewReader(chatReq) + } + r := httptest.NewRequest(method, path, body) + r.RemoteAddr = remote + r.Host = "127.0.0.1:3425" + r.Header.Set("Origin", origin) + r.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/537.36 obsidian/1.9.12 Chrome/138.0 Electron/37.2.0 Safari/537.36") + if method == "OPTIONS" { + r.Header.Set("Access-Control-Request-Method", "POST") + r.Header.Set("Access-Control-Request-Headers", "content-type, x-stainless-os, x-stainless-lang") + } else { + r.Header.Set("Content-Type", "application/json") + } + w := httptest.NewRecorder() + srv.ServeHTTP(w, r) + return w + } + const here = "127.0.0.1:50123" + w := do(here, "OPTIONS", "/v1/chat/completions", obsidian) + if w.Code != http.StatusNoContent || w.Header().Get("Access-Control-Allow-Origin") != obsidian || + w.Header().Get("Access-Control-Allow-Headers") != "content-type, x-stainless-os, x-stainless-lang" || + !strings.Contains(w.Header().Get("Access-Control-Allow-Methods"), "POST") { + t.Fatalf("preflight: %d %v", w.Code, w.Header()) + } + if hits.Load() != 0 { + t.Fatal("a preflight reached the vendor") + } + w = do(here, "POST", "/v1/chat/completions", obsidian) + if w.Code != http.StatusOK || w.Header().Get("Access-Control-Allow-Origin") != obsidian || !strings.Contains(w.Body.String(), "ok") { + t.Fatalf("chat without a key: %d %v %s", w.Code, w.Header(), w.Body) + } + if w := do(here, "GET", "/v1/models", obsidian); w.Code != http.StatusOK || w.Header().Get("Access-Control-Allow-Origin") != obsidian { + t.Errorf("models: %d %v", w.Code, w.Header()) + } + // another app's scheme: passed on as before, with no CORS headers + if w := do(here, "OPTIONS", "/v1/chat/completions", "app://other.example"); w.Code == http.StatusNoContent || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("another app's preflight: %d %v", w.Code, w.Header()) + } + if w := do(here, "POST", "/v1/chat/completions", "app://other.example"); w.Code != http.StatusOK || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("another app's call: %d %v", w.Code, w.Header()) + } + // from another machine, the key as always + n := hits.Load() + if w := do("192.168.1.9:50123", "POST", "/v1/chat/completions", obsidian); w.Code != http.StatusUnauthorized { + t.Errorf("keyless from the LAN: %d %s", w.Code, w.Body) + } + if hits.Load() != n { + t.Error("a keyless call from the LAN reached the vendor") + } +} diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 2b5ea9c2f..1a76391bf 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4704,6 +4704,7 @@ const I18N = { "New dsh sessions start on this. A session made before keeps its model, open now or reopened later, until you pick another in it with /model or the model button by its message box. A dsh started with -p or in a terminal reads it at start-up.": "新的 dsh 会话会使用这项设置。之前建的会话,无论现在开着还是以后再打开,都保留原来的模型,直到你在其中用 /model 或输入框旁的模型按钮另选一个。用 -p 或在终端里启动的 dsh 在启动时读取它。", "DeepSeek Harness Desktop hasn't been opened yet: it starts on this the first time it opens.": "DeepSeek Harness 桌面版还没打开过:第一次打开时就会使用这项设置。", "OpenBot reads its custom endpoints at start-up — restart OpenBot to see magpie's models in its model picker, before adding or editing an endpoint there.": "OpenBot 启动时读取自定义端点,需重启 OpenBot 才能在它的模型选择器中看到 magpie 的模型;在此之前请不要在 OpenBot 里添加或编辑端点。", + "Obsidian holds Copilot's settings while it runs — reload Copilot in Settings › Community plugins (or restart Obsidian) to see magpie's models, before changing Copilot's settings there.": "Obsidian 运行时会保留 Copilot 的设置:请在“设置 › 第三方插件”中重新加载 Copilot(或重启 Obsidian)以看到 magpie 的模型;在此之前请不要在那里修改 Copilot 的设置。", "OpenChamber takes the new model for new sessions; sessions already open keep theirs.": "OpenChamber 的新会话会使用新模型;已打开的会话保留原来的模型。", "Kiro Crew takes the new harness for new sessions; sessions already open keep theirs.": "Kiro Crew 的新会话会使用新的 harness;已打开的会话保留原来的。", "Kiro Crew runs on {harness}, so magpie connected {harness} too; turning Kiro Crew off disconnects it again.": "Kiro Crew 运行在 {harness} 上,所以 magpie 也一并接入了 {harness};关闭 Kiro Crew 时会把它一起断开。", @@ -9623,6 +9624,7 @@ const I18N = { "New dsh sessions start on this. A session made before keeps its model, open now or reopened later, until you pick another in it with /model or the model button by its message box. A dsh started with -p or in a terminal reads it at start-up.": "新的 dsh 會話會使用這項設定。之前建立的會話,無論現在開著還是以後再打開,都保留原來的模型,直到你在其中用 /model 或輸入框旁的模型按鈕另選一個。用 -p 或在終端裡啟動的 dsh 在啟動時讀取它。", "DeepSeek Harness Desktop hasn't been opened yet: it starts on this the first time it opens.": "DeepSeek Harness 桌面版還沒開啟過:第一次開啟時就會使用這項設定。", "OpenBot reads its custom endpoints at start-up — restart OpenBot to see magpie's models in its model picker, before adding or editing an endpoint there.": "OpenBot 啟動時讀取自訂端點,需重新啟動 OpenBot 才能在它的模型選擇器中看到 magpie 的模型;在此之前請不要在 OpenBot 裡新增或編輯端點。", + "Obsidian holds Copilot's settings while it runs — reload Copilot in Settings › Community plugins (or restart Obsidian) to see magpie's models, before changing Copilot's settings there.": "Obsidian 執行時會保留 Copilot 的設定:請在「設定 › 社群外掛」中重新載入 Copilot(或重新啟動 Obsidian)以看到 magpie 的模型;在此之前請不要在那裡修改 Copilot 的設定。", "OpenChamber takes the new model for new sessions; sessions already open keep theirs.": "OpenChamber 的新會話會使用新模型;已打開的會話保留原來的模型。", "Kiro Crew takes the new harness for new sessions; sessions already open keep theirs.": "Kiro Crew 的新工作階段會使用新的 harness;已開啟的工作階段保留原本的。", "Kiro Crew runs on {harness}, so magpie connected {harness} too; turning Kiro Crew off disconnects it again.": "Kiro Crew 執行在 {harness} 上,所以 magpie 也一併接入了 {harness};關閉 Kiro Crew 時會把它一起中斷。", @@ -14544,6 +14546,7 @@ const I18N = { "New dsh sessions start on this. A session made before keeps its model, open now or reopened later, until you pick another in it with /model or the model button by its message box. A dsh started with -p or in a terminal reads it at start-up.": "新しい dsh セッションはこれで始まります。以前に作ったセッションは、今開いていても後で開き直しても、その中で /model か入力欄の横のモデルボタンで別のモデルを選ぶまで今のモデルのままです。-p 付きやターミナルで起動した dsh は起動時に読み込みます。", "DeepSeek Harness Desktop hasn't been opened yet: it starts on this the first time it opens.": "DeepSeek Harness デスクトップ版はまだ一度も開かれていません。初めて開いたときからこの設定で始まります。", "OpenBot reads its custom endpoints at start-up — restart OpenBot to see magpie's models in its model picker, before adding or editing an endpoint there.": "OpenBot は起動時にカスタムエンドポイントを読み込みます。モデル選択に magpie のモデルを表示するには OpenBot を再起動してください。それまでは OpenBot でエンドポイントを追加・編集しないでください。", + "Obsidian holds Copilot's settings while it runs — reload Copilot in Settings › Community plugins (or restart Obsidian) to see magpie's models, before changing Copilot's settings there.": "Obsidian は実行中 Copilot の設定を保持します。magpie のモデルを表示するには、設定 › コミュニティプラグインで Copilot を再読み込み(または Obsidian を再起動)してください。それまでは Copilot の設定を変更しないでください。", "OpenChamber takes the new model for new sessions; sessions already open keep theirs.": "OpenChamber は新しいセッションで新しいモデルを使います。開いているセッションは今のモデルのままです。", "Kiro Crew takes the new harness for new sessions; sessions already open keep theirs.": "Kiro Crew は新しいセッションから新しいハーネスを使います。開いているセッションは元のままです。", "Kiro Crew runs on {harness}, so magpie connected {harness} too; turning Kiro Crew off disconnects it again.": "Kiro Crew は {harness} 上で動くため、magpie は {harness} も接続しました。Kiro Crew をオフにすると、こちらも切断します。", @@ -19465,6 +19468,7 @@ const I18N = { "New dsh sessions start on this. A session made before keeps its model, open now or reopened later, until you pick another in it with /model or the model button by its message box. A dsh started with -p or in a terminal reads it at start-up.": "Neue dsh-Sitzungen starten damit. Eine vorher angelegte Sitzung behält ihr Modell, ob jetzt offen oder später wieder geöffnet, bis Sie darin mit /model oder der Modell-Schaltfläche neben dem Eingabefeld ein anderes wählen. Ein mit -p oder im Terminal gestartetes dsh liest es beim Start.", "DeepSeek Harness Desktop hasn't been opened yet: it starts on this the first time it opens.": "DeepSeek Harness Desktop wurde noch nie geöffnet: Beim ersten Öffnen startet es mit dieser Einstellung.", "OpenBot reads its custom endpoints at start-up — restart OpenBot to see magpie's models in its model picker, before adding or editing an endpoint there.": "OpenBot liest seine eigenen Endpunkte beim Start – OpenBot neu starten, um magpies Modelle in seiner Modellauswahl zu sehen, bevor dort ein Endpunkt hinzugefügt oder bearbeitet wird.", + "Obsidian holds Copilot's settings while it runs — reload Copilot in Settings › Community plugins (or restart Obsidian) to see magpie's models, before changing Copilot's settings there.": "Obsidian hält die Einstellungen von Copilot, solange es läuft – Copilot unter Einstellungen › Community-Plugins neu laden (oder Obsidian neu starten), um magpies Modelle zu sehen, bevor du dort Copilots Einstellungen änderst.", "OpenChamber takes the new model for new sessions; sessions already open keep theirs.": "OpenChamber nimmt das neue Modell für neue Sitzungen; bereits offene behalten ihres.", "Kiro Crew takes the new harness for new sessions; sessions already open keep theirs.": "Kiro Crew nutzt den neuen Harness für neue Sitzungen; bereits offene Sitzungen behalten ihren.", "Kiro Crew runs on {harness}, so magpie connected {harness} too; turning Kiro Crew off disconnects it again.": "Kiro Crew läuft auf {harness}, daher hat magpie {harness} gleich mit verbunden; schaltest du Kiro Crew aus, wird es wieder getrennt.", @@ -19752,6 +19756,7 @@ const NOTICES = [ "New dsh sessions start on this. A session made before keeps its model, open now or reopened later, until you pick another in it with /model or the model button by its message box. A dsh started with -p or in a terminal reads it at start-up.", "DeepSeek Harness Desktop hasn't been opened yet: it starts on this the first time it opens.", "OpenBot reads its custom endpoints at start-up — restart OpenBot to see magpie's models in its model picker, before adding or editing an endpoint there.", + "Obsidian holds Copilot's settings while it runs — reload Copilot in Settings › Community plugins (or restart Obsidian) to see magpie's models, before changing Copilot's settings there.", "OpenChamber takes the new model for new sessions; sessions already open keep theirs.", "Kiro Crew takes the new harness for new sessions; sessions already open keep theirs.", "Kiro Crew runs on {harness}, so magpie connected {harness} too; turning Kiro Crew off disconnects it again.", diff --git a/internal/gui/assets/icons/obsidian.svg b/internal/gui/assets/icons/obsidian.svg new file mode 100644 index 000000000..a3fffb363 --- /dev/null +++ b/internal/gui/assets/icons/obsidian.svg @@ -0,0 +1 @@ +Obsidian