Commit Graph
18 Commits
Author SHA1 Message Date
yetone 273b9f5a99 deps: modernc sqlite v1.61.0 / libc v1.79.0, so /etc/services is parsed on use, not at every start
libc v1.67.6's netdb package had an init() that read and parsed
/etc/protocols and /etc/services on every launch: 3.66 MB and 44k
allocations, ~3-4 ms, with ~1.9 MB kept for the life of the gateway.
libc v1.78.0 and later load it through a sync.Once on first use, and
magpie never looks a service up. `magpie statusline`, which Claude Code
runs on every message, pays this on each launch.

Bumped (all released more than two weeks ago): modernc.org/sqlite
v1.44.3 -> v1.61.0, libc v1.67.6 -> v1.79.0, memory v1.11.0 -> v1.12.1,
golang.org/x/sys v0.46.0 -> v0.49.0, go-humanize, go-isatty and
go-strftime as sqlite's go.mod pins them. go mod tidy.

Measured on mote (M5 Pro), sandbox HOME with a copy of real accounts,
main e697e7ddf vs this change:
- GODEBUG=inittrace=1: init 16.7 MB / 150k allocs -> 13.0 MB / 106k;
  the netdb line is gone.
- `echo {} | magpie statusline` under /usr/bin/time -l, 3 runs each:
  instructions retired 324-330M -> 254-278M (about -20%), peak
  footprint 24.6-25.1 MB -> 22.3-22.6 MB.

Run: go vet ./... (mote); GOOS=linux and GOOS=windows go vet of
internal/sqlitedb, internal/agent, internal/provider; go test
internal/sqlitedb, internal/agent and internal/provider -run
'Cherry|Cindy|Aion|Newmax|Import|SQLite' (the sqlite readers): ok.
Not run: the full go test ./... suite before the push.
2026-11-10 12:26:39 +08:00
yetone 9a00bfed14 deps: moejs v0.1.0
moejs v0.1.0 is out (Ion_Mio_ on X): less memory, about 3x faster than
alpha.11 on V8's benchmark, 2.9x C QuickJS on a 100K-token agent request.
It pulls in github.com/MoeForge/moego (MIT) for base64.

THIRD_PARTY_NOTICES names v0.1.0; sections 1 to 4 of moejs's notices are
the same as at alpha.11 (diffed). go mod tidy also marks gen2brain/h265
and santhosh-tekuri/jsonschema direct, which internal/gateway imports.

Run at 608c1543e plus this change (the rebase onto 93bbcc8bf adds only
that gateway commit):
- mote (macOS): GOOS=windows go vet ./... ok; go test -timeout 45m ./...
  88 packages ok, internal/gui red on TestGatewayModeStatsNameTheGatewaySessions
  alone, 3 of 3 on origin/main b475004d5 too (#5690, first hour of a local
  day; mote ran at 00:37 PST).
- magpie-desktop (Linux): go vet -tags gtk3 ./... ok; agentplug,
  middleware, plugin ok.
Not tried: a real plugin in a running magpie.
2026-11-09 16:57:15 +08:00
yetone a25d3d0815 claude: a JSON schema is answered in the interactive mode, through an answer tool
With the interactive mode on, a request with a JSON schema was refused
with a 400 since v0.1.2592: interactive Claude Code takes --json-schema and does nothing
with it, its StructuredOutput tool being -p's alone. It now runs in the
interactive mode like any other request.

- serveClaudeSubscription compiles the schema (santhosh-tekuri/jsonschema
  v6.0.3, draft-07 unless it says otherwise, as -p reads one; a $ref
  outside the schema is refused, never fetched) and adds an answer tool,
  StructuredOutput or a numbered name apart from the client's tools, with
  the schema as its input schema, through the bridge's MCP server. A
  schema that can't be compiled is a 400 before any run.
- mcpCall checks each call against the schema: one that doesn't fit is
  told why (isError) to be made again, as -p's is; one that fits is kept.
- At the turn's result the kept input is the reply's structured output.
  A turn that ended with no call is told once to call the tool, and
  fails "no answer fitting the schema" if it still doesn't. Neither the
  call nor the words around it reach the client.
