agent: Obsidian, magpie's models in Copilot for Obsidian (shirotokiren on X)

shirotokiren asked for magpie to set up Obsidian's AI plugins, naming
Copilot and Smart Connections.

The new agent "obsidian" finds the vaults in Obsidian's obsidian.json:
~/Library/Application Support/obsidian on a Mac, %APPDATA%\obsidian on
Windows, and on Linux $XDG_CONFIG_HOME/obsidian or the Flatpak or Snap
folder. In each vault that has Copilot for Obsidian 4+
(.obsidian/plugins/copilot), magpie edits data.json in the shape
Copilot 4.0.19 reads:
- it adds providers.magpie, openai-compatible at /agent/obsidian/v1,
  with requiresApiKey false and no keychain id;
- it adds one configuredModels entry per magpie model, with a
  deterministic uuid v5 id, plus limits, image input and reasoning
  efforts;
- new models go into backends.chat.enabledModels;
- on the first wire it sets defaultModelKey, and stashes the old value.

A sync keeps the models the user turned off, their default, and the
name they gave the provider. It writes only the keys that change
(edit.PatchJSON, then temp and rename), and nothing when nothing
changed. A provider named magpie counts as magpie's only when its
baseUrl is magpie's Obsidian route. One the user added by hand under
that name is theirs: it doesn't read as connected, Disconnect leaves
it, and Connect says so and writes nothing. Disconnect takes magpie's entries out and puts the old default
back. Copilot 3, a data.json it can't parse, and no vault with Copilot
are each an error, and nothing is written. A notice asks the user to
reload Copilot, since Obsidian holds the settings in memory.

The gateway now answers CORS for app://obsidian.md keylessly
(appOrigin). Copilot streams through the window's fetch, and without
CORS headers it can read no reply. Only Obsidian's own window sends
that origin, so it gets no more than its calls without an Origin get.
From the network it still needs a key.

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.

Run (mote, at 401187300 + this commit, then again after rebasing on
9c39edb92):
- gofmt
- go vet for darwin, linux nogui and windows
- go test -run 'Obsidian|Notice|CORS|Craft' ./internal/agent ./internal/gateway
- GUI, chromium and webkit: i18n-keys, i18n-en-no-cjk, icon-one-tone
  (56 of 56)
At 9c39edb92 + this commit: the whole internal/agent package ok
(211s), vet for darwin, linux nogui and windows, CORS tests ok.
At 4d95d81ea + this commit: Obsidian, HandWired and Spelled tests,
vet for darwin and windows, and the three GUI files again (56 of 56).
win-run: TestObsidian* ok on Windows 11.

Broken by hand (each went red, then was restored):
- corsGuard without the appOrigin branch: TestCORSObsidian, preflight
  404.
- re-enabling every magpie model on sync: TestObsidianCopilot, "a
  model the user turned off came back on".
- dropping the user's configuredModels: TestObsidianCopilot.
- counting any provider named magpie as magpie's:
  TestObsidianCopilotHandWiredMagpieIsTheirs.

Not tried: a real Obsidian with Copilot loading the written data.json.
The fixtures follow Copilot 4.0.19's types and migrations. Not tried
over LAN either. The full suite runs after the tag.
This commit is contained in:
yetone
2026-11-10 20:06:21 +08:00
parent 4d95d81eae
commit 4a9142ccd4
10 changed files with 1176 additions and 4 deletions
+1
View File
@@ -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) |
+2
View File
@@ -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/<id>` 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.<id>.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: <gateway>, apiKey: <key naming Antigravity>, 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 `<gateway>/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 `<url>/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 `<name> (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, `<id>:<level>` named `<name> (<Level>)` (`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 `<url>/v1/chat/completions` with the key as a bearer token and a User-Agent of `antigravity/hub/<version>`. 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'
File diff suppressed because one or more lines are too long
+1
View File
@@ -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),
+594
View File
@@ -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": {"<id>": {"path":
// "<vault folder>", "ts": …, "open": true}}}. A plugin keeps its settings
// in <vault>/.obsidian/plugins/<id>/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": {"<id>": {"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": ["<configuredModelId>", …]}},
// "defaultModelKey": "<configuredModelId>"
//
// 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/<id>").
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, ".", `\.`) }
+466
View File
@@ -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)
}
}
+25 -3
View File
@@ -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 <key> (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
+80
View File
@@ -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")
}
}
+5
View File
@@ -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.",
+1
View File
@@ -0,0 +1 @@
<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Obsidian</title><path d="M19.355 18.538a68.967 68.959 0 0 0 1.858-2.954.81.81 0 0 0-.062-.9c-.516-.685-1.504-2.075-2.042-3.362-.553-1.321-.636-3.375-.64-4.377a1.707 1.707 0 0 0-.358-1.05l-3.198-4.064a3.744 3.744 0 0 1-.076.543c-.106.503-.307 1.004-.536 1.5-.134.29-.29.6-.446.914l-.31.626c-.516 1.068-.997 2.227-1.132 3.59-.124 1.26.046 2.73.815 4.481.128.011.257.025.386.044a6.363 6.363 0 0 1 3.326 1.505c.916.79 1.744 1.922 2.415 3.5zM8.199 22.569c.073.012.146.02.22.02.78.024 2.095.092 3.16.29.87.16 2.593.64 4.01 1.055 1.083.316 2.198-.548 2.355-1.664.114-.814.33-1.735.725-2.58l-.01.005c-.67-1.87-1.522-3.078-2.416-3.849a5.295 5.295 0 0 0-2.778-1.257c-1.54-.216-2.952.19-3.84.45.532 2.218.368 4.829-1.425 7.531zM5.533 9.938c-.023.1-.056.197-.098.29L2.82 16.059a1.602 1.602 0 0 0 .313 1.772l4.116 4.24c2.103-3.101 1.796-6.02.836-8.3-.728-1.73-1.832-3.081-2.55-3.831zM9.32 14.01c.615-.183 1.606-.465 2.745-.534-.683-1.725-.848-3.233-.716-4.577.154-1.552.7-2.847 1.235-3.95.113-.235.223-.454.328-.664.149-.297.288-.577.419-.86.217-.47.379-.885.46-1.27.08-.38.08-.72-.014-1.043-.095-.325-.297-.675-.68-1.06a1.6 1.6 0 0 0-1.475.36l-4.95 4.452a1.602 1.602 0 0 0-.513.952l-.427 2.83c.672.59 2.328 2.316 3.335 4.711.09.21.175.43.253.653z"/></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB