Commit Graph
9 Commits
Author SHA1 Message Date
yetone e4197144a8 perf: every package's package-level regexps compile on first use
v0.1.3516 made gateway's and redact's patterns lazy. The other 299
package-level regexp.MustCompile calls, in 148 files across agent,
provider, gui, library, codexcat, sessions, usage, plugin and the rest,
now go through lazyre.New too, so a launch that never reaches them
(`magpie statusline`, run by Claude Code on every message) doesn't
compile them. Fields, maps and params that held them are *lazyre.RE.

Measured on mote (M5 Pro), sandbox HOME, v0.1.3516-equivalent build
(t42) against this one (t43):
- GODEBUG=inittrace=1 sum: 7.39 MB / 69,837 allocs -> 4.62 MB / 46,765
- `magpie statusline`, 3 runs each: instructions retired ~212M -> ~176M,
  peak memory footprint 19.2-19.4 MB -> 16.8-17.0 MB

Run: go vet ./... (darwin) ok; GOOS=windows go vet on each of the 30
changed packages ok; GOOS=linux go vet ok except ., internal/cli and
internal/gui, which stop in wails v3's cgo files when cross-compiled
(the same at main). New TestAllLazyPatternsCompile at the root compiles
all 574 registered patterns (ok), so a bad pattern fails a test rather
than a first use.
Not run before push: the changed packages' own test suites; they run
on mote after it.
2026-11-10 12:54:39 +08:00
yetone 1fd02d33ce agentplug: an agent plugin can pick the model its agent starts on in a second file (str_, PiG)
str_ on Discord (#help, v0.1.3005): PiG's row on the Agents page only
switched the model list on, where Pi's picks the model it starts on.
PiG, like Pi, keeps its providers in ~/.pig/agent/models.json and the
model a session starts on in settings.json (defaultProvider,
defaultModel; PiG's docs/site/docs/settings.md, startup_model.go). An
agent plugin could name a model key only in the one file connect
writes, so agent-pig 0.1.0 had to be connect-only.

An agent's descriptor can now say `startup: {config, format, model,
keys}`: the other file, the key that holds the model (the id without
magpie's prefix) and keys written beside it. With it the row gets a
model field as a built-in's does. Picking one of magpie's writes
connect's keys into config and the model and keys into startup.config,
each key kept aside as before; a model of magpie's picked in the agent
itself still reads as magpie's; a model of the user's own picked there
while magpie's provider is listed counts as connected (Beside), not
drift, and is kept on disconnect. Sync rewrites the list and leaves the
startup model where it is. Off, or `magpie <id> default` with the plugin
gone (RestoreGone), puts both files back. startup without connect, beside
agent.model, in config's own file, or naming the model key among keys
is refused. An older magpie ignores the field, so agent-pig 0.1.1
(plugins repo) stays connect-only there. Every other agent plugin
already names its model in its own config; pig is the only
connect-only one.

Run (mote):
- go test -count=1 ./internal/agentplug/: ok
- go test -count=1 -run 'TestPlugged|TestPlugin|TestRestoreGone|TestAgent'
  ./internal/agent/: ok
- go vet, GOOS=linux and GOOS=windows go vet of both packages; gofmt -l
  clean
- the four TestPluggedStartup* tests on the old code: red (the row had
  a provider field and only listed models)
- real PiG 0.5.3 (darwin-arm64 release, SHA256SUMS checked) in a sandbox
  HOME, models.json written by agent-pig 0.1.1's own connect and
  settings.json as startup writes it, against a fake OpenAI server:
  `pig -p` sent model deepseek/flash with the gateway key. With an
  enabledModels scope that leaves it out, PiG started on the scope's
  first model (said in the plugin's README).

Broken by hand: no startRestore in Unwire (TestPluggedStartupModel and
OwnPickKept red); no Beside (OwnPickKept red, "wired false").

Not tried: the GUI and the TUI with the real row (app.js unchanged; the
row is the model field every built-in has), Windows and Linux runs of
PiG, a real magpie gateway in front of PiG, a real vendor model.
2026-11-05 10:46:46 +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
JoeyWu-tech d10cdf7969 agentplug: a late timeout no longer fails every connect after it (#3727)
An agent module loads and connects under limit, whose timer interrupts
the module once its second has passed. When the timer fired just as the
call returned, Stop didn't wait for its func, which could still be on
its way to Interrupt when limit read fired. The interrupt then landed on
an idle runtime, and moejs keeps one that lands while nothing runs for
the next call, whatever it is (its Interrupt doc). That call's own limit
never fired, so nothing cleared it: the agent's every connect after
failed with "connect: interrupted: took too long" until magpie loaded
the module again. A module that takes about its second, on a busy
machine, is the case.

limit now waits for the timer's func when Stop says it has begun, then
clears the interrupt it gave. A call the timer ran out on reads took too
long when it failed, as before, and keeps what it returned when it
finished; before, which of the two it got depended on the same race.
afterFunc stands in for time.AfterFunc, so a test can hold the timer's
func.

internal/middleware's timer func can run late the same way; there it
stops only the next call, not every one after: #3742.

What was run (tree 0199ae4d, on origin/main 68ee4117, go1.26.8,
linux/amd64):
- TestLimitRunsOutAsTheCallEnds, new: in a synctest bubble the timer's
  func is held as the call returns. limit hasn't returned while it is
  held; once it is let go, a call that finished keeps its nil, one that
  failed reads took too long, and the connect after answers at once.
- TestLimitStopsAModuleStillRunning, new, green with main's limit too:
  limit's everyday case. A connect that never ends, at once or after an
  await, reads "connect: took too long" and the three connects after it
  answer; a load that never ends reads took too long.
- Each 50 of 50 ok, and -race -count=40 -cpu 1,2 ok with no race.
- Broken by hand, each red with its own message:
  - main's limit, through afterFunc: both cases, limit returning while
    the func was held and the connect after failing "connect:
    interrupted: took too long", and the failed call returning the
    module's own error;
  - no wait for the timer's func: both, returning while it was held,
    and the connect after;
  - the interrupt cleared before the wait: both, the connect after;
  - the interrupt also cleared as each call starts, with no wait:
    both, returning while the func was held;
  - no clear: both tests, every connect after;
  - the timer never stopped, so every call waits for its func: both
    cases, the connect after taking its whole second;
  - a call the timer ran out on always reading took too long: the one
    that finished;
  - one that failed keeping its own error: the one that failed, and
    TestLimitStopsAModuleStillRunning's three cases, with the runtime's
    "interrupted: took too long".
- The issue's case, with a pause put into the timer's func before it
  interrupts, a connect that busy-waits 100ms and connectLimit at 50ms
  for that one call: on 68ee4117 the three connects after all failed
  "connect: interrupted: took too long"; here that call returned once
  the pause ended, and all three answered.
- gofmt -l lists nothing; GOOS=linux, windows and darwin go vet -tags
  nogui ./..., GOOS=windows go vet ./..., GOOS=linux and darwin go build
  -tags nogui ./... and GOOS=windows go build ./...: exit 0 each. go vet
  and go build without the tag on linux: exit 1, pkg-config finding no
  fontconfig, libsoup-3.0 or gio-unix-2.0 (no GTK or WebKitGTK headers
  on this box).
- Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp
  (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout
  45m, log kept): 66 ok, internal/agentplug among them, and 7 red, none
  in what this changes:
  - agent TestCodexDriftReached and TestCodexBehindReverseProxy: #3398;
    TestInstalledVersion, TestCursorFolderFromTheEditorIsNotTheCLI,
    TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
    TestQoderSettingsFromAnIDEPluginIsNotTheCLI,
    TestOmpDetectedWithPiDir and TestZedAppPath: #3141;
    TestReasonixCLIRequiresSupportedNativeVersion and
    TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git,
    #3641.
  - davsync TestSyncTeraCloudStillSeesOtherWrites: #3420.
  - edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram: this
    box's umask 077, #3640.
  - gateway TestPluginToldWhereTheAgentWorks: this box's /tmp/.git,
    #3675.
  - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie:
    this box's millions of open fds, #3649.
  - provider: "fatal error: close of synctest channel from outside
    bubble", #3632; the package's tests after it didn't run.

Not tried: Windows or macOS, and a real plugin's module that takes
about its second; the timing is injected.

Reviewed on macOS arm64, go1.26.8, rebased on 430e3050d: -race
-count=40 -cpu 1,2 on internal/agentplug ok (and -count=20 again after
the rebase). Broken by hand: main's limit through afterFunc turned both
new cases red with the messages above; dropping ClearInterrupt turned
all four red. internal/plugin, internal/library and internal/cli ok;
gofmt clean; vet ok for linux nogui, windows, darwin. Not run:
internal/agent (slow, no change there beyond the import).
2026-10-27 15:52:01 +08:00
yetone 3ec3cb704b plugin: turning an agent plugin off or removing it puts the agent's config back first (#3810)
An agent a plugin adds is known only while the plugin is on. Turning
the plugin off or removing it (CLI `magpie plugin off/rm`, or the
Plugins page) left the agent's config on magpie, and `magpie <agent>
default` then said `unknown agent`, with nothing to put it back.

- provider.SetPluginOff (off) and provider.RemovePlugin first call
  provider.PluginAgentGoing, set by internal/agent to UnwirePlugin: the
  agent is disconnected as `magpie <agent> default` does (Disconnect),
  while the plugin still loads. A plugin off already is read from its
  module as it is; one whose module is gone puts back each file whose
  stash names its spec. If that fails, the plugin is left as it was
  and the error says why.
- The stash now records the plugin's spec and the file's format, so
  `magpie <id> default` for the agent of a plugin deleted on disk puts
  the file back from the stash alone (agent.RestoreGone; an older
  stash's format comes from its file's name, agentplug.FormatOf). A
  file that no longer holds magpie's gateway key is the user's and is
  left alone; one that can't be read is unknown: nothing is written,
  the stash is kept. With the plugin only switched off, `default` says
  the agent is off magpie already instead of "unknown agent".
- Turning the plugin back on (or installing it again) does not rewire
  the agent by itself: its config stays as the user had it. Connecting
  it (its switch on the Agents page) puts back the model it was on,
  through Disconnect's `.reconnect`. The CLI says so when it turns off
  or removes a plugin whose agent was on magpie.

Run (this change on origin/main f3c4d7b7a, then rebased onto
0fb0bfda3, which changes only an internal/gateway test; provider and
cli run again at the pushed head):
- gofmt -l: none; go vet -tags nogui on darwin, linux, windows for
  agent, agentplug, cli, provider, gui, plugin: ok.
- go test -tags nogui -timeout 45m -count=1 ./internal/agent
  ./internal/agentplug ./internal/cli ./internal/provider
  ./internal/plugin ./internal/gui: agent, agentplug, cli, plugin, gui
  ok; provider crashes in TestUnreadLoginsWriteErrorsKeepCredentials
  ("close of synctest channel from outside bubble", filememo.Forget),
  the same on origin/main 0fb0bfda3 run alone: #3632, open, not this
  change. At the pushed head: cli ok; provider with -skip
  TestUnreadLogins ok.
- Real use, sandbox HOME, magpie built from this tree, gateway on
  127.0.0.1:3491, web on 3492: `magpie plugin add agent-kilo`
  (@magpie-community/agent-kilo 0.1.0, not on npm, from the plugins
  repo's dist branch), a kilo.jsonc with comments and a provider of its
  own, `magpie kilo magpie/deepseek/deepseek-chat` (wired, provider
  block added). Then, each time from wired: `magpie plugin off` -> cmp
  byte-identical; `plugin on` -> still the user's; `plugin rm` ->
  byte-identical; POST /api/plugins/off and /api/plugins/remove (the
  Plugins page's calls) -> byte-identical; plugin dir deleted and
  plugins.json emptied by hand, then `magpie kilo default` -> put back,
  byte-identical. `magpie kilo default` with the plugin off says it is
  off magpie already.

Broken by hand, each red, then restored:
- PluginAgentGoing left nil: the four off/remove tests fail.
- the SetPluginOff call removed: Off and ModuleGone tests fail; the
  RemovePlugin call removed: Remove and RemovedWhileOff fail.
- Spec not stashed: ModuleGone fails. pluggedOff disabled:
  RemovedWhileOff fails. FormatOf fallback removed: TestRestoreGoneAgent
  fails. The gateway-key check removed: LeavesAFileOffMagpie fails.
- Unwire instead of Disconnect: the Off test fails (How "first", not
  "again"). The off-plugin check in RestoreGone skipped: the Off test
  fails. RestoreGone not called from the CLI: TestGoneAgentDefault
  fails with `unknown agent "kilo"`.

Not tried: the Windows box; a real Kilo CLI reading the restored file;
the GUI suite (no Plugins page code changed: the page's calls reach the
same provider functions, tried above through the web API). Not changed:
an inline JSON object magpie wrote into comes back reformatted (same
values) on any plugin agent's Disconnect, `default` included: #3814.
2026-10-27 10:01:46 +08:00
yetone dbf331211f agents: an agent plugin with no model key is connect only, a switch with no model picker (#2374, rocona)
A Raycast plugin wants magpie to write the gateway, the agent's key and
the model list, and leave the model to Raycast's own picker. agent.model
was required ("agent.model names no key"), and the row always had a
model picker whose pick Raycast never read.

An agent export without model is now connect only:
- its one field is provider, magpie or nothing, as an app whose one
  setting is magpie as its provider (ZCode); ListsModels is set, so the
  row has the model list button and no model picker; no new UI control
  and no new strings
- connect is called without model and only its keys are written; the
  stash, the restore on Disconnect, the agent's own key and Check work
  as before; Sync calls connect again on a catalog change
- such a module must export connect (else it doesn't load, saying why),
  and connect must return keys (else the connect errs and nothing is
  written), so the row never says connected with nothing written
An export with model behaves as before. Docs: the plugins page (en, zh,
ja) and docs/subsystems/agent-wiring.md.

Tests (internal/agent/plugged_connect_only_test.go):
- TestPluggedConnectOnly: one provider field, menu, connect without a
  model, no model key written, the user's key and theme kept, list
  follows a catalog change, Check sees a base moved by hand, off puts
  everything back.
- TestPluggedConnectOnlyWritesSomething: no connect is a load error;
  connect returning {} errs and writes nothing.
Broken by hand (only forced false and model passed): both FAIL.
The /api/state row for such an agent was dumped through gui.state() in
a temporary test: key provider, one magpie option, menu true, the same
shape as ZCode's. zcode-models, plugin-agent and agent-connect GUI tests
pass in Chromium and WebKit (46/46; every language, 1100/980 and 420).

Run at origin/main 9d97fd073 + this change and the #2373/#2372/#2374 commits beside it (one tree), -tags nogui -count=1
-timeout 45m: internal/agent, plugin, provider, catalog,
gui, gateway ok. gofmt -l clean; go vet -tags nogui ./... for GOOS
darwin, linux, windows clean.

Full suite: SUITE_LINE
2026-10-15 23:08:04 +08:00
yetone c3bbf16022 agentplug: an agent plugin's keys are written in the order it gave them (#1890)
What: connect's result is taken from the module as JSON text (moejs
AppendJSON keeps JS insertion order) instead of rt.ToGo, which made a Go
map at every level. An object or array connect returns reaches the writer
as a json.RawMessage, so edit.SetJSON writes it in the plugin's order;
strings, numbers, booleans and null are their Go values as before (the
gateway-key mark still matches a string). edit.SetYAML now takes a
json.RawMessage too, as a block-style node in the text's order (it would
have written the bytes as a list of ints), and the env format writes it
compact as before.

Why: Kilo's agent plugin (magpie-community/plugins#90) returns each
model's effort variants weakest first, low, medium, high, the order Kilo
lists them in. Go maps marshal sorted, so Kilo showed high, low, medium.
magpie's own OpenCode wiring already keeps order (openCodeVariants).
The key paths connect returns are still applied in sorted order: each is
a separate edit, and the user's file around them is untouched.

Siblings: rt.ToGo's other caller (middleware's string lists) writes no
file; the Library's MCP block for a plugin agent is built by magpie, not
returned by the plugin.

Run:
- TestPluggedKeepsPluginOrder (Kilo-shaped connect, a kilo.jsonc with a
  comment, a theme, $schema, a provider of the user's own with keys
  zeta, alpha and a trailing key) and TestPluggedKeepsPluginOrderYAMLAndEnv.
  With agentplug.go put back: FAIL, variants written high, low, medium
  and provider keys sorted. With yaml.go put back: FAIL, the object
  written as a list of byte values. Both pass with the change.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., the three builds: OK.
- go test -tags nogui -timeout 40m ./... under a scratch HOME: all ok.
  (A first run with the default 10m timeout timed out in
  internal/gateway while four other sessions' suites ran on this box and
  the disk was full; the gateway package took 973s under that load and
  passed.)
- Real use, sandbox HOME: this build, `magpie plugin add` of
  packages/kilo at plugins PR #90 head b67360cb7, a provider whose
  fake-chat has efforts stored high, low, medium; `magpie kilo
  magpie/fakeup/fake-chat` wrote variants low, medium, high with the
  user's comment, $schema, theme and own provider in place, and
  @kilocode/cli 7.8.8 `kilo models magpie --verbose` lists them low,
  medium, high. `magpie kilo default` put the file back; the only
  difference is Kilo's own one-time permission migration.
2026-10-13 10:55:45 +08:00
yetone 26816de2f9 library, agentplug: an agent a plugin adds is given the Library's instructions, MCP servers and skills where its agent.library says (AlmarionAI on X)
Agent plugins wired models and keys only: library.targetOf had no case
for them, so the Library's instructions, MCP servers and skills never
reached an agent a plugin adds, while the announcement said the
Library carries over.

An agent export can now say
  library: { instructions, mcp, mcpFormat, skills }
each a path (~ and $VAR expanded, as config is). mcpFormat names the
agent whose MCP file it is shaped like (agentplug.MCPFormats: claude,
codex, gemini, opencode, cursor, zed, ... 18 of the library's
mcpFormats). A format outside the list, or an mcp without one, keeps
the plugin from loading. library.pluginTarget makes such an agent a
Target, so it is written as any agent is: magpie's marker block in the
instructions file, servers merged beside the user's own (their fields
kept), skills linked or copied, Applied recording only magpie's part,
backups kept. Takes refuses a place the plugin doesn't name, and says
which agent.library key would give it.

Docs: docs/subsystems/library.md and agent-wiring.md; plugins.html
(en, zh, ja) gets the library field and what magpie does with it.

Run:
- internal/library/agent_plugin_test.go: TestPluginAgentGetsTheLibrary,
  TestPluginAgentWithoutAPlaceIsRefused, TestPluginAgentMCPFormat,
  TestPluginMCPFormatsAreWritten. With targetOf's plugin case and the
  check() validation taken out by hand, the first three go red.
- e2e: a nogui build in a scratchpad HOME (env -i, no live configs),
  `magpie plugin add` of a throwaway toy agent plugin; `library
  instructions set/agents`, `library mcp add/rm` wrote and took back
  only magpie's block and server, the user's "mine" server, its "note"
  field and other keys kept, backups made; with mcp dropped from the
  plugin, `library mcp add ... agents=toy` is refused naming
  agent.library.mcp.
- go test -tags nogui ./... (one unrelated FIFO flake in internal/agent,
  fixed in the commit before), gofmt -l clean, go vet for GOOS=linux
  and GOOS=windows clean. No GUI code changed.
2026-10-11 07:55:23 +08:00
yetone cb406c8425 plugins: a plugin can add an agent magpie has no setup of its own for
Plugins could be subscription providers or gateway middleware. Now a third
kind: an agent plugin, so a user whose agent magpie doesn't ship can still
put it on magpie.

- internal/agentplug: a plugin's magpie.agent module (or a *.agent.js file)
  exports agent = {id, name, config, format?, model, prefix?, bin?, dir?,
  ua?, icon?, notice?} and an optional connect({gateway, model, models,
  agent}) returning the other keys to write. Compiled in moejs, reloaded
  when plugins.json or the file changes; why one didn't load is kept.
- internal/jsmod: module compiling (imports kept inside the plugin), moved
  out of middleware so both share it.
- internal/agent/plugged.go: each becomes an Agent (Plugin set) after
  magpie's own. JSON, YAML and env files are edited key by key, comments
  kept; what each key held is stashed typed under plugin:<id>:<path>, and
  its own model or Disconnect puts every key back. A built-in id is
  refused; a connect that throws writes nothing. Key magpie-<id>; usage
  names it by key or ua (usage.PluginAgents).
- GUI Plugins page: an Agent kind chip and glyph, a Discover "Agents"
  section (market kind "agent"), and an installed row line "Adds X to
  Agents" or why it didn't load. zh, zh-TW, ja, de strings.
- Docs: site Plugins page (en, zh, ja) "Agent plugins", reference.md,
  agent-wiring.md, gateway-middleware.md.

Run:
- go test ./... (all ok); gofmt -l clean; GOOS=linux go vet -tags nogui
  ./... and GOOS=windows go vet ./... clean.
- TestPluggedYAML, TestPluggedJSONUnwire, TestPluggedRefused.
- GUI: plugin-agent.test.cjs 22/22 (en, zh, zh-TW, ja, de; 980 and 420;
  chromium and webkit); all plugin-*.test.cjs, i18n-keys,
  deprecated-subscriptions, filter-ime: 315 pass, 0 fail.
- Real use, in a sandbox HOME: an Aider plugin (~/.aider.conf.yml, prefix
  openai/, connect writes openai-api-base/key) installed in a dev build;
  picking DeepSeek V4.1 Flash on the Agents page wired the file keeping the
  user's comment and keys; real aider 0.86.2 `--message` answered through
  magpie from the real DeepSeek account; usage.jsonl recorded agent aider,
  provider deepseek, 200; Disconnect restored the file byte for byte.
2026-10-10 18:39:47 +08:00