plugins: a package that declares magpie.agent is an agent, with a main or without (plugins#737)
miaocell's magpie-agent-deva ships a Bun module as its main beside its moejs agent file (deva.agent.js), because the agent needs a runtime. The market's GitHub list decided the kind by whether a main was there, so it listed the package under Providers, and the Installed row wore a Provider chip and a provider logo though the module serves no provider. Now readTagged gives Kind "agent" to any package that declares magpie.agent; middleware, page and hooks still need no main to be that kind. The file looked for in the repository is still the module Bun loads (its main), or the agent file when there is no main. The Installed row of an agent plugin wears Provider only when its module serves a provider, and its logo is the agent glyph unless it does. The moejs descriptor contract is unchanged. The community registry.json already gives kimi-desktop and reasonix-desktop (both with a main) kind agent; the plugins repo's check now fails an agent package listed as any other kind. Docs: docs/reference.md, docs/subsystems/provider-plugins.md, and site/public/docs plugins.html in en, zh and ja say an agent that needs a runtime keeps its agent file and adds a Bun main, and is listed as an agent either way. Run (on mote, at this head rebased onb047cfe73): - TestTaggedAgentWithMain (new; the reporter's real package.json, index.mjs and deva.agent.js in testdata): go test -run 'Tagged|PkgEntry|Readme|GitHub' ./internal/plugin ok. Red with github.go at its parent: kind "". - plugin-agent.test.cjs (new rows: an agent with a main and no provider, one switched off, one that serves a provider), chromium and webkit, en, zh, zh-TW, ja, de: ok. Red at origin/mainb047cfe73: the deva row's chips were [Agent, Provider]. - Every plugin*.test.cjs plus i18n-keys, both engines: 1090 of 1094 ok. The 4 reds are plugin-move-unserved "Try again takes the models unticked" (Model 1 folded behind "Show the other 29"), red the same at origin/main b047cfe73; filed as #4410. - gofmt -l, go vet ./internal/plugin ./internal/gui, GOOS=linux and GOOS=windows go vet ./internal/plugin, go test -run 'Budget|I18n' ./internal/gui (TestCoreScriptBudget, budget not raised): ok. Not tried: installing magpie-agent-deva from the real GitHub list in a running app (the list is read from the test server); Windows and Linux runs of the GUI tests.
This commit is contained in:
+7
-2
@@ -1364,8 +1364,13 @@ call costs. Each is left out when it isn't known (a routing group has no
|
||||
```
|
||||
|
||||
An id magpie's own agents use is refused. In the market an agent's entry has
|
||||
`"kind": "agent"` (`@magpie-community/agent-<name>`). The full reference is
|
||||
on the site's Plugins page, under Agent plugins.
|
||||
`"kind": "agent"` (`@magpie-community/agent-<name>`). An agent that needs a
|
||||
runtime (a timer, a file watched) keeps its agent file in moejs and adds a
|
||||
Bun module as the package's `main`; a package that declares `magpie.agent`
|
||||
is an agent in the market and on GitHub's list either way, and its
|
||||
Installed row wears Provider only when that module serves a provider
|
||||
(plugins#737). The full reference is on the site's Plugins page, under
|
||||
Agent plugins.
|
||||
|
||||
### What a model costs
|
||||
|
||||
|
||||
@@ -225,6 +225,8 @@ Plugins are installed from, and magpie's own npm questions (a package's newest v
|
||||
|
||||
A repository tagged `magpie-plugin` shows the licence GitHub's search reads from its `LICENSE` file. GitHub gives `NOASSERTION` for a file it can't match to one (MIT's text with a line of credit added) and nothing for none, and magpie drops `NOASSERTION`, so such a card had no licence while the same package on npm shows its `package.json` `license`. `readTagged` in [`github.go`](../../internal/plugin/github.go) now keeps `package.json`'s `license` (a string) as `PkgLicense`, and `License` falls back to it, on a fresh read and on one kept across searches (`fresh`) ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)). `TestTaggedRepos` covers both cases and the one with neither.
|
||||
|
||||
A tagged repository's kind (`Tagged.Kind`, the card's chip and the GitHub strip's kind filter) comes from what its `package.json` declares. `magpie.agent` makes it an agent whether or not it has a `main` or `exports`: an agent that needs a runtime (a poller, a file watched) ships its agent file in moejs and a Bun module as `main`, and read only by the absence of `main` it was listed as a provider (miaocell/magpie-agent-deva, [magpie-community/plugins#737](https://github.com/magpie-community/plugins/issues/737)). Middleware, a page and request hooks are still a kind only when that is all the package is, since a page or a hook beside a provider's module is that provider's accessory. A package with a module of its own has that module checked as committed (its `main`, the agent's too), else the one file it declares (`TestTaggedAgentWithMain`). One card has one kind, the declared one winning; an Installed row wears every chip it has, and an agent's wears Provider only when its module serves a provider (`plugin-agent.test.cjs`).
|
||||
|
||||
The same read keeps what the package says of itself: `magpie.name` (`ownName`) and `magpie.summary` (`ownSummary` in [`market.go`](../../internal/plugin/market.go): a language to a one-line sentence of at most 300 bytes, no control or format characters, anything else none) become `Tagged.Name` and `Summary`, and npm's copy's say them instead when the card installs from npm. `ghListing` in `plugins.js` puts them on the card in place of the repository's name and GitHub's description (which stays the English line when the package gives none), with an "Its own words" chip whose tip says nobody reviewed them; they never get the community badge and never resolve a name. A `summary` that isn't an object of strings reads as none, never as a `package.json` that doesn't parse, which would leave the repository out (MYCF711, [#3608](https://github.com/yetone/magpie/issues/3608)). `TestReadTaggedOwnWords`, `TestOwnWordsBounds`, `plugin-own-words.test.cjs`.
|
||||
|
||||
## How ownership changes
|
||||
|
||||
@@ -1225,7 +1225,7 @@
|
||||
if (e.tools?.length) nm.append(kindChip("tl"));
|
||||
if (e.page) nm.append(kindChip("pg"));
|
||||
if (e.panels?.length) nm.append(kindChip("pn"));
|
||||
if (e.providers?.length || !(e.gatewayOnly || e.middlewareOnly || e.inMagpieOnly || toolsOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv"));
|
||||
if (e.providers?.length || !(e.gatewayOnly || e.middlewareOnly || e.inMagpieOnly || e.isAgent || toolsOnly || (mw && !e.isMiddleware) || (ag && !e.isAgent))) nm.append(kindChip("pv"));
|
||||
who.append(nm);
|
||||
const subs = subsOf(pkg);
|
||||
const sub = el("div", "sub");
|
||||
@@ -1280,7 +1280,7 @@
|
||||
if ((mw || e.isGateway || ownOpts) && !e.off && !ask && editing?.pkg === pkg) who.append(optionsEditor(e));
|
||||
// the plugin's own picture (package.json's magpie.icon) before its
|
||||
// first provider's, which a plugin of several gives each its own (#1775)
|
||||
r.append(logo(l?.icon || l?.npm?.icon || e.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.inMagpieOnly && e.isAgent && !e.isMiddleware ? "ag" : e.inMagpieOnly && (e.page || e.panels?.length) && !e.isAgent && !e.isMiddleware ? "pg" : toolsOnly && !e.page && !mw && !ag ? "tl" : ""), who);
|
||||
r.append(logo(l?.icon || l?.npm?.icon || e.icon || subs[0]?.icon || ag?.icon, false, e.middlewareOnly ? "mw" : e.isAgent && !e.isMiddleware && !e.providers.length ? "ag" : e.inMagpieOnly && (e.page || e.panels?.length) && !e.isAgent && !e.isMiddleware ? "pg" : toolsOnly && !e.page && !mw && !ag ? "tl" : ""), who);
|
||||
const val = el("div", "val");
|
||||
const b = busy.get(pkg) || busy.get(e.spec);
|
||||
// npm's newer version, or a git one's repository at a newer commit
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
// Agent plugins on the Plugins page: a plugin that adds an agent wears the
|
||||
// Agent chip, not Provider, and says which agent it adds to the Agents
|
||||
// page (or why it didn't load, in red); one switched off is an Agent still;
|
||||
// one that is middleware too wears both chips. Discover lists the market's
|
||||
// one that is middleware too wears both chips. One with a Bun module of its
|
||||
// own (main) beside its agent, which needs a runtime, is an Agent too, not
|
||||
// a Provider, on or off (miaocell, plugins#737); one whose module serves a
|
||||
// provider as well wears both. Discover lists the market's
|
||||
// agent plugins in their own section with the Agent chip, wearing the
|
||||
// picture its package gives (npm's magpie.icon, kept by magpie as a file)
|
||||
// when the market gives it none. Every language,
|
||||
@@ -16,11 +19,15 @@ const { chromium, webkit } = require("playwright");
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
|
||||
const AIDER = "/Users/x/ag/aider", BROKEN = "/Users/x/ag/broken", OFF = "/Users/x/ag/off", BOTH = "/Users/x/ag/both";
|
||||
const DEVA = "/Users/x/ag/deva", DEVAOFF = "/Users/x/ag/idle", PROV = "/Users/x/ag/prov";
|
||||
const state = { bun: true, bunVersion: "1.3.0", plugins: [
|
||||
{ spec: AIDER, providers: [], moved: [], isAgent: true, inMagpieOnly: true, agent: { id: "aider", name: "Aider" } },
|
||||
{ spec: BROKEN, providers: [], moved: [], isAgent: true, inMagpieOnly: true, agent: { error: `agent id "codex" is magpie's own` } },
|
||||
{ spec: OFF, off: true, providers: [], moved: [], isAgent: true, inMagpieOnly: true },
|
||||
{ spec: BOTH, providers: [], moved: [], isAgent: true, inMagpieOnly: true, isMiddleware: true, agent: { id: "jot", name: "Jot" }, middleware: { hooks: ["onRequest"], calls: 0, avgMicros: 0, failures: 0 } },
|
||||
{ spec: DEVA, providers: [], moved: [], named: true, isAgent: true, agent: { id: "deva", name: "Deva" } },
|
||||
{ spec: DEVAOFF, off: true, providers: [], moved: [], isAgent: true },
|
||||
{ spec: PROV, providers: ["provx"], moved: [], named: true, isAgent: true, agent: { id: "provx", name: "Provx" } },
|
||||
] };
|
||||
// a 1x1 picture
|
||||
const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", "base64");
|
||||
@@ -51,11 +58,11 @@ function server(lang) {
|
||||
}
|
||||
|
||||
const L = {
|
||||
en: { installed: "Installed", agent: "Agent", mw: "Middleware", provider: "Provider", adds: "Adds Aider to Agents", addsJot: "Adds Jot to Agents", broken: /^Agent didn't load: agent id "codex"/, off: "Off", nothing: "Signs in to nothing", sec: "Agents" },
|
||||
zh: { installed: "已安装", agent: "Agent", mw: "中间件", provider: "供应商", adds: "把 Aider 加到 Agent 页", addsJot: "把 Jot 加到 Agent 页", broken: /^Agent 没有加载:agent id "codex"/, off: "关闭", nothing: "不能登录", sec: "Agent" },
|
||||
"zh-TW": { installed: "已安裝", agent: "Agent", adds: "把 Aider 加到 Agent 頁", addsJot: "把 Jot 加到 Agent 頁", broken: /^Agent 沒有載入:/, sec: "Agent" },
|
||||
ja: { installed: "インストール済み", agent: "エージェント", adds: "Aider をエージェントページに追加します", addsJot: "Jot をエージェントページに追加します", broken: /^エージェントを読み込めませんでした:/, sec: "エージェント" },
|
||||
de: { installed: "Installiert", agent: "Agent", adds: "Fügt Aider zu Agenten hinzu", addsJot: "Fügt Jot zu Agenten hinzu", broken: /^Agent nicht geladen: /, sec: "Agenten" },
|
||||
en: { addsDeva: "Adds Deva to Agents", installed: "Installed", agent: "Agent", mw: "Middleware", provider: "Provider", adds: "Adds Aider to Agents", addsJot: "Adds Jot to Agents", broken: /^Agent didn't load: agent id "codex"/, off: "Off", nothing: "Signs in to nothing", sec: "Agents" },
|
||||
zh: { addsDeva: "把 Deva 加到 Agent 页", installed: "已安装", agent: "Agent", mw: "中间件", provider: "供应商", adds: "把 Aider 加到 Agent 页", addsJot: "把 Jot 加到 Agent 页", broken: /^Agent 没有加载:agent id "codex"/, off: "关闭", nothing: "不能登录", sec: "Agent" },
|
||||
"zh-TW": { addsDeva: "把 Deva 加到 Agent 頁", installed: "已安裝", agent: "Agent", adds: "把 Aider 加到 Agent 頁", addsJot: "把 Jot 加到 Agent 頁", broken: /^Agent 沒有載入:/, sec: "Agent" },
|
||||
ja: { addsDeva: "Deva をエージェントページに追加します", installed: "インストール済み", agent: "エージェント", adds: "Aider をエージェントページに追加します", addsJot: "Jot をエージェントページに追加します", broken: /^エージェントを読み込めませんでした:/, sec: "エージェント" },
|
||||
de: { addsDeva: "Fügt Deva zu Agenten hinzu", installed: "Installiert", agent: "Agent", adds: "Fügt Aider zu Agenten hinzu", addsJot: "Fügt Jot zu Agenten hinzu", broken: /^Agent nicht geladen: /, sec: "Agenten" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
@@ -109,6 +116,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
if (w.mw) assert.deepEqual(await kinds(both), [w.mw, w.agent]);
|
||||
assert.ok((await both.locator(".pm-mw").allInnerTexts()).map((x) => x.trim()).includes(w.addsJot));
|
||||
|
||||
// an agent with a module of its own (main): an Agent, not a Provider
|
||||
const deva = row("deva");
|
||||
assert.deepEqual(await kinds(deva), [w.agent]);
|
||||
assert.equal((await deva.locator(".pm-mw").innerText()).trim(), w.addsDeva);
|
||||
if (w.nothing) assert.ok(!(await deva.innerText()).includes(w.nothing));
|
||||
assert.deepEqual(await kinds(row("idle")), [w.agent], "off, an agent with a main is an agent still");
|
||||
if (w.provider) assert.deepEqual(await kinds(row("prov")), [w.agent, w.provider], "an agent whose module serves a provider is both");
|
||||
|
||||
// the row's text fits: nothing wider than the page
|
||||
const over = await page.evaluate(() => document.scrollingElement.scrollWidth - document.scrollingElement.clientWidth);
|
||||
assert.ok(over <= 0, "page scrolls sideways by " + over);
|
||||
|
||||
+34
-26
@@ -45,7 +45,7 @@ type Tagged struct {
|
||||
// it as, its version, and whether it is gateway middleware or an agent
|
||||
Package string `json:"package,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Kind string `json:"kind,omitempty"` // "middleware", "agent", "page" or "hooks" when that is all it is
|
||||
Kind string `json:"kind,omitempty"` // "agent" when it adds an agent (a module of its own too or not); "middleware", "page" or "hooks" when that is all it is
|
||||
// its package.json's magpie.icon, as an installed plugin gives its
|
||||
// provider one: an https URL or a data:image URI, as it is written
|
||||
Icon string `json:"icon,omitempty"`
|
||||
@@ -459,20 +459,23 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool
|
||||
// and what it says of itself, shown on its card as its own words
|
||||
// rather than the community's (#3608)
|
||||
t.Name, t.Summary = ownName(pj.Magpie.Name), ownSummary(pj.Magpie.Summary)
|
||||
if pj.Main == "" && len(pj.Exports) == 0 {
|
||||
switch {
|
||||
case strings.TrimSpace(pj.Magpie.Middleware) != "":
|
||||
t.Kind = "middleware"
|
||||
case strings.TrimSpace(pj.Magpie.Agent) != "":
|
||||
t.Kind = "agent"
|
||||
case strings.TrimSpace(pj.Magpie.Page.File) != "":
|
||||
t.Kind = "page"
|
||||
// gateway hooks alone (magpie.hooks) need no entry of their
|
||||
// own, as the host loads them: the hooks file is the one to
|
||||
// find (#3821)
|
||||
case strings.TrimSpace(pj.Magpie.Hooks) != "":
|
||||
t.Kind = "hooks"
|
||||
}
|
||||
// runs is whether Bun loads a module of its own (main, exports)
|
||||
runs := pj.Main != "" || len(pj.Exports) > 0
|
||||
switch {
|
||||
case !runs && strings.TrimSpace(pj.Magpie.Middleware) != "":
|
||||
t.Kind = "middleware"
|
||||
// a package that adds an agent is an agent plugin, its Bun module
|
||||
// (main) only what keeps the agent working, not a provider
|
||||
// (plugins#737)
|
||||
case strings.TrimSpace(pj.Magpie.Agent) != "":
|
||||
t.Kind = "agent"
|
||||
case !runs && strings.TrimSpace(pj.Magpie.Page.File) != "":
|
||||
t.Kind = "page"
|
||||
// gateway hooks alone (magpie.hooks) need no entry of their
|
||||
// own, as the host loads them: the hooks file is the one to
|
||||
// find (#3821)
|
||||
case !runs && strings.TrimSpace(pj.Magpie.Hooks) != "":
|
||||
t.Kind = "hooks"
|
||||
}
|
||||
// published to npm from this repository: npm's copy is the one
|
||||
// built to be installed (a repository often leaves its dist out,
|
||||
@@ -510,17 +513,22 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool
|
||||
// that is only a command (bin), an MCP server, has none and
|
||||
// would never load (#1327)
|
||||
if IsGit(t.Spec) || !npmNames {
|
||||
entry := pj.Magpie.Middleware
|
||||
if t.Kind == "agent" {
|
||||
entry = pj.Magpie.Agent
|
||||
} else if t.Kind == "page" {
|
||||
entry = pj.Magpie.Page.File
|
||||
} else if t.Kind == "hooks" {
|
||||
entry = pj.Magpie.Hooks
|
||||
} else if t.Kind != "middleware" {
|
||||
entry = pkgEntry(pj.Exports, pj.Main)
|
||||
if !IsGit(t.Spec) {
|
||||
entry = pkgEntry(nil, "")
|
||||
// a package with a module of its own loads that module, an
|
||||
// agent plugin's too; else the one file it declares
|
||||
entry := pkgEntry(pj.Exports, pj.Main)
|
||||
if !IsGit(t.Spec) {
|
||||
entry = pkgEntry(nil, "")
|
||||
}
|
||||
if !runs {
|
||||
switch t.Kind {
|
||||
case "middleware":
|
||||
entry = pj.Magpie.Middleware
|
||||
case "agent":
|
||||
entry = pj.Magpie.Agent
|
||||
case "page":
|
||||
entry = pj.Magpie.Page.File
|
||||
case "hooks":
|
||||
entry = pj.Magpie.Hooks
|
||||
}
|
||||
}
|
||||
if path.Ext(entry) != "" {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// An agent plugin whose agent needs a runtime (a poller, files watched)
|
||||
// ships a Bun module as its main beside its moejs agent file. It loads
|
||||
// and adds its agent, but the GitHub list read a package with a main as
|
||||
// a provider and showed it under Providers (miaocell, plugins#737). A
|
||||
// package that declares magpie.agent is an agent plugin, main or not;
|
||||
// the file looked for in the repository is still the one Bun loads, its
|
||||
// main. The package.json, module and agent file are
|
||||
// miaocell/magpie-agent-deva's, as they are; it isn't on npm.
|
||||
func TestTaggedAgentWithMain(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var asked []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) {
|
||||
mu.Lock()
|
||||
asked = append(asked, q.URL.Path)
|
||||
mu.Unlock()
|
||||
name, ok := strings.CutPrefix(q.URL.Path, "/raw/")
|
||||
f, err := os.ReadFile(filepath.Join("testdata/github/raw", filepath.FromSlash(name)))
|
||||
if !ok || err != nil {
|
||||
http.Error(w, `"Not Found"`, 404)
|
||||
return
|
||||
}
|
||||
w.Write(f)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
api, raw, reg := githubAPI, githubRaw, npmRegistry
|
||||
githubAPI, githubRaw, npmRegistry = srv.URL, srv.URL+"/raw", srv.URL+"/npm"
|
||||
t.Cleanup(func() { githubAPI, githubRaw, npmRegistry = api, raw, reg })
|
||||
|
||||
const repo = "miaocell/magpie-agent-deva"
|
||||
got, keep, known, err := readTagged(context.Background(), Tagged{Spec: "github:" + repo, Repo: repo}, "main")
|
||||
if !keep || !known || err != nil || got.Kind != "agent" || got.Package != "magpie-agent-deva" || got.Spec != "github:"+repo {
|
||||
t.Fatalf("an agent with a main: kind %q, package %q, spec %q, kept %v, known %v, %v", got.Kind, got.Package, got.Spec, keep, known, err)
|
||||
}
|
||||
mu.Lock()
|
||||
a := slices.Clone(asked)
|
||||
mu.Unlock()
|
||||
if !slices.Contains(a, "/raw/"+repo+"/main/index.mjs") {
|
||||
t.Fatalf("its main wasn't looked for: asked %v", a)
|
||||
}
|
||||
|
||||
// an agent alone, no main, as before: its agent file is the one
|
||||
// looked for
|
||||
got, keep, _, err = readTagged(context.Background(), Tagged{Spec: "github:someone/agent-aider", Repo: "someone/agent-aider"}, "main")
|
||||
if !keep || err != nil || got.Kind != "agent" {
|
||||
t.Fatalf("an agent alone: %+v, kept %v, %v", got, keep, err)
|
||||
}
|
||||
}
|
||||
+34
File diff suppressed because one or more lines are too long
+163
@@ -0,0 +1,163 @@
|
||||
// The Bun side of the plugin. Magpie's Agents page writes what was picked into
|
||||
// ~/.deva/.magpie-agent.json; this applies it to Deva's own config.json.
|
||||
//
|
||||
// Deva keeps its providers in a JSON array and only reads that file when it
|
||||
// starts. config.json is written even while Deva runs (and re-checked every
|
||||
// tick, since Deva saves its in-memory copy over it), but secrets.json is not:
|
||||
// Deva reads that one once and later saves the whole store from memory, so a
|
||||
// key written while it runs would be invisible to it and clobbered by its next
|
||||
// save. The key therefore waits for the exit.
|
||||
//
|
||||
// The provider's key is written at all because the gateway hands out the whole
|
||||
// model catalogue to an unknown key and only the ticked ones to the key magpie
|
||||
// issued — without it Deva's "add model" lists everything.
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import { restore, selectionFrom, syncSelection } from "./lib/deva-config.mjs"
|
||||
import { secretHolds } from "./lib/deva-secrets.mjs"
|
||||
import {
|
||||
deleteProviderSecret,
|
||||
devaRunning,
|
||||
files,
|
||||
readJson,
|
||||
safeStorageKeyFromDisk,
|
||||
setProviderSecret,
|
||||
writeJson,
|
||||
} from "./lib/deva-files.mjs"
|
||||
|
||||
const STARTED = Symbol.for("magpie.deva-agent.adapter.v1")
|
||||
const POLL_MS = 2000
|
||||
|
||||
function start(input) {
|
||||
if (globalThis[STARTED]) return
|
||||
globalThis[STARTED] = true
|
||||
|
||||
const log = (level, message) => {
|
||||
try {
|
||||
input?.client?.app?.log?.({ body: { service: "deva", level, message } })?.catch?.(() => {})
|
||||
} catch {
|
||||
/* Logging must never take the host down. */
|
||||
}
|
||||
}
|
||||
|
||||
let lastMessage = ""
|
||||
const say = (message) => {
|
||||
if (message === lastMessage) return
|
||||
lastMessage = message
|
||||
log("info", message)
|
||||
}
|
||||
|
||||
log("info", "deva: adapter started")
|
||||
|
||||
// safeStorage key, read at most once on success.
|
||||
let storageKey
|
||||
|
||||
const gatewayKey = async () => {
|
||||
if (storageKey !== undefined) return storageKey
|
||||
storageKey = await safeStorageKeyFromDisk()
|
||||
return storageKey
|
||||
}
|
||||
|
||||
const tick = async () => {
|
||||
const f = files()
|
||||
if (!fs.existsSync(f.home)) return
|
||||
|
||||
const picked = readJson(f.selection)
|
||||
if (!picked.ok && !picked.missing) return
|
||||
const selection = picked.ok ? selectionFrom(picked.value) : null
|
||||
|
||||
const stateFile = readJson(f.state)
|
||||
const state = stateFile.ok && stateFile.value && typeof stateFile.value === "object" ? stateFile.value : null
|
||||
|
||||
// Deva is written to even while it runs. It only reads config.json at start,
|
||||
// so nothing shows up until the user restarts it — but waiting for the exit
|
||||
// means never writing at all when Deva stays open, and Deva saves its own
|
||||
// in-memory copy over ours the moment anything is touched there. Writing
|
||||
// anyway and re-checking the file every tick is what keeps the two in step.
|
||||
if (!selection) {
|
||||
// Disconnected: put back what was there before the first pick.
|
||||
if (!state) return
|
||||
const config = readJson(f.config)
|
||||
if (!config.ok) return
|
||||
const next = restore(config.value, state)
|
||||
if (JSON.stringify(next) !== JSON.stringify(config.value)) {
|
||||
if (!fs.existsSync(f.backup)) writeJson(f.backup, config.value)
|
||||
writeJson(f.config, next)
|
||||
}
|
||||
// secrets.json is read once by Deva and then saved whole from memory, so
|
||||
// touching it while Deva runs would be undone by Deva's next save. Wait
|
||||
// for the exit, and keep the state file until the key is really gone.
|
||||
if (state.ownedSecret) {
|
||||
if (await devaRunning()) return say("Deva 正在运行,等它退出后清理网关密钥。")
|
||||
deleteProviderSecret(f.secrets, state.providerId)
|
||||
}
|
||||
fs.rmSync(f.state, { force: true })
|
||||
return say("已恢复 Deva 原来的模型设置。重开 Deva 才看得到。")
|
||||
}
|
||||
|
||||
const config = readJson(f.config)
|
||||
if (!config.ok) return say("找不到 Deva 的 config.json,等 Deva 启动一次。")
|
||||
|
||||
let result
|
||||
try {
|
||||
result = syncSelection(config.value, selection, state)
|
||||
} catch (error) {
|
||||
return say(`没有写入 Deva:${error?.message ?? error}`)
|
||||
}
|
||||
|
||||
// Compared against what is on disk rather than against the last pick: Deva
|
||||
// rewrites this file from its own memory whenever it is used, which drops
|
||||
// what magpie put there. Noticing that and putting it back keeps the two
|
||||
// from drifting apart after the first sync.
|
||||
if (result.changed) {
|
||||
if (!fs.existsSync(f.backup)) writeJson(f.backup, config.value)
|
||||
writeJson(f.config, result.config)
|
||||
}
|
||||
|
||||
// The key is what makes the gateway answer with only the ticked models.
|
||||
// Without it "add model" in Deva lists the whole catalogue.
|
||||
//
|
||||
// Deva reads secrets.json once and later saves the whole store from memory,
|
||||
// so a write here while it runs is invisible to it and gets clobbered by its
|
||||
// next save. The key therefore waits for the exit, unlike config.json.
|
||||
let nextState = result.state
|
||||
if (selection.gatewayKey) {
|
||||
const key = await gatewayKey()
|
||||
const stored = readProviderSecret(f.secrets, result.state.providerId)
|
||||
let held = Boolean(key) && secretHolds(stored, key, selection.gatewayKey)
|
||||
if (!held) {
|
||||
if (!key) {
|
||||
/* cannot encrypt on this platform: the key stays the user's to fill */
|
||||
} else if (await devaRunning()) {
|
||||
say("Deva 正在运行,网关密钥等它退出后写入。")
|
||||
} else if (setProviderSecret(f.secrets, result.state.providerId, selection.gatewayKey, key).written) {
|
||||
held = true
|
||||
}
|
||||
}
|
||||
if (held !== Boolean(nextState.ownedSecret)) nextState = { ...nextState, ownedSecret: held }
|
||||
}
|
||||
|
||||
// `added` follows the ticked list even when nothing in config.json moved:
|
||||
// bookkeeping left stale is how a model that should have been taken back
|
||||
// ends up staying in Deva forever.
|
||||
if (JSON.stringify(nextState) !== JSON.stringify(stateFile.value)) writeJson(f.state, nextState)
|
||||
|
||||
say(
|
||||
result.changed
|
||||
? `已把 ${selection.models.length} 个模型写进 Deva。重开 Deva 后在它的模型列表里选一个用。`
|
||||
: `Deva 里已是勾选的 ${selection.models.length} 个模型。`
|
||||
)
|
||||
}
|
||||
|
||||
const loop = () => {
|
||||
tick().catch((error) => log("error", `deva: ${error?.message ?? error}`))
|
||||
}
|
||||
|
||||
loop()
|
||||
setInterval(loop, POLL_MS).unref?.()
|
||||
}
|
||||
|
||||
export default async function devaAgent(input) {
|
||||
start(input)
|
||||
return {}
|
||||
}
|
||||
+29
File diff suppressed because one or more lines are too long
@@ -865,6 +865,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
|
||||
<li><b>実行のされ方。</b><a href="#middleware">ミドルウェア</a>と同じく、magpie 自身のプロセスの moejs で動きます。インポートはプラグイン内のファイルのみ、Node API はなく、<code>console.log</code> は magpie のログに出ます。読み込みと <code>connect</code> はそれぞれ 1 秒まで。モジュールが読み込めない、または <code>connect</code> が例外を投げたプラグインは、プラグインページの行に理由を表示し、何も書き込みません。</li>
|
||||
<li><b>ライブラリ。</b><code>library</code> があれば、組み込みのエージェントと同じくライブラリの中身を受け取ります:指示はファイル内の magpie の目印の行の間に、MCP サーバーはユーザー自身のものと同じファイルに(ユーザーが足したフィールドは残ります)、スキルはリンクかコピーでフォルダに入ります。外すときは magpie が書いた分だけを取り除き、元の内容は magpie のバックアップに残ります。<code>mcpFormat</code> がリストにない、または <code>mcp</code> に <code>mcpFormat</code> がないと、プラグインは読み込まれません。</li>
|
||||
<li><b>宣言。</b><code>package.json</code> の <code>"magpie": { "agent": "./agent.js" }</code>、または <code>*.agent.js</code>(または <code>.mjs</code>)という単一ファイル。1 つのパッケージがプロバイダー、ミドルウェア、エージェントを兼ねられます。プラグインマーケットではエージェントのエントリーに <code>"kind": "agent"</code> を付け、<span class="ui">エージェント</span>の下に並びます。コミュニティのものは <code>@magpie-community/agent-<name></code> と名付けます。</li>
|
||||
<li><b>ランタイムが必要なエージェント。</b>エージェントのファイルは moejs のモジュールのままで、タイマーもプラグイン外からの import もありません。エージェントにそれ以上(タイマー、ファイルの監視、アプリ自身の設定への値の反映)が必要なときは、パッケージに Bun のモジュールを <code>main</code> として加えられ、プロバイダープラグインのものと同じように動きます。それでもエージェントプラグインです。<code>magpie.agent</code> を宣言したパッケージは、<code>main</code> の有無にかかわらず、GitHub のものも <span class="ui">エージェント</span> の下に並び、<span class="ui">インストール済み</span> の行にはエージェントのチップが付きます。プロバイダーのチップが付くのは、そのモジュールがプロバイダーを提供するときだけです。</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="pages"><a class="anchor" href="#pages">ウィンドウのページ</a></h2>
|
||||
|
||||
@@ -865,6 +865,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
|
||||
<li><b>How it runs.</b> As <a href="#middleware">middleware</a> does: in moejs, in magpie’s own process, with imports inside the plugin only, no Node APIs and <code>console.log</code> into magpie’s log. Loading and <code>connect</code> each have a second. A plugin whose module doesn’t load, or whose <code>connect</code> throws, says why in its row on the Plugins page and writes nothing.</li>
|
||||
<li><b>The Library.</b> With <code>library</code>, the agent is one of the Library’s agents: its instructions go between magpie’s marker lines in the file, its MCP servers into the file beside the user’s own (whose other fields are kept), and its skills linked or copied into the folder. Taking one off takes away only what magpie wrote there, and what a file held before is kept in magpie’s backups. An <code>mcpFormat</code> that isn’t one of the list, or an <code>mcp</code> without one, keeps the plugin from loading.</li>
|
||||
<li><b>Declaring it.</b> <code>"magpie": { "agent": "./agent.js" }</code> in <code>package.json</code>, or a single file named <code>*.agent.js</code> (or <code>.mjs</code>). A package can be a provider, middleware and an agent at once. In the plugin market an agent’s entry has <code>"kind": "agent"</code> and is listed under <span class="ui">Agents</span>; a community one is named <code>@magpie-community/agent-<name></code>.</li>
|
||||
<li><b>An agent that needs a runtime.</b> The agent file stays a moejs module, with no timers and nothing imported from outside the plugin. When the agent needs more (a timer, a file watched, a value carried over into the app’s own config), the package can also have a Bun module as its <code>main</code>, run as a provider plugin’s is. It is still an agent plugin: a package that declares <code>magpie.agent</code> is listed under <span class="ui">Agents</span>, on GitHub too, with a <code>main</code> or without, and its row in <span class="ui">Installed</span> wears the Agent chip, and the Provider chip only when its module serves a provider.</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="pages"><a class="anchor" href="#pages">Pages in the window</a></h2>
|
||||
|
||||
@@ -865,6 +865,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
|
||||
<li><b>运行方式。</b>和<a href="#middleware">中间件</a>一样:在 magpie 自己的进程里用 moejs 运行,只能导入插件内的文件,没有 Node API,<code>console.log</code> 进 magpie 的日志。加载和 <code>connect</code> 各有一秒。模块加载失败或 <code>connect</code> 抛错的插件,会在插件页它那一行写明原因,并且什么都不写入。</li>
|
||||
<li><b>资源库。</b>写了 <code>library</code>,这个 Agent 就和内置 Agent 一样拿到资源库的内容:指令写在文件里 magpie 的两行标记之间,MCP 服务器和用户自己的写在同一个文件里(用户自己加的字段保留),技能以链接或副本放进文件夹。取消时只拿走 magpie 写的部分,文件原来的内容留在 magpie 的备份里。<code>mcpFormat</code> 不在列表中,或写了 <code>mcp</code> 却没写 <code>mcpFormat</code>,插件不会加载。</li>
|
||||
<li><b>声明方式。</b><code>package.json</code> 里写 <code>"magpie": { "agent": "./agent.js" }</code>,或者一个名为 <code>*.agent.js</code>(或 <code>.mjs</code>)的单文件。一个包可以同时是供应商、中间件和 Agent。插件市场里 Agent 条目写 <code>"kind": "agent"</code>,列在 <span class="ui">Agent</span> 下;社区包命名为 <code>@magpie-community/agent-<name></code>。</li>
|
||||
<li><b>需要运行时的 Agent。</b>Agent 文件仍是 moejs 模块,没有定时器,也不能导入插件以外的东西。Agent 需要更多(定时器、监视文件、把值同步进应用自己的配置)时,包可以再带一个 Bun 模块作为 <code>main</code>,像供应商插件的那样运行。它仍是 Agent 插件:声明了 <code>magpie.agent</code> 的包,不管有没有 <code>main</code>,都列在 <span class="ui">Agent</span> 下,GitHub 上的也一样;它在<span class="ui">已安装</span>里那一行带 Agent 标记,只有它的模块提供了供应商时才同时带供应商标记。</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="pages"><a class="anchor" href="#pages">窗口里的页面</a></h2>
|
||||
|
||||
Reference in New Issue
Block a user