openai-decisions: OpenAI Decisions as a System One provider (#762)
New package @magpie-community/opencode-openai-decisions-auth (provider
openai-decisions, model gpt-6-luna) by genglintong: answers magpie's
System One (base /systemone through its fetch) with OpenAI's
POST /v1/decisions, converting choice/score/noul to choice/score/predicate
and back with probabilities, confidence and usage. Sign-in is a plain
OpenAI API key from the host's getAuth, read again per request.
The six points of the 11-05 review, checked at 613fc413a:
1. credentials.mjs, the saved-key reader and the keyless method are gone;
no read of providers.json, APPDATA or ~/.config/magpie anywhere.
2. A per-question {"type":"refusal"} is left out of answers; the others
and usage are kept (all refused gives answers {}). magpie's own
Decisions translation reads a missing answer as a refusal too.
3. Omitted, null or blank instructions get a non-empty default.
4. Registry entry on one line; merges cleanly with origin/main 9204c079.
5. Renamed; package.json magpie.icon and registry icon are an SVG data URI.
6. No test writes to disk; comments in English; the only repo link left is
this one (NOTICE, for the opencode2.mjs bridge, byte-identical to
scripts/opencode2.mjs at main).
Run at 613fc413a and at its merge with origin/main 9204c079, off the Mac:
- WSL magpie-desktop, fresh HOME: bun test packages/openai-decisions 23
pass 0 fail; bun scripts/check.mjs 56/56 (merged tree 57/57);
node 22.23.4 --test test/*.test.mjs 23/23 on the merged tree; full
bun test of the merged tree: 8111 pass, 19 skip, 0 fail.
- Windows xiaomi-gpu, fresh HOME and USERPROFILE, Bun 1.4.2: 23 pass 0
fail, check.mjs 56/56.
- Broken by hand, each red then restored: refusal thrown again (3 red),
blank instructions passed through (1 red), key captured at load instead
of per request (1 red), redirect:"error" dropped (1 red), URL check
dropped (1 red).
- Tests reach no network (fetch injected or globalThis.fetch stubbed).
npm pack --dry-run lists the 10 files; every runtime import is in files.
Not tried: a real OpenAI Decisions call (no credentials used), Windows or
Linux in a real magpie.
This commit is contained in:
@@ -1,12 +1,12 @@
|
||||
# magpie-community plugins
|
||||
|
||||
[OpenCode](https://opencode.ai) provider plugins for coding-plan
|
||||
subscriptions, and [gateway middleware](#gateway-middleware),
|
||||
subscriptions and decision APIs, and [gateway middleware](#gateway-middleware),
|
||||
[gateway hooks](#gateway-hooks), [routing strategies](#routing-strategies), [tools for every
|
||||
agent](#tools-for-every-agent), [pages](#pages) and [agents](#agents) for
|
||||
magpie, maintained by the community. To make one, see
|
||||
[Write your own](#write-your-own). Each package signs in to one
|
||||
subscription and makes its requests. The packages work in OpenCode and in
|
||||
[Write your own](#write-your-own). Each provider package signs in to its
|
||||
vendor service and makes its requests. The packages work in OpenCode and in
|
||||
[magpie](https://usemagpie.ai), which runs OpenCode's provider plugins.
|
||||
|
||||
| Package | Signs in to | Provider id |
|
||||
@@ -38,6 +38,7 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
| [minimax](packages/minimax) | MiniMax Code (international): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code-global` |
|
||||
| [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` |
|
||||
| [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` |
|
||||
@@ -52,6 +53,9 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
| [zed](packages/zed) | Zed (Pro, Pro Trial, Student, Business): Anthropic, OpenAI, Google and xAI models hosted by Zed | `zed` |
|
||||
| [zen-free](packages/zen-free) | OpenCode Zen free models with the public credential | `opencode-zen-free` |
|
||||
|
||||
Decision providers are used through magpie's classifiers and `/v1/systemone`;
|
||||
see their package READMEs for client compatibility.
|
||||
|
||||
## Gateway middleware
|
||||
|
||||
These packages aren't OpenCode plugins. magpie runs them in its gateway, on the requests every agent sends and the replies it gets back, whichever provider serves them. Each one is a port of something [New API](https://github.com/QuantumNous/new-api) does for its channels, or something agents commonly need.
|
||||
@@ -361,6 +365,8 @@ Each package is a folder under `packages/<name>/`:
|
||||
- `loader(getAuth, provider)` returns what the AI SDK is given:
|
||||
`baseURL`, `apiKey`, `headers` and a `fetch` that signs each request
|
||||
and refreshes the token (saving it with `client.auth.set`).
|
||||
- Keep Magpie's provider credentials owned by the host: use `getAuth`
|
||||
for the selected account.
|
||||
- A provider that models.dev doesn't list is declared in a `config` hook
|
||||
that sets `config.provider[<id>] = { name, npm, api, models }`. The npm
|
||||
field names the AI SDK package the models speak:
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Add a native Magpie decision provider for OpenAI Decisions.
|
||||
- Convert System One choice, score and noul questions while retaining probabilities, provider confidence and usage.
|
||||
- Use standard API-key sign-in and the host's selected-account auth; remove direct reads of Magpie's credential store.
|
||||
- Omit per-question refusals while preserving other answers, and supply non-empty default instructions.
|
||||
- Preserve upstream errors and cancellation; reject unsupported or invalid ordinary request/answer shapes.
|
||||
- Use the community provider package name, inline SVG icon and canonical OpenCode compatibility bridge.
|
||||
- Document installation, credential ownership, classifier setup, quota handling and verification limits.
|
||||
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 lintonggeng
|
||||
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.
|
||||
@@ -0,0 +1,8 @@
|
||||
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 the public provider/auth/decision contracts.
|
||||
No third-party provider application logic is bundled here.
|
||||
@@ -0,0 +1,206 @@
|
||||
# OpenAI Decisions for Magpie
|
||||
|
||||
A provider exposing OpenAI's native **Decisions API** through Magpie's
|
||||
**System One** interface. Use it as a chat routing group's classifier or
|
||||
as a member of a decision-model group with other System One providers.
|
||||
|
||||
**Provider id:** `openai-decisions`. **Model:** `openai-decisions/gpt-6-luna`.
|
||||
|
||||
Magpie already speaks System One for compatible decision providers. OpenAI
|
||||
uses a different path and question/answer schema, which this plugin converts.
|
||||
The built-in OpenAI provider serves Chat/Responses; this provider calls
|
||||
`POST https://api.openai.com/v1/decisions` and returns native probabilities.
|
||||
|
||||
## Install and sign in
|
||||
|
||||
Install a released community package through Magpie:
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/opencode-openai-decisions-auth
|
||||
magpie plugin login openai-decisions
|
||||
```
|
||||
|
||||
For an unpublished package or a source checkout, run from the root of
|
||||
`magpie-community/plugins` instead:
|
||||
|
||||
```sh
|
||||
magpie plugin add ./packages/openai-decisions
|
||||
magpie plugin login openai-decisions
|
||||
```
|
||||
|
||||
In Magpie's Plugins page, install **OpenAI Decisions**, then sign in with
|
||||
an OpenAI API key that can access Decisions. The community's distribution
|
||||
branch can supply a released package before its first npm publication.
|
||||
|
||||
### Credentials and compatibility
|
||||
|
||||
The plugin receives the selected account's API key from the host's
|
||||
`getAuth` callback. Magpie keeps the sign-in in its `plugin-auth.json`
|
||||
(Unix permissions 0600); OpenCode keeps it in its own `auth.json`.
|
||||
Requests use the selected key's OpenAI API allowance. Account/key changes
|
||||
and sign-out are read again for each request.
|
||||
|
||||
The loader layout supports Magpie/OpenCode 1.x and the community's OpenCode
|
||||
2.x compatibility bridge. This is a decision provider; ordinary chat clients
|
||||
need an explicit decision call to consume its output. Live OpenCode decision
|
||||
workflows and Windows/Linux execution have not been verified. Earlier
|
||||
gateway checks used Magpie 0.1.3039; a minimum compatible release has not
|
||||
been established.
|
||||
|
||||
## Use System One
|
||||
|
||||
Send this request to `http://127.0.0.1:3425/v1/systemone`:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "openai-decisions/gpt-6-luna",
|
||||
"state": {"message": "What does HTTP 404 mean?"},
|
||||
"questions": {
|
||||
"intent": {
|
||||
"type": "choice",
|
||||
"instructions": "Which kind of request is this?",
|
||||
"criteria": {"question": "Asks for an explanation", "code_change": "Asks to modify code"}
|
||||
},
|
||||
"is_question": {"type": "noul", "instructions": "Does this ask a question?"},
|
||||
"effort": {
|
||||
"type": "score",
|
||||
"instructions": "How much work does this request require?",
|
||||
"criteria": ["Little work", "Some work", "Much work", "Most work"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Decision groups and automatic effort
|
||||
|
||||
With an existing TypeSafe provider, create a group containing only decision
|
||||
models. Choose a new name: `magpie group add` replaces a group of the same name.
|
||||
|
||||
```sh
|
||||
magpie group add Decisions models=typesafe/jev-latest,openai-decisions/gpt-6-luna routing=order
|
||||
```
|
||||
|
||||
Use `"model":"group/decisions"` to let Magpie's order and failover pick the
|
||||
provider. For an existing chat group whose ID is `coding`, enable automatic
|
||||
effort with:
|
||||
|
||||
```sh
|
||||
magpie group set coding classifier=openai-decisions/gpt-6-luna effort=auto
|
||||
```
|
||||
|
||||
Replace `coding` with your group's ID. Use `classifier=group/decisions`
|
||||
to select the decision group instead. Chat models belong in the chat group's
|
||||
`models`; decision models belong in `classifier` or a decision-only group.
|
||||
Magpie keeps decision models out of ordinary chat catalogs.
|
||||
|
||||
## Protocol and limits
|
||||
|
||||
| System One | OpenAI Decisions | Returned answer |
|
||||
| --- | --- | --- |
|
||||
| Text `state` | Text `input` | Shared evidence |
|
||||
| Object/array `state` | User message containing `input_json` | Shared evidence |
|
||||
| Numeric/boolean `state` | JSON text `input` | Shared evidence |
|
||||
| `choice` with a criteria map | `choice` with options | Selected value, probability map, confidence |
|
||||
| `score` with ordered criteria | `score` with levels | Expected zero-based score, legend, probabilities, confidence |
|
||||
| `noul` with optional true/false criteria | `predicate` | Probability in `noul` |
|
||||
|
||||
Structured instructions and descriptions become compact JSON. Predicate
|
||||
definitions and score ordering are retained. If instructions are omitted,
|
||||
null or blank, the adapter supplies:
|
||||
`Answer this question using the supplied input and criteria.`
|
||||
Explicit non-empty instructions are preserved.
|
||||
|
||||
An upstream question with `type: "refusal"` is omitted from `answers`;
|
||||
other questions retain their answers, probabilities and usage. If every
|
||||
question is refused, `answers` is empty. A refusal does not invent a choice
|
||||
or probability. Missing, duplicate, unrequested or invalid ordinary answers
|
||||
remain errors and produce HTTP 502.
|
||||
|
||||
This version accepts text and ordinary JSON, with 1–400 questions, 2–255
|
||||
choice options and 2–10 ordered score levels. Unsupported fields, images
|
||||
and `box` are outside its declared capabilities; compressed requests are
|
||||
not implemented. OpenAI's confidence is retained. Magpie derives its own
|
||||
routing confidence; values from different vendors need separate calibration.
|
||||
|
||||
Upstream error status/body, retry/rate-limit headers and request IDs are
|
||||
preserved. Cancellation propagates upstream. Requests use the fixed OpenAI
|
||||
endpoint, a fresh header set and no redirects.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Result | Check |
|
||||
| --- | --- |
|
||||
| 400 | Use the documented model, question fields and limits. |
|
||||
| Upstream 401/403 | Check the selected key and its Decisions access. |
|
||||
| Upstream 429 | Check quota units and actual token usage, honor `Retry-After` when present and space checks accordingly. |
|
||||
| 503: credentials unavailable | Sign in to OpenAI Decisions with an API key again. |
|
||||
| 502 | Inspect Magpie's request record: the upstream was unreachable or returned an invalid/incomplete ordinary answer. |
|
||||
|
||||
The adapter does not retry. Magpie owns routing and failover. A quota refusal
|
||||
does not establish that a model is unsupported; start with one short question
|
||||
when testing a constrained allowance.
|
||||
|
||||
## Develop and contribute
|
||||
|
||||
From the community repository root:
|
||||
|
||||
```sh
|
||||
bun scripts/check.mjs openai-decisions
|
||||
bun test packages/openai-decisions
|
||||
```
|
||||
|
||||
For Node's test runner, run `npm test` from `packages/openai-decisions`.
|
||||
To install and list the provider without signing in or using a real account:
|
||||
|
||||
```sh
|
||||
MAGPIE=/absolute/path/to/magpie scripts/try.sh openai-decisions
|
||||
```
|
||||
|
||||
The harness isolates configuration under `.sandbox/openai-decisions`.
|
||||
Automated tests use in-memory synthetic credentials and injected fetches;
|
||||
they make no vendor calls or credential fixtures on disk.
|
||||
|
||||
[index.mjs](index.mjs) registers the provider and selected-account auth.
|
||||
[adapter.mjs](adapter.mjs) converts requests/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 evidence and untested scope.
|
||||
|
||||
Review checks:
|
||||
|
||||
- Receive credentials only through the host's selected-account auth.
|
||||
- Preserve predicate definitions, score ordering and vendor probabilities.
|
||||
- Keep per-question refusals separate from invalid or missing answers.
|
||||
- Supply non-empty instructions when System One omits or blanks 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: [OpenAI Decisions](https://developers.openai.com/api/docs/guides/decisions),
|
||||
[Magpie provider contract](https://github.com/yetone/magpie/blob/v0.1.3039/docs/subsystems/provider-plugins.md).
|
||||
|
||||
MIT. Not affiliated with OpenAI.
|
||||
|
||||
## 中文
|
||||
|
||||
安装社区发行包并使用 OpenAI API key 登录:
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/opencode-openai-decisions-auth
|
||||
magpie plugin login openai-decisions
|
||||
```
|
||||
|
||||
未发布时,在社区仓库根目录使用
|
||||
`magpie plugin add ./packages/openai-decisions`,再执行同一登录命令。
|
||||
提供方 ID 保持 `openai-decisions`,模型为 `openai-decisions/gpt-6-luna`。
|
||||
|
||||
统一入口为 Magpie `/v1/systemone`。支持选择、评分和是非概率;已有聊天组可设置
|
||||
`classifier=openai-decisions/gpt-6-luna effort=auto`,也可使用决策模型组
|
||||
`group/decisions`。凭据由宿主提供当前选中账号的 API key,登录记录保存在宿主的
|
||||
`plugin-auth.json` 或 `auth.json`,请求使用该 key 所属账号的 API 额度。
|
||||
|
||||
单题被拒绝时只省略该题,其余答案继续返回;全部拒绝时答案为空。缺省或空白指令会
|
||||
补上非空默认描述,结构化指令和判断条件仍保留。遇到 429 按额度单位、实际 token
|
||||
用量与 `Retry-After` 放慢调用。真实 OpenCode 决策流程及 Windows/Linux 尚未验证;
|
||||
完整范围见 [VERIFICATION.md](VERIFICATION.md)。
|
||||
@@ -0,0 +1,71 @@
|
||||
# Verification
|
||||
|
||||
## Maintainer-requested revision — 2026-11-11
|
||||
|
||||
The revision addresses the six requests in
|
||||
[the maintainer's review](https://github.com/magpie-community/plugins/pull/762#issuecomment-6662604576).
|
||||
|
||||
- Authentication uses only the host's selected-account `getAuth` callback.
|
||||
The saved-key reader, keyless method and disk credential fixtures are removed.
|
||||
- Per-question refusals are omitted, while ordinary answers and usage are retained.
|
||||
Duplicate, missing and unrequested answers still fail validation.
|
||||
- Omitted, null and blank System One instructions receive a non-empty default.
|
||||
- The package is `@magpie-community/opencode-openai-decisions-auth`, with an
|
||||
inline SVG data icon, a single-line registry entry and English code comments.
|
||||
- README, registry summaries, changelog and notice reflect the API-key-only
|
||||
behavior. Third-party provider repository references are removed.
|
||||
|
||||
### Regression evidence
|
||||
|
||||
The revised tests first ran against the previous implementation:
|
||||
**16 passed, 7 failed**. Failures included blank upstream instructions,
|
||||
per-question refusals turning a successful response into HTTP 502, the extra
|
||||
keyless sign-in, and the old package metadata. They then passed after the fix:
|
||||
**23 passed, 0 failed** on Node and Bun.
|
||||
|
||||
The package tests are offline. Credentials and responses are synthetic and
|
||||
in-memory; no test creates a credential file or a `.data/` directory.
|
||||
They cover all three question types, partial/all refusals, missing or invalid
|
||||
ordinary answers, structured evidence, defaults, account changes, sign-out,
|
||||
errors, cancellation and loader compatibility.
|
||||
|
||||
### Current-main integration
|
||||
|
||||
The full suite at `cdbfa0b` rebased onto `f8a52a2` completed with
|
||||
**8,073 passed, 9 skipped, 0 failed** on Bun 1.4.4. The test HOME was an
|
||||
isolated directory under macOS's native temporary root, outside the Git
|
||||
checkout. Skipped optional/live/platform checks remain unverified.
|
||||
|
||||
The whole-community loader checker passed all **56** checks. Magpie's sandbox
|
||||
harness listed this provider with one model and no sign-in or vendor request.
|
||||
The package contains ten files and excludes the removed credential reader;
|
||||
credential/private-data scans, local Markdown links and the JSON request
|
||||
example passed.
|
||||
|
||||
The final metadata/documentation follow-up embeds an SVG data icon and places
|
||||
the registry entry beside the API-key providers. Focused tests and the loader
|
||||
checker are rerun after those changes; runtime modules remain identical to the
|
||||
full-suite run. Live OpenCode decision workflows and Windows/Linux execution
|
||||
have not been verified.
|
||||
|
||||
## Earlier local gateway checks — 2026-11-05
|
||||
|
||||
The earlier revision used Magpie 0.1.3039, Node 26.3.0 and Bun 1.4.4.
|
||||
|
||||
| Request model | Result | Actual model |
|
||||
| --- | --- | --- |
|
||||
| `typesafe/jev-latest` | HTTP 200; choice/noul/score answers present | `jev-1.14.0` |
|
||||
| `openai-decisions/gpt-6-luna` | HTTP 200; choice/noul/score answers present | `gpt-6-luna` |
|
||||
| `group/decisions` | HTTP 200; all three answers present | `jev-1.14.0`, first in group order |
|
||||
|
||||
A temporary chat group used `classifier=openai-decisions/gpt-6-luna` and
|
||||
`effort=auto`. Magpie recorded a real `kind=routing`, HTTP 200 classifier
|
||||
call before its downstream `openai/gpt-5.6-luna` chat returned `OK`.
|
||||
The temporary group was removed.
|
||||
|
||||
Those calls predate removal of the saved-key method and are historical protocol
|
||||
and gateway evidence. They do not establish a live standard-key sign-in check
|
||||
for the current revision. Live upstream quota failures and safety refusals were
|
||||
not forced; their status and per-question handling are verified with fixtures.
|
||||
Images and box decisions are outside the adapter's declared capabilities.
|
||||
Confidence values retain their vendor's original calibration.
|
||||
@@ -0,0 +1,183 @@
|
||||
export const MODEL = "gpt-6-luna";
|
||||
const SYSTEM_ONE_URL = "https://api.openai.com/v1/systemone";
|
||||
const DECISIONS_URL = "https://api.openai.com/v1/decisions";
|
||||
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);
|
||||
const instructions = supplied.trim() ? supplied : "Answer this question using the supplied input and criteria.";
|
||||
if (question.type === "noul" && record(question.criteria)) {
|
||||
return JSON.stringify({ instructions, criteria: question.criteria });
|
||||
}
|
||||
return instructions;
|
||||
}
|
||||
|
||||
function choiceEntries(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(new Set(question.choices).size === question.choices.length, "choices must be unique");
|
||||
return question.choices.map((value) => [value, null]);
|
||||
}
|
||||
requireValue(record(question.criteria), "choice requires a criteria object");
|
||||
return Object.entries(question.criteria);
|
||||
}
|
||||
|
||||
export function toOpenAIRequest(body) {
|
||||
fields(body, ["model", "state", "questions"], "request");
|
||||
requireValue(body.model === MODEL, `Only ${MODEL} is 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 = entries.map(([name, question]) => {
|
||||
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 = { name, type: question.type, instructions: questionInstructions(question) };
|
||||
switch (question.type) {
|
||||
case "choice": {
|
||||
const criteria = choiceEntries(question);
|
||||
requireValue(criteria.length >= 2 && criteria.length <= 255, "choice requires 2–255 options");
|
||||
requireValue(criteria.every(([key]) => key.length > 0), "Choice names must not be empty");
|
||||
return { ...common, choices: criteria.map(([value, text]) => ({ value, ...(text != null ? { description: description(text) } : {}) })) };
|
||||
}
|
||||
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");
|
||||
return { ...common, levels: question.criteria.map((value, index) => ({ label: String(index), ...(value != null ? { description: description(value) } : {}) })) };
|
||||
case "noul":
|
||||
requireValue(question.choices === undefined, "noul does not accept choices");
|
||||
requireValue(question.criteria == null || record(question.criteria) && Object.keys(question.criteria).every((key) => key === "true" || key === "false"), "noul criteria accept true and false only");
|
||||
return { ...common, type: "predicate" };
|
||||
default:
|
||||
throw new Error("Unsupported question type; use choice, score or noul");
|
||||
}
|
||||
});
|
||||
const input = typeof body.state === "string"
|
||||
? body.state
|
||||
: typeof body.state === "object"
|
||||
? [{ role: "user", content: [{ type: "input_json", data: body.state }] }]
|
||||
: JSON.stringify(body.state);
|
||||
return { model: MODEL, input, questions };
|
||||
}
|
||||
|
||||
function probability(value) {
|
||||
requireValue(typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1, "Invalid upstream probability or confidence");
|
||||
return value;
|
||||
}
|
||||
|
||||
function distribution(values, expected, score) {
|
||||
requireValue(Array.isArray(values) && values.length === expected.length, "Incomplete upstream probability distribution");
|
||||
const seen = new Set();
|
||||
const result = values.map((item) => {
|
||||
requireValue(record(item), "Invalid upstream probability entry");
|
||||
requireValue(score ? Number.isInteger(item.value) : typeof item.value === "string", "Invalid upstream probability value");
|
||||
const key = String(item.value);
|
||||
requireValue(expected.includes(key) && !seen.has(key), "Unexpected or duplicate upstream probability value");
|
||||
seen.add(key);
|
||||
return [key, probability(item.probability)];
|
||||
});
|
||||
requireValue(Math.abs(result.reduce((sum, [, value]) => sum + value, 0) - 1) <= 0.02, "Upstream probabilities do not sum to one");
|
||||
return Object.fromEntries(result);
|
||||
}
|
||||
|
||||
export function fromOpenAIResponse(upstream, source) {
|
||||
const request = toOpenAIRequest(source);
|
||||
requireValue(record(upstream) && typeof upstream.model === "string", "Invalid upstream decision response");
|
||||
requireValue(Array.isArray(upstream.answers) && upstream.answers.length === request.questions.length, "Incomplete upstream answers");
|
||||
const byName = new Map(request.questions.map((question) => [question.name, question]));
|
||||
const answers = new Map();
|
||||
const seen = new Set();
|
||||
for (const answer of upstream.answers) {
|
||||
requireValue(record(answer) && byName.has(answer.name) && !seen.has(answer.name), "Unexpected or duplicate upstream answer");
|
||||
seen.add(answer.name);
|
||||
if (answer.type === "refusal") continue;
|
||||
const question = byName.get(answer.name);
|
||||
requireValue(answer.type === question.type, "Wrong upstream answer type");
|
||||
let result;
|
||||
if (answer.type === "predicate") {
|
||||
result = { type: "noul", noul: probability(answer.probability) };
|
||||
} else if (answer.type === "choice") {
|
||||
const keys = question.choices.map((choice) => choice.value);
|
||||
requireValue(keys.includes(answer.choice), "Upstream chose an unknown option");
|
||||
result = { type: "choice", choice: answer.choice, probabilities: distribution(answer.probabilities, keys, false), confidence: probability(answer.confidence) };
|
||||
} else {
|
||||
requireValue(typeof answer.score === "number" && Number.isFinite(answer.score) && answer.score >= 0 && answer.score <= question.levels.length - 1, "Invalid upstream score");
|
||||
result = {
|
||||
type: "score", score: answer.score,
|
||||
legend: Object.fromEntries(question.levels.map((level, index) => [String(index), level.description ?? level.label])),
|
||||
probabilities: distribution(answer.probabilities, question.levels.map((_, index) => String(index)), true),
|
||||
confidence: probability(answer.confidence),
|
||||
};
|
||||
}
|
||||
answers.set(answer.name, result);
|
||||
}
|
||||
// Keep request order, omitting refused questions without manufacturing answers.
|
||||
return { ...upstream, answers: Object.fromEntries(request.questions.filter(({ name }) => answers.has(name)).map(({ name }) => [name, answers.get(name)])) };
|
||||
}
|
||||
|
||||
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 = toOpenAIRequest(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 OpenAI API key");
|
||||
} catch {
|
||||
return refused(503, "OpenAI credentials unavailable; check this provider's API-key sign-in");
|
||||
}
|
||||
const headers = new Headers({ "content-type": "application/json", accept: "application/json", authorization: `Bearer ${key}` });
|
||||
let upstream;
|
||||
try {
|
||||
upstream = await fetchImpl(DECISIONS_URL, { method: "POST", headers, body: JSON.stringify(payload), signal: request.signal, redirect: "error" });
|
||||
} catch (error) {
|
||||
if (request.signal.aborted) throw error;
|
||||
return refused(502, "Could not reach OpenAI Decisions");
|
||||
}
|
||||
const keptHeaders = responseHeaders(upstream);
|
||||
if (!upstream.ok) return new Response(upstream.body, { status: upstream.status, headers: keptHeaders });
|
||||
try {
|
||||
const result = fromOpenAIResponse(await upstream.json(), source);
|
||||
return Response.json(result, { status: upstream.status, headers: keptHeaders });
|
||||
} catch (error) {
|
||||
if (request.signal.aborted) throw error;
|
||||
return refused(502, "OpenAI returned an invalid or incomplete decision answer", keptHeaders);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { createDecisionFetch, MODEL } from "./adapter.mjs";
|
||||
|
||||
const ID = "openai-decisions";
|
||||
const BASE = "https://api.openai.com/v1";
|
||||
const model = {
|
||||
id: MODEL,
|
||||
name: "GPT-6 Luna · Decisions",
|
||||
decides: true,
|
||||
tool_call: false,
|
||||
reasoning: false,
|
||||
limit: { context: 0, output: 0 },
|
||||
modalities: { input: ["text"], output: ["text"] },
|
||||
cost: { input: 0.1, output: 0 },
|
||||
};
|
||||
|
||||
// Export only the plugin function; Magpie invokes each exported function as a plugin.
|
||||
export const OpenAIDecisionsPlugin = async () => ({
|
||||
async config(config) {
|
||||
config.provider ??= {};
|
||||
config.provider[ID] ??= { name: "OpenAI Decisions", npm: "@ai-sdk/openai-compatible", api: BASE, decide: true, models: { [MODEL]: model } };
|
||||
},
|
||||
auth: {
|
||||
provider: ID,
|
||||
methods: [
|
||||
{ type: "api", label: "OpenAI API key", placeholder: "sk-…" },
|
||||
],
|
||||
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;
|
||||
} }),
|
||||
};
|
||||
},
|
||||
},
|
||||
provider: {
|
||||
id: ID,
|
||||
async models() {
|
||||
return { [MODEL]: model };
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
export { OpenAIDecisionsPlugin } from "./index.mjs";
|
||||
@@ -0,0 +1,596 @@
|
||||
// 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/<name>/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 {}
|
||||
})()
|
||||
void refresh()
|
||||
}
|
||||
|
||||
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) }
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-openai-decisions-auth",
|
||||
"version": "0.1.0",
|
||||
"description": "Expose OpenAI Decisions through Magpie's native 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": "OpenAI 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%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"},
|
||||
"engines": {"node": ">=20"},
|
||||
"license": "MIT",
|
||||
"keywords": ["opencode", "opencode-plugin", "magpie", "magpie-plugin", "openai", "decisions", "system-one"],
|
||||
"repository": {"type": "git", "url": "https://github.com/magpie-community/plugins.git", "directory": "packages/openai-decisions"}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createDecisionFetch, fromOpenAIResponse, toOpenAIRequest } from "../adapter.mjs";
|
||||
|
||||
const body = () => ({
|
||||
model: "gpt-6-luna",
|
||||
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: "decision-test", model: "gpt-6-luna", usage: { input_tokens: 42, output_tokens: 0 },
|
||||
answers: [
|
||||
{ name: "levels", type: "predicate", probability: 0.9 },
|
||||
{ name: "intent", type: "choice", choice: "question", confidence: 0.8, probabilities: [{ value: "question", probability: 0.9 }, { value: "edit", probability: 0.1 }] },
|
||||
{ name: "effort", type: "score", score: 0.6, confidence: 0.3, probabilities: [0.6, 0.2, 0.2, 0].map((probability, value) => ({ value, label: String(value), probability })) },
|
||||
],
|
||||
});
|
||||
|
||||
test("converts JSON evidence and all three native classifier questions", () => {
|
||||
const source = body();
|
||||
const out = toOpenAIRequest(source);
|
||||
assert.equal(out.model, "gpt-6-luna");
|
||||
assert.deepEqual(out.input, [{ role: "user", content: [{ type: "input_json", data: source.state }] }]);
|
||||
assert.deepEqual(out.questions[0], { name: "intent", type: "choice", instructions: "Which task?", choices: [{ value: "question", description: "Explain a fact" }, { value: "edit" }] });
|
||||
assert.deepEqual(out.questions[1].levels, source.questions.effort.criteria.map((description, index) => ({ label: String(index), description })));
|
||||
assert.deepEqual(out.questions[2], { name: "levels", type: "predicate", instructions: source.questions.levels.instructions });
|
||||
assert.equal(source.questions.levels.type, "noul");
|
||||
});
|
||||
|
||||
test("accepts text evidence and Magpie's documented choices shorthand", () => {
|
||||
const source = { model: "gpt-6-luna", state: "hello", questions: { intent: { type: "choice", instructions: "Kind?", choices: ["question", "edit"] } } };
|
||||
assert.equal(toOpenAIRequest(source).input, "hello");
|
||||
assert.deepEqual(toOpenAIRequest(source).questions[0].choices, [{ value: "question" }, { value: "edit" }]);
|
||||
});
|
||||
|
||||
test("numeric and boolean System One state use text instead of an invalid input_json scalar", () => {
|
||||
for (const state of [42, true, false]) {
|
||||
assert.equal(toOpenAIRequest({ ...body(), state }).input, JSON.stringify(state));
|
||||
}
|
||||
});
|
||||
|
||||
test("retains structured instructions and criteria, including predicate definitions", () => {
|
||||
const source = { model: "gpt-6-luna", state: [1, 2], questions: {
|
||||
kind: { type: "choice", instructions: { question: "Which?", record: { id: 1 } }, criteria: { first: { examples: [1] }, other: null } },
|
||||
yes: { type: "noul", instructions: "Does this match?", criteria: { true: { rule: "positive" }, false: "negative" } },
|
||||
rating: { type: "score", criteria: [1, { label: "higher" }, null] },
|
||||
} };
|
||||
const out = toOpenAIRequest(source);
|
||||
assert.deepEqual(JSON.parse(out.questions[0].instructions), source.questions.kind.instructions);
|
||||
assert.deepEqual(JSON.parse(out.questions[0].choices[0].description), { examples: [1] });
|
||||
assert.deepEqual(JSON.parse(out.questions[1].instructions), { instructions: "Does this match?", criteria: source.questions.yes.criteria });
|
||||
assert.deepEqual(out.questions[2].levels, [{ label: "0", description: "1" }, { label: "1", description: '{"label":"higher"}' }, { label: "2" }]);
|
||||
});
|
||||
|
||||
test("supplies non-empty instructions for omitted, null and blank System One instructions", () => {
|
||||
for (const instructions of [undefined, null, "", " \n\t"]) {
|
||||
const source = body();
|
||||
for (const question of Object.values(source.questions)) question.instructions = instructions;
|
||||
for (const question of toOpenAIRequest(source).questions) {
|
||||
assert.equal(typeof question.instructions, "string");
|
||||
assert.ok(question.instructions.trim().length > 0);
|
||||
}
|
||||
assert.equal(source.questions.intent.instructions, instructions);
|
||||
source.questions.levels.criteria = { true: "Matches", false: "Does not match" };
|
||||
const predicate = toOpenAIRequest(source).questions[2];
|
||||
const combined = JSON.parse(predicate.instructions);
|
||||
assert.ok(combined.instructions.trim().length > 0);
|
||||
assert.deepEqual(combined.criteria, source.questions.levels.criteria);
|
||||
}
|
||||
});
|
||||
|
||||
test("restores named answers independent of order and preserves probabilities, confidence and usage", () => {
|
||||
const out = fromOpenAIResponse(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.intent.confidence, 0.8);
|
||||
assert.equal(out.answers.effort.score, 0.6);
|
||||
assert.deepEqual(out.answers.effort.probabilities, { 0: 0.6, 1: 0.2, 2: 0.2, 3: 0 });
|
||||
assert.deepEqual(out.answers.levels, { type: "noul", noul: 0.9 });
|
||||
assert.deepEqual(out.usage, { input_tokens: 42, output_tokens: 0 });
|
||||
assert.equal(out.id, "decision-test");
|
||||
});
|
||||
|
||||
test("omits a per-question refusal while preserving the other answers and usage", () => {
|
||||
for (const name of ["intent", "effort", "levels"]) {
|
||||
const upstream = reply();
|
||||
upstream.answers = upstream.answers.map((answer) => answer.name === name ? { name, type: "refusal" } : answer);
|
||||
const out = fromOpenAIResponse(upstream, body());
|
||||
assert.deepEqual(Object.keys(out.answers), Object.keys(body().questions).filter((key) => key !== name));
|
||||
assert.equal(Object.hasOwn(out.answers, name), false);
|
||||
assert.deepEqual(out.usage, upstream.usage);
|
||||
for (const [key, answer] of Object.entries(fromOpenAIResponse(reply(), body()).answers)) {
|
||||
if (key !== name) assert.deepEqual(out.answers[key], answer);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("an all-refusal response keeps empty answers instead of inventing probabilities", () => {
|
||||
const upstream = reply();
|
||||
upstream.answers = upstream.answers.map(({ name }) => ({ name, type: "refusal" }));
|
||||
const out = fromOpenAIResponse(upstream, body());
|
||||
assert.deepEqual(out.answers, {});
|
||||
assert.deepEqual(out.usage, upstream.usage);
|
||||
});
|
||||
|
||||
test("refusals still reject duplicate, unknown and missing question answers", () => {
|
||||
for (const answers of [
|
||||
[{ name: "intent", type: "refusal" }, { name: "intent", type: "refusal" }, reply().answers[2]],
|
||||
[{ name: "unknown", type: "refusal" }, reply().answers[1], reply().answers[2]],
|
||||
[{ name: "intent", type: "refusal" }],
|
||||
]) assert.throws(() => fromOpenAIResponse({ ...reply(), answers }, body()));
|
||||
});
|
||||
|
||||
test("does not treat prototype-named choices or question IDs as object properties", () => {
|
||||
const source = JSON.parse('{"model":"gpt-6-luna","state":"hello","questions":{"__proto__":{"type":"choice","instructions":"Kind?","criteria":{"__proto__":null,"constructor":null}}}}');
|
||||
const out = fromOpenAIResponse({ model: "gpt-6-luna", answers: [{ name: "__proto__", type: "choice", choice: "__proto__", confidence: 1, probabilities: [{ value: "__proto__", probability: 1 }, { value: "constructor", probability: 0 }] }] }, source);
|
||||
assert.equal(Object.hasOwn(out.answers, "__proto__"), true);
|
||||
assert.equal(Object.hasOwn(out.answers.__proto__.probabilities, "__proto__"), true);
|
||||
});
|
||||
|
||||
test("rejects unsupported fields and question types before requesting the upstream", () => {
|
||||
for (const source of [
|
||||
{ ...body(), stream: true },
|
||||
{ ...body(), model: "another-model" },
|
||||
{ ...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: ["question", "edit"] } } },
|
||||
{ ...body(), questions: { x: { ...body().questions.intent, temperature: 0 } } },
|
||||
{ ...body(), questions: { x: { type: "noul", criteria: { other: "not a boolean definition" } } } },
|
||||
]) assert.throws(() => toOpenAIRequest(source));
|
||||
});
|
||||
|
||||
test("rejects missing, duplicate, wrong-type and unrequested answers", () => {
|
||||
for (const mutate of [
|
||||
(r) => r.answers.pop(),
|
||||
(r) => r.answers.push(r.answers[0]),
|
||||
(r) => { r.answers[0].name = "unexpected"; },
|
||||
(r) => { r.answers[0].type = "choice"; },
|
||||
]) {
|
||||
const upstream = reply();
|
||||
mutate(upstream);
|
||||
assert.throws(() => fromOpenAIResponse(upstream, body()));
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects invalid or incomplete probability distributions and invalid scores", () => {
|
||||
for (const mutate of [
|
||||
(r) => { r.answers[1].probabilities[0].probability = NaN; },
|
||||
(r) => { r.answers[1].probabilities[0].probability = 1.1; },
|
||||
(r) => r.answers[1].probabilities.pop(),
|
||||
(r) => { r.answers[1].probabilities[1].value = "question"; },
|
||||
(r) => { r.answers[1].probabilities[0].probability = 0.1; },
|
||||
(r) => { r.answers[1].choice = "unknown"; },
|
||||
(r) => { r.answers[1].confidence = -1; },
|
||||
(r) => { r.answers[2].score = 4; },
|
||||
(r) => { r.answers[0].probability = -0.1; },
|
||||
]) {
|
||||
const upstream = reply();
|
||||
mutate(upstream);
|
||||
assert.throws(() => fromOpenAIResponse(upstream, body()));
|
||||
}
|
||||
});
|
||||
|
||||
test("fetch uses the fixed Decisions URL, current key and a fresh header set", async () => {
|
||||
let call;
|
||||
const fetcher = createDecisionFetch({ getKey: () => "fixture-upstream-key", fetchImpl: async (url, init) => { call = { url, init }; return Response.json(reply(), { headers: { "x-request-id": "req-test", "set-cookie": "not-forwarded" } }); } });
|
||||
const response = await fetcher("https://api.openai.com/v1/systemone", { method: "POST", headers: { authorization: "Bearer local-gateway-key", "x-magpie-private": "not-forwarded" }, body: JSON.stringify(body()) });
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(call.url, "https://api.openai.com/v1/decisions");
|
||||
assert.equal(call.init.redirect, "error");
|
||||
assert.equal(call.init.headers.get("authorization"), "Bearer fixture-upstream-key");
|
||||
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://api.openai.com/v1/chat/completions", { method: "POST", body: JSON.stringify(body()) }],
|
||||
["https://api.openai.com/v1/systemone?upstream=elsewhere", { method: "POST", body: JSON.stringify(body()) }],
|
||||
["https://api.openai.com/v1/systemone", { method: "GET" }],
|
||||
["https://api.openai.com/v1/systemone", { method: "POST", body: "invalid-json" }],
|
||||
]) assert.equal((await fetcher(url, init)).status, 400);
|
||||
assert.equal(sent, 0);
|
||||
});
|
||||
|
||||
test("preserves upstream 401/429/503 status, error body and retry headers", async () => {
|
||||
for (const status of [401, 429, 503]) {
|
||||
const raw = JSON.stringify({ error: { message: "Upstream refused this request" } });
|
||||
const fetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => new Response(raw, { status, headers: { "retry-after": "5", "content-type": "application/json" } }) });
|
||||
const response = await fetcher("https://api.openai.com/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("an incomplete successful upstream response becomes 502", async () => {
|
||||
const fetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => Response.json({ model: "gpt-6-luna", answers: [] }) });
|
||||
assert.equal((await fetcher("https://api.openai.com/v1/systemone", { method: "POST", body: JSON.stringify(body()) })).status, 502);
|
||||
});
|
||||
|
||||
test("a successful response with a per-question refusal remains HTTP 200", async () => {
|
||||
const upstream = reply();
|
||||
upstream.answers[0] = { name: "levels", type: "refusal" };
|
||||
const fetcher = createDecisionFetch({ getKey: () => "fixture", fetchImpl: async () => Response.json(upstream) });
|
||||
const response = await fetcher("https://api.openai.com/v1/systemone", { method: "POST", body: JSON.stringify(body()) });
|
||||
assert.equal(response.status, 200);
|
||||
const out = await response.json();
|
||||
assert.deepEqual(Object.keys(out.answers), ["intent", "effort"]);
|
||||
assert.equal(out.answers.intent.choice, "question");
|
||||
});
|
||||
|
||||
test("cancellation reaches the upstream without retries or a manufactured answer", 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://api.openai.com/v1/systemone", { method: "POST", signal: controller.signal, body: JSON.stringify(body()) }), { name: "AbortError" });
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import { OpenAIDecisionsPlugin } from "../index.mjs";
|
||||
|
||||
test("registers one decision model with standard API-key sign-in only", async () => {
|
||||
const plugin = await OpenAIDecisionsPlugin({});
|
||||
const config = {};
|
||||
await plugin.config(config);
|
||||
const provider = config.provider["openai-decisions"];
|
||||
assert.equal(provider.decide, true);
|
||||
assert.equal(provider.models["gpt-6-luna"].decides, true);
|
||||
assert.equal(provider.models["gpt-6-luna"].tool_call, false);
|
||||
assert.equal(plugin.auth.provider, "openai-decisions");
|
||||
assert.equal(plugin.auth.methods.length, 1);
|
||||
assert.equal(plugin.auth.methods[0].type, "api");
|
||||
assert.notEqual(plugin.auth.methods[0].keyless, true);
|
||||
assert.equal(plugin.auth.methods[0].authorize, undefined);
|
||||
});
|
||||
|
||||
test("the loader leaves missing or non-API sign-ins inactive", async () => {
|
||||
const plugin = await OpenAIDecisionsPlugin({});
|
||||
for (const auth of [undefined, {}, { type: "oauth", access: "fixture-oauth" }, { type: "api", key: "" }, { type: "api", key: 42 }]) {
|
||||
assert.deepEqual(await plugin.auth.loader(async () => auth), {});
|
||||
}
|
||||
});
|
||||
|
||||
test("direct sign-in follows the selected account's key and stops after sign-out", async () => {
|
||||
const plugin = await OpenAIDecisionsPlugin({});
|
||||
let auth = { type: "api", key: "fixture-direct-one" };
|
||||
const sent = [];
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
globalThis.fetch = async (_url, init) => {
|
||||
sent.push(init.headers.get("authorization"));
|
||||
return Response.json({ model: "gpt-6-luna", answers: [{ name: "ok", type: "predicate", probability: 1 }] });
|
||||
};
|
||||
const loaded = await plugin.auth.loader(async () => auth);
|
||||
assert.equal(loaded.apiKey, "fixture-direct-one");
|
||||
const request = { method: "POST", body: JSON.stringify({ model: "gpt-6-luna", state: "Hello", questions: { ok: { type: "noul", instructions: "Is this a greeting?" } } }) };
|
||||
assert.equal((await loaded.fetch(loaded.baseURL + "/systemone", request)).status, 200);
|
||||
auth = { type: "api", key: "fixture-direct-two" };
|
||||
assert.equal((await loaded.fetch(loaded.baseURL + "/systemone", request)).status, 200);
|
||||
auth = { type: "oauth", access: "fixture-other-account" };
|
||||
assert.equal((await loaded.fetch(loaded.baseURL + "/systemone", request)).status, 503);
|
||||
assert.deepEqual(sent, ["Bearer fixture-direct-one", "Bearer fixture-direct-two"]);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("community package entries use the provider package name and an HTTPS/data icon", async () => {
|
||||
const exports = await import("../index.mjs");
|
||||
assert.deepEqual(Object.keys(exports), ["OpenAIDecisionsPlugin"]);
|
||||
const packageJson = JSON.parse(readFileSync(new URL("../package.json", import.meta.url)));
|
||||
assert.equal(packageJson.name, "@magpie-community/opencode-openai-decisions-auth");
|
||||
assert.match(packageJson.magpie.icon, /^(https:\/\/|data:image\/)/);
|
||||
assert.equal(packageJson.main, "./opencode.mjs");
|
||||
const legacy = await import("../opencode.mjs");
|
||||
assert.deepEqual(Object.keys(legacy), ["OpenAIDecisionsPlugin"]);
|
||||
const modern = await import("../opencode2.mjs");
|
||||
assert.equal(modern.default.id, packageJson.name);
|
||||
assert.equal(typeof modern.default.setup, "function");
|
||||
});
|
||||
@@ -167,6 +167,7 @@
|
||||
"summary": { "en": "Email alerts when a provider call fails or a quota window runs out: your own SMTP account, your own words in the mail, and your own list of what to watch, with cooldowns and an hourly cap so a bad hour stays bounded — plus an optional periodic usage digest.", "zh": "供应商调用失败或额度窗口用尽时发邮件提醒:用你自己的 SMTP 账号、自己的邮件文案、自己勾选的监控事项;同类事件冷却合并,另有每小时上限,糟糕的一小时不会失控;另可开启定期用量摘要。" } },
|
||||
{ "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-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,
|
||||
|
||||
Reference in New Issue
Block a user