diff --git a/packages/agentcompass/README.md b/packages/agentcompass/README.md index ebef13f..eeb318b 100644 --- a/packages/agentcompass/README.md +++ b/packages/agentcompass/README.md @@ -149,14 +149,29 @@ git clone https://github.com/akiiwa-games/magpie-agentcompass-router.git cd magpie-agentcompass-router ``` -将插件添加到 Magpie 并启用 `agentcompass`: +将插件添加到 Magpie(三种来源任选其一): ```bash -magpie plugin add /path/to/magpie-agentcompass-router -magpie plugin login agentcompass +magpie plugin add @magpie-community/gateway-agentcompass # 插件市场(npm) +magpie plugin add github:akiiwa-games/magpie-agentcompass-router # GitHub +magpie plugin add /path/to/magpie-agentcompass-router # 本地目录 magpie plugin list ``` +只用模式 A(网关中间件)时,添加后即可使用,无需登录。要用模式 B(Routing Group Classifier),见下文「配置方式二:模式 B」:先设 `enableDecisionProvider: true`、重启 Magpie,再 `magpie plugin login agentcompass`。 + +#### 各安装来源下的名称 + +Magpie 用包名(去掉 scope 与 `middleware-` / `opencode-` / `tools-` 等前缀)给插件的账号池策略加前缀,所以策略名随安装来源变化;决策 Provider 的模型名取自插件声明的 Provider ID,与来源无关: + +| 安装来源 | 账号池策略(`routings`) | Classifier 模型(模式 B) | +| :--- | :--- | :--- | +| 插件市场 `@magpie-community/gateway-agentcompass` | `gateway-agentcompass/agentcompass`、`gateway-agentcompass/agentcompass-pure` | `agentcompass/agentcompass-systemone` | +| GitHub `github:akiiwa-games/magpie-agentcompass-router` | `agentcompass/agentcompass`、`agentcompass/agentcompass-pure` | `agentcompass/agentcompass-systemone` | +| 本地目录 | `<目录名>/agentcompass`、`<目录名>/agentcompass-pure` | `agentcompass/agentcompass-systemone` | + +以本机实际输出为准:`magpie plugin list` 的 `routings ...` 一行列出策略名;开启 `enableDecisionProvider` 并登录后,`agentcompass (AgentCompass, 1 models) signed in` 一行表示决策 Provider 已就绪。客户端在模式 A 请求的虚拟模型 `agentcompass` / `agentcompass/*` 由中间件按请求中的模型名匹配,也与安装来源无关。 + 或在 `~/.magpie/plugins/` 创建软链接: ```bash @@ -208,7 +223,16 @@ New-Item -ItemType SymbolicLink -Path "$HOME\.magpie\plugins\agentcompass" -Targ 如果你喜欢使用 Magpie UI 的 **Routing Groups(路由组)** 可视化界面: -1. 在插件选项中显式开启 `"enableDecisionProvider": true`,并在 Magpie 中登录启用本插件提供的 Provider:`magpie plugin login agentcompass`(显示名称为 `AgentCompass`); +1. 依次执行:在插件选项中开启 `"enableDecisionProvider": true` → 重启 Magpie → 登录本插件提供的 Provider(无需 Key,显示名称为 `AgentCompass`): + + ```bash + magpie plugin options <插件 spec,见 magpie plugin list> '{"enableDecisionProvider": true}' + # 重启 Magpie(或 magpie web) + magpie plugin login agentcompass + magpie plugin list # 应出现:agentcompass (AgentCompass, 1 models) signed in + ``` + + 未开启该选项时插件不注册任何 Provider,Classifier 列表中也不会出现它。插件版本需为 `0.1.1` 及以上:`0.1.0` 在开启选项后仍不注册 Provider([issue #1](https://github.com/akiiwa-games/magpie-agentcompass-router/issues/1)),`/v1/systemone` 会返回 `magpie has no Jev provider` 或 `magpie knows no Jev model`; 2. 进入你的 **Routing Group** 设置,将 **Classifier(分类器模型)** 选择为 `agentcompass/agentcompass-systemone`(CLI:`magpie group set effort=auto classifier=agentcompass/agentcompass-systemone`); 3. 在 Magpie 全局设置中,可将 `ClassifyTimeout` 调整为 `8000`–`30000` ms(最高支持 `60000` ms); 4. 在 Routing Group 中按标准类别(如 `direction_reasoning`、`debug_review`、`self_contained_code`、`bounded_bulk_work`)配置你的目标模型列表——插件会自动运行 AgentCompass 算法,选出最匹配的规则分支与思考档位(`low` / `medium` / `high` / `xhigh`)。 diff --git a/packages/agentcompass/package.json b/packages/agentcompass/package.json index c810f16..344e3c3 100644 --- a/packages/agentcompass/package.json +++ b/packages/agentcompass/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/gateway-agentcompass", - "version": "0.1.0", + "version": "0.1.1", "description": "Intent, multi-dimensional capability, Model DNA, subscription quota opportunity-cost, and session-affinity routing plugin for Magpie, powered by AgentCompass.", "type": "module", "main": "./src/index.js", diff --git a/packages/agentcompass/src/index.js b/packages/agentcompass/src/index.js index efe80da..1655b5e 100644 --- a/packages/agentcompass/src/index.js +++ b/packages/agentcompass/src/index.js @@ -486,8 +486,10 @@ export async function handleSystemOneRequest(bodyObj, pluginOptions = {}) { /** * Default Magpie Gateway / Middleware Plugin export (`src/index.js`). - * By default, does not register a fake `auth` or `provider` entry in `cfg.provider` - * so Magpie treats the package purely as a gateway hook + middleware plugin. + * By default it registers no `auth` hook and no `cfg.provider` entry, so Magpie treats the package + * purely as a gateway hook + middleware plugin. With `enableDecisionProvider: true` it adds the + * `agentcompass` decision provider: the `config` entry (`decide`, the `decides` model) and the keyless + * `auth` hook whose loader serves `/systemone`; Magpie needs both. */ export async function AgentCompassRouterPlugin(input, pluginOptions = {}) { if (pluginOptions.enableDecisionProvider !== true) { @@ -502,6 +504,7 @@ export async function AgentCompassRouterPlugin(input, pluginOptions = {}) { cfg.provider[PROVIDER_ID] = { name: "AgentCompass", icon: AGENTCOMPASS_ICON_DATA_URI, + api: DECISION_BASE_URL, decide: true, models: { [DECISION_MODEL_ID]: { @@ -515,28 +518,73 @@ export async function AgentCompassRouterPlugin(input, pluginOptions = {}) { }, }; }, - async fetch(reqInput, init) { - const rawBody = init?.body - ? typeof init.body === "string" - ? init.body - : new TextDecoder().decode(init.body) - : reqInput instanceof Request - ? await reqInput.text() - : "{}"; - let parsed = {}; - try { - parsed = JSON.parse(rawBody); - } catch {} - - const reply = await handleSystemOneRequest(parsed, pluginOptions); - return new Response(JSON.stringify(reply), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); + // Magpie lists, signs in and serves only providers a plugin's auth hook names (host.js `auths()`, + // `providers()`; Go `plugin.Provider` is "a provider a plugin signs in to"). It posts System One's + // questions to the provider's base `/systemone` through the fetch the auth loader returns. A + // `config` entry alone is never listed: no Classifier option, no `magpie plugin login agentcompass`, + // and `/v1/systemone` answers 404 (issue #1). + auth: { + provider: PROVIDER_ID, + icon: AGENTCOMPASS_ICON_DATA_URI, + single: true, + methods: [ + { + type: "api", + // keyless: nothing to type and no account of the user's (Magpie's publicPlugin) + keyless: true, + label: "Enable AgentCompass decision provider", + async authorize() { + return { type: "success", key: DECISION_ACCOUNT_KEY }; + }, + }, + ], + async loader() { + return { + baseURL: DECISION_BASE_URL, + apiKey: DECISION_ACCOUNT_KEY, + fetch: (reqInput, init) => systemOneFetch(reqInput, init, pluginOptions), + }; + }, }, }; } +/** Local base the decision provider is served under; nothing is sent over the network. */ +export const DECISION_BASE_URL = "https://agentcompass.local/v1"; +const DECISION_ACCOUNT_KEY = "agentcompass-local"; + +function requestPath(reqInput) { + const raw = typeof reqInput === "string" ? reqInput : reqInput?.url ?? String(reqInput ?? ""); + try { + return new URL(raw).pathname; + } catch { + return raw; + } +} + +/** The decision provider's fetch: answers `/systemone`, and nothing else. */ +export async function systemOneFetch(reqInput, init, pluginOptions = {}) { + const json = (status, value) => + new Response(JSON.stringify(value), { status, headers: { "Content-Type": "application/json" } }); + if (!requestPath(reqInput).replace(/\/+$/, "").endsWith("/systemone")) { + return json(404, { + error: { type: "not_found_error", message: `${PROVIDER_ID} answers only /systemone (System One decisions)` }, + }); + } + const rawBody = init?.body + ? typeof init.body === "string" + ? init.body + : new TextDecoder().decode(init.body) + : reqInput instanceof Request + ? await reqInput.text() + : "{}"; + let parsed = {}; + try { + parsed = JSON.parse(rawBody); + } catch {} + return json(200, await handleSystemOneRequest(parsed, pluginOptions)); +} + export default { id: "agentcompass", server: AgentCompassRouterPlugin, diff --git a/packages/agentcompass/test/router.test.mjs b/packages/agentcompass/test/router.test.mjs index 0fbb3a2..c83e152 100644 --- a/packages/agentcompass/test/router.test.mjs +++ b/packages/agentcompass/test/router.test.mjs @@ -351,7 +351,8 @@ test("4. Native Magpie `/v1/systemone` Decision Handler (`handleSystemOneRequest assert.equal(cfg.provider[PROVIDER_ID].decide, true); assert.equal(cfg.provider[PROVIDER_ID].models[DECISION_MODEL_ID].decides, true); - const httpRes = await optInPlugin.fetch("http://127.0.0.1/v1/systemone", { + const { fetch: decisionFetch, baseURL } = await optInPlugin.auth.loader(async () => ({}), {}); + const httpRes = await decisionFetch(`${baseURL}/systemone`, { method: "POST", body: JSON.stringify({ model: DECISION_MODEL_ID, @@ -374,6 +375,87 @@ test("4. Native Magpie `/v1/systemone` Decision Handler (`handleSystemOneRequest assert.equal(json.answers.intent.choice, "bounded_bulk_work"); }); +/** + * What Magpie's plugin host (0.1.2804 through 0.1.2891, `internal/plugin/host.js`) needs before a + * decision provider exists, emulated: the server function is called with plugins.json's options + * (`fn(input, p.options)`); a provider is listed, signed in and served only when a hook's + * `auth.provider` names it (`auths()` / `providers()`); `decide` and the model's `decides` come from + * the config entry (`info()`); `magpie plugin login` takes a keyless `api` method's `authorize()`; + * System One is posted to the loader's `baseURL` + `/systemone` through the loader's `fetch` (`load()`). + * A `config` entry with no auth hook passed the old test and was never listed (issue #1). + */ +async function magpieHostView(serverFn, options) { + const hooks = (await serverFn({}, options)) ?? {}; + const config = {}; + if (typeof hooks.config === "function") await hooks.config(config); + const auth = hooks.auth?.provider ? hooks.auth : null; + if (!auth) return { providers: [] }; + const cfg = config.provider?.[auth.provider] ?? {}; + const keyless = (auth.methods ?? []).filter( + (m) => m.type === "api" && m.keyless === true && typeof m.authorize === "function" + ); + const signedIn = keyless.length ? await keyless[0].authorize() : null; + const loaded = signedIn?.type === "success" && auth.loader ? await auth.loader(async () => signedIn, cfg) : {}; + return { + providers: [ + { + id: auth.provider, + name: cfg.name ?? auth.provider, + decide: cfg.decide === true, + decisionModels: Object.entries(cfg.models ?? {}).filter(([, m]) => m.decides === true).map(([id]) => id), + keyless: keyless.length > 0, + signedIn: signedIn?.type === "success", + baseURL: typeof loaded.baseURL === "string" ? loaded.baseURL : "", + fetch: typeof loaded.fetch === "function" ? loaded.fetch : null, + }, + ], + }; +} + +test("4d. Decision provider registers the way Magpie's host lists, signs in and serves it (issue #1)", async () => { + const pluginEntry = (await import("../src/index.js")).default; + assert.equal(pluginEntry.id, "agentcompass"); + + for (const options of [{}, { enableDecisionProvider: false }, { enableDecisionProvider: "true" }]) { + assert.deepEqual((await magpieHostView(pluginEntry.server, options)).providers, [], JSON.stringify(options)); + } + + const { providers } = await magpieHostView(pluginEntry.server, { + enableDecisionProvider: true, + injectProtocolEffort: true, + routeAllModels: true, + }); + assert.equal(providers.length, 1, "magpie plugin list must show the agentcompass provider"); + const [p] = providers; + assert.equal(p.id, PROVIDER_ID); + assert.equal(p.name, "AgentCompass"); + assert.equal(p.decide, true); + assert.deepEqual(p.decisionModels, [DECISION_MODEL_ID], "agentcompass/agentcompass-systemone is a Classifier option"); + assert.ok(p.keyless && p.signedIn, "magpie plugin login agentcompass signs in without a key"); + assert.match(p.baseURL, /^https?:\/\//); + assert.equal(typeof p.fetch, "function"); + + const answered = await p.fetch(`${p.baseURL}/systemone`, { + method: "POST", + body: JSON.stringify({ + model: DECISION_MODEL_ID, + state: { task: "Find the root cause of a deadlock across three services" }, + questions: { work_kind: { type: "choice" }, reasoning_depth: { type: "score" } }, + }), + }); + assert.equal(answered.status, 200); + const body = await answered.json(); + assert.equal(body.model, DECISION_MODEL_ID); + assert.equal(typeof body.answers.work_kind.choice, "string"); + assert.equal(typeof body.answers.reasoning_depth.score, "number"); + + // Only System One is served: a chat request sent to the provider is refused, never answered as a model. + const chat = await p.fetch(`${p.baseURL}/chat/completions`, { method: "POST", body: "{}" }); + assert.equal(chat.status, 404); + const viaRequest = await p.fetch(new Request(`${p.baseURL}/systemone`, { method: "POST", body: "{}" })); + assert.equal(viaRequest.status, 200); +}); + test("5. Pool strategy `agentcompass` / `agentcompass-pure` orders non-resting lowest-used seat indexes first", () => { const seats = [ { key: "seat-resting", used: 10, resting: true },