Commit Graph
5 Commits
Author SHA1 Message Date
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 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 466cafa0cf idle: the loops that look every few seconds wake together on the clock's beat (#3185)
An idle magpie serve still woke ~6 times a second with nothing to do.
Its loops each kept a ticker of their own, started at their own instant:
awake.Keep (5s), the plugin config's KeepFresh (5s), the middleware
observer (5s), OTel's session watch (5s idle), the Codex daemon check
(15s), dsh's wiring (30s), the model lists' look (1m). Every one woke
the process apart, a few threads each time.

internal/beat's Next(every) fires at the next multiple of every on the
clock, so the 5s loops come due at one instant, the 15s and 30s ones on
every third and sixth of it, and the runtime runs timers due together
in one wakeup. Each loop now waits on beat.Next instead of its ticker.
No channel is shared between callers (a synctest bubble's channel
reached from another crashes the process, #3632).

Run at this head (05ea29ac8 + this):
- Sandbox HOME serve, idle, 90s warm-up then 120s of proc_pid_rusage
  (pkg_idle_wkups + interrupt_wkups), old (origin/main 19253f67b) and new
  taking turns: old 6.1, 5.3, 6.2 wakeups/s; new 2.7, 2.6 (an earlier
  shared-timer form of beat), 3.0 (this one). CPU 0.20-0.36 ms/s old,
  0.11-0.22 new.
- TestIntervalsMeet (5s/15s/30s/1m beats from 09:00:03.2 and on a beat),
  TestNextFires; go test ./internal/beat ./internal/awake
  ./internal/middleware ./internal/otlp -count=3, ./internal/pluginrt,
  ./internal/agent -run 'Dsh|CodexDaemon', ./internal/provider -skip
  TestUnreadLoginsWriteErrorsKeepCredentials (#3632): ok.
  ./internal/pluginrt -count=3 fails TestKeepFreshFollowsPluginsYml
  ("two plugins fresh-test") on origin/main too; -count=1 is ok.
- gofmt; go vet darwin, GOOS=linux and GOOS=windows -tags nogui.
Not tried: a GUI build's wakeups (the tray process has AppKit's own).
2026-10-26 10:27:01 +08:00
yetone 091153bf71 idle: the loops following magpie's files wake on its own writes, not a 1-2s poll (#3185)
An idle `magpie serve` (no providers, no requests) woke 12-13 times a
second. A runtime trace showed the wakers were polling loops: the
middleware observer's refresh every 1s, pluginrt.KeepFresh's stat of five
files every 2s, OTel's session watch every 2s and its exporter tick every
5s, all with nothing to do.

Now filememo.Forget, which every write magpie makes of settings,
providers, sign-ins and caller keys already calls, also closes a channel
(filememo.Written). The plugins.json, tools and plugins.yml saves call it
too. The middleware observer, KeepFresh and OTel's session watch wait on
it, and look every filememo.OthersEvery (5s) only for what another
process (the CLI, a second magpie) wrote. Each takes the channel before
it looks, so a write made during a look isn't missed. middleware's
current() also reloads at once when filememo's generation moved, rather
than after its 1s skip. OTel's session watch waits 5s, not 2s, while
sessions aren't exported, and its exporter's timer runs only while a
batch holds something.

Measured: sandbox HOME, MAGPIE_ADDR=127.0.0.1:3481, `magpie serve`,
proc_pid_rusage (idle + interrupt wakeups) over 30s after 40s warm-up,
old (cec54c1d0) and new builds alternated:
  old  13.2 / 13.3 / 12.2 wakeups/s, 0.40 / 0.35 / 0.42 ms CPU/s
  new   7.9 /  8.6 wakeups/s,         0.22 / 0.30 ms CPU/s
What's left is the Go runtime itself, awake.Keep's 5s tick and the 5s
looks for other processes' writes.

Tests: TestKeepFreshFollowsPluginsYml now also runs KeepFresh with a 1h
interval and needs Set to apply at once; TestStrategiesFollowOwnWrite
needs a plugin turned off through plugin.SetOff to stop being served
within 2s, with no refresh by hand; TestWritten. With the Written cases
replaced by a nil channel, both of the first two went red (applied = 1,
want 0; still served 2s after). Run at this head: go test -count=1
-timeout 45m ./internal/filememo ./internal/plugin ./internal/pluginrt
./internal/middleware ./internal/otlp ./internal/settings
./internal/access: all ok. GOOS=linux and GOOS=windows go vet -tags
nogui ./internal/...: clean. gofmt -l internal: clean.

Not run: the full suite and internal/gateway's tests (gateway.go only
changes KeepFresh's interval argument, and it compiles under vet); the
macOS app with its window open (only headless serve was measured).
2026-10-25 23:45:34 +08:00
yetone 3f913b3de6 plugins: a JS gateway plugin serves routings (strategies) and watches usage rows (onUsage); plugins/middleware is "JS gateway plugins" (P4)
A plugin's gateway module (magpie.middleware, or its alias magpie.gateway,
or a *.gateway.js file) may now export, besides onRequest/onEvent/onResponse:

- strategies: {name: (pool, seats, options) => order}. Each is a routing
  "<short name>/<name>", registered with routes.Register while the plugin is
  on and loaded and removed when it goes off or reloads. Seats are
  routes.Seat in camelCase JSON. 20ms each; it fails open: a throw, a timeout
  or a result that isn't an order of the seats means the listed order. The
  failure is counted and logged, rate-limited. A file's name is made into a
  routing-safe prefix.
- onUsage(row, options): gets an allow-listed usage row (no bodies, prompts,
  error text, sessions or request ids). The rows come from a bounded queue
  (1024) with one worker, off the request path; a full queue drops the row
  and counts it, and a request never waits. 250ms each.

plugins/middleware is renamed "JS gateway plugins", with a new Sub
(en/zh/zh-TW/ja/de). It registers usage.Observe(middleware.Points()). Off,
no JS hook, strategy or onUsage runs. InUse is unchanged.

providers.json keeps a routing of the form <plugin>/<name> as saved
(provider.PluginRouting) in provider and group Save, whether or not a
plugin serves it now. Before this, `group set g routing=pick/last`
stored nothing.

GUI: the settings state carries jsRoutings. Provider and group routing
pickers offer the served ones, marked data-feature=middleware. A saved
routing that no plugin serves now shows as it is, with a hint. The
Plugins page's line shows routings, how often they were asked, onUsage
rows and dropped rows. The CLI accepts `group set <id> routing=<plugin>/<name>`.
`magpie plugin` lists a module's routings and onUsage; a strategy-only
module had printed nothing after "gateway middleware".

Docs: docs/subsystems/gateway-middleware.md (Routings and usage rows,
limits, verification) and plugin-runtime.md (P4: community plugins at
every point). site/public/docs plugins.html in en, zh and ja has an
example: internal/middleware/testdata/spread.gateway.js, which
TestDocsExample runs.

What was run (worktree on 4df1ba0c6, -p 2):
- gofmt -l: clean. go vet on internal/{middleware,cli,gui,plugin,provider}
  and plugins/...: darwin, GOOS=linux -tags nogui, GOOS=windows; all
  clean, run after the last Go change.
- go test, after the last Go change: internal/middleware ok,
  plugins/middleware ok, internal/provider ok (210s), internal/cli ok
  (203s). Earlier in the work: internal/plugin ok (385s), internal/pluginrt
  ok, internal/gui (Go) ok (320s), and plugins/... ok. The first
  plugins/... run printed a bare FAIL line that `tail` cut off before its
  cause showed. The rerun was all ok; the cause is unknown.
- GUI, both engines (routing-*, group-*, builtins, i18n-keys, gui-de/ja/zh-tw,
  plugin-middleware): 1220 tests, 1204 pass, 16 fail.
  - routing-manual (4): mine. A group's own "manual" was offered a second
    time as a routing no plugin serves. Fixed in client.js withJS. The
    coordinator is rerunning routing-manual, keys-fold, group-fold,
    intent-entry and routing-js alone in both engines, so that rerun is
    not recorded here.
  - routing-model-rest: red alone too, and red on untouched 4df1ba0c6
    (3/20). It is #2115; I commented there with the webkit cases.
  - group-member-weight webkit de 420 is #2387.
  - group-from-model-add webkit zh: it passes alone 2 of 2. Under load it
    waits a fixed 2s for the save post. Filed as #2388.
  - routing-keys-fold (webkit zh/ja/de), routing-group-fold (goto timeout)
    and routing-intent-entry (browser launch timeout 180s) are load
    timeouts. The coordinator is rerunning them alone.
- routing-js.test.cjs (new) passed in chromium en and zh, before the full run.

Broken by hand, each test went red, then restored:
- the permutation check: TestStrategyFailsOpen;
- the queue's non-blocking send: TestOnUsageNeverBlocks ("Ledger waited
  2.04s");
- the allow-list: TestUsageRowAllowList;
- unregister on off: TestStrategiesServedWhileOn and
  TestStrategiesStopWithServe;
- the CLI pattern: TestParseRoutingStays;
- Observe in plugins/middleware: TestOnServesStrategies;
- PluginRouting in provider.go and in group.go: TestPluginRoutingKept;
- the prefix sanitizing: TestRoutingFromFileName;
- the CLI list line: TestPluginListSaysMiddleware;
- the GUI's data-feature mark and its unserved-saved entry: routing-js.

Real use: a sandbox HOME, the gateway served on 127.0.0.1:3682 by a
-tags nogui build, a fake vendor on 3681, and providers fa (key ka) and
fb (key kb) in group g. pick.gateway.js has strategy last (reverse) and an
onUsage that logs.
- `group set g routing=pick/last` stored it.
- A request to group/g reached the vendor with Bearer kb, and the
  "usage-row fb m in=5 keys=17" line was logged.
- `plugin off pick.gateway.js`: Bearer ka (listed order), no onUsage,
  routing still pick/last.
- `plugin on`: Bearer kb and onUsage again.
- `plugin builtin off middleware` says "in use and stays on", as InUse
  should.
- Not tried: the GUI against that gateway, or a real vendor account.
2026-10-15 22:36:59 +08:00