- claudePrint no longer lists the schema. The two refusal tests
  (TestClaudeTUIOnRefusesPrint, TestClaudeTUIRefusalIsNoAccountsFault)
  now use the case that is still refused before any run: an image by
  its URL that can't be downloaded (127.0.0.1, which magpie never
  fetches).
- The provider editor's card no longer says -p takes "a JSON schema"
  the interactive mode can't (en, zh-CN, zh-TW, ja, de).
- docs/subsystems/claude-subscription-bridge.md: the refusal list, and
  how a schema is answered.

Run:
- A real run, haiku, the test account in a sandbox HOME, real Claude
  Code 2.1.316 through the helper with --json-schema and a stdio MCP
  server named magpie serving the answer tool and its description: the
  result's structured_output was null (the premise), and the model
  called mcp__magpie__StructuredOutput at once with
  {"color":"Sky blue","hex":"#87CEEB"}, which fits the schema's
  pattern. 7.2s, one turn. Not run: the whole gateway path with a real
  account (the unit tests drive it with Claude Code's real transcript
  rows).
- mote, at this tree (base 14e351378, origin/main just fetched): gofmt,
  go vet (darwin, windows, linux -tags nogui), go mod verify ok;
  go test ./internal/gateway ./internal/claudetui: claudetui ok, gateway
  red in TestCodexPoolSaysTheClientsVersion only, which is #4807 (red in
  a full package run on mote, another test's Codex identity reaches it);
  alone at this tree -count=3 ok. claude-mode 44/44 and i18n-keys 4/4 in
  chromium and webkit.
- Broken by hand: answer() taking every call without checking it made
  TestClaudeTUISchemaAnswer red ("a call that doesn't fit was told
  Answer received.").
2026-11-02 00:35:21 +08:00
yetone d614f21721 gateway: a HEIC photo goes to the vendor as JPEG, or PNG with alpha (qikamatata on X)
Pi and Pi Desktop send an iPhone photo dragged in as image/heic, and
DeepSeek flash on WorkBuddy (a plugin's fetch) turned it away; most
vendors take JPEG, PNG, GIF and WebP only.

What: heicAsJPEG (heic.go) runs at the top of Server.serve, after
offAsNone, so every route below sees the converted image: a provider's
own, a plugin's fetch, the describer, every translation. count_tokens
does the same. It walks images through walkImages, the one image walker,
so it covers Chat image_url (string or object), Responses input_image,
Anthropic image blocks and Gemini inlineData, tool results included. It
goes by the bytes (ftyp + an HEVC still's brand), so a HEIC labelled
image/jpeg or image/png is converted too, and a JPEG labelled heic is
left alone. Other fields of the block (detail, cache_control) are kept.
Transparent images go as PNG, opaque ones as JPEG q90.

Cost: a body with no "image/hei" and no base64 ftyp mark ("eXB" + 5
chars, at the same place in any base64 that starts at the file) is not
walked. Caps: 48 MB of base64, 50 MP, the long side written at 4096 px,
one decode at a time, 30 s wait (a late result is cached for the next
turn), a 64 MB / 32 entry cache by sha256, since agents resend a
conversation's images every turn. Any failure, panic included, leaves
the image as it came. Measured on mote (M5 Pro): 12 MP 0.44 s, 24 MP
0.86 s, 48 MP 1.6 s / ~1 GB held, freed at once with FreeOSMemory.

Why gen2brain/h265 v0.2.4: pure Go (release builds are CGO_ENABLED=0),
MIT, no dependencies, SIMD on amd64 and arm64, maintained (latest
2026-10-29). Not chosen: gen2brain/heic (wazero WASM or a libheif dylib
through purego), jdeng/goheif (cgo libde265), OS converters (Windows
needs the paid HEVC extension, Linux tools are often missing).

Tests (heic_test.go, fixtures made on mote with sips, 1.6 KB each):
12 shapes converted with their kept fields, pixels kept, 7 non-HEIC
cases byte-identical, a cut file / a panicking decoder / a timeout go
as they came, and a plugin's fetch (fake plugin, new FAKE_SEES image
model) gets JPEG on /v1/chat/completions and /v1/messages.

Run at this tree (733fac48f + this change), on mote:
- gofmt -l internal: clean
- GOOS=darwin/linux/windows go vet -tags nogui ./internal/gateway
  ./internal/plugin: ok
- CGO_ENABLED=0 go build ./internal/gateway for darwin, linux, windows
  x amd64, arm64: ok
- go test ./internal/gateway ./internal/plugin -count=1 -timeout 45m:
  ok (774s, 134s)
- win-run (Windows amd64) and wsl-run (Linux amd64, AVX2 path):
  go test ./internal/gateway -run HEIC: ok

Broken by hand, each red, then restored:
- no heicAsJPEG call in serve: TestHEICReachesPluginAsJPEG red
- media_type not set for Anthropic: the messages subtests red
- no base64 mark scan: the "labelled jpeg/png" subtests red

Not tried: a real Pi -> WorkBuddy request with a real account; a real
iPhone gridded HEIC (only sips files and Apple's 26 MB wallpaper); a HEIC
behind an http URL (not fetched, goes as it came); Anthropic document
blocks, Responses input_file and images/edits.
2026-11-01 15:04:28 +08:00
yetone 60520ddb3b moejs: v0.1.0-alpha.11, at its new module path github.com/MoeForge/moejs
Gateway middleware and agent plugins run on moejs. alpha.11 moves the
module to github.com/MoeForge/moejs; every other API change since
alpha.4 is an addition. What magpie gets: faster calls, loops, property
lookups and JSON.parse, allocation-free await, a bytecode verifier, a
correct default.pgo, and Intl / toLocaleString in plugin code.

Checked against both tags' source: every name magpie uses (NewRuntime,
Options, Compile, Link, Hook, Value, Arg, Undefined, NativeFunc,
Referrer, the Promise results, Exception) has the same signature, and
Options' defaults (shared frozen builtins, no timers) are unchanged.
fetch, Streams, URL, node:fs and node:buffer live in the separate
webapi and node packages, installed only on request; magpie installs
neither, so a plugin still reaches no network or file.

Intl's CLDR, Unicode, ICU and V8 material is compiled into every build,
and moejs asks a program that includes it to carry sections 1 to 4 of
its notices. THIRD_PARTY_NOTICES holds them verbatim. Release archives
ship no LICENSE today either; that is not changed here.

Doc and site links (docs/, site/public/docs/{,zh/,ja/}plugins.html)
point at the new repo.

Run on mote at this tree: gofmt; go build -trimpath -s -w (60,670,658
bytes on origin/main 58fb3a778, 62,329,250 now, +1.66MB); go vet of
middleware, jsmod, agentplug for darwin, linux and windows; go test
./internal/middleware/... ./internal/jsmod/... ./internal/agentplug/...
ok; go test -run 'Middleware|Strateg|OnUsage|JSPlugin|Agentplug|AgentPlug'
./internal/gateway ./internal/provider ./internal/plugin ./internal/gui
ok.
Not run: the full suite, the GUI suite, a real request through a
middleware in a running gateway.
2026-10-28 14:36:17 +08:00
yetone 88ac42843d icons: a big picture is sent to the window scaled to 256px (#909, #1956, #2459)
A webview keeps every picture on the page decoded at its own size. The
Plugins page draws 152 icons at 20 to 64 points, and some stored icons
are 1254x1254, so opening Plugins alone added ~122 MiB to the renderer.

GET /api/icons/{name} now sends a PNG, JPEG or WebP longer than 256px
as a PNG copy scaled to 256 on its longest side (CatmullRom), made on
its first ask under the cache dir (icons-small) through temp-and-rename
and kept. SVGs, small pictures, pictures over 64M pixels and anything
that fails to decode are sent as they are. pruneIcons drops a copy
whose original is gone. golang.org/x/image goes from indirect v0.41.0
to direct v0.43.0 (needs only x/text v0.38, nothing else bumped).

Measured in Chromium (WebView2's engine) on a dev backend with a copy
of the real library and its 111 stored icons (6.2 MB):
- renderer RSS after opening Plugins: 369 -> 304 MiB
- renderer after visiting every page, on Settings: 310 -> 290 MiB
- decoded image area on Plugins: 18.5 -> 6.5 megapixels
- 15 scaled copies made, 596 KB in all
What is left on Plugins is SVGs, which rasterise at draw size.

Run at this head (before rebase onto 634cbf587, which touches only
internal/agent):
- go test ./internal/provider -count=1 -timeout 45m
  -skip '^TestUnreadLoginsWriteErrorsKeepCredentials$' (#3632): ok 95s
- go test ./internal/gui -count=1 -run 'Icon|Plugin': ok
- GOOS=linux and GOOS=windows go vet -tags nogui on both packages: ok
- gofmt -l internal/: clean
Broken by hand: with scaling turned off in scaledIcon,
TestBigIconServedScaled goes red ("want a scaled copy").
Not tried: WebView2 itself on Windows, and WebKitGTK.
2026-10-26 17:05:16 +08:00
yetone de49433ff8 filememo: another process's writes to magpie's files are watched for, not polled every 5s (#3185)
An idle magpie still woke a dozen times on each 5s beat: the loops that
follow plugins.yml, settings.json, providers.json, the plugin list, tools
and access each looked at the disk for what the CLI or a second magpie
wrote. The gateway now watches those files' folders (fsnotify: FSEvents,
inotify, ReadDirectoryChangesW), and a change from another process wakes
the same loops at once, as magpie's own writes do (filememo.Written).
With the watch running the loops look for a change they missed only once
a minute (OthersEvery); where the folders can't be watched, or the watch
errs, they go on looking every 5s.

Run at 466cafa0c + this change. The rebase onto 13f9c7fca brought in
internal/gateway's claude bridge and redact files, none of the files here;
after it, go build ./... and the filememo, pluginrt, awake tests ran again ok:
- go test -timeout 45m ./internal/filememo ./internal/pluginrt
  ./internal/middleware ./internal/otlp ./internal/gateway: all ok
  (gateway 384s).
- TestWatchWakesOnOthersWrites -count=3 ok; red with wake() taken out.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui on the
  changed packages ok.
- Real gateway, sandbox HOME, idle: proc_pid_rusage wakeups over 120s
  after a 90s warm-up, two rounds each: v0.1.1561 2.1 / 2.7 per second,
  this 1.9 / 2.0 (and 1.8 in a third run).
- Same gateway: plugins.yml replaced from outside with broken YAML; the
  gateway logged "plugins: ... doesn't parse" 0.02s after the write
  (it could take up to 5s before). File restored after.

Not tried: Linux and Windows real runs (vet only).
2026-10-26 11:22:20 +08:00
yetone 92ac1c878e search: the web search MCP server has a web_fetch tool that reads a page by its URL (#2286, blackrion)
An agent that mounted magpie's web search over MCP (Cursor, Claude Desktop)
found pages it couldn't open: it has no fetch tool of its own. web_fetch
(url, max_chars, offset) reads one.

- The URL is the agent's, so the page is downloaded the way a caller's
  image is (publicClient): public addresses only, every resolved address
  checked and pinned, redirects (at most 5) checked the same, a request
  from this computer included; only http and https. 30 s and 5 MiB at most.
- HTML is decoded from its charset (x/net/html/charset; golang.org/x/net
  added) and given as Markdown: title, headings, lists, links made
  absolute, code and pre; script, style, hidden elements dropped. Other
  text as it is; anything else, or a 4xx/5xx, is the tool's error.
- 20000 characters by default (at most 100000) from offset, with the
  offset the rest starts at.
- Each call reserves the gateway key's limit, as a search does.
- The tool description is neutral (names neither magpie nor a vendor).
- GUI: the MCP row's text names both tools (en, zh, zh-TW, ja, de).
  Docs: gateway-routing's MCP section, README (en, zh-CN).

Run: go test -tags nogui ./internal/gateway -run 'WebFetch|SearchMCP';
GOOS=linux/windows go vet ./internal/gateway; gofmt -l clean. GUI:
search-mcp, i18n-keys, gui-ja, gui-de, gui-zh-tw 32/32 (chromium +
webkit). Broken by hand: webFetchClient = http.DefaultClient turns
TestWebFetchOnlyPublic red (the local test server was reached).
Tried by hand (a throwaway test, not committed) against go.dev/doc,
en.wikipedia.org/wiki/Magpie and http://github.com/yetone (redirected to
https; links come out by name, not the pinned address: the first try gave
https://216.239.34.21:443/..., fixed by taking each redirect's URL from
CheckRedirect), and an httpbin redirect to 127.0.0.1, refused.

Full suite: SUITE_LINE
2026-10-15 23:08:00 +08:00
yetone 89825eca1a go.mod: go mod tidy — moejs is required directly (internal/gateway imports it), and go.sum drops testify 1.11.1 and go-spew/go-difflib, which nothing builds with
go mod verify, go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and the gateway and library tests pass.
2026-10-06 04:01:01 +08:00
yetone eebd0b4222 plugin, gateway, gui: a plugin can be gateway middleware — onRequest, onEvent and onResponse run in magpie's gateway on what agents send and get back (moejs) — a plugin could only be a subscription provider, run in the Bun host, a process away from the gateway. A plugin may now declare middleware (package.json magpie.middleware, or a *.middleware.js / .mjs file), run in-process by moejs (pure-Go JS engine): compiled once, one runtime per request from a pool, so every hook of a request shares ctx.state. onRequest(body, ctx) sees the agent's body in its own API before routing; what it returns is the body the next middleware and the gateway get, undefined leaves the bytes as they were, ctx.reject(status, msg) answers with an error in the agent's API's shape. onEvent(ev, ctx) sees each SSE event's JSON (export const events = [...] filters by name; an object changes it, null drops it, undefined passes the bytes through untouched; data: [DONE] is no JSON and passes by). onResponse(body, ctx) sees a whole JSON reply, with ctx.status. ctx has protocol, model, stream, path, agent, the plugin's options and state. A hook that throws, returns a non-object or runs past its limit (250ms request/response, 50ms an event, 1s load; interrupted) leaves the request or reply as it was and is counted and logged (60 lines a minute); a compressed reply passes as-is. Files are reloaded within a second of a change. Only agents' requests run through it (serveAgent at the gateway's agent entry points and the Codex backend), never magpie's own titles, classifier or stand-ins; it sees bodies before redaction. A middleware-only package is skipped by the Bun host. The Plugins page marks a middleware with a chip, its hooks, calls and µs per call (JSON in and out counted), failures in red with the last error, and a load error. en/zh/ja/de; docs/reference.md and usemagpie.ai/docs/plugins#middleware (en/zh/ja) with an alias example. Tested with a real DeepSeek account through magpie web --gateway in a sandbox HOME: an alias middleware served "fast" and named it in message_start, a reject came back as 403 permission_error, a Chat stream uppercased; real Claude Code (sandbox CLAUDE_CONFIG_DIR) did Read, Bash and Glob tool turns through three middlewares with 0 failures: ≈1–1.6µs an event, 0.2–0.7ms an onRequest that parses and rewrites Claude Code's ≈80KB body. Real use found two bugs fixed here: [DONE] parsed as JSON (SyntaxError on every Chat stream) and stats leaving out the JSON time. internal/middleware tests (chain, undefined keeps bytes, reject, fail-open on throw/spin/string with the runtime reused, async hook, load errors, off and Bun skip, reload, split/CRLF/filtered/dropped stream events, [DONE] untouched, whole reply and gzip, 64 in parallel; BenchmarkEvent ≈0.9µs, 11 allocs) and TestMiddlewareThroughGateway (alias routed, events by protocol, redaction still upstream, reject in Anthropic's shape; fails without the change) are new; plugin-middleware.test.cjs (Chromium and WebKit, en and zh: chip, hooks and stats, failures with last error, broken and off, no left border) fails without it. The other plugin GUI tests and click-scroll pass in WebKit. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass (internal/provider failed once under load and passes alone). 2026-10-05 19:14:31 +08:00
yetone b0a0165fc9 usage: a notification when a window is nearly used up or a balance runs low (#368) — Settings has Usage alert (off, or a share of 1–100%, 80 by default) and Low balance alert (off, or an amount, 5 by default), and magpie quota alert sets them from the command line. Each subscription or plan window, other than one set aside, is told once a run when it reaches the share, and a balance once until topped up past the amount again; what was said is kept, so a restart doesn't say it again, and a failed or stale reading neither alerts nor clears. The system's notifications are started only when first needed, so a Mac build that can't have them or a Linux desktop without a daemon still starts, and Settings says when they are refused or unavailable; a click opens the Usage page. TestDueAlerts and friends, TestAlertText and usage-alert.test.cjs fail without the change. 2026-10-01 04:16:28 +08:00
Zhizhen He d36dbe46f5 chore: go mod tidy (#66) 2026-09-25 22:11:19 +08:00
yetone dfc2d7fa93 library: MCP servers, skills and instructions are kept once in magpie and given to any agent from one place, with a market to find and add them (#29). Each agent reads MCP servers and skills from files of its own and in a format of its own, so one server was set up again in Claude Code, Codex, Gemini CLI, OpenCode, Pi, Goose, Cursor, Copilot CLI and Crush. The Library view keeps each once: a server is added (stdio, http or sse, its env and headers) and switched on per agent with its icon, and magpie writes it into each agent's config in that agent's format, leaving what the agent has of its own as it is; a server or skill an agent already has is shown, to bring into the library. A skill is a folder with a SKILL.md, kept in the library from GitHub (owner/repo, or a link to a folder in one; updated from it later) or linked from a folder on this machine, and linked into each agent's skills folder. The instructions every agent reads (CLAUDE.md, AGENTS.md, GEMINI.md…) can be kept as one too. The market offers checked MCP servers first, then the official MCP Registry's, filled in from what the registry says each needs (keys asked for in a form, never guessed), and skills.sh's most installed skills with what each says it is for; each shows its real icon (the vendor's own, else its GitHub owner's), fetched through magpie only for the icons the market or the library gave out, and an added server or skill keeps its icon in the library. What magpie changes in an agent's files is backed up first 2026-09-25 14:11:17 +08:00
yetone c3931c91df codex: magpie's models join Codex's own rather than replacing them — signed in (ChatGPT or an API key), Codex keeps its built-in OpenAI provider and sign-in and is pointed at magpie with openai_base_url alone, so its official models still go to OpenAI on the user's own account, its threads (listed per provider) stay together, and the Codex app keeps its model picker; magpie's gateway answers at /backend-api/codex, passing Codex's own models through as they came, serving magpie's (provider/model) itself, and handing out OpenAI's model list with magpie's after it for /model. Compacting a magpie model's conversation is done by that model with Codex's own prompt; Codex's compressed request bodies are read, and usage is counted for both. Not signed in, magpie stays a provider of Codex's as before; a magpie set up that way moves over the next time a magpie model is picked 2026-09-25 02:42:24 +08:00
yetone 41931e2895 agent: omp (oh-my-pi) — its model picked in magpie like any agent's; a model through magpie adds magpie as a keyless provider in ~/.omp/agent/models.yml with the catalog as its models, and sets config.yml's modelRoles.default to magpie/<provider>/<model>; its other roles and the rest of both files stay as they are, comments too, and default takes magpie's entry out unless another role still uses it (#34) 2026-09-24 22:36:15 +08:00
yetone efbe5660b0 backup: everything set up in magpie carried to another machine in one file — magpie backup writes the providers with their keys (or none, with --no-keys), the pictures picked for them, the settings, the profiles and every agent's model, sealed with a passphrase (AES-256-GCM, PBKDF2-SHA256) so nothing in it reads without it; magpie restore puts it in, replacing providers by id, keeping the keys already there for one that came without, and setting models only for the agents installed there; subscriptions stay with the machine they were signed in on (#28) 2026-09-24 20:34:15 +08:00
yetone 0b0f258c0f providers: import from other apps — the add sheet's Import… reads the providers CC Switch (its database, or the older config.json) and Alma have set up, read-only, and lists them to pick from: what magpie has already is marked, a key for a vendor that is already here can join it as another key, an id in use is kept beside or replaced, and sign-ins, Azure, Gemini-protocol relays and entries pointing at magpie itself are shown but not offered; keys are read again on import and only reach the window masked 2026-09-24 18:48:08 +08:00
yetoneandClaude 0a234ce41d dial: one dial for every coding agent's model
Wails v3 tray panel and window, TUI and CLI. Switches model, effort and
provider for Claude Code, Codex, Gemini CLI, OpenCode, Pi, Goose, Cursor,
Copilot CLI and Crush with format-preserving config edits. Providers page
and registry, stored keys, live vendor model lists, profiles.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-22 21:47:29 +08:00