Commit Graph
6 Commits
Author SHA1 Message Date
yetone 7aff42d863 plugin host: the sign-in lock and file waits no longer freeze the event loop (#5112)
pause() was Atomics.wait, which blocks Bun's one thread. lockAuth spun on
plugin-auth.json.lock with pause(5) for up to 2 x AUTH_LOCK_STALE (20s),
and writeDurable and readFileSteady waited up to 500ms each, so one
plugin's renewal storm stalled every plugin's requests, model lists and
check-ins (499s while the port still answered). Reported by mycf_711.

- pause() is gone; sleep() is an awaited setTimeout.
- lockAuth, writeDurable, keepAuth, writeAuth and changeAuth are async,
  and so are their callers (setAuth, removeAuth, settle, save, apiKey,
  staleAccess, import/take/signOut, pi.js modify/delete).
- changeAuth takes in-process changes one at a time (authQueue) before
  the file lock, so a host's own changes don't poll against each other;
  the lock poll backs off 5ms to 50ms. Stale-lock takeover (10s) and the
  change being made on a fresh read under the lock are unchanged.
- The sync readFileSteady (readAuth, hot path) no longer waits: it retries
  twice at once, and readAuth keeps the last good read when the OS still
  refuses (a failed read is unknown, not none). Under the lock the wait
  is async (readFileSteadyAsync, 50 x 10ms as before).

Test: TestAuthLockWaitDoesNotFreezeTheHost holds the lock 600ms and checks
a timer keeps ticking while changeAuth waits, 20 concurrent changes lose
none, and a lock 11s old is taken over. On the old host.js it fails
("the lock is still held at 300ms": the loop froze 10s). Verified by
putting the old host.js and pi.js back.

Run (mote, at this tree): go test ./internal/plugin ./internal/gateway
./internal/provider all ok; gofmt, GOOS=windows/linux go vet of
internal/plugin clean. Not run: full go test ./..., a real Windows host
under a renewal storm. The serial-fallback total budget is #5113.
2026-11-04 01:53:46 +08:00
yetone a64b3a8d46 plugin: a pi provider's message_start tells the prompt's usage pi's start named, so Claude Code's context meter isn't 0 until the turn ends (#1887)
What: pi.js wrote message_start with usageOf() and no argument, so every
field was 0 until message_delta. Claude Code's context meter reads the
usage the assistant message has so far, and a turn interrupted before
message_delta was stored with 0. message_start now carries the vendor's
prompt (input, cache read, cache write) and the output pi's start named
(startUsage): from pi's start event's partial.usage, as the issue
describes, or, as pi-ai's anthropic-messages pushes start before it reads
the vendor's message_start (start's usage is still 0 then), from the
partial message the events after it share. That message is pi's own,
still being written (by the time magpie reads it pi may have pushed the
whole turn), so only its prompt is taken from it, never its output.
message_delta is unchanged: the whole turn's cumulative usage from done.

Siblings, the gateway's translators to Anthropic's stream:
- Gemini / Code Assist (codeassist.go): usageMetadata rides on the first
  chunk, but KStart was emitted before reading it. KStart now carries the
  prompt (input, cached); output stays 0 there.
- Chat Completions (chat.go): most streams count only at their end, so
  nothing to tell; a stream that counts on its first chunk now has its
  prompt on KStart.
- Responses: response.created has no usage. Anthropic-to-Anthropic and the
  Claude subscription already carry it. Cursor, Kiro, Devin, Qoder,
  Command Code send KStart before any usage is known.

Ledger: no double count. The usage sniffer and the collector both take
each field's latest non-zero value (Usage.add replaces, it doesn't sum),
and continuation/search take a try's KStart usage as its own (this =
ev.Usage) and KUsage replaces it. message_delta's input equals
message_start's, which Anthropic's clients also take as the same count.

Run (Go 1.26.8, darwin):
- TestPiPackage with a fake pi stream as the issue's (start with
  partial.usage input 11, cache 3/2, output 0, text, done with output 7):
  message_start 11/3/2/0, message_delta 11/3/2/7; and pi-ai's order
  ("late": start with zero usage, then the shared message counted):
  message_start 11/3/2/0. Red with message_start back on usageOf(), and
  the late case red when only start's usage is read.
- TestPromptUsageOnMessageStart (Gemini, chat counting per chunk, chat
  counting at the end): red with codeassist.go and chat.go stashed.
- go test ./internal/plugin and ./internal/gateway in full (-timeout 28m;
  the default 10m timed out under load average ~20). The disk filled
  during the run (3.7G free, not this change's): every failure was
  ENOSPC, and each of them (37 gateway, TestFakePlugin) passed on rerun.
- gofmt -l; go vet for darwin, linux and windows on both packages.
Not tried against a real pi vendor or Claude Code's meter.

Reported-by: guoqchen1001
2026-10-13 10:29:31 +08:00
tobitege 21702d01ff Add German translation; harden paths against unset env vars (#770)
* Add German translation and harden paths against unset env vars

Add a German locale to the GUI, tray menu, usage alerts and website home page, and refuse to start when the home folder is unset or relative so nothing is written under the working folder; the pi plugin no longer adopts the user's PI_CODING_AGENT_DIR, and an inherited APPIMAGE no longer selects portable mode. Scripts refuse to run from the wrong folder or empty a shared out folder, and a new internal/testenv sandboxes every test package from the user's real files, which also fixes the Claude picker and Termux installer tests on Windows.

* Makefile: know magpie's folder by its go.mod, so paths with spaces work

The check compared $(CURDIR) with $(dir $(abspath …)), which make splits on spaces, so a checkout under 'My Projects' or 'John Doe' refused every target. It now reads go.mod relative to the working folder and wants magpie's module there: make -C and a symlinked Makefile work, make -f from another folder still stops before any recipe runs.

* i18n: German for the strings main added since, with a parity test

75 strings main added (group order, patterns, slow-start wait, usage caps, RTK savings …) get their German, and two that main dropped go. gui-de.test.cjs checks, as gui-ja does, that de has every zh string with its placeholders and tags, and that the window reads in German when picked or on a German system.

* appdir: ignore relative folder variables when reading, keep them for children

CheckEnv no longer unsets anything. magpie reads the XDG folders, APPDATA/LOCALAPPDATA and every agent's folder variable through appdir.Getenv/LookupEnv, which pass over a relative value; the environment stays as it is, so the agents magpie starts get the variable as the user set it. That covers what proc.UserPath lends from the login shell too, which is set after main's check and reached the desktop app unchecked. On Windows a path rooted on the current drive (\Users\x, Git Bash's /c/x) counts as usable, and magpie version and help answer without a home, before run makes any folder.

* Sandbox the tests main added since

internal/wslrun gets testenv's TestMain, and four tests main added that set HOME alone set their home with testenv.SetHome, so on Windows they don't read the runner's profile through USERPROFILE.

* agentenv: PI_CONFIG_DIR and OPENCODE_DB take relative names on purpose

omp puts $PI_CONFIG_DIR under the home and OpenCode a relative $OPENCODE_DB in its data folder, so neither depends on the working folder: appdir no longer passes them over.

* i18n: German for the Library's multi-select and System One's decision API

The 19 strings main added since (#791's skill multi-select, the decision API snippets) get their German; the one main replaced (four APIs → five APIs) goes.

* appdir: tidy the import into magpie's group; say what Go makes of /c/x

The appdir import joins the group of magpie's own imports where a file has one. rooted's comment now says that Go takes a Git Bash path like /c/x as \c\x on the current drive, not C:\x.
2026-10-04 23:30:56 +08:00
yetone 0ae7330242 plugin: a pi package's sign-in screen on pi's terminal UI is asked in magpie, and an empty reply a package makes of a vendor's error says the error (all pi plugins: Kiro's login hung, pi-zcode's quota ran out as an empty answer) — pi-provider-kiro asks how to sign in through ctx.ui.custom, a component of pi-tui (a SelectList, then Input fields for a start URL and region), and magpie gave pi's runner no UI, so custom came back undefined and the sign-in waited forever. pi's runner now has a UI for the sign-in's questions: select, confirm, input and editor become magpie's sign-in prompts, and custom draws the package's component and asks its list or field the same way, answering through the component's own onSelect/onSubmit, until the package calls done. A component may keep its parts to itself (Kiro's gives only render and handleInput) and each package loads its own copy of pi-tui, so the parts are found by what drawing walks: every container goes through its children, so the arrays iterated while it renders are what it shows, in order; the text above the list is its question. Outside a sign-in the UI answers as pi's no-UI context does. session_start now reaches every package at startup, which Kiro needs to keep the context it asks through. Separately, pi-zcode turns ZCode's 1005 quota error into a reply with no content; magpie keeps the small JSON or text bodies a package's fetch gets while it streams, and a stream that ends empty answers that body's message and code (429 for quota or rate limits, else 502) instead of an empty message. TestPiPackage drives a fake package that asks on real pi-tui classes (a list, then a start URL field) and fakes ZCode's empty quota reply; it fails on the old code (no first prompt) and passes. With real accounts in a sandbox HOME: Kiro's "Kiro Login" (API Key, Web Login, Device Code) came as a select, Web Login gave the app.kiro.dev sign-in, and after signing in kiro-plugin/claude-sonnet-4-5 called get_weather and answered with its result. pi-cursor (1.4.38, latest) answers plain turns but its models say no get_weather tool exists, though the package sends it (toolCount 1, its MCP schema) and Cursor's stream carries fields the package doesn't know; that is between pi-cursor and Cursor. The ZCode quota path wasn't tried with a real account. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-03 23:47:15 +08:00
yetone 67092380fb plugin: pi packages run as pi runs them — a program a login starts can't take the host's stdin, a select is answered with its option's id, and the extensions get pi's runner, pi's auth.json and session_start (owner: 都补上,用真实账号测) — tried with real accounts, five pi packages had problems that the fake one didn't show. pi-devin-plus runs devin auth login with stdio "inherit" when it finds no Devin sign-in, and the program read magpie's next requests from the host's stdin as its answer ("Login canceled") while writing over its answers; host.js now gives every program started through Bun.spawn and Bun.spawnSync (all of node:child_process goes through them) nothing to read and stderr to write. pi-zcode asks its region with onSelect and options { id, label }, pi's own shape, and checks the id ("bigmodel"); pi.js answered with the label, so the login said "Login cancelled". Packages read their sign-in back from pi's auth.json (readStoredCredential: pi-zcode for its plans, pi-cursor for its token, pi-provider-qoder through the registry, pi-antigravity syncs its accounts through it) and register what they find on session_start (pi-zcode its plans' models, pi-devin-plus and pi-xai-oauth refresh their catalogs), and a provider registered after loading went into a queue nothing read. Now each package is bound with pi's ExtensionRunner as pi's session binds it (bindCore: no UI, tools or session of magpie's), so a later registerProvider reaches the runtime; each pi provider's first account is kept in $PI_CODING_AGENT_DIR/auth.json as pi keeps it, written when it changes; and a provider newly signed in, and each one signed in when the host starts, is sent session_start, after which magpie lists its models again if they changed. A runner that can't be made leaves the packages registered as before. TestPiPackage now has a select answered with an id, a login that starts a program on the terminal, and a session_start that reads the sign-in from pi's auth.json and adds a model; it fails on the old code (the label answered; the model never listed, auth.json empty) and passes. With real accounts in a sandbox HOME: pi-zcode signed in through Z.ai and lists 11 models (none before); its requests reach ZCode but the account's Start Plan answers 200 {"code":1005,"msg":"exceed quota limit"}, which pi-zcode reads as an empty answer (its bug). pi-provider-qoder signed in through Google, 16 models, tool round trips on Kimi-K3 and Efficient. pi-devin-plus signed in, its catalog refreshed on session_start (53 models), tool round trips on swe-2 and claude-opus-5.5; pi-xai-oauth (grok-4.7) and pi-antigravity (gemini-3.8-flash) tool round trips; @rahularya01/pi-cursor answers text (its agent doesn't call a client's tools, upstream). pi-provider-kiro wasn't signed in: it needs pi's terminal, a Builder ID or an IdC login. go vet, builds (darwin, GOOS=linux -tags nogui, GOOS=windows) pass. 2026-10-03 22:51:24 +08:00
yetone 1baad0d2d4 plugin: pi packages are plugins as OpenCode's are — a pi coding agent package (its extensions) adds providers to magpie: their models, their sign-in, renewals and requests (owner: 我希望全面兼容 pi 插件!!!!!!!!!!) — a package is pi's when its package.json has a "pi" manifest, the "pi-package" keyword, or pi-coding-agent among its dependencies (IsPi, mirrored in host.js). Adding or updating one installs @earendil-works/pi-coding-agent beside it, and the plugin host loads every pi package through pi's own loader (pi.js: discoverAndLoadExtensions and ModelRuntime, with the credentials kept in plugin-auth.json), so an extension's registerCommand, registerTool and pi.on are taken and left unused, and its registerProvider calls become magpie providers. A provider's models keep their context, output, images and the reasoning levels their thinkingLevelMap allows; its OAuth login runs as pi runs it, each onPrompt asked in magpie's sign-in in turn, onAuth's page opened, a later prompt being the code pasted back; a provider with apiKey takes a key; magpie renews through refreshToken and saves the result. Requests arrive as Anthropic Messages and go to pi's stream: system and tools, images, tool results, thinking budgets and effort as the nearest level the model has (and the least it allows when it can't turn thinking off: Antigravity's gpt-oss refused requests without one), max_tokens held to the model's; the answer comes back as Messages SSE or JSON with thinking and its signature, redacted thinking, tool calls (their thought signatures kept for the next turn), usage, and a failure before anything is said as the vendor's status with Retry-After. The Plugins page's search also finds pi packages that bring a provider. Tried with the owner's real Antigravity account through pi-antigravity, next to the Grok OpenCode plugin in the same host: 14 models listed, Gemini streaming with usage, Claude Sonnet thinking with signatures, gpt-oss, tool round trips on gemini-3.8-flash, gemini-3.1-pro and claude-sonnet-4-6, a 400 and Antigravity's 429 passed on with their status. A Claude Code turn didn't get through: Antigravity answers 429 to any system prompt with Claude Code's billing header or its "Claude agent" line, through magpie's built-in Antigravity just the same. TestPiPackage (a fake pi package: models, an OAuth login asking twice with a wrong code then a right one, a key, streaming and JSON answers, thinking and tool signatures back, a 429, a renewal) and TestSearchFindsPiPackages pass. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass but TestClaudeRunEndsWhenTheClientLeaves, TestProvidersAnswerWhileListsComeIn and TestSavedButSignedOutClaudeServed, timing tests that pass alone. 2026-10-03 19:12:19 +08:00