diff --git a/README.md b/README.md index 42c5bd65c..f0f88584c 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ vendor service and makes its requests. The packages work in OpenCode and in | [mimo](packages/mimo) | Xiaomi MiMo, with a Xiaomi account | `mimo-app` | | [nous](packages/nous) | Nous Portal models, with Nous Portal's device sign-in | `nous-portal` | | [openai-decisions](packages/openai-decisions) | OpenAI's native Decisions API as System One for magpie's classifiers and decision groups, with standard API-key sign-in and per-question refusal handling | `openai-decisions` | +| [openrouter-decisions](packages/openrouter-decisions) | OpenRouter's Decisions API (Microsoft Decision 1.1 and 1) as System One for magpie's classifiers and decision groups, with API-key sign-in, credit usage and per-question refusal handling | `openrouter-decisions` | | [opendesign](packages/opendesign) | Open Design Cloud (open-design.ai), with the Open Design CLI's device sign-in | `opendesign` | | [qoder](packages/qoder) | Qoder subscription (qoder.com), with Qoder's device sign-in | `qoder` | | [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` | diff --git a/packages/openrouter-decisions/CHANGELOG.md b/packages/openrouter-decisions/CHANGELOG.md new file mode 100644 index 000000000..70c8f6a90 --- /dev/null +++ b/packages/openrouter-decisions/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +## 0.1.0 — 2026-11-18 + +First release. Exposes OpenRouter's Decisions API +(`POST https://openrouter.ai/api/alpha/decisions`) through Magpie's System +One interface, with `microsoft/microsoft-decision-1.1` as the model. + +- `choice`, `score` and `noul` questions with probabilities, confidence and + a score legend restored from the upstream answer. +- `choices: [...]` shorthand expanded to a criteria map; blank criteria text + falls back to the option name so the upstream's non-empty constraint holds. +- Object, numeric and boolean System One state becomes JSON text evidence; + text passes through; multimodal state parts keep their array form. +- Per-question refusals stay refusals; other answers and usage are retained. +- OpenRouter credit usage shown through `auth.usage` (`/api/v1/auth/key`, + `/api/v1/credits`). +- Fixed upstream endpoint, fresh header set, no redirects; cancellation + propagates; one quick network-level retry absorbs momentary proxy or DNS + failures while HTTP error answers are never retried. diff --git a/packages/openrouter-decisions/LICENSE b/packages/openrouter-decisions/LICENSE new file mode 100644 index 000000000..e6bc674fe --- /dev/null +++ b/packages/openrouter-decisions/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 magpie-community contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/openrouter-decisions/NOTICE.md b/packages/openrouter-decisions/NOTICE.md new file mode 100644 index 000000000..c6cd4f06a --- /dev/null +++ b/packages/openrouter-decisions/NOTICE.md @@ -0,0 +1,9 @@ +The OpenCode 2.x compatibility bridge, `opencode2.mjs`, is an unmodified +copy of `scripts/opencode2.mjs` from magpie-community/plugins, distributed +under that repository's MIT license. Keep it byte-identical to that copy. + +Upstream: https://github.com/magpie-community/plugins + +The implementation follows magpie's public provider/auth/decision contracts +and OpenRouter's public Decisions API. No third-party provider application +logic is bundled here. diff --git a/packages/openrouter-decisions/README.md b/packages/openrouter-decisions/README.md new file mode 100644 index 000000000..b6e6820d8 --- /dev/null +++ b/packages/openrouter-decisions/README.md @@ -0,0 +1,200 @@ +# OpenRouter Decisions for Magpie + +A provider exposing **OpenRouter's [Decisions API](https://openrouter.ai/docs/guides/features/decisions)** +through Magpie's **System One** interface. Use it as a chat routing group's +classifier (intent or reasoning effort) or as a member of a decision-model +group with other System One providers. + +**Provider id:** `openrouter-decisions`. **Models:** +`openrouter-decisions/microsoft-decision-1.1` and +`openrouter-decisions/microsoft-decision-1` (Microsoft's System One decision +models on OpenRouter; 1.1 reads text and images, 1 is text-only and cheaper). + +Magpie already speaks System One for compatible decision providers. OpenRouter +speaks the same question/answer dialect on a different path with a few extra +constraints, which this plugin converts: + +| System One | OpenRouter Decisions | +| --- | --- | +| `POST /v1/systemone` (via the plugin's `fetch`) | `POST https://openrouter.ai/api/alpha/decisions` | +| `model: "microsoft-decision-1.1"` | `model: "microsoft/microsoft-decision-1.1"` | +| object / number / boolean `state` | JSON text `state` | +| `choice` with a `choices` array | expanded to a `criteria` map | +| blank criteria text | the option name, then a positional label | +| `score` with ordered criteria | same array, blank levels labeled | +| `noul` with optional true/false criteria | same fields | + +Answers are converted back with validation: probabilities must cover every +option and sum to one (±0.02), a `score` must land inside `0..N-1`, and a +per-question `refusal` stays a refusal while other answers and usage are +kept. + +## Install and sign in + +Install a released community package through Magpie: + +```sh +magpie plugin add @magpie-community/opencode-openrouter-decisions-auth +magpie plugin login openrouter-decisions +``` + +For an unpublished package or a source checkout, run from the root of +`magpie-community/plugins` instead: + +```sh +magpie plugin add ./packages/openrouter-decisions +magpie plugin login openrouter-decisions +``` + +In Magpie's Plugins page, install **OpenRouter Decisions**, then sign in with +an OpenRouter API key (`sk-or-…`). The key is kept in Magpie's +`plugin-auth.json` (Unix permissions 0600); requests use the selected key's +OpenRouter allowance. + +## Use as a classifier + +As an intent classifier: + +```sh +magpie group add my-group models=provider/model-a,provider/model-b routing=order +magpie group rule add my-group use=provider/model-a intent="a hard task: designing or debugging" +magpie group set my-group classifier=openrouter-decisions/microsoft-decision-1.1 +``` + +As an effort classifier (the group needs at least two models, and members +need reasoning levels): + +```sh +magpie group set my-group classifier=openrouter-decisions/microsoft-decision-1.1 effort=auto +``` + +## Call System One directly + +```sh +curl -s -X POST http://127.0.0.1:3425/v1/systemone \ + -H "Authorization: Bearer $MAGPIE_KEY" -H "Content-Type: application/json" \ + -d '{ + "model": "openrouter-decisions/microsoft-decision-1.1", + "state": {"message": "What does HTTP 404 mean?"}, + "questions": { + "is_question": {"type": "noul", "instructions": "Does this ask a question?"}, + "intent": { + "type": "choice", + "instructions": "Which kind of request is this?", + "criteria": {"question": "Asks for an explanation", "code_change": "Asks to modify code"} + }, + "effort": { + "type": "score", + "instructions": "How much work does this request require?", + "criteria": ["Little work", "Some work", "Much work", "Most work"] + } + } + }' +``` + +A real response: + +```json +{ + "model": "microsoft/microsoft-decision-1.1-20261117", + "answers": { + "is_question": {"type": "noul", "noul": 0.998}, + "intent": {"type": "choice", "choice": "question", + "probabilities": {"question": 0.998, "code_change": 0.0017}, "confidence": 0.9966}, + "effort": {"type": "score", "score": 0.179, + "legend": {"0": "Little work", "1": "Some work", "2": "Much work", "3": "Most work"}, + "probabilities": {"0": 0.858, "1": 0.112, "2": 0.021, "3": 0.0086}, "confidence": 0.811} + }, + "usage": {"input_tokens": 114, "output_tokens": 3, "cost": 0.000004788}, + "provider": "Azure" +} +``` + +## Usage + +`auth.usage` reads OpenRouter's `/api/v1/auth/key` and `/api/v1/credits`; +`magpie quota` shows the credit window, its percentage and the remaining +balance. + +## Protocol and limits + +- Only `POST /v1/systemone` is accepted; other paths and methods are refused + with 400 and never sent upstream. +- The upstream request goes to the fixed `https://openrouter.ai/api/alpha/decisions` + with a fresh header set, no redirects, and no gateway headers or cookies. +- 1–400 questions, 2–255 choice options, 2–10 ordered score levels. +- Upstream error status, body, `Retry-After`, `x-request-id` and + `x-ratelimit-*` headers pass through unchanged. +- Cancellation propagates; HTTP error answers are never retried. One quick + network-level retry absorbs a momentary proxy or DNS failure. +- The decision models stay out of the chat catalog and refuse conversation. +- The adapter does not retry rate limits and owns no failover; Magpie routes. + +## Develop and contribute + +```sh +npm test # or: node --test test/*.test.mjs +bun scripts/check.mjs openrouter-decisions # from the community repo root +MAGPIE=/absolute/path/to/magpie scripts/try.sh openrouter-decisions +``` + +The tests are offline: credentials and responses are synthetic and in-memory, +and no test writes a credential file or touches the network. + +[index.mjs](index.mjs) registers the provider, the selected-account auth and +the usage hook. [adapter.mjs](adapter.mjs) converts requests and answers and +sends the fixed upstream request. Keep `opencode2.mjs` byte-identical to the +community's canonical `scripts/opencode2.mjs`. See [NOTICE.md](NOTICE.md) +for attribution and [VERIFICATION.md](VERIFICATION.md) for live evidence and +untested scope. + +Review checks: + +- Receive credentials only through the host's selected-account auth. +- Preserve probabilities, confidence, the score legend and per-question + refusals. +- Supply non-empty instructions and criteria wherever the upstream requires + them. +- Keep tests offline and free of credential files; code comments use English. +- Keep the root README, package README, bilingual registry and changelog + aligned. +- Verify live routing separately from fixtures; pace live checks by actual + quota. +- Keep credentials, internal endpoints and local artifacts outside the + package. + +References: [OpenRouter Decisions](https://openrouter.ai/docs/guides/features/decisions), +[Magpie provider contract](https://usemagpie.ai/docs/plugins#provider). + +MIT. Not affiliated with OpenRouter or Microsoft. + +## 中文 + +安装社区发行包并使用 OpenRouter API key 登录: + +```sh +magpie plugin add @magpie-community/opencode-openrouter-decisions-auth +magpie plugin login openrouter-decisions +``` + +未发布时,在社区仓库根目录使用 +`magpie plugin add ./packages/openrouter-decisions`,再执行同一登录命令。 +提供方 ID 为 `openrouter-decisions`,模型为 +`openrouter-decisions/microsoft-decision-1.1` 与 +`openrouter-decisions/microsoft-decision-1`。 + +统一入口为 Magpie `/v1/systemone`。支持选择、评分和是非概率(含概率分布、 +置信度与评分档位说明);单题拒绝(refusal)原样保留,其余答案与用量不受影响。 +作为意图分类器时,路由记录会显示命中的意图与 `sure` 置信度;作为推理强度 +分类器时,用评分题给每一轮打难度(组内需至少两个带推理档位的模型)。 + +凭据由宿主提供当前选中账号的 API key;用量钩子读取 OpenRouter 的额度与 +余额,显示在 `magpie quota` 与供应商卡片上。只接受发往固定上游地址的请求, +错误状态码、`Retry-After` 与限流头原样透传;瞬时网络故障自动快速重试一次, +HTTP 错误回答不重试,故障切换交给 magpie。 + +## 客户端兼容性 + +- Magpie:完整支持(意图分类器、推理强度分类器、决策模型组、`/v1/systemone`)。 +- OpenCode 1.x:加载与登录可用;决策输出需要客户端自己发起决策调用。 +- OpenCode 2.x:通过 `opencode2.mjs` 桥接加载;决策工作流未端到端验证。 diff --git a/packages/openrouter-decisions/VERIFICATION.md b/packages/openrouter-decisions/VERIFICATION.md new file mode 100644 index 000000000..303f42791 --- /dev/null +++ b/packages/openrouter-decisions/VERIFICATION.md @@ -0,0 +1,33 @@ +# Verification + +## Initial release — 2026-11-18 + +The adapter's 15 offline tests pass on Node (`node --test test/*.test.mjs`). +They cover the request mapping (state forms, the `choices` shorthand, blank +criteria fallbacks, instruction defaults), answer validation (probability +distributions, score ranges, refusals, malformed answers), endpoint and +header hygiene (fixed upstream URL, fresh header set, no forwarded gateway +headers or cookies), upstream error passthrough, credential loss, the +network retry, and cancellation. + +Live end-to-end checks ran on magpie 0.1.4462 with a real OpenRouter key: + +- `POST /v1/systemone` with `choice`, `score` and `noul` questions returned + calibrated probabilities, the score legend and usage (`provider: "Azure"`). +- As an intent classifier (`magpie group rule add … intent=…` with + `classifier=openrouter-decisions/microsoft-decision-1.1`), the decision + reached the gateway in ~1.1–3.0 s and the recorded `classified` entry + carried the matched intent and `sure` values of 0.94 and 0.99. +- As an effort classifier (`magpie group set … effort=auto`), the + group saved and the provider registered with `decides: true`; the model + stays out of `/v1/models` and refuses conversation requests. +- `magpie quota` showed the OpenRouter credit window and balance through + the usage hook. + +A transient network failure against the proxy was observed in production +use (`Could not reach OpenRouter` after ~3 s); the next call succeeded. The +single quick retry was added for that case and is covered by a test. + +Not verified: OpenCode 2.x decision workflows end to end, other OpenRouter +decision models, image (`box`) inputs — the model does not declare them and +the adapter does not accept `box` questions. diff --git a/packages/openrouter-decisions/adapter.mjs b/packages/openrouter-decisions/adapter.mjs new file mode 100644 index 000000000..34687da5a --- /dev/null +++ b/packages/openrouter-decisions/adapter.mjs @@ -0,0 +1,231 @@ +// Converts Magpie's System One requests into OpenRouter's Decisions API +// (POST https://openrouter.ai/api/alpha/decisions) and converts the answers back. +// OpenRouter already speaks a System One dialect, so the mapping is shallow: +// validate, translate the state into a supported form, and verify answers. + +// The models this provider serves. Both are Microsoft's System One decision +// models on OpenRouter; 1.1 reads text and images, 1 is text-only and cheaper. +export const MODELS = { + "microsoft-decision-1.1": { upstream: "microsoft/microsoft-decision-1.1", images: true }, + "microsoft-decision-1": { upstream: "microsoft/microsoft-decision-1", images: false }, +}; +export const MODEL = "microsoft-decision-1.1"; +const BASE = "https://openrouter.ai/api/v1"; +const SYSTEM_ONE_URL = `${BASE}/systemone`; +const DECISIONS_URL = "https://openrouter.ai/api/alpha/decisions"; +const FALLBACK_INSTRUCTIONS = "Answer this question using the supplied input and criteria."; + +const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value); + +function requireValue(condition, message) { + if (!condition) throw new Error(message); +} + +function fields(value, allowed, name) { + requireValue(record(value), `${name} must be an object`); + requireValue(Object.keys(value).every((key) => allowed.includes(key)), `${name} contains an unsupported field`); +} + +function description(value) { + return typeof value === "string" ? value : JSON.stringify(value); +} + +function questionInstructions(question) { + const supplied = question.instructions == null ? "" : description(question.instructions); + return supplied.trim() ? supplied : FALLBACK_INSTRUCTIONS; +} + +// Magpie allows `choices: ["a", "b"]` as a shorthand for a criteria map. +// OpenRouter's Decisions API documents the criteria form only, so expand it. +function choiceCriteria(question) { + if (question.choices !== undefined) { + requireValue(question.criteria === undefined, "choice accepts criteria or choices, not both"); + requireValue(Array.isArray(question.choices) && question.choices.every((value) => typeof value === "string"), "choices must be strings"); + requireValue(question.choices.every((value) => value.length > 0), "Choice names must not be empty"); + requireValue(new Set(question.choices).size === question.choices.length, "choices must be unique"); + return Object.fromEntries(question.choices.map((value) => [value, null])); + } + requireValue(record(question.criteria), "choice requires a criteria object"); + return question.criteria; +} + +// OpenRouter rejects blank criteria text ("String should have at least 1 +// character"), while System One allows a bare option name or a null level. +// Fall back to the option name, then to a positional label. +function criterionText(value, fallback) { + const text = value == null ? "" : description(value); + return text.trim() ? text : fallback; +} + +export function toOpenRouterRequest(body) { + fields(body, ["model", "state", "questions"], "request"); + const spec = MODELS[body.model]; + requireValue(spec, `Only ${Object.keys(MODELS).join(" and ")} are supported`); + requireValue(Object.hasOwn(body, "state") && body.state !== null, "state is required"); + requireValue(record(body.questions), "questions must be an object"); + const entries = Object.entries(body.questions); + requireValue(entries.length > 0 && entries.length <= 400, "Expected 1–400 questions"); + const questions = {}; + for (const [name, question] of entries) { + requireValue(name.length > 0, "Question IDs must not be empty"); + fields(question, ["type", "instructions", "criteria", "choices"], "question"); + requireValue(question.instructions == null || typeof question.instructions === "string" || typeof question.instructions === "object", "instructions must be text or structured JSON"); + const common = { type: question.type, instructions: questionInstructions(question) }; + switch (question.type) { + case "choice": { + const criteria = choiceCriteria(question); + const keys = Object.keys(criteria); + requireValue(keys.length >= 2 && keys.length <= 255, "choice requires 2–255 options"); + requireValue(keys.every((key) => key.length > 0), "Choice names must not be empty"); + requireValue(new Set(keys).size === keys.length, "Choice names must be unique"); + questions[name] = { ...common, criteria: Object.fromEntries(keys.map((key) => [key, criterionText(criteria[key], key)])) }; + break; + } + case "score": + requireValue(question.choices === undefined, "score does not accept choices"); + requireValue(Array.isArray(question.criteria) && question.criteria.length >= 2 && question.criteria.length <= 10, "score requires 2–10 ordered criteria"); + questions[name] = { ...common, criteria: question.criteria.map((value, index) => criterionText(value, `Level ${index}`)) }; + break; + case "noul": + requireValue(question.choices === undefined, "noul does not accept choices"); + if (question.criteria !== undefined) { + requireValue(record(question.criteria) && Object.keys(question.criteria).every((key) => key === "true" || key === "false"), "noul criteria accept true and false only"); + questions[name] = { + ...common, + criteria: Object.fromEntries(Object.entries(question.criteria).map(([key, value]) => [key, criterionText(value, key === "true" ? "True" : "False")])), + }; + } else { + questions[name] = common; + } + break; + default: + throw new Error("Unsupported question type; use choice, score or noul"); + } + } + // OpenRouter accepts a text state, or an array of text/media parts. Anything + // else (plain objects, numbers, booleans) becomes JSON text evidence. The + // text-only model takes every part as its JSON text. + const state = typeof body.state === "string" + ? body.state + : (Array.isArray(body.state) ? body.state.map((part) => typeof part === "string" ? part : JSON.stringify(part)) : JSON.stringify(body.state)); + return { model: spec.upstream, state, questions }; +} + +function probability(value, name) { + requireValue(typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1, `Invalid ${name}`); + return value; +} + +function distribution(map, expected, name) { + requireValue(record(map), `${name} probabilities must be an object`); + const keys = Object.keys(map); + requireValue(keys.length === expected.length && expected.every((key) => Object.hasOwn(map, key)), `Incomplete ${name} probability distribution`); + let sum = 0; + const result = {}; + for (const key of expected) { + result[key] = probability(map[key], name); + sum += result[key]; + } + requireValue(Math.abs(sum - 1) <= 0.02, `${name} probabilities do not sum to one`); + return result; +} + +export function fromOpenRouterResponse(upstream, source) { + const request = toOpenRouterRequest(source); + requireValue(record(upstream), "Invalid upstream decision response"); + requireValue(record(upstream.answers), "Invalid upstream answers"); + const answers = {}; + for (const [name, question] of Object.entries(request.questions)) { + const answer = upstream.answers[name]; + requireValue(record(answer), `Missing upstream answer for "${name}"`); + if (answer.type === "refusal") { + answers[name] = { type: "refusal" }; + continue; + } + requireValue(answer.type === question.type, `Wrong upstream answer type for "${name}"`); + if (answer.type === "noul") { + answers[name] = { type: "noul", noul: probability(answer.noul, "noul") }; + } else if (answer.type === "choice") { + const keys = Object.keys(request.questions[name].criteria); + requireValue(keys.includes(answer.choice), "Upstream chose an unknown option"); + answers[name] = { + type: "choice", + choice: answer.choice, + probabilities: distribution(answer.probabilities, keys, "choice"), + confidence: probability(answer.confidence, "confidence"), + }; + } else { + const count = request.questions[name].criteria.length; + requireValue(typeof answer.score === "number" && Number.isFinite(answer.score) && answer.score >= 0 && answer.score <= count - 1, "Invalid upstream score"); + answers[name] = { + type: "score", + score: answer.score, + legend: Object.fromEntries(request.questions[name].criteria.map((text, index) => [String(index), text])), + probabilities: distribution(answer.probabilities, request.questions[name].criteria.map((_, index) => String(index)), "score"), + confidence: probability(answer.confidence, "confidence"), + }; + } + } + return { ...upstream, answers }; +} + +function responseHeaders(response) { + const headers = new Headers({ "content-type": response.headers.get("content-type") || "application/json" }); + for (const [key, value] of response.headers) { + if (key === "retry-after" || key === "x-request-id" || key.startsWith("x-ratelimit-")) headers.set(key, value); + } + return headers; +} + +function refused(status, message, headers) { + return Response.json({ error: { type: status === 400 ? "invalid_request_error" : "api_error", message } }, { status, headers }); +} + +export function createDecisionFetch({ getKey, fetchImpl = globalThis.fetch }) { + return async (input, init) => { + let request, source, payload; + try { + request = new Request(input, init); + requireValue(request.url === SYSTEM_ONE_URL && request.method === "POST", "Only POST /v1/systemone is supported"); + source = await request.json(); + payload = toOpenRouterRequest(source); + } catch (error) { + if (request?.signal.aborted) throw error; + return refused(400, error instanceof SyntaxError ? "Invalid JSON request" : error.message); + } + request.signal.throwIfAborted(); + let key; + try { + key = await getKey(); + requireValue(typeof key === "string" && key.trim().length > 0 && !/[\r\n]/.test(key), "Missing OpenRouter API key"); + } catch { + return refused(503, "OpenRouter credentials unavailable; check this provider's API-key sign-in"); + } + const headers = new Headers({ "content-type": "application/json", accept: "application/json", authorization: `Bearer ${key}` }); + // A momentary network failure (proxy restart, DNS hiccup) should not lose + // the routing decision: retry network-level errors once, quickly. HTTP + // error responses are upstream answers and are never retried. + let upstream; + for (let attempt = 0; ; attempt++) { + try { + upstream = await fetchImpl(DECISIONS_URL, { method: "POST", headers, body: JSON.stringify(payload), signal: request.signal, redirect: "error" }); + break; + } catch (error) { + if (request.signal.aborted) throw error; + if (attempt > 0) return refused(502, `Could not reach OpenRouter: ${error?.message || "network error"}`); + await new Promise((resolve) => setTimeout(resolve, 400)); + } + } + const keptHeaders = responseHeaders(upstream); + if (!upstream.ok) return new Response(upstream.body, { status: upstream.status, headers: keptHeaders }); + try { + const result = fromOpenRouterResponse(await upstream.json(), source); + return Response.json(result, { status: upstream.status, headers: keptHeaders }); + } catch (error) { + if (request.signal.aborted) throw error; + return refused(502, "OpenRouter returned an invalid or incomplete decision answer", keptHeaders); + } + }; +} + +export const _internal = { SYSTEM_ONE_URL, DECISIONS_URL }; diff --git a/packages/openrouter-decisions/index.mjs b/packages/openrouter-decisions/index.mjs new file mode 100644 index 000000000..6b6465bb9 --- /dev/null +++ b/packages/openrouter-decisions/index.mjs @@ -0,0 +1,103 @@ +import { createDecisionFetch, MODELS } from "./adapter.mjs"; + +const ID = "openrouter-decisions"; +const BASE = "https://openrouter.ai/api/v1"; +// $ per 1M tokens, billed on input only; both models answer with decisions, +// never conversation. 1.1 reads text and images, 1 is text-only. +const modelSpecs = { + "microsoft-decision-1.1": { + name: "Microsoft Decision 1.1", + modalities: { input: ["text"], output: ["text"] }, + }, + "microsoft-decision-1": { + name: "Microsoft Decision 1", + modalities: { input: ["text"], output: ["text"] }, + }, +}; +const models = Object.fromEntries(Object.entries(MODELS).map(([id, spec]) => [ + id, + { + id, + name: modelSpecs[id].name, + decides: true, + tool_call: false, + reasoning: false, + limit: { context: 32768, output: 0 }, + modalities: modelSpecs[id].modalities, + cost: { input: 0.042, output: 0 }, + }, +])); + +// Export only the plugin function; Magpie invokes each exported function as a plugin. +export const OpenRouterDecisionsPlugin = async () => ({ + async config(config) { + config.provider ??= {}; + config.provider[ID] ??= { + name: "OpenRouter Decisions", + npm: "@ai-sdk/openai-compatible", + api: BASE, + decide: true, + models, + }; + }, + auth: { + provider: ID, + methods: [ + { type: "api", label: "OpenRouter API key", placeholder: "sk-or-…" }, + ], + async loader(getAuth) { + const auth = await getAuth(); + if (auth?.type !== "api" || typeof auth.key !== "string" || !auth.key.trim()) return {}; + return { + baseURL: BASE, + apiKey: auth.key, + fetch: createDecisionFetch({ getKey: async () => { + const current = await getAuth(); + return current?.type === "api" ? current.key : undefined; + } }), + }; + }, + // magpie's own hook: show this account's OpenRouter credit usage + async usage(getAuth) { + const auth = await getAuth(); + if (auth?.type !== "api" || typeof auth.key !== "string" || !auth.key.trim()) return { error: "Not signed in" }; + const headers = { authorization: `Bearer ${auth.key}` }; + try { + const res = await fetch(`${BASE}/auth/key`, { headers }); + if (!res.ok) return { error: `OpenRouter answered ${res.status}` }; + const { data } = await res.json(); + if (!data) return { error: "OpenRouter returned no key info" }; + const windows = []; + if (typeof data.limit === "number" && data.limit > 0 && typeof data.usage === "number") { + windows.push({ + name: "Credits", + used: Math.round((data.usage / data.limit) * 1000) / 10, + amount: data.usage, + limit: data.limit, + unit: "credits", + display: `${data.usage.toFixed(2)} / ${data.limit.toFixed(2)} credits`, + }); + } + const result = { plan: data.is_free_tier ? "Free tier" : "Paid", user: data.label, windows }; + try { + const creditsRes = await fetch(`${BASE}/credits`, { headers }); + if (creditsRes.ok) { + const credits = (await creditsRes.json()).data; + if (credits && typeof credits.total_credits === "number" && typeof credits.total_usage === "number") { + result.balance = `$${(credits.total_credits - credits.total_usage).toFixed(2)}`; + } + } + } catch { /* balance is best-effort */ } + return result; + } catch { + return { error: "Could not reach OpenRouter" }; + } + }, + }, + provider: { + id: ID, + async models() { + return models; + }, + }, +}); diff --git a/packages/openrouter-decisions/opencode.mjs b/packages/openrouter-decisions/opencode.mjs new file mode 100644 index 000000000..5a9a55f32 --- /dev/null +++ b/packages/openrouter-decisions/opencode.mjs @@ -0,0 +1 @@ +export { OpenRouterDecisionsPlugin } from "./index.mjs"; diff --git a/packages/openrouter-decisions/opencode2.mjs b/packages/openrouter-decisions/opencode2.mjs new file mode 100644 index 000000000..b9393085e --- /dev/null +++ b/packages/openrouter-decisions/opencode2.mjs @@ -0,0 +1,620 @@ +// The OpenCode 2.x face of a package whose plugins are written for +// OpenCode 1.x (and magpie's plugin host). +// +// OpenCode 2.x loads a package's `exports["."]` and wants its default to be +// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions +// (plugins#657). This file is that default. It runs each 1.x plugin the +// package's opencode.mjs exports and hands 2.x what the plugin's hooks say: +// +// auth.methods → the integration's sign-in methods +// config() → the provider, its package, base URL and models +// provider.models → the signed-in account's own model list +// auth.loader → each request's base URL, key, headers and fetch +// +// What 2.x has no place for is left out: chat.headers and chat.params +// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin, +// tools and events. +// +// scripts/opencode2.mjs is the one copy that is edited. Every package that +// has it carries the same bytes as packages//opencode2.mjs, and +// scripts/check.mjs fails when a copy differs. + +import { readFileSync } from "node:fs" +import * as v1 from "./opencode.mjs" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// The key the SDK is made with: the account's own goes on each request in +// its place (see wrapFetch), so a key read when the SDK was made can't go +// out after the account changed. +const PLACEHOLDER = "opencode2-v1-key" + +// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from +// swapping @ai-sdk/* for its native providers, which never call the sdk +// hook below; openai-compatible's is the one 2.x ships, the others are AI +// SDK v6's dist-tag, the line 2.x's bridge runs. +export function packageOf(npm) { + const name = npm || "@ai-sdk/openai-compatible" + if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41" + if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6` + return `aisdk:${name}` +} + +// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read +// them: a default {server} is the one plugin, else every function export +// and every {server} object. +export function pluginsOf(mod) { + const d = mod?.default + if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d)) + return typeof d.server === "function" ? [d.server] : [] + const out = [] + for (const value of Object.values(mod ?? {})) { + const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null + if (fn && !out.includes(fn)) out.push(fn) + } + return out +} + +const int = (n, fallback = 0) => { + const v = Math.trunc(Number(n)) + return Number.isFinite(v) && v >= 0 ? v : fallback +} +const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0) +const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}) +const json = (v) => { + try { + return JSON.parse(JSON.stringify(v ?? null)) + } catch { + return null + } +} +const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string")) +const nonEmpty = (o) => (Object.keys(o).length ? o : undefined) + +// connKey names a connection the way 2.x does. +const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`) + +// ---- sign-in ------------------------------------------------------------ + +// fields is a 1.x method's prompts as a 2.x form. +export function fieldsOf(prompts) { + const out = [] + for (const p of prompts ?? []) { + if (!p?.key) continue + const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) } + if (p.placeholder) f.placeholder = String(p.placeholder) + if (p.type === "select" && Array.isArray(p.options)) + f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) + // a prompt shown only when another answer says so can't be required, and + // neither can one whose own validate() accepts an empty answer (the + // browser sign-in's optional API key) + if (!p.condition && p.required !== false) f.required = true + out.push(f) + } + return out.length ? out : undefined +} + +// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes +// auth.json: the result without its type and provider. +function v1Saved(r) { + const { type: _t, provider: _p, ...rest } = r + if ("key" in r) return { type: "api", ...rest } + return { type: "oauth", ...rest } +} + +// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for +// both kinds, the 1.x auth kept whole in its metadata. No refresh is +// registered, so 2.x hands the credential over as it is and the plugin's +// own loader renews it, as it does on 1.x. +export function credentialOf(methodID, r) { + if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed") + const saved = json(v1Saved(r)) + if (saved.type === "api") + return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } } + return { + type: "oauth", + methodID, + access: String(saved.access ?? ""), + refresh: String(saved.refresh ?? ""), + expires: int(saved.expires), + metadata: { v1: saved }, + } +} + +// authOfValue is the 1.x auth a 2.x credential stands for. +export function authOfValue(value) { + if (!value) return null + if (value.type === "oauth") { + const v1 = record(value.metadata).v1 + if (v1 && typeof v1 === "object") return v1 + return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires } + } + if (value.type === "key") { + const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {} + return { type: "api", key: value.key, ...meta } + } + return null +} + +const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""]) + +// ---- models ------------------------------------------------------------- + +const MODALITIES = ["text", "audio", "image", "video", "pdf"] + +// internalOf is a config model as 1.x hands it to provider.models: what +// fromModelsDevModel makes of it, with the config's own variants. +export function internalOf(providerID, conf, key, m) { + const mods = record(m.modalities) + const has = (list, k) => Array.isArray(list) && list.includes(k) + const cost = record(m.cost) + return { + ...m, + id: key, + providerID, + name: m.name ?? key, + api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" }, + status: m.status ?? "active", + headers: m.headers ?? {}, + options: m.options ?? {}, + cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } }, + limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) }, + capabilities: { + temperature: m.temperature ?? false, + reasoning: m.reasoning ?? false, + attachment: m.attachment ?? false, + toolcall: m.tool_call ?? true, + input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])), + output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])), + interleaved: m.interleaved ?? false, + }, + release_date: m.release_date ?? "", + variants: record(m.variants), + } +} + +// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info. +export function modelOf(providerID, provider, key, m) { + const caps = record(m.capabilities) + const listFrom = (obj, list) => { + if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k]) + if (Array.isArray(list)) return list.map(String) + return ["text"] + } + const input = listFrom(caps.input, m.modalities?.input) + const output = listFrom(caps.output, m.modalities?.output) + const c = record(m.cost) + const cache = record(c.cache) + const npm = m.api?.npm ?? m.provider?.npm + const url = m.api?.url ?? m.provider?.api + const settings = { ...record(json(m.options)) } + if (url && url !== provider.baseURL) settings.baseURL = url + const variants = Object.entries(record(m.variants)) + .filter(([, v]) => !record(v).disabled) + .map(([id, v]) => { + const { disabled: _d, ...rest } = record(json(v)) + return nonEmpty(rest) ? { id, settings: rest } : { id } + }) + const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active" + const out = { + id: key, + modelID: String(m.api?.id ?? m.id ?? key), + providerID, + name: String(m.name ?? key), + capabilities: { + tools: caps.toolcall ?? m.tool_call ?? true, + input: input.length ? input : ["text"], + output: output.length ? output : ["text"], + ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}), + }, + variants, + time: { released: Date.parse(m.release_date ?? "") || 0 }, + cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }], + status, + enabled: true, + limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 }, + } + if (m.limit?.input) out.limit.input = int(m.limit.input) + if (npm && npm !== provider.npm) out.package = packageOf(npm) + if (nonEmpty(settings)) out.settings = settings + const headers = strings(m.headers) + if (nonEmpty(headers)) out.headers = headers + return out +} + +// ---- requests ----------------------------------------------------------- + +const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input)) + +// wrapFetch sends a request the SDK made from the provider's settings the +// way 1.x would have sent it with the loader's options: the loader's base +// URL in place of the configured one, the account's key in place of the +// placeholder, the loader's headers added, through the loader's fetch. +export function wrapFetch(next, base, options) { + return async (input, init = {}) => { + const o = await options() + let url = urlOf(input) + const from = String(base ?? "").replace(/\/+$/, "") + const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : "" + if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length) + const req = input instanceof Request ? input : null + const headers = new Headers(init.headers ?? req?.headers ?? undefined) + for (const [k, v] of [...headers.entries()]) { + if (!v.includes(PLACEHOLDER)) continue + if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key)) + else headers.delete(k) + } + for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v) + const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch + if (req && init.body === undefined) { + const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text() + return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal }) + } + return send(url, { ...init, headers }) + } +} + +// ---- one plugin --------------------------------------------------------- + +async function setupPlugin(ctx, fn, live) { + const directory = ctx?.location?.directory ?? process.cwd() + // the active account each provider was last read for, and the renewed + // auth a plugin saved for it (2.x has no way for a plugin to write a + // credential back, so it is kept in the plugin's storage, under the + // credential it renews and the token it was renewed from) + const current = new Map() + const saved = new Map() + const signingIn = new Map() + const storeKey = (id, key) => `v1auth/${id}/${key}` + + const client = { + auth: { + async set(arg) { + const id = arg?.path?.id + const body = json(arg?.body) + const cur = id && current.get(id) + // a sign-in's own saves belong to the credential it is about to + // make, not the one that was active when it started + if (!cur || !body || signingIn.get(id) > 0) return { data: true } + const entry = { fp: cur.fp, auth: body } + saved.set(storeKey(id, cur.key), entry) + await Promise.resolve() + .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry)) + .catch(() => {}) + return { data: true } + }, + async get() { + return { data: undefined } + }, + }, + app: { log: async () => ({ data: true }) }, + } + + const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {} + const cfg = { provider: {} } + try { + await hooks.config?.(cfg) + } catch {} + const auth = hooks.auth + const authID = auth?.provider ? String(auth.provider) : undefined + const providers = record(cfg.provider) + + // getAuth reads the active account: the credential 2.x holds, or what the + // plugin last saved renewing it. + const getAuth = async (id) => { + const connection = await ctx.integration.connection.active(id).catch(() => undefined) + if (!connection) { + current.delete(id) + return undefined + } + const value = await ctx.integration.connection.resolve(connection).catch(() => undefined) + const base = authOfValue(value) + if (!base) { + current.delete(id) + return undefined + } + const key = connKey(connection) + const fp = fingerprint(base) + // ours: a credential one of this plugin's own sign-ins made + const ours = value?.type === "oauth" && !!record(value.metadata).v1 + current.set(id, { key, fp, ours }) + const sk = storeKey(id, key) + let entry = saved.get(sk) + if (!entry) { + entry = await Promise.resolve() + .then(() => ctx.storage?.get?.(sk)) + .catch(() => undefined) + if (entry) saved.set(sk, entry) + } + return entry && entry.fp === fp && entry.auth ? entry.auth : base + } + + // the sign-in methods + if (authID && Array.isArray(auth.methods) && auth.methods.length) { + const label = (c) => { + const a = authOfValue(c) + const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account + return typeof name === "string" && name ? name : undefined + } + const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1) + const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1)) + const title = record(providers[authID]).name + // 2.x runs a transform again on every reload, from nothing + await ctx.integration.transform((editor) => { + let keyed = false + // the integration 2.x makes for an id it doesn't know is named by the + // id; the provider's own name reads better in the sign-in list + if (typeof title === "string" && title) + try { + editor.update?.(authID, (i) => { + if (i && (!i.name || i.name === authID)) i.name = title + }) + } catch {} + auth.methods.forEach((m, i) => { + if (!m) return + const methodID = `v1-${i}` + const form = fieldsOf(m.prompts) + if (m.type === "api" && typeof m.authorize !== "function") { + if (keyed) return + keyed = true + editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } }) + return + } + if (typeof m.authorize !== "function") return + editor.method.update({ + integrationID: authID, + method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) }, + async authorize(answer) { + begin() + let ended = false + const done = () => { + if (!ended) end() + ended = true + } + try { + const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)])) + const r = await m.authorize(inputs) + if (m.type === "api") { + done() + return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) } + } + if (r?.method === "code") + return { + url: String(r.url ?? ""), + instructions: String(r.instructions ?? ""), + mode: "code", + callback: async (code) => { + try { + return credentialOf(methodID, await r.callback(code)) + } finally { + done() + } + }, + } + const callback = Promise.resolve() + .then(() => r.callback()) + .then((res) => credentialOf(methodID, res)) + .finally(done) + callback.catch(() => {}) + return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback } + } catch (e) { + done() + throw e + } + }, + label, + }) + }) + }) + } + + // the loader's options for the account signed in now, read again when + // the account changes + let loaded = null + const loaderOptions = async (id) => { + if (id !== authID || typeof auth?.loader !== "function") { + const a = authID === id ? await getAuth(id) : undefined + return { key: a?.type === "api" ? a.key : undefined } + } + const a = await getAuth(id) + if (!a) return {} + const fp = current.get(id)?.key + "\0" + fingerprint(a) + if (loaded?.fp !== fp) { + const p = Promise.resolve() + .then(() => auth.loader(() => getAuth(id), providerOf(id))) + .then((o) => record(o)) + loaded = { fp, p } + p.catch(() => { + if (loaded?.fp === fp) loaded = null + }) + } + const o = await loaded.p + const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined + return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch } + } + + // the providers, with the list the account's own read last gave each + const source = new Map() + // providerOf is a provider as 1.x hands it to provider.models and + // auth.loader + const providerOf = (id) => { + const conf = record(providers[id]) + const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))])) + return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models } + } + const listed = new Set() + for (const [id, conf0] of Object.entries(providers)) { + const conf = record(conf0) + // a provider entry that only names the sign-in (no package, no models) + // is not a provider of models + if (!conf.npm && !Object.keys(record(conf.models)).length) continue + const options = record(conf.options) + const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options + // with no base URL the config leaves it to the loader: a name that + // can't resolve stands in for it, and each request swaps in the + // loader's (wrapFetch) + const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid` + const npm = conf.npm ?? "@ai-sdk/openai-compatible" + const info = { + id, + ...(id === authID ? { integrationID: id } : {}), + name: String(conf.name ?? id), + activation: "auto", + package: packageOf(npm), + settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) }, + } + const headers = { ...strings(conf.headers), ...strings(optHeaders) } + if (nonEmpty(headers)) info.headers = headers + const prov = { baseURL, npm } + const fromConfig = () => + Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m)))) + listed.add(id) + await ctx.provider.transform((editor) => { + const s = source.get(id) + editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection }) + }) + source.set(id, { conf, prov, models: null, connection: undefined }) + } + + // each request: the placeholder key, and the fetch that swaps in the + // account's. A provider the package doesn't list (one 2.x has built in + // that the plugin only signs in to) is left to 2.x unless the plugin's + // loader serves it and one of the plugin's own sign-ins is active. + const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : [] + for (const id of new Set([...listed, ...own])) { + const base = source.get(id)?.prov.baseURL + await ctx.aisdk.hook( + "sdk", + async (evt) => { + const opts = evt.options + if (!opts || opts.__opencode2) return + if (!listed.has(id)) { + await getAuth(id) + if (!current.get(id)?.ours) return + } + opts.__opencode2 = true + opts.apiKey = PLACEHOLDER + opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id)) + }, + { providerID: id }, + ) + } + + // refresh reads the account's own list after a sign-in or a switch + const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined + let refreshing = null + let again = false + // the account the list was last read for: a credential.updated that + // leaves it as it was reads nothing again + let readFor = null + const stateOf = async () => { + const c = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = c ? await getAuth(authID) : undefined + return connKey(c) + "\0" + (a ? fingerprint(a) : "") + } + const refresh = () => { + if (refreshing) { + again = true + return refreshing + } + refreshing = (async () => { + try { + if (!authID || !source.has(authID)) return + const s = source.get(authID) + const connection = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = connection ? await getAuth(authID) : undefined + readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { + if (s.connection || s.models) { + s.connection = undefined + s.models = null + await ctx.provider.reload() + } + return + } + const provider = providerOf(authID) + let got + try { + got = await hooks.provider.models(provider, { auth: a }) + } catch { + got = null + } + if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) { + again = true + return + } + s.connection = connection + s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + await ctx.provider.reload() + await ctx.model?.reload?.() + } finally { + refreshing = null + if (again && live.on) { + again = false + void refresh() + } + } + })() + return refreshing + } + + if (authID && ctx.event?.subscribe) + void (async () => { + try { + // a switch names the integration; an update (a sign-in, a removal) + // names nothing, so it reads again only when this account changed + const types = ["credential.switched", "credential.updated"] + for await (const event of ctx.event.subscribe({ types })) { + if (!live.on) return + if (event?.type === "credential.switched" && event?.data?.integrationID === authID) { + loaded = null + await refresh() + } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) { + await refresh() + } + } + } catch {} + })() + // A plugin still reading its list in the background when the first read + // returned (agy-cli: `agy models` and a session probe take seconds, and + // the first read gets its static list) says so through + // provider.warming(): the list is read once more when that ends, once, + // and no later than a minute on. + const warmed = async () => { + let w + try { + w = typeof hooks.provider?.warming === "function" ? hooks.provider.warming() : null + } catch { + return + } + if (!w || typeof w.then !== "function") return + let timer + await Promise.race([ + Promise.resolve(w).catch(() => {}), + new Promise((r) => { + timer = setTimeout(r, 60_000) + timer.unref?.() + }), + ]) + clearTimeout(timer) + if (live.on) await refresh() + } + void refresh().then(warmed, () => {}) +} + +export async function setup(ctx, mod = v1) { + const live = { on: true } + for (const fn of pluginsOf(mod)) { + try { + await setupPlugin(ctx, fn, live) + } catch (e) { + // one plugin failing to start leaves the package's others working + console.error(`${pkg.name}: ${e?.message ?? e}`) + } + } + return () => { + live.on = false + } +} + +export default { id: pkg.name, setup: (ctx) => setup(ctx) } diff --git a/packages/openrouter-decisions/package.json b/packages/openrouter-decisions/package.json new file mode 100644 index 000000000..d52d536de --- /dev/null +++ b/packages/openrouter-decisions/package.json @@ -0,0 +1,19 @@ +{ + "name": "@magpie-community/opencode-openrouter-decisions-auth", + "version": "0.1.0", + "description": "Expose OpenRouter's decision models (Microsoft Decision 1.1/1) through Magpie's System One decision API.", + "type": "module", + "main": "./opencode.mjs", + "exports": {".": "./opencode2.mjs"}, + "files": ["index.mjs", "adapter.mjs", "opencode.mjs", "opencode2.mjs", "README.md", "LICENSE", "NOTICE.md", "CHANGELOG.md", "VERIFICATION.md"], + "scripts": {"test": "node --test test/*.test.mjs"}, + "magpie": { + "name": "OpenRouter Decisions", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Ccircle%20cx%3D%2232%22%20cy%3D%2232%22%20r%3D%2229%22%20fill%3D%22%230f172a%22%2F%3E%3Cpath%20d%3D%22M20%2040a12%2012%200%201%201%2012%2012%22%20fill%3D%22none%22%20stroke%3D%22%2365a3ff%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%2F%3E%3Ccircle%20cx%3D%2244%22%20cy%3D%2228%22%20r%3D%226%22%20fill%3D%22%2365a3ff%22%2F%3E%3C%2Fsvg%3E", + "maxConcurrency": 8 + }, + "engines": {"node": ">=20"}, + "license": "MIT", + "keywords": ["opencode", "opencode-plugin", "magpie", "magpie-plugin", "openrouter", "decisions", "system-one"], + "repository": {"type": "git", "url": "https://github.com/magpie-community/plugins.git", "directory": "packages/openrouter-decisions"} +} diff --git a/packages/openrouter-decisions/test/adapter.test.mjs b/packages/openrouter-decisions/test/adapter.test.mjs new file mode 100644 index 000000000..4b45ef80d --- /dev/null +++ b/packages/openrouter-decisions/test/adapter.test.mjs @@ -0,0 +1,186 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createDecisionFetch, fromOpenRouterResponse, MODELS, toOpenRouterRequest } from "../adapter.mjs"; + +const UPSTREAM_MODEL = MODELS["microsoft-decision-1.1"].upstream; + +const body = () => ({ + model: "microsoft-decision-1.1", + state: { message: "What does HTTP 404 mean?", previous_message_kind: "question" }, + questions: { + intent: { type: "choice", instructions: "Which task?", criteria: { question: "Explain a fact", edit: null } }, + effort: { type: "score", instructions: "How hard?", criteria: ["Little work", "Some work", "Much work", "Most work"] }, + levels: { type: "noul", instructions: "Are these kinds levels of one scale?" }, + }, +}); + +const reply = () => ({ + id: "gen-dec-test", + model: UPSTREAM_MODEL, + provider: "Microsoft", + usage: { input_tokens: 42, output_tokens: 0, cost: 0.0000018 }, + answers: { + levels: { type: "noul", noul: 0.9, confidence: 0.9 }, + intent: { type: "choice", choice: "question", confidence: 0.8, probabilities: { question: 0.9, edit: 0.1 } }, + effort: { type: "score", score: 1.84, confidence: 0.85, probabilities: { 0: 0.01, 1: 0.14, 2: 0.85, 3: 0 } }, + }, +}); + +test("serves both Microsoft decision models and maps the upstream slug", () => { + for (const id of Object.keys(MODELS)) { + const out = toOpenRouterRequest({ ...body(), model: id }); + assert.equal(out.model, MODELS[id].upstream); + } + assert.throws(() => toOpenRouterRequest({ ...body(), model: "microsoft-decision-9" })); +}); + +test("maps the System One request onto the OpenRouter Decisions request", () => { + const out = toOpenRouterRequest(body()); + assert.equal(out.model, UPSTREAM_MODEL); + assert.equal(typeof out.state, "string"); + assert.deepEqual(JSON.parse(out.state), body().state); + assert.deepEqual(out.questions.intent, { type: "choice", instructions: "Which task?", criteria: { question: "Explain a fact", edit: "edit" } }); + assert.deepEqual(out.questions.effort.criteria, ["Little work", "Some work", "Much work", "Most work"]); + assert.deepEqual(out.questions.levels, { type: "noul", instructions: "Are these kinds levels of one scale?" }); +}); + +test("passes text state through and expands the choices shorthand", () => { + const out = toOpenRouterRequest({ model: "microsoft-decision-1.1", state: "hello", questions: { intent: { type: "choice", instructions: "Kind?", choices: ["question", "edit"] } } }); + assert.equal(out.state, "hello"); + assert.deepEqual(out.questions.intent.criteria, { question: "question", edit: "edit" }); +}); + +test("keeps multimodal state parts as an array of strings", () => { + const state = ["Look:", { type: "image_url", image_url: { url: "data:image/jpeg;base64,AA" } }]; + const out = toOpenRouterRequest({ ...body(), state }); + assert.equal(Array.isArray(out.state), true); + assert.equal(out.state[0], "Look:"); + assert.deepEqual(JSON.parse(out.state[1]), state[1]); +}); + +test("supplies fallback instructions and keeps predicate definitions", () => { + const source = body(); + for (const question of Object.values(source.questions)) question.instructions = " "; + source.questions.levels.criteria = { true: "Matches", false: "Does not match" }; + const out = toOpenRouterRequest(source); + for (const question of Object.values(out.questions)) assert.ok(question.instructions.trim().length > 0); + assert.deepEqual(out.questions.levels.criteria, { true: "Matches", false: "Does not match" }); +}); + +test("restores probabilities, confidence, legend and usage", () => { + const out = fromOpenRouterResponse(reply(), body()); + assert.equal(out.answers.intent.choice, "question"); + assert.deepEqual(out.answers.intent.probabilities, { question: 0.9, edit: 0.1 }); + assert.equal(out.answers.effort.score, 1.84); + assert.deepEqual(out.answers.effort.probabilities, { 0: 0.01, 1: 0.14, 2: 0.85, 3: 0 }); + assert.deepEqual(out.answers.levels, { type: "noul", noul: 0.9 }); + assert.deepEqual(out.usage, reply().usage); +}); + +test("a per-question refusal stays a refusal", () => { + const upstream = reply(); + upstream.answers.intent = { type: "refusal" }; + const out = fromOpenRouterResponse(upstream, body()); + assert.deepEqual(out.answers.intent, { type: "refusal" }); + assert.equal(out.answers.effort.score, 1.84); +}); + +test("rejects unsupported requests before calling upstream", () => { + for (const source of [ + { ...body(), stream: true }, + { ...body(), model: "typesafe/jev-1.14" }, + { ...body(), questions: {} }, + { ...body(), questions: { x: { type: "text", instructions: "Explain" } } }, + { ...body(), questions: { x: { type: "choice", instructions: "Kind?", criteria: { only: null } } } }, + { ...body(), questions: { x: { ...body().questions.intent, choices: ["a", "b"] } } }, + { ...body(), questions: { x: { type: "noul", criteria: { other: "x" } } } }, + ]) assert.throws(() => toOpenRouterRequest(source)); +}); + +test("rejects missing, wrong-type and malformed answers", () => { + for (const mutate of [ + (r) => delete r.answers.intent, + (r) => { r.answers.intent.type = "noul"; }, + (r) => { r.answers.intent.choice = "unknown"; }, + (r) => { r.answers.intent.probabilities = { question: 1 }; }, + (r) => { r.answers.intent.probabilities = { question: 0.5, edit: 0.4 }; }, + (r) => { r.answers.intent.confidence = 2; }, + (r) => { r.answers.effort.score = 9; }, + (r) => { r.answers.levels.noul = -0.1; }, + ]) { + const upstream = reply(); + mutate(upstream); + assert.throws(() => fromOpenRouterResponse(upstream, body())); + } +}); + +test("fetch posts to the fixed Decisions URL with the current key only", async () => { + let call; + const fetcher = createDecisionFetch({ getKey: () => "sk-or-fixture", fetchImpl: async (url, init) => { call = { url, init }; return Response.json(reply(), { headers: { "x-request-id": "req-test", "set-cookie": "no" } }); } }); + const response = await fetcher("https://openrouter.ai/api/v1/systemone", { method: "POST", headers: { authorization: "Bearer gateway-key", "x-magpie-private": "no" }, body: JSON.stringify(body()) }); + assert.equal(response.status, 200); + assert.equal(call.url, "https://openrouter.ai/api/alpha/decisions"); + assert.equal(call.init.redirect, "error"); + assert.equal(call.init.headers.get("authorization"), "Bearer sk-or-fixture"); + assert.equal(call.init.headers.has("x-magpie-private"), false); + assert.equal(response.headers.has("set-cookie"), false); + assert.equal(response.headers.get("x-request-id"), "req-test"); + assert.equal((await response.json()).answers.intent.choice, "question"); +}); + +test("does not send malformed requests or arbitrary endpoints upstream", async () => { + let sent = 0; + const fetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => { sent++; throw Error("should not send"); } }); + for (const [url, init] of [ + ["https://elsewhere.example/v1/systemone", { method: "POST", body: JSON.stringify(body()) }], + ["https://openrouter.ai/api/v1/chat/completions", { method: "POST", body: JSON.stringify(body()) }], + ["https://openrouter.ai/api/v1/systemone", { method: "GET" }], + ["https://openrouter.ai/api/v1/systemone", { method: "POST", body: "nope" }], + ]) assert.equal((await fetcher(url, init)).status, 400); + assert.equal(sent, 0); +}); + +test("missing credentials become 503 and never reach upstream", async () => { + let sent = 0; + const fetcher = createDecisionFetch({ getKey: async () => undefined, fetchImpl: async () => { sent++; return Response.json({}); } }); + assert.equal((await fetcher("https://openrouter.ai/api/v1/systemone", { method: "POST", body: JSON.stringify(body()) })).status, 503); + assert.equal(sent, 0); +}); + +test("preserves upstream error status, body and retry headers", async () => { + for (const status of [401, 429, 503]) { + const raw = JSON.stringify({ error: { message: "upstream refused" } }); + const fetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => new Response(raw, { status, headers: { "retry-after": "5", "content-type": "application/json" } }) }); + const response = await fetcher("https://openrouter.ai/api/v1/systemone", { method: "POST", body: JSON.stringify(body()) }); + assert.equal(response.status, status); + assert.equal(await response.text(), raw); + assert.equal(response.headers.get("retry-after"), "5"); + } +}); + +test("a transient network failure is retried once, an HTTP error is not", async () => { + let calls = 0; + const retryFetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => { calls++; if (calls === 1) throw new Error("socket hang up"); return Response.json(reply()); } }); + const ok = await retryFetcher("https://openrouter.ai/api/v1/systemone", { method: "POST", body: JSON.stringify(body()) }); + assert.equal(ok.status, 200); + assert.equal(calls, 2); + const noRetryFetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => { calls++; return new Response("{}", { status: 503 }); } }); + const refused = await noRetryFetcher("https://openrouter.ai/api/v1/systemone", { method: "POST", body: JSON.stringify(body()) }); + assert.equal(refused.status, 503); + assert.equal(calls, 3); + const giveUpFetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => { throw new Error("ECONNREFUSED"); } }); + const failed = await giveUpFetcher("https://openrouter.ai/api/v1/systemone", { method: "POST", body: JSON.stringify(body()) }); + assert.equal(failed.status, 502); + assert.match(JSON.stringify(await failed.json()), /ECONNREFUSED/); +}); + +test("an incomplete upstream success becomes 502", async () => { + const fetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => Response.json({ model: UPSTREAM_MODEL, answers: {} }) }); + assert.equal((await fetcher("https://openrouter.ai/api/v1/systemone", { method: "POST", body: JSON.stringify(body()) })).status, 502); +}); + +test("cancellation reaches upstream", async () => { + const controller = new AbortController(); + const fetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async (_url, init) => { assert.equal(init.signal.aborted, false); controller.abort(); init.signal.throwIfAborted(); } }); + await assert.rejects(fetcher("https://openrouter.ai/api/v1/systemone", { method: "POST", signal: controller.signal, body: JSON.stringify(body()) }), { name: "AbortError" }); +}); diff --git a/registry.json b/registry.json index 8237e459e..3e5801c2e 100644 --- a/registry.json +++ b/registry.json @@ -177,6 +177,7 @@ { "package": "@magpie-community/opencode-cloudflare-workers-ai-auth", "name": "Cloudflare Workers AI", "providers": ["cloudflare-workers-ai"], "community": true, "summary": { "en": "Cloudflare Workers AI with your API token (Workers AI:Edit): 28+ models discovered live from models.dev, the 8 paid-only models flagged, and a Neurons/day allowance row in magpie quota.", "zh": "用你的 Cloudflare API Token(Workers AI:Edit 权限)登录 Workers AI:28+ 模型经 models.dev 实时发现,付费专属模型自动标注,magpie quota 显示每日 Neurons 免费额度。" } }, { "package": "@magpie-community/opencode-openai-decisions-auth", "name": "OpenAI Decisions", "providers": ["openai-decisions"], "community": true, "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20rx%3D%2214%22%20fill%3D%22%23111827%22%2F%3E%3Cpath%20d%3D%22M20%2032h12V20h12M32%2032v12h12%22%20fill%3D%22none%22%20stroke%3D%22white%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%2F%3E%3Ccircle%20cx%3D%2220%22%20cy%3D%2232%22%20r%3D%225%22%20fill%3D%22white%22%2F%3E%3Ccircle%20cx%3D%2246%22%20cy%3D%2220%22%20r%3D%225%22%20fill%3D%22white%22%2F%3E%3Ccircle%20cx%3D%2246%22%20cy%3D%2244%22%20r%3D%225%22%20fill%3D%22white%22%2F%3E%3C%2Fsvg%3E", "summary": { "en": "OpenAI's native Decisions API as System One for Magpie classifiers and decision groups: choice, score and boolean probabilities, with standard API-key sign-in and per-question refusal handling.", "zh": "将 OpenAI 原生 Decisions API 转为 System One,供 Magpie 分类器与决策模型组使用,保留选择、评分和布尔概率;使用标准 API key 登录,单题拒绝时保留其余答案。" } }, + { "package": "@magpie-community/opencode-openrouter-decisions-auth", "name": "OpenRouter Decisions", "providers": ["openrouter-decisions"], "community": true, "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Ccircle%20cx%3D%2232%22%20cy%3D%2232%22%20r%3D%2229%22%20fill%3D%22%230f172a%22%2F%3E%3Cpath%20d%3D%22M20%2040a12%2012%200%201%201%2012%2012%22%20fill%3D%22none%22%20stroke%3D%22%2365a3ff%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%2F%3E%3Ccircle%20cx%3D%2244%22%20cy%3D%2228%22%20r%3D%226%22%20fill%3D%22%2365a3ff%22%2F%3E%3C%2Fsvg%3E", "summary": { "en": "OpenRouter's Decisions API as System One for Magpie classifiers and decision groups: Microsoft Decision 1.1 and 1, with choice, score and boolean probabilities, credit usage and per-question refusal handling.", "zh": "将 OpenRouter Decisions API 转为 System One,供 Magpie 分类器与决策模型组使用:Microsoft Decision 1.1 与 1,保留选择、评分和布尔概率、额度用量,单题拒绝时保留其余答案。" } }, { "package": "@magpie-community/opencode-river-auth", "name": "River", "providers": ["river"], "community": true, "summary": { "en": "River (river.ai) pay-as-you-go inference with your API key: per-account models from /v1/models, documented reasoning efforts and live prices from River's public pricing endpoint.", "zh": "用你的 API key 接入 River (river.ai) 按量计费推理:按账号从 /v1/models 列出模型,带官方推理档位与实时价格。" } }, { "package": "@magpie-community/opencode-sap-aicore-auth", "name": "SAP AI Core", "providers": ["sap-aicore"], "community": true,