sap-aicore 0.3.0: a new provider for SAP AI Core's GPT Responses and Claude Messages deployments (caikn, #651)
A new provider package, @magpie-community/opencode-sap-aicore-auth 0.3.0
(packages/sap-aicore). It signs in from a local SAP AI Core client-secret
credential file, discovers the account's running GPT (Responses) and Claude
(Messages, Bedrock) deployments per resource group, and sends requests only to
https://*.authentication.*.hana.ondemand.com (token) and
https://api.ai.*.hana.ondemand.com (inference). Image input is gated per model
on the catalog's inputTypes. Also: the root README row, a registry.json entry,
.DS_Store in .gitignore, and scripts/check.mjs accepts an empty static model
list for a package whose provider.models hook is a function with the same id
(npm and the loader are still required).
Reviewed at head b44b3e1b68889c2a12bcaa37ad5d546a398bdde0, with main 9bba5fed
merged in locally, on a Mac mini (macOS, Bun 1.4.2), no real SAP account:
- bun test packages/sap-aicore scripts: 351 pass, 0 fail.
- bun scripts/check.mjs: every package ok, sap-aicore included.
- The two tests that reached the network at e955194 now use inputs root()
really rejects (/oauth, /v1), and a new test stubs fetch and checks that
/oauth/token and /v2 are accepted and the token is posted to
<authUrl>/oauth/token once. plugin.test.js fails on any unstubbed fetch.
- Whole package under a preload that records every non-loopback fetch, connect
and DNS lookup: 0 attempts (the preload caught a deliberate fetch to
example.invalid, so it does record).
- Broken by hand: putting the e955194 inputs back turns the test red through
the new guard; making root() keep the given path turns the new
/oauth/token + /v2 test red; letting root() accept any path turns 3 URL
tests red.
- Not tried: a real SAP AI Core account (the author's run record covers one
GPT and one Claude turn, plain and with a tool call; no image turn).
The first version goes out through the dist branch (npm doesn't have the name).
This commit is contained in:
@@ -2,3 +2,4 @@ node_modules/
|
||||
.sandbox/
|
||||
*.log
|
||||
.env
|
||||
.DS_Store
|
||||
|
||||
@@ -37,6 +37,7 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
| [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` |
|
||||
| [raccoon](packages/raccoon) | SenseTime Raccoon (商汤小浣熊, xiaohuanxiong.com): account credits and daily check-in, with browser sign-in or Raccoon desktop's sign-in | `raccoon` |
|
||||
| [river](packages/river) | River (river.ai) pay-as-you-go inference, with your API key: per-account models, documented reasoning efforts and live prices | `river` |
|
||||
| [sap-aicore](packages/sap-aicore) | SAP AI Core deployments for account-scoped GPT Responses and Claude Messages models | `sap-aicore` |
|
||||
| [sensenova](packages/sensenova) | SenseNova (商汤日日新) Token Plan: one console sign-in gives the credit pools, windows and grants, and (with an optional API key) the plan's models for chat | `sensenova-token-plan` |
|
||||
| [trae](packages/trae) | Trae CN (trae.cn) and Trae international (trae.ai), free tier included, with Trae's browser sign-in (experimental) | `trae-cn`, `trae-global` |
|
||||
| [workbuddy](packages/workbuddy) | WorkBuddy (China build, CodeBuddy plan) | `workbuddy` |
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 SAP AI Core plugin contributors
|
||||
Copyright (c) 2026 magpie-community contributors (opencode2.mjs)
|
||||
|
||||
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,162 @@
|
||||
# SAP AI Core plugin for Magpie
|
||||
|
||||
Connect your coding agent through Magpie to existing SAP AI Core deployments. The plugin handles SAP sign-in and token renewal without giving SAP credentials to your agent.
|
||||
|
||||
## Supported models
|
||||
|
||||
GPT discovery accepts model names with major version **6 or higher**, including minor versions and variants (for example, `gpt-6-mini`, `gpt-6.2`, or `gpt-7-mini`). No fixed model-name or backend-version allowlist is required. Deployments must still be `RUNNING` under `foundation-models` / `azure-openai`, with matching configuration, active backend, and non-deprecated/non-retired catalog version evidence. When several eligible deployments share a GPT model name, the lowest deployment ID wins, even across backend versions; metadata comes from that selected version.
|
||||
Claude discovery is contract-based, not a fixed name list: any running `foundation-models` / `aws-bedrock` Claude deployment that satisfies SAP's documented Bedrock Messages contract is exposed under a conventional ID derived from its model metadata, so a newer compatible model/version needs no plugin release. The live-verified Claude baselines are `claude-opus-4-8` and `claude-sonnet-4-6`. Additional GPT models pass the version-floor policy; additional Claude models are supported by contract. Their live inference, optional capabilities, and limits remain unverified until exercised against a real deployment. SAP's [Responses API documentation](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/responses-api-a40ffca.md) notes that not all models support Responses; discovery eligibility alone does not prove compatibility.
|
||||
|
||||
|
||||
All support text replies, streaming, and agent-executed function tools; Claude also supports native signed thinking. GPT routes through OpenAI Responses, Claude through native Anthropic Messages on SAP's Bedrock invoke endpoints — both under the same `sap-aicore` provider and account.
|
||||
|
||||
A GPT-5.x or lower-major deployment you already run stays in SAP AI Core but is not discovered or selectable through this plugin; the plugin never upgrades, migrates, or deletes it. Newer eligible GPT (major version 6 or higher) and compatible Claude deployments appear automatically, with no plugin release.
|
||||
|
||||
This adapter accepts text, agent-executed tool calls, and image input. Image input is gated per model on the API: a deployment's catalog version must advertise `image` in its `inputTypes`. When it does, GPT accepts `input_image` parts (Responses) and Claude accepts base64 `image` blocks (Messages); a text-only version rejects images with an explicit unsupported-content error rather than silently dropping them. All current GPT-6 and Claude deployments tested advertise image.
|
||||
|
||||
|
||||
## Before you start
|
||||
|
||||
You need:
|
||||
|
||||
- Magpie installed, with Bun available for its plugin host.
|
||||
- SAP AI Core on the **extended** service plan and a **client-secret** service key.
|
||||
- An existing **RUNNING** supported deployment in your selected resource group, under `foundation-models` / `azure-openai` (GPT) or `foundation-models` / `aws-bedrock` (Claude).
|
||||
|
||||
Installation does not create service keys, resource groups, or deployments. See SAP's [service plans](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/service-plans-c7244c6.md) and [deployment guide](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/create-a-deployment-b32e7a8.md).
|
||||
|
||||
## Quick start
|
||||
|
||||
### 1. Create your credential file
|
||||
|
||||
Save a JSON file outside this repository, for example `~/aicore-credentials.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"authUrl": "https://your-tenant.authentication.eu10.hana.ondemand.com",
|
||||
"baseUrl": "https://api.ai.prod.eu10.hana.ondemand.com",
|
||||
"clientId": "sb-your-client-id",
|
||||
"clientSecret": "your-client-secret",
|
||||
"resourceGroup": "your-resource-group"
|
||||
}
|
||||
```
|
||||
|
||||
Use your service key's values, not the example URLs. `authUrl` excludes `/oauth/token`; `baseUrl` excludes `/v2`. Choose the resource group containing your supported deployments. [Credential field mapping](docs/credentials.md#service-key-mapping) explains where to find each value.
|
||||
|
||||
Protect the file:
|
||||
|
||||
```sh
|
||||
chmod 600 ~/aicore-credentials.json
|
||||
```
|
||||
|
||||
### 2. Install and sign in
|
||||
|
||||
```sh
|
||||
magpie plugin add /absolute/path/to/magpie_aicore
|
||||
magpie plugin login sap-aicore
|
||||
```
|
||||
|
||||
When prompted, enter the **absolute path** to your credential file. Sign-in checks the credentials with SAP before saving the account.
|
||||
|
||||
For a released community version, install `@magpie-community/opencode-sap-aicore-auth` instead of the local folder. New packages are available through the community repository's `dist` channel after merge, even before their first npm publication (requires Magpie 0.1.1243 or newer).
|
||||
|
||||
This package uses the OpenCode plugin shape, but its credential-file sign-in and account-scoped mixed-protocol catalog are verified in **Magpie only**. Standalone OpenCode compatibility is not claimed.
|
||||
|
||||
|
||||
### 3. Start the gateway
|
||||
|
||||
```sh
|
||||
magpie serve
|
||||
```
|
||||
|
||||
## Use with your coding agent
|
||||
|
||||
Configure your agent to use the gateway address and caller authentication configured in Magpie. Select a discovered `sap-aicore/<model-id>`, such as one of the baselines above.
|
||||
|
||||
Pick the protocol that matches the model: GPT models speak OpenAI Responses (call the gateway directly, or use Magpie's Chat Completions conversion), and Claude models speak native Anthropic Messages. The plugin implements no cross-protocol converter — route a Claude model to a Messages client and a GPT model to a Responses client. See the [API reference](docs/api-reference.md) for curl examples and tool-history requirements per protocol.
|
||||
|
||||
## Credentials and accounts
|
||||
|
||||
Magpie remembers the credential-file reference; SAP tokens stay in memory and renew automatically. Keep the file available at the same path.
|
||||
|
||||
For multiple credential files or resource groups, sign in each absolute path separately. After rotating credentials, sign in again; restart any other running gateways that need the updated credentials. See [accounts and credential updates](docs/credentials.md#accounts-and-credential-updates).
|
||||
|
||||
## Multiple accounts and routing
|
||||
|
||||
Sign in each credential file as a separate account. Magpie then routes and fails over across them automatically.
|
||||
|
||||
```sh
|
||||
magpie plugin login sap-aicore # enter ~/aicore-a.json
|
||||
magpie plugin login sap-aicore # enter ~/aicore-b.json
|
||||
magpie accounts sap-aicore # confirm both are listed
|
||||
```
|
||||
|
||||
### Choosing a routing mode
|
||||
|
||||
The plugin does not report SAP quota windows to Magpie, so quota-aware modes (`smart`, `pace`) have no SAP data to weigh and behave like `order`. Use one of the two recommended modes:
|
||||
|
||||
| Situation | Recommended setup | Command |
|
||||
|---|---|---|
|
||||
| One primary account, others as backup | `routing=order` + `stays=session` | `magpie provider set sap-aicore routing=order` |
|
||||
| Several concurrent coding sessions | `routing=usage` + `stays=session` | `magpie provider set sap-aicore routing=usage` |
|
||||
|
||||
`stays=session` keeps each conversation on the account that answered its first turn, so tool loops and follow-up turns stay together and do not jump accounts mid-session. New sessions are spread across accounts by recent load.
|
||||
|
||||
Enable sink so a rate-limited account moves to the back immediately instead of being retried:
|
||||
|
||||
```sh
|
||||
magpie provider set sap-aicore sink=on
|
||||
```
|
||||
|
||||
### What multiple accounts protect against
|
||||
|
||||
| Setup | Benefit | Limit |
|
||||
|---|---|---|
|
||||
| Different credential files, same resource group | Separate credential identities; one credential failure leaves others working | Same SAP deployments and quota |
|
||||
| Different resource groups, same tenant | Separate deployments and workloads | Tenant-level model rate limits are shared by default |
|
||||
| Different tenants | Quota and credential isolation | Shared hyperscaler capacity or regional outages can still affect both |
|
||||
|
||||
SAP rate limits are tenant-wide and reset per minute. A 429 response can mean the tenant quota is exhausted, a resource-group limit is hit, or the backend is temporarily saturated — account rotation does not help when the limit is tenant-wide. See SAP's [rate limit documentation](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/rate-limit-management-6cbc230.md) for quota management and increase requests.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | What to check |
|
||||
|---|---|
|
||||
| Sign-in fails | Absolute file path, JSON fields, service-key values, and service URLs. |
|
||||
| No models appear | Resource group, deployment status, model eligibility, and matching active-version evidence. |
|
||||
| A selected model is unavailable | Deployment status or version may have changed; refresh discovery or restart the gateway. |
|
||||
| Unsupported parameter | Check the [supported request fields](docs/api-reference.md#request-fields). |
|
||||
|
||||
See [troubleshooting](docs/troubleshooting.md) for account selection, errors, and gateway constraints.
|
||||
|
||||
## Live run record
|
||||
|
||||
Authorized, credential-redacted live verification on 2026-11-03 (plugin `0.2.3`, Node `v26.13.0`), dispatched through the plugin's own `auth.loader().fetch` to real SAP AI Core in an existing resource group with isolated temporary stores. This exercises the plugin-to-SAP dispatch path, not the installed Magpie gateway process; the gateway journey is recorded separately in the [source project](https://github.com/caikn/magpie-plugin-aicore/issues/14). No tokens, client secrets, resource-group names, or deployment URLs are shown; eight synthetic generations were used.
|
||||
|
||||
| Scenario | `gpt-6-astra` (Responses) | `claude-opus-4-8` (Messages) |
|
||||
|---|---|---|
|
||||
| Plain text | HTTP 200, `completed`, usage 14→8 | HTTP 200, `end_turn`, usage 29→17 |
|
||||
| Streamed | HTTP 200, incremental `output_text` deltas, `response.completed` | HTTP 200, incremental deltas, `stop_reason: end_turn`, `message_stop` |
|
||||
| Forced tool call | `function_call verify_value {"value":7}` | `tool_use verify_value {"value":7}` |
|
||||
| Tool-result continuation | HTTP 200, `completed`, "The result is 14." | HTTP 200, `end_turn`, "…returned **14** (7 doubled)." |
|
||||
|
||||
Each request carried the account's SAP Bearer and resource-group header injected by the loader; the caller's gateway key was never forwarded. This single dated run is not a quota, latency, or billing guarantee, and does not cover token expiry/renewal, 429/quota exhaustion, reauthorization races, or reasoning-signature replay.
|
||||
|
||||
|
||||
## Limitations and security
|
||||
|
||||
- Only running deployments are exposed. GPT requires major version 6 or higher, not a fixed model/version list; Claude is accepted by the documented SAP Bedrock Messages contract (`foundation-models` / `aws-bedrock`). Existing GPT-5.x and lower-major deployments remain in SAP but are never listed, upgraded, or deleted.
|
||||
- Text, agent-executed function tools, and image input (Claude also: native signed thinking and `cache_control`). Image input is enabled per model from the catalog `inputTypes` and rejected with an explicit error on text-only versions; audio, video, hosted tools, and other multimodal input remain unsupported.
|
||||
- No deployment management, server-side conversation storage, or automatic model substitution.
|
||||
- Capability status differs by evidence: the GPT pair and the two Claude baselines are directly verified; other eligible models' live inference, optional reasoning controls, and context/output limits are **not** verified until exercised against a real deployment. Being listed never asserts completed live acceptance.
|
||||
- Keep credentials outside the repository. Never use a SAP client secret or access token as the agent's gateway key.
|
||||
- Local cancellation does not guarantee SAP computation or billing stops. Magpie may retry failed requests; do not assume exactly-once generation.
|
||||
- MIT licensed; not affiliated with or endorsed by SAP. The license does not grant SAP productive-use approval.
|
||||
|
||||
## More information
|
||||
|
||||
- [Credentials and accounts](docs/credentials.md)
|
||||
- [API reference](docs/api-reference.md)
|
||||
- [Troubleshooting](docs/troubleshooting.md)
|
||||
- [Development](https://github.com/caikn/magpie-plugin-aicore/blob/main/docs/development.md)
|
||||
- [Community publication](https://github.com/caikn/magpie-plugin-aicore/blob/main/docs/publication.md)
|
||||
@@ -0,0 +1,103 @@
|
||||
# API reference
|
||||
|
||||
## Gateway request
|
||||
|
||||
Use the address and caller-key policy configured in Magpie. This is a gateway key, never a SAP credential.
|
||||
|
||||
```sh
|
||||
MAGPIE_GATEWAY=http://127.0.0.1:3425 # replace with the address printed by Magpie
|
||||
MAGPIE_KEY=magpie # replace if your caller-key policy differs
|
||||
curl "$MAGPIE_GATEWAY/v1/responses" \
|
||||
-H "Authorization: Bearer $MAGPIE_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "sap-aicore/gpt-6-astra",
|
||||
"input": "Reply with RESPONSES_OK.",
|
||||
"store": false,
|
||||
"stream": false,
|
||||
"max_output_tokens": 1024
|
||||
}'
|
||||
```
|
||||
|
||||
`stream:false` returns whole JSON; `stream:true` returns SSE. Chat clients can use Magpie's existing `/v1/chat/completions` conversion to Responses. The plugin implements no Chat transport or converter.
|
||||
|
||||
## Request fields
|
||||
|
||||
Supported fields include `model`, native text/history `input`, `instructions`, positive integer `max_output_tokens`, string `prompt_cache_key`, function `tools`, `tool_choice`, `stream`, and `include:["reasoning.encrypted_content"]`. When the selected model's catalog version advertises image input (`inputTypes` contains `image`), user-message `input_image` parts carrying a `data:` or `https:` `image_url` (optional `detail:auto|low|high`) are accepted and forwarded verbatim; text-only versions reject them. Live-verified: `gpt-6-astra` read a base64 PNG through `/responses`.
|
||||
|
||||
Reasoning accepts `effort:low`, `medium`, or `high`, optionally with `summary:auto`. Cache-key acceptance does not guarantee cache hits. Output budgets of 1024 and 128000 were accepted; this is not a maximum-length generation guarantee.
|
||||
|
||||
`store:false` is supplied when omitted. Explicit `background:false` is accepted. Stateful storage, `previous_response_id`, conversation references, background jobs, lifecycle requests, compaction, hosted tools, non-image multimodal input (audio, video, file references), and Chat request fields are unsupported. Unsupported fields fail rather than being silently removed.
|
||||
|
||||
## Function tools and history
|
||||
|
||||
Tools use native Responses function definitions with `name`, `parameters`, and supported `strict:true`. The agent executes tools; the plugin does not.
|
||||
|
||||
Continuation must preserve original input and every returned output item in order, including reasoning items and exact argument strings. Pair results using `call_id`, not the output item's `id`:
|
||||
|
||||
```js
|
||||
const results = reply.output.filter(item => item.type === "function_call").map(item => ({
|
||||
type: "function_call_output",
|
||||
call_id: item.call_id,
|
||||
output: JSON.stringify(executeFunction(item.name, JSON.parse(item.arguments))),
|
||||
}))
|
||||
const continuation = {
|
||||
...request,
|
||||
input: [...request.input, ...reply.output, ...results],
|
||||
store: false,
|
||||
tool_choice: "none",
|
||||
}
|
||||
```
|
||||
|
||||
Keep tools declared. Wrap string input as a user message before assembling history. When include is omitted for tools, reasoning, or reasoning history, the plugin supplies encrypted-reasoning inclusion; explicit supported arrays, including an empty array, remain unchanged. Live GPT probes returned no reasoning items, so genuine encrypted reasoning replay is not established.
|
||||
|
||||
## Claude (native Anthropic Messages)
|
||||
|
||||
Claude models use native Anthropic Messages, not Responses. Send to `/v1/messages`; Magpie rewrites it to the account root and the plugin dispatches to the deployment's Bedrock `/invoke` (whole) or `/invoke-with-response-stream` (streaming).
|
||||
|
||||
```sh
|
||||
curl "$MAGPIE_GATEWAY/v1/messages" \
|
||||
-H "Authorization: Bearer $MAGPIE_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "sap-aicore/claude-opus-4-8",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{ "role": "user", "content": "Reply with MESSAGES_OK." }]
|
||||
}'
|
||||
```
|
||||
|
||||
Supported fields: `model`, `messages`, string or text-block `system`, required non-negative integer `max_tokens`, `stop_sequences`, custom-function `tools` (`name`, `input_schema`, optional `description`, `type:"custom"`, `strict`, and `cache_control`), `tool_choice` (`auto`/`any`/`tool`/`none`), `temperature`/`top_p`/`top_k`, `stream`, and `thinking`. Enabled thinking requires a positive integer `budget_tokens`; disabled/adaptive thinking does not accept a budget. Recognized `thinking.display`, `thinking.block_binding`, and `output_config.effort` controls are structurally validated and preserved for upstream contract validation. Text-block `cache_control:{"type":"ephemeral"}` is accepted. When the selected model's catalog version advertises image input, user-message `image` blocks with a base64 `source` (`{"type":"base64","media_type":...,"data":...}`) are accepted and forwarded to Bedrock; non-base64 sources (such as `url`) and image blocks for text-only versions are rejected. Live-verified: `claude-opus-4-8` read a base64 PNG through `/invoke`. The routing `model` and `stream` selector are removed from the upstream body and `anthropic_version:"bedrock-2023-05-31"` is supplied; a conflicting body version is rejected.
|
||||
|
||||
The discovered Opus 4.8 version `1` rejects explicit `temperature`, `top_p`, and enabled/fixed-budget thinking locally. Sonnet 4.6 version `1` rejects combined `temperature` plus `top_p`, and enabled thinking with forced tool use; either sampling setting individually and fixed-budget thinking are retained. Both baseline versions advertise and enforce `max_tokens <= 128000`; this is not a maximum-length generation guarantee. Newer releases or active versions do not inherit these restrictions or limits: structurally valid recognized controls reach upstream validation. No sampling defaults are injected. Unknown body/tool fields, metadata, non-image multimodal content, and hosted tools are rejected; base64 image blocks are accepted only when the matched catalog version advertises image input. Two explicit boolean client-only tool hints, `eager_input_streaming` and `defer_loading`, are accepted and removed before Bedrock dispatch; they are not native tool capabilities.
|
||||
|
||||
Agent-executed continuation resends the original messages, the complete returned assistant `content` array in order (text, `tool_use`, signed `thinking` including empty text, `redacted_thinking`), and a user message of `tool_result` blocks paired by the original `tool_use.id`. The agent executes tools; the plugin neither executes them nor repairs reasoning. A rejected signature or mismatched result surfaces as an upstream error.
|
||||
|
||||
Streaming is accepted only when the matched catalog version explicitly reports support. SAP's data-only Anthropic SSE (`message_start`, `content_block_*`, `message_delta`, `message_stop`, `error`; no `event:` or `[DONE]` required) is relayed one bounded frame at a time. Text and `input_json_delta` tool arguments arrive incrementally. Successful completion requires a valid `message_start`, a `message_delta` carrying a non-empty `stop_reason`, and `message_stop`; a bare stop frame, malformed terminal state, or missing terminal is a failure.
|
||||
|
||||
## Discovery and versions
|
||||
|
||||
The [supported model/version table](../README.md#supported-models) defines eligibility. Discovery reads the selected account's resource group, follows offset pagination, and reconciles configuration identity, backend active version, and catalog metadata. Only running supported deployments are exposed. A `latest` selector without a resolved supported backend version is insufficient. Deprecated or retired versions are excluded; the plugin never upgrades deployments.
|
||||
|
||||
Successful discovery is cached for five minutes, including an empty list. Either monotonic elapsed time or wall-clock age can expire the cache, so system sleep does not extend its lifetime. Expiry, retirement, and account replacement invalidate it. Failed refresh does not authorize stale dispatch. Restart rebuilds the registry without requiring a prior client model-list request.
|
||||
|
||||
The two GPT baseline versions report catalog context length 1050000; the two Claude baseline versions report 1000000. These are catalog-derived, not stress-tested limits. Only the Claude baseline active versions `1` advertise the directly established output ceiling 128000. Missing version-specific limits remain unknown; the plugin does not derive prices. Distinct raw SAP identities can deduplicate only with matching authoritative Claude identity metadata and compatible version/contract facts; ambiguous collisions fail discovery.
|
||||
|
||||
## Upstream transport and streaming
|
||||
|
||||
Each model is accepted only on its own protocol's account-root route (GPT `/responses`, Claude `/messages`), POST only, with no query or fragment; a model addressed through the wrong route fails before any inference credential is sent. Dispatch uses the validated returned deployment URL — plus `/responses` for GPT, or `/invoke`/`/invoke-with-response-stream` for Claude — without an API-version query. Accepted deployment URLs must have the selected AI Core origin and `/v2/inference/deployments/<id>` path. SAP Bearer authentication and the selected resource group replace incoming SDK credentials; Magpie-only headers are stripped.
|
||||
|
||||
Native output items, identity, usage, status, error, and incomplete details remain distinct. SSE carries output text, function-argument, output-item, and completed/incomplete/failed events; no `[DONE]` marker is required. Individual bounded frames are decoded incrementally across UTF-8/network boundaries, not accumulated as a whole reply.
|
||||
|
||||
Magpie may request upstream streaming for whole clients and gather the result. It can adapt request fields, add a final-answer phase, and turn a failed terminal into a gateway HTTP error. Exact native fidelity applies at plugin fetch, not byte-for-byte across the gateway.
|
||||
|
||||
Observed with Magpie `0.1.2630` at the actual gateway: whole Claude clients use upstream SSE; cache breakpoints are added; `tools[].strict` is removed. Opus `temperature`/`top_p` and unsupported `top_logprobs` disappear before plugin validation. Enabled thinking on Opus and Sonnet becomes adaptive, without `budget_tokens`; Sonnet combined sampling loses `top_p`. A synthetic newer model loses both sampling fields but retains its larger output budget. Sonnet individual `temperature` is preserved, and baseline `max_tokens:128001` is rejected before SAP inference. These host adaptations conflict with end-to-end explicit-intent preservation: the plugin validates only what it receives, and does not repair or hide the host behavior. Exact native controls and strict-tool fidelity are verified separately through Bun IPC.
|
||||
|
||||
For `stop_sequence`, the plugin preserves both `stop_reason:"stop_sequence"` and `stop_sequence:"STOP"` through whole Bun IPC and raw native SSE. The installed gateway streamed client preserves them, but its whole-client gathering normalizes the reason to `end_turn`. The primary acceptance test records that host adaptation instead of treating it as native fidelity. Native failures may also become gateway HTTP errors and trigger account cooldown; another pinned account remains usable.
|
||||
|
||||
The gateway also rewrites Claude response `model` from the backend's canonical ID (for example `claude-opus-4-8`) to the provider-qualified request ID (`sap-aicore/claude-opus-4-8`) for both whole and streamed clients. Bun IPC whole/streamed replies preserve the backend ID. Gateway identity assertions record the prefixing while rejecting unrelated model IDs; this remains a response-identity fidelity gap against the spec.
|
||||
|
||||
Active operations default to a 120-second idle timeout and a separate 900-second total cap. The idle timer starts at request entry and resets when the plugin relays a stream chunk; active streams can therefore exceed two minutes, but stalls and the total cap still abort the owned request. Configure `idleTimeoutMs` and `totalTimeoutMs` on the plugin input or `config.provider["sap-aicore"].options`; positive numeric values are rounded down and bounded to 1–3600000 ms. A stalled streamed body reports `inference-idle-timeout`; the total cap and pre-stream timeout report `inference-timeout`. Request/whole bodies and individual frames remain bounded to 16 MiB; OAuth/discovery retain separate 15-second bounds. Cancellation aborts owned HTTP/body delivery, not necessarily SAP compute or billing.
|
||||
|
||||
The plugin sends one generation per fetch and adds no inference retries. Magpie's retries and routing failover remain independent; exactly-once generation is not guaranteed. See [troubleshooting](troubleshooting.md).
|
||||
|
||||
References: [SAP Responses API](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/responses-api-a40ffca.md), [SAP AWS Bedrock](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/aws-bedrock-6a81f85.md), [supported models](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/supported-models-509e588.md).
|
||||
@@ -0,0 +1,50 @@
|
||||
# Credentials and accounts
|
||||
|
||||
The plugin accepts a JSON credential file with `authUrl`, `baseUrl`, `clientId`, `clientSecret`, and `resourceGroup`. Every field must be a nonempty string. Sign in using an absolute file path; store the file outside the repository with mode `0600`.
|
||||
|
||||
## Service-key mapping
|
||||
|
||||
Create the file manually from an SAP AI Core client-secret service key:
|
||||
|
||||
| Service-key field | Credential-file field |
|
||||
|---|---|
|
||||
| `url` | `authUrl` |
|
||||
| `serviceurls.AI_API_URL` | `baseUrl` |
|
||||
| `clientid` | `clientId` |
|
||||
| `clientsecret` | `clientSecret` |
|
||||
| Your chosen existing resource group | `resourceGroup` |
|
||||
|
||||
Service-binding JSON and x.509 certificate service keys are not accepted. See SAP's [Create a Service Key](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/create-a-service-key-7323ff4.md).
|
||||
|
||||
## Field requirements
|
||||
|
||||
- `authUrl`: HTTPS OAuth root on a supported `*.authentication.<region>.hana.ondemand.com` host, without `/oauth/token`.
|
||||
- `baseUrl`: HTTPS AI Core root on a supported `api.ai.*.hana.ondemand.com` host, without `/v2`.
|
||||
- URLs must not contain embedded credentials, nondefault ports, extra paths, query strings, or fragments.
|
||||
- `clientId` must not contain a colon. `clientSecret` must not contain a colon or control characters.
|
||||
- `resourceGroup` must identify the group used for both discovery and inference.
|
||||
|
||||
OAuth uses raw UTF-8 HTTP Basic authentication, form content type, and only `grant_type=client_credentials` in the form body. The plugin does not try alternate authentication encodings. See SAP's [Use a Service Key](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/use-a-service-key-3a97465.md).
|
||||
|
||||
## Accounts and credential updates
|
||||
|
||||
```sh
|
||||
magpie plugin login sap-aicore
|
||||
magpie accounts sap-aicore --json
|
||||
```
|
||||
|
||||
Sign in each credential-file path separately. Reusing the same normalized path replaces its account after successful authorization; different paths represent different accounts, even if their contents describe the same SAP identity.
|
||||
|
||||
After credential rotation, update your external file and sign in again. Credentials are loaded once per account generation, not watched continuously. Another running gateway does not observe cross-process reauthorization at the same file path; restart it to load the changed credentials.
|
||||
|
||||
To pin a gateway request, set `X-Magpie-Account` to the account's displayed user label from the account listing. Labels can look like `API key …abcd`. JavaScript Fetch headers require byte strings; encode a non-ASCII label with `Buffer.from(label,"utf8").toString("latin1")`. Magpie removes the pin header before SAP dispatch. A pinned request does not select another account in its place.
|
||||
|
||||
## Persistence and token lifecycle
|
||||
|
||||
Magpie persists only API authentication type, an opaque key derived from the normalized credential-file path, and credential-file metadata. Client secrets and SAP tokens are not copied into the account store.
|
||||
|
||||
Tokens stay in account-scoped memory. Renewal is on demand 60 seconds before expiry, or halfway through short token lifetimes. Both monotonic elapsed time and wall-clock deadlines bound reuse: system sleep cannot extend a SAP token's lifetime, and a backward wall-clock adjustment cannot extend its monotonic lifetime. Concurrent callers share acquisition; cancelling one waiter does not cancel acquisition still needed by another. File reads and token exchanges have 15-second bounds.
|
||||
|
||||
Only verified OAuth client-credential refusal expires sign-in. Network errors, cancellation, timeouts, malformed responses, and discovery/inference failures do not by themselves expire the account. See [error handling](troubleshooting.md#error-handling).
|
||||
|
||||
[Back to setup](../README.md)
|
||||
@@ -0,0 +1,53 @@
|
||||
# Troubleshooting
|
||||
|
||||
## Sign-in fails
|
||||
|
||||
Check the absolute credential-file path, readable valid JSON, required fields, and current client-secret service-key values. Service bindings and certificate keys are not accepted. Use service roots without endpoint paths. See [credentials](credentials.md).
|
||||
|
||||
Only supported SAP `*.hana.ondemand.com` service hosts are accepted. Other landscapes, embedded URL credentials, nondefault ports, or query/fragment components are rejected. Do not disable TLS verification to work around a trust failure.
|
||||
|
||||
## No models appear or a model becomes unavailable
|
||||
|
||||
Check the credential file's resource group, RUNNING deployment status, scenario/executable, and [model eligibility](../README.md#supported-models). GPT requires major version 6 or higher, not a fixed name or backend date. The active backend version must match the catalog and any configured version pin. For both GPT and Claude, `latest` is only a configuration selector: backend details must report a concrete version, even when the catalog includes a `latest` entry. Catalog availability alone does not mean a deployment exists. Unresolved, deprecated, or retired versions remain unavailable.
|
||||
|
||||
Discovery refreshes after its five-minute cache expires, including time spent in system sleep. Restart the gateway to rebuild immediately and wait for startup discovery to finish before sending requests. A retained visible host catalog is not proof that the deployment is still usable; dispatch checks the current registry.
|
||||
|
||||
## Unsupported request parameters
|
||||
|
||||
Use the [API request fields](api-reference.md#request-fields). Responses does not accept Chat fields directly. Supported reasoning effort is low/medium/high with optional automatic summary; none is unsupported. Use stateless history rather than a previous response ID. Preserve complete tool history and original call IDs.
|
||||
|
||||
For Claude, use `/v1/messages` and the [native Messages fields](api-reference.md#claude-native-anthropic-messages), not Responses `input`. Enabled thinking requires a positive integer `budget_tokens`; adaptive/disabled thinking must omit it. Opus 4.8 active version `1` rejects `temperature`, `top_p`, and enabled thinking. Sonnet 4.6 active version `1` accepts either sampling setting individually, not both, and rejects enabled thinking with forced tool use. Both baseline versions enforce `max_tokens <= 128000`. Newer versions do not inherit these limits or model-specific restrictions. Unknown request/tool fields fail explicitly; only the documented boolean pi tool hints are consumed during adaptation.
|
||||
|
||||
Claude streaming requires explicit support on the matched catalog version; omitted support does not authorize streaming. A stream must include a valid message start and stop-reason delta before its stop frame. An identity-resolution error means non-empty catalog identity metadata was unrecognized or conflicted; an explicit non-Anthropic provider cannot qualify through a Claude name substring.
|
||||
|
||||
## Credential updates and multiple accounts
|
||||
|
||||
Sign in again after changing credentials and restart other running gateways. Reauthorization in another process cannot revoke an already-running host's in-memory account generation at an identical file path. Deleting/recreating a file at that path is not an automatic rotation signal.
|
||||
|
||||
Use the displayed account label to pin requests; see [account selection](credentials.md#accounts-and-credential-updates). Do not guess a selector from a hash or send SAP credentials as the gateway key.
|
||||
|
||||
## First request after overnight sleep returns discovery 401
|
||||
|
||||
`discovery-response` with HTTP 401 means an AI Core discovery endpoint rejected the request before inference; it does not establish an OAuth client-secret refusal. Older plugin versions used only a monotonic expiry clock, which pauses during system sleep in Bun on macOS and could retain yesterday's expired token. Token reuse now checks wall-clock deadlines as well.
|
||||
|
||||
Fully quit and reopen the Magpie app, or restart the gateway process, to load the fixed plugin and discard the old in-memory token. Restarting pi alone does not reset the gateway's token. Do not rotate credentials based on this error alone. If discovery still returns 401 with a fresh token, check the service-key/API landscape pairing and account access.
|
||||
|
||||
## Error handling
|
||||
|
||||
- Verified OAuth client refusal expires the affected sign-in.
|
||||
- Discovery/inference 401 keeps sign-in; verified invalid/expired Bearer rejection discards the token for a subsequent independent operation, without replaying the failed generation in the plugin.
|
||||
- 404 can mean the selected model/deployment is unavailable.
|
||||
- 429 may mean tenant/resource-group quota or backend capacity. Numeric-seconds Retry-After is preserved when supplied; the status alone does not identify the cause.
|
||||
- Temporary upstream failures, timeouts, and cancellation remain errors rather than successful empty replies.
|
||||
- An HTTP 200 stream may still fail or end incomplete. Native failure events and missing/malformed terminals must not be interpreted as completion.
|
||||
- Long active streams no longer hit the former two-minute total cutoff: defaults are 120 seconds idle and 900 seconds total. `inference-idle-timeout` means no stream chunk was relayed within the idle window; `inference-timeout` means the total cap or pre-stream deadline expired. See [timeout options](api-reference.md#upstream-transport-and-streaming). Magpie may wrap either stream-read failure as "connection lost mid-reply"; that wording alone does not establish an AI Core network outage.
|
||||
|
||||
Error descriptions are credential-redacted; native identities, output history, status, and error categories are retained. Magpie may retry or fail over independently. Do not assume one client request means exactly one billed generation.
|
||||
|
||||
## Cancellation and host constraints
|
||||
|
||||
Local abort stops owned HTTP/body delivery but does not prove SAP backend termination or billing cessation. Independent requests can continue after another request is cancelled.
|
||||
|
||||
Host initialization hooks do not supply a caller abort signal; they have internal deadlines. On cold fetch, the host may initialize credentials/discovery before the plugin sees and rejects an unsafe request URL. Cancelling sign-in after authorization does not necessarily prevent the host saving the successful account. These constraints do not authorize unsafe inference routing or stale-registry dispatch.
|
||||
|
||||
[Back to setup](../README.md)
|
||||
@@ -0,0 +1,3 @@
|
||||
// OpenCode 1.x and Magpie load this plugin-only entry point.
|
||||
// OpenCode 2.x uses the upstream adapter in opencode2.mjs.
|
||||
export { SAPAICorePlugin } from "./src/index.js"
|
||||
@@ -0,0 +1,594 @@
|
||||
// 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
|
||||
if (!p.condition) 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,45 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-sap-aicore-auth",
|
||||
"version": "0.3.0",
|
||||
"description": "SAP AI Core deployments in Magpie with credential-file sign-in, account-scoped discovery and native Responses / Messages transport",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"main": "opencode.mjs",
|
||||
"exports": {
|
||||
".": "./opencode2.mjs"
|
||||
},
|
||||
"files": [
|
||||
"src/*.js",
|
||||
"opencode.mjs",
|
||||
"opencode2.mjs",
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"docs/credentials.md",
|
||||
"docs/api-reference.md",
|
||||
"docs/troubleshooting.md"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"keywords": [
|
||||
"magpie",
|
||||
"magpie-plugin",
|
||||
"opencode-plugin",
|
||||
"sap",
|
||||
"sap-aicore"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/sap-aicore"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/magpie-community/plugins/issues"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,703 @@
|
||||
import { claudeFamily, resolveCanonicalClaude } from "./identity.js"
|
||||
import { AI_HOST, SAFE_TEXT, isObject } from "./transport.js"
|
||||
|
||||
const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/
|
||||
const SAFE_PATH = /^(?:\/[A-Za-z0-9_-]+)+$/
|
||||
const safeId = v => typeof v === "string" && SAFE_ID.test(v)
|
||||
|
||||
const TIMEOUT_MS = 15000
|
||||
const PAGE_SIZE = 100
|
||||
const MAX_PAGES = 128
|
||||
const MAX_ROWS = 4096
|
||||
const MAX_BODY_BYTES = 1024 * 1024
|
||||
const MAX_TOTAL_BYTES = 16 * 1024 * 1024
|
||||
const MAX_REQUESTS = 512
|
||||
|
||||
const ERRORS = {
|
||||
destination: "SAP AI Core: unsafe deployment-list destination.",
|
||||
response: "SAP AI Core: deployment listing returned an unexpected response.",
|
||||
network: "SAP AI Core: deployment listing could not be reached.",
|
||||
timeout: "SAP AI Core: deployment discovery timed out.",
|
||||
cancelled: "SAP AI Core: deployment discovery was cancelled.",
|
||||
exhausted: "SAP AI Core: deployment listing exceeded its bounds.",
|
||||
identity: "SAP AI Core: a Claude deployment's model identity could not be resolved.",
|
||||
conflict: "SAP AI Core: distinct Claude deployments resolved to the same model identity.",
|
||||
}
|
||||
|
||||
const OWNED = new WeakSet()
|
||||
|
||||
/** @returns {Error & {code: string, status?: number, retryAfter?: string}} */
|
||||
function failure(code) {
|
||||
const error = Object.assign(new Error(ERRORS[code]), { code })
|
||||
OWNED.add(error)
|
||||
return error
|
||||
}
|
||||
|
||||
function safeFailure(error) {
|
||||
return OWNED.has(error) ? error : failure("response")
|
||||
}
|
||||
|
||||
function abortReason(signal) {
|
||||
return OWNED.has(signal?.reason) ? signal.reason : failure("cancelled")
|
||||
}
|
||||
|
||||
function rootOrigin(aiRoot) {
|
||||
if (typeof aiRoot !== "string" || !/^https:\/\//i.test(aiRoot) || /[\x00-\x20\x7f-\x9f\\\s?#]/.test(aiRoot) ||
|
||||
/%(?:2f|5c|2e)/i.test(aiRoot) || /\/(?:\.|\.\.)(?:\/|$)/.test(aiRoot)) return null
|
||||
let base
|
||||
try { base = new URL(aiRoot) } catch { return null }
|
||||
if (base.protocol !== "https:" || base.username || base.password || base.port ||
|
||||
base.search || base.hash || base.pathname !== "/" || !AI_HOST.test(base.hostname) ||
|
||||
(aiRoot !== base.origin && aiRoot !== base.origin + "/")) return null
|
||||
return base.origin
|
||||
}
|
||||
|
||||
function requestContext(aiRoot, resourceGroup, bearer, signal, rejectedToken) {
|
||||
const origin = rootOrigin(aiRoot)
|
||||
if (origin === null) throw failure("destination")
|
||||
if (typeof resourceGroup !== "string" || !SAFE_TEXT.test(resourceGroup)) throw failure("destination")
|
||||
if (typeof bearer !== "function") throw failure("response")
|
||||
return { origin, resourceGroup, bearer, signal, rejectedToken, requests: 0, totalBytes: 0 }
|
||||
}
|
||||
|
||||
function requestURL(origin, path, query) {
|
||||
if (typeof path !== "string" || !SAFE_PATH.test(path)) throw failure("destination")
|
||||
const url = new URL(origin + path)
|
||||
if (query) for (const key of Object.keys(query)) url.searchParams.set(key, query[key])
|
||||
return url.href
|
||||
}
|
||||
|
||||
async function requestJSON(context, path, query) {
|
||||
if (context.requests >= MAX_REQUESTS) throw failure("exhausted")
|
||||
context.requests++
|
||||
const href = requestURL(context.origin, path, query)
|
||||
if (context.signal.aborted) throw abortReason(context.signal)
|
||||
const token = await context.bearer()
|
||||
if (context.signal.aborted) throw abortReason(context.signal)
|
||||
if (typeof token !== "string" || !SAFE_TEXT.test(token)) throw failure("response")
|
||||
let response
|
||||
try {
|
||||
response = await globalThis.fetch(href, {
|
||||
method: "GET",
|
||||
redirect: "error",
|
||||
headers: {
|
||||
Authorization: "Bearer " + token,
|
||||
"AI-Resource-Group": context.resourceGroup,
|
||||
Accept: "application/json",
|
||||
},
|
||||
signal: context.signal,
|
||||
})
|
||||
} catch (error) {
|
||||
if (context.signal.aborted) throw abortReason(context.signal)
|
||||
throw failure("network")
|
||||
}
|
||||
if (context.signal.aborted) {
|
||||
void response?.body?.cancel?.().catch(() => {})
|
||||
throw abortReason(context.signal)
|
||||
}
|
||||
if (response.redirected || (response.url && response.url !== href) || (response.status >= 300 && response.status < 400)) {
|
||||
void response.body?.cancel?.().catch(() => {})
|
||||
throw failure("destination")
|
||||
}
|
||||
if (!response.ok) {
|
||||
if (response.status === 401 && /^Bearer\b/i.test(response.headers?.get?.("www-authenticate") ?? "") &&
|
||||
/\berror\s*=\s*(?:"(?:invalid_token|expired_token)"|(?:invalid_token|expired_token))(?=\s|,|$)/i.test(response.headers?.get?.("www-authenticate") ?? "")) context.rejectedToken?.()
|
||||
const error = failure("response")
|
||||
if (response.status >= 400 && response.status <= 599) error.status = response.status
|
||||
const retryAfter = response.headers?.get?.("retry-after")
|
||||
if (/^\d{1,10}$/.test(retryAfter ?? "")) error.retryAfter = retryAfter
|
||||
void response.body?.cancel?.().catch(() => {})
|
||||
throw error
|
||||
}
|
||||
const { json, bytes } = await readJSON(response, context.signal, MAX_TOTAL_BYTES - context.totalBytes)
|
||||
context.totalBytes += bytes
|
||||
return json
|
||||
}
|
||||
|
||||
function pageRows(json) {
|
||||
if (!json || typeof json !== "object" || Array.isArray(json)) throw failure("response")
|
||||
if (!Array.isArray(json.resources)) throw failure("response")
|
||||
if (json.count !== undefined && !(Number.isSafeInteger(json.count) && json.count >= 0)) throw failure("response")
|
||||
return json.resources
|
||||
}
|
||||
|
||||
function deploymentId(row) {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row)) throw failure("response")
|
||||
if (!safeId(row.id)) throw failure("response")
|
||||
return row.id
|
||||
}
|
||||
|
||||
async function readJSON(response, signal, remainingBytes) {
|
||||
const reader = response.body?.getReader?.()
|
||||
if (!reader) throw failure("response")
|
||||
const chunks = []
|
||||
let size = 0
|
||||
const cancel = () => { void reader.cancel().catch(() => {}) }
|
||||
signal.addEventListener("abort", cancel, { once: true })
|
||||
try {
|
||||
for (;;) {
|
||||
if (signal.aborted) throw abortReason(signal)
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
size += value.byteLength
|
||||
if (size > MAX_BODY_BYTES || size > remainingBytes) throw failure("exhausted")
|
||||
chunks.push(value)
|
||||
}
|
||||
const text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))
|
||||
return { json: JSON.parse(text), bytes: size }
|
||||
} catch (error) {
|
||||
cancel()
|
||||
if (signal.aborted) throw abortReason(signal)
|
||||
throw safeFailure(error)
|
||||
} finally {
|
||||
signal.removeEventListener("abort", cancel)
|
||||
reader.releaseLock()
|
||||
}
|
||||
}
|
||||
|
||||
async function collect(context) {
|
||||
const rows = []
|
||||
const seen = new Set()
|
||||
let skip = 0
|
||||
for (let pages = 0; ; pages++) {
|
||||
if (context.signal.aborted) throw abortReason(context.signal)
|
||||
if (pages >= MAX_PAGES) throw failure("exhausted")
|
||||
const resources = pageRows(await requestJSON(context, "/v2/lm/deployments", {
|
||||
scenarioId: "foundation-models",
|
||||
executableIds: "azure-openai,aws-bedrock",
|
||||
status: "RUNNING",
|
||||
$top: String(PAGE_SIZE),
|
||||
$skip: String(skip),
|
||||
}))
|
||||
if (resources.length === 0) return rows
|
||||
for (const row of resources) {
|
||||
const id = deploymentId(row)
|
||||
if (seen.has(id)) throw failure("response")
|
||||
seen.add(id)
|
||||
rows.push(row)
|
||||
}
|
||||
if (rows.length > MAX_ROWS) throw failure("exhausted")
|
||||
const next = skip + resources.length
|
||||
if (!Number.isSafeInteger(next) || next <= skip) throw failure("response")
|
||||
skip = next
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {{aiRoot?: string, resourceGroup?: string, bearer?: () => Promise<string>, signal?: AbortSignal, rejectedToken?: () => void}} request */
|
||||
async function operation({ aiRoot, resourceGroup, bearer, signal, rejectedToken } = {}, run) {
|
||||
const controller = new AbortController()
|
||||
const abort = reason => { if (!controller.signal.aborted) controller.abort(reason) }
|
||||
let timer
|
||||
let onAbort
|
||||
const stop = new Promise((_, reject) => {
|
||||
onAbort = () => reject(abortReason(controller.signal))
|
||||
controller.signal.addEventListener("abort", onAbort, { once: true })
|
||||
timer = setTimeout(() => abort(failure("timeout")), TIMEOUT_MS)
|
||||
})
|
||||
const relay = () => abort(abortReason(signal))
|
||||
if (signal) {
|
||||
if (signal.aborted) abort(abortReason(signal))
|
||||
else signal.addEventListener("abort", relay, { once: true })
|
||||
}
|
||||
const work = (async () => run(requestContext(aiRoot, resourceGroup, bearer, controller.signal, rejectedToken)))()
|
||||
work.catch(() => {})
|
||||
try {
|
||||
return await Promise.race([work, stop])
|
||||
} catch (error) {
|
||||
abort(failure("cancelled"))
|
||||
throw safeFailure(error)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
controller.signal.removeEventListener("abort", onAbort)
|
||||
signal?.removeEventListener("abort", relay)
|
||||
}
|
||||
}
|
||||
|
||||
// test-only: exposes the raw pre-enrichment collection phase for tests.
|
||||
// Production uses discover(), which runs collection and enrichment together.
|
||||
export async function listDeployments(request = {}) {
|
||||
return operation(request, collect)
|
||||
}
|
||||
|
||||
export function isPermittedModel(modelName) {
|
||||
if (typeof modelName !== "string") return false
|
||||
const match = /^gpt-(\d+)(?:\.\d+)*(?:-[a-z0-9]+)*$/.exec(modelName)
|
||||
return match !== null && match[0] === modelName && Number(match[1]) >= 6
|
||||
}
|
||||
|
||||
function deploymentUrl(raw, origin, id) {
|
||||
if (typeof raw !== "string" || !/^https:\/\//i.test(raw) ||
|
||||
/[\x00-\x20\x7f-\x9f\\\s?#]/.test(raw) || /%(?:2f|5c|2e)/i.test(raw)) return null
|
||||
let url
|
||||
try { url = new URL(raw) } catch { return null }
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.port ||
|
||||
url.search || url.hash || url.origin !== origin) return null
|
||||
const path = "/v2/inference/deployments/" + id
|
||||
if (url.pathname !== path || raw !== origin + path) return null
|
||||
return raw
|
||||
}
|
||||
|
||||
const EXECUTABLES = new Set(["azure-openai", "aws-bedrock"])
|
||||
|
||||
function resolveIdentity(deployment, configuration) {
|
||||
if (!isObject(configuration)) return null
|
||||
if (typeof configuration.executableId !== "string" || configuration.scenarioId !== "foundation-models" || !EXECUTABLES.has(configuration.executableId)) return null
|
||||
const executableId = configuration.executableId
|
||||
if (deployment.scenarioId !== undefined && deployment.scenarioId !== "foundation-models") return null
|
||||
if (deployment.executableId !== undefined && deployment.executableId !== executableId) return null
|
||||
|
||||
const bindings = configuration.parameterBindings
|
||||
if (!Array.isArray(bindings)) return null
|
||||
for (const b of bindings) {
|
||||
if (!isObject(b) || typeof b.key !== "string" || typeof b.value !== "string") return null
|
||||
}
|
||||
const names = bindings.filter(b => b.key === "modelName")
|
||||
const versions = bindings.filter(b => b.key === "modelVersion")
|
||||
if (names.length !== 1 || versions.length > 1) return null
|
||||
const modelName = names[0].value
|
||||
if (!modelName) return null
|
||||
let configuredVersion = "latest"
|
||||
if (versions.length === 1) {
|
||||
if (!versions[0].value) return null
|
||||
configuredVersion = versions[0].value
|
||||
}
|
||||
|
||||
let configurationID = null
|
||||
if (configuration.id !== undefined) {
|
||||
if (!safeId(configuration.id)) return null
|
||||
configurationID = configuration.id
|
||||
}
|
||||
if (deployment.configurationId !== undefined) {
|
||||
if (!safeId(deployment.configurationId)) return null
|
||||
if (configurationID !== null && configurationID !== deployment.configurationId) return null
|
||||
configurationID ??= deployment.configurationId
|
||||
}
|
||||
return { modelName, configuredVersion, configurationID, executableId }
|
||||
}
|
||||
|
||||
// Resolve the concrete backend version, reconciling any configured pin.
|
||||
function resolveActive(deployment, modelName, configuredVersion) {
|
||||
const backend = deployment?.details?.resources?.backendDetails?.model
|
||||
if (!isObject(backend)) return null
|
||||
if (typeof backend.name !== "string" || backend.name !== modelName) return null
|
||||
const version = backend.version
|
||||
if (typeof version !== "string" || !version || version === "latest") return null
|
||||
if (configuredVersion !== "latest" && configuredVersion !== version) return null
|
||||
return version
|
||||
}
|
||||
|
||||
function dateUTC(y, mo, da) {
|
||||
const t = Date.UTC(y, mo - 1, da)
|
||||
const d = new Date(t)
|
||||
return d.getUTCFullYear() === y && d.getUTCMonth() === mo - 1 && d.getUTCDate() === da ? t : null
|
||||
}
|
||||
|
||||
export function parseDate(s) {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s)
|
||||
return m ? dateUTC(Number(m[1]), Number(m[2]), Number(m[3])) : null
|
||||
}
|
||||
|
||||
function todayUTC() {
|
||||
const now = new Date()
|
||||
return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
|
||||
}
|
||||
|
||||
function scenariosAllow(scenarios, executableId) {
|
||||
if (!Array.isArray(scenarios)) return false
|
||||
for (const s of scenarios) {
|
||||
if (!isObject(s) || typeof s.scenarioId !== "string" || typeof s.executableId !== "string") return false
|
||||
}
|
||||
return scenarios.some(s => s.scenarioId === "foundation-models" && s.executableId === executableId)
|
||||
}
|
||||
|
||||
// The single, validated catalog model entry for this model under its executable.
|
||||
function catalogModel(catalog, modelName, executableId) {
|
||||
if (!isObject(catalog) || !Array.isArray(catalog.resources)) return null
|
||||
if (catalog.count !== undefined && !(Number.isSafeInteger(catalog.count) && Number(catalog.count) >= 0)) return null
|
||||
const models = catalog.resources.filter(r => isObject(r) && r.model === modelName)
|
||||
if (models.length !== 1) return null
|
||||
const model = models[0]
|
||||
if (model.executableId !== undefined && model.executableId !== executableId) return null
|
||||
if (!scenariosAllow(model.allowedScenarios, executableId)) return null
|
||||
return model
|
||||
}
|
||||
|
||||
// Version-matched metadata for a validated catalog model entry. Facts are taken
|
||||
// from the concrete resolved version, never inherited across versions/models.
|
||||
function resolveMetadata(model, activeVersion, executableId) {
|
||||
if (!Array.isArray(model.versions)) return null
|
||||
const matched = model.versions.filter(v => isObject(v) && v.name === activeVersion)
|
||||
if (matched.length !== 1) return null
|
||||
const version = matched[0]
|
||||
|
||||
if (version.deprecated !== undefined && typeof version.deprecated !== "boolean") return null
|
||||
if (version.deprecated === true) return null
|
||||
if (version.isLatest !== undefined && typeof version.isLatest !== "boolean") return null
|
||||
if (version.allowedScenarios !== undefined && !scenariosAllow(version.allowedScenarios, executableId)) return null
|
||||
if (version.streamingSupported !== undefined) {
|
||||
if (typeof version.streamingSupported !== "boolean") return null
|
||||
}
|
||||
if (version.inputTypes !== undefined) {
|
||||
if (!Array.isArray(version.inputTypes) || !version.inputTypes.every(t => typeof t === "string")) return null
|
||||
if (!version.inputTypes.includes("text")) return null
|
||||
}
|
||||
|
||||
const metadata = {}
|
||||
if (version.contextLength !== undefined) {
|
||||
if (!Number.isSafeInteger(version.contextLength) || version.contextLength <= 0) return null
|
||||
metadata.contextLength = version.contextLength
|
||||
}
|
||||
if (version.retirementDate !== undefined) {
|
||||
if (typeof version.retirementDate !== "string") return null
|
||||
if (version.retirementDate !== "") {
|
||||
const retires = parseDate(version.retirementDate)
|
||||
if (retires === null || retires <= todayUTC()) return null
|
||||
metadata.retirementDate = version.retirementDate
|
||||
}
|
||||
}
|
||||
if (version.streamingSupported !== undefined) metadata.streamingSupported = version.streamingSupported
|
||||
if (version.deprecated !== undefined) metadata.deprecated = version.deprecated
|
||||
if (version.inputTypes !== undefined) metadata.inputTypes = Object.freeze([...version.inputTypes])
|
||||
return metadata
|
||||
}
|
||||
|
||||
function freezeEntry(deployment, identity, url, activeVersion, metadata, extra) {
|
||||
const entry = {
|
||||
...extra,
|
||||
modelName: identity.modelName,
|
||||
deploymentID: deployment.id,
|
||||
deploymentURL: url,
|
||||
configuredVersion: identity.configuredVersion,
|
||||
activeVersion,
|
||||
activeEvidence: "deployment-backend",
|
||||
scenarioID: "foundation-models",
|
||||
executableID: identity.executableId,
|
||||
}
|
||||
if (identity.configurationID !== null) entry.configurationID = identity.configurationID
|
||||
if (Object.keys(metadata).length) entry.metadata = Object.freeze(metadata)
|
||||
return Object.freeze(entry)
|
||||
}
|
||||
|
||||
// GPT major version >= 6, OpenAI Responses on /responses.
|
||||
function resolveResponses(deployment, identity, model, url) {
|
||||
if (!isPermittedModel(identity.modelName)) return null
|
||||
const activeVersion = resolveActive(deployment, identity.modelName, identity.configuredVersion)
|
||||
if (activeVersion === null) return null
|
||||
const metadata = resolveMetadata(model, activeVersion, "azure-openai")
|
||||
if (metadata === null || metadata.streamingSupported === false) return null
|
||||
return freezeEntry(deployment, identity, url, activeVersion, metadata, {
|
||||
protocol: "responses",
|
||||
canonicalID: identity.modelName,
|
||||
displayLabel: identity.modelName,
|
||||
apiNpm: "@ai-sdk/openai",
|
||||
routePolicy: Object.freeze({ path: "/responses", query: false }),
|
||||
capabilities: Object.freeze({ text: true, functionTool: true, streaming: true, image: metadata.inputTypes?.includes("image") === true }),
|
||||
})
|
||||
}
|
||||
// Verified request-policy baselines. Emitted only for the two live-verified
|
||||
// baseline canonical IDs at their verified active version "1"; newer versions
|
||||
// never inherit these controls or the 128000 output maximum.
|
||||
const BASELINE_POLICY = {
|
||||
"claude-opus-4-8": { maxOutputTokens: 128000, rejectTemperature: true, rejectTopP: true, rejectEnabledThinking: true },
|
||||
"claude-sonnet-4-6": { maxOutputTokens: 128000, rejectCombinedSampling: true, rejectForcedToolThinking: true },
|
||||
}
|
||||
|
||||
// Identity evidence kept out of the public frozen entry: true when the canonical
|
||||
// ID was established from authoritative display metadata rather than SAP-format
|
||||
// fallback. Discovery's collision rule consults it; transport never sees it.
|
||||
const IDENTITY_AUTHORITATIVE = new WeakMap()
|
||||
|
||||
function baselinePolicy(canonicalID, activeVersion) {
|
||||
if (activeVersion !== "1" || !Object.hasOwn(BASELINE_POLICY, canonicalID)) return null
|
||||
return Object.freeze({ ...BASELINE_POLICY[canonicalID] })
|
||||
}
|
||||
|
||||
// Claude: contract-based family rule (no model/version allowlist), native
|
||||
// Anthropic Messages on the Bedrock invoke endpoints. The canonical agent-facing
|
||||
// ID is resolved from model metadata; the raw SAP identity stays in the entry
|
||||
// for version reconciliation and account-local routing but is opaque to
|
||||
// transport. A Claude deployment whose canonical identity cannot be resolved is
|
||||
// an observable discovery error, not a silent omission.
|
||||
function resolveAnthropic(deployment, identity, model, url) {
|
||||
const activeVersion = resolveActive(deployment, identity.modelName, identity.configuredVersion)
|
||||
if (activeVersion === null) return null
|
||||
const metadata = resolveMetadata(model, activeVersion, "aws-bedrock")
|
||||
if (metadata === null) return null
|
||||
// Preserve raw metadata so malformed types fail closed rather than becoming absent.
|
||||
if (!claudeFamily({ provider: model.provider, sapIdentity: identity.modelName, displayName: model.displayName })) return null
|
||||
const resolved = resolveCanonicalClaude({ sapIdentity: identity.modelName, displayName: model.displayName })
|
||||
if (resolved === null) throw failure("identity")
|
||||
const requestPolicy = baselinePolicy(resolved.canonicalID, activeVersion)
|
||||
const entry = freezeEntry(deployment, identity, url, activeVersion, metadata, {
|
||||
protocol: "anthropic",
|
||||
canonicalID: resolved.canonicalID,
|
||||
displayLabel: resolved.displayLabel,
|
||||
apiNpm: "@ai-sdk/anthropic",
|
||||
routePolicy: Object.freeze({ invoke: "/invoke", stream: "/invoke-with-response-stream", query: false }),
|
||||
capabilities: Object.freeze({ text: true, functionTool: true, streaming: metadata.streamingSupported === true, image: metadata.inputTypes?.includes("image") === true }),
|
||||
...(requestPolicy ? { requestPolicy } : {}),
|
||||
})
|
||||
IDENTITY_AUTHORITATIVE.set(entry, typeof model.displayName === "string" && model.displayName.trim() !== "")
|
||||
return entry
|
||||
}
|
||||
|
||||
/** @param {{deployment?: any, configuration?: any, catalog?: any, aiRoot?: string}} request */
|
||||
export function resolveDeployment({ deployment, configuration, catalog, aiRoot } = {}) {
|
||||
const origin = rootOrigin(aiRoot)
|
||||
if (origin === null || !isObject(deployment) || deployment.status !== "RUNNING") return null
|
||||
if (!safeId(deployment.id)) return null
|
||||
|
||||
const url = deploymentUrl(deployment.deploymentUrl, origin, deployment.id)
|
||||
if (url === null) return null
|
||||
|
||||
const identity = resolveIdentity(deployment, configuration)
|
||||
if (identity === null) return null
|
||||
|
||||
const model = catalogModel(catalog, identity.modelName, identity.executableId)
|
||||
if (model === null) return null
|
||||
|
||||
if (identity.executableId === "azure-openai") return resolveResponses(deployment, identity, model, url)
|
||||
if (identity.executableId === "aws-bedrock") return resolveAnthropic(deployment, identity, model, url)
|
||||
return null
|
||||
}
|
||||
|
||||
const CATALOG_PATH = "/v2/lm/scenarios/foundation-models/models"
|
||||
const CONFIGURATION_PATH = "/v2/lm/configurations/"
|
||||
const DEPLOYMENT_PATH = "/v2/lm/deployments/"
|
||||
|
||||
const backendModel = d => d?.details?.resources?.backendDetails?.model
|
||||
|
||||
function backendMalformed(d) {
|
||||
if (d.details === undefined) return false
|
||||
if (!isObject(d.details)) return true
|
||||
if (d.details.resources === undefined) return false
|
||||
if (!isObject(d.details.resources)) return true
|
||||
if (d.details.resources.backendDetails === undefined) return false
|
||||
if (!isObject(d.details.resources.backendDetails)) return true
|
||||
const model = d.details.resources.backendDetails.model
|
||||
if (model === undefined) return false
|
||||
if (!isObject(model)) return true
|
||||
if (model.name !== undefined && typeof model.name !== "string") return true
|
||||
if (model.version !== undefined && typeof model.version !== "string") return true
|
||||
return false
|
||||
}
|
||||
|
||||
function listIneligible(row, origin) {
|
||||
if (typeof row.status !== "string" || row.status === "") throw failure("response")
|
||||
if (row.status !== "RUNNING") return true
|
||||
if (row.scenarioId !== undefined && row.scenarioId !== "foundation-models") return true
|
||||
if (row.executableId !== undefined && !EXECUTABLES.has(row.executableId)) return true
|
||||
if (row.deploymentUrl !== undefined && deploymentUrl(row.deploymentUrl, origin, row.id) === null) return true
|
||||
if (row.configurationId !== undefined && !safeId(row.configurationId)) return true
|
||||
if (backendMalformed(row)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
function listComplete(row) {
|
||||
const model = backendModel(row)
|
||||
return row.deploymentUrl !== undefined && row.configurationId !== undefined &&
|
||||
typeof model?.name === "string" && typeof model?.version === "string"
|
||||
}
|
||||
|
||||
function structuredDetail(detail, id) {
|
||||
if (!isObject(detail) || detail.id !== id || typeof detail.status !== "string") return false
|
||||
for (const key of ["configurationId", "deploymentUrl", "scenarioId", "executableId"]) {
|
||||
if (detail[key] !== undefined && typeof detail[key] !== "string") return false
|
||||
}
|
||||
return !backendMalformed(detail)
|
||||
}
|
||||
|
||||
function repair(row, detail, origin) {
|
||||
if (!structuredDetail(detail, row.id)) throw failure("response")
|
||||
if (detail.status !== row.status) return null
|
||||
|
||||
const merged = { ...row }
|
||||
|
||||
if (detail.configurationId !== undefined) {
|
||||
if (!safeId(detail.configurationId)) return null
|
||||
if (row.configurationId === undefined) merged.configurationId = detail.configurationId
|
||||
else if (row.configurationId !== detail.configurationId) return null
|
||||
}
|
||||
if (merged.configurationId === undefined) return null
|
||||
|
||||
if (detail.deploymentUrl !== undefined) {
|
||||
const url = deploymentUrl(detail.deploymentUrl, origin, row.id)
|
||||
if (url === null) return null
|
||||
if (row.deploymentUrl === undefined) merged.deploymentUrl = url
|
||||
else if (deploymentUrl(row.deploymentUrl, origin, row.id) !== url) return null
|
||||
}
|
||||
if (merged.deploymentUrl === undefined) return null
|
||||
|
||||
for (const key of ["scenarioId", "executableId"]) {
|
||||
if (detail[key] === undefined) continue
|
||||
if (row[key] === undefined) merged[key] = detail[key]
|
||||
else if (row[key] !== detail[key]) return null
|
||||
}
|
||||
|
||||
const detailModel = backendModel(detail)
|
||||
if (detailModel !== undefined) {
|
||||
const listModel = backendModel(row)
|
||||
const model = {}
|
||||
for (const field of ["name", "version"]) {
|
||||
const listVal = listModel?.[field]
|
||||
const detailVal = detailModel[field]
|
||||
if (listVal !== undefined && detailVal !== undefined && listVal !== detailVal) return null
|
||||
const value = detailVal ?? listVal
|
||||
if (value !== undefined) model[field] = value
|
||||
}
|
||||
merged.details = { resources: { backendDetails: { model } } }
|
||||
}
|
||||
if (!isObject(backendModel(merged))) return null
|
||||
|
||||
return merged
|
||||
}
|
||||
|
||||
async function candidate(context, row) {
|
||||
if (listIneligible(row, context.origin)) return null
|
||||
if (listComplete(row)) return row
|
||||
return repair(row, await requestJSON(context, DEPLOYMENT_PATH + row.id), context.origin)
|
||||
}
|
||||
|
||||
function structuredConfiguration(json, configurationId) {
|
||||
if (!isObject(json)) return false
|
||||
if (typeof json.scenarioId !== "string" || typeof json.executableId !== "string") return false
|
||||
if (!Array.isArray(json.parameterBindings)) return false
|
||||
for (const b of json.parameterBindings) {
|
||||
if (!isObject(b) || typeof b.key !== "string" || typeof b.value !== "string") return false
|
||||
}
|
||||
if (json.id !== undefined && (!safeId(json.id) || json.id !== configurationId)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
// The memo caches the in-flight promise, not the resolved value, so concurrent
|
||||
// enrichment workers asking for the same configuration or the catalog share one
|
||||
// fetch rather than each issuing its own.
|
||||
function configuration(context, memo, configurationId) {
|
||||
if (!memo.has(configurationId)) {
|
||||
memo.set(configurationId, (async () => {
|
||||
const json = await requestJSON(context, CONFIGURATION_PATH + configurationId)
|
||||
if (!structuredConfiguration(json, configurationId)) throw failure("response")
|
||||
return json
|
||||
})())
|
||||
}
|
||||
return memo.get(configurationId)
|
||||
}
|
||||
|
||||
function catalog(context, memo) {
|
||||
if (memo.catalog === undefined) {
|
||||
memo.catalog = (async () => {
|
||||
const json = await requestJSON(context, CATALOG_PATH)
|
||||
pageRows(json)
|
||||
return json
|
||||
})()
|
||||
}
|
||||
return memo.catalog
|
||||
}
|
||||
|
||||
// Resolve up to ENRICH_CONCURRENCY rows at once, preserving input order in the
|
||||
// results. The first failure stops new work from being picked up and is rethrown
|
||||
// once in-flight work settles; the operation's shared signal aborts the rest.
|
||||
const ENRICH_CONCURRENCY = 8
|
||||
|
||||
async function mapBounded(items, limit, fn) {
|
||||
const results = new Array(items.length)
|
||||
let next = 0
|
||||
let failed = null
|
||||
async function worker() {
|
||||
while (failed === null) {
|
||||
const i = next++
|
||||
if (i >= items.length) return
|
||||
try { results[i] = await fn(items[i]) }
|
||||
catch (error) { if (failed === null) failed = error; return }
|
||||
}
|
||||
}
|
||||
const workers = []
|
||||
for (let i = 0; i < Math.min(limit, items.length); i++) workers.push(worker())
|
||||
await Promise.all(workers)
|
||||
if (failed !== null) throw failed
|
||||
return results
|
||||
}
|
||||
|
||||
// Conservative structural equality of the selection-relevant facts two entries
|
||||
// must share before distinct raw SAP identities may collapse to one canonical
|
||||
// ID. Any difference in protocol, version, capabilities, route, metadata or
|
||||
// request policy keeps them a conflict rather than an equivalence.
|
||||
const selectionShape = e =>
|
||||
JSON.stringify([e.protocol, e.activeVersion, e.executableID, e.capabilities, e.routePolicy,
|
||||
e.metadata ?? null, e.requestPolicy ?? null])
|
||||
const compatibleSelection = (a, b) => selectionShape(a) === selectionShape(b)
|
||||
|
||||
async function resolveRow(context, aiRoot, configs, catalogMemo, row) {
|
||||
const deployment = await candidate(context, row)
|
||||
if (deployment === null) return null
|
||||
return resolveDeployment({
|
||||
deployment,
|
||||
configuration: await configuration(context, configs, deployment.configurationId),
|
||||
catalog: await catalog(context, catalogMemo),
|
||||
aiRoot,
|
||||
})
|
||||
}
|
||||
|
||||
async function enrich(context, aiRoot, rows) {
|
||||
const configs = new Map()
|
||||
const catalogMemo = {}
|
||||
const chosen = new Map()
|
||||
// Rows are resolved concurrently but reduced in input order, so duplicate
|
||||
// selection (lowest deployment ID) and conflict detection stay deterministic.
|
||||
const entries = await mapBounded(rows, ENRICH_CONCURRENCY, row => resolveRow(context, aiRoot, configs, catalogMemo, row))
|
||||
for (const entry of entries) {
|
||||
if (entry === null) continue
|
||||
const prior = chosen.get(entry.canonicalID)
|
||||
if (prior === undefined) { chosen.set(entry.canonicalID, entry); continue }
|
||||
// GPT versions share a model ID; select the lowest eligible deployment ID.
|
||||
// Claude duplicates still require the same active version.
|
||||
const sameConcrete = prior.modelName === entry.modelName &&
|
||||
((prior.protocol === "responses" && entry.protocol === "responses") || prior.activeVersion === entry.activeVersion)
|
||||
// Distinct raw SAP identities may share one canonical ID only when both were
|
||||
// established from authoritative display metadata and select a compatible
|
||||
// model. A fallback-only equivalence, or any incompatibility (version,
|
||||
// protocol, capability, policy, metadata), is an observable identity
|
||||
// conflict rather than a guessed merge.
|
||||
if (!sameConcrete) {
|
||||
const equivalent = IDENTITY_AUTHORITATIVE.get(prior) === true &&
|
||||
IDENTITY_AUTHORITATIVE.get(entry) === true && compatibleSelection(prior, entry)
|
||||
if (!equivalent) throw failure("conflict")
|
||||
}
|
||||
if (entry.deploymentID < prior.deploymentID) chosen.set(entry.canonicalID, entry)
|
||||
}
|
||||
const registry = Object.create(null)
|
||||
for (const canonicalID of [...chosen.keys()].sort()) registry[canonicalID] = chosen.get(canonicalID)
|
||||
return Object.freeze(registry)
|
||||
}
|
||||
|
||||
export async function discover(request = {}) {
|
||||
return operation(request, async context => enrich(context, request.aiRoot, await collect(context)))
|
||||
}
|
||||
|
||||
export function projectModels(registry) {
|
||||
const catalog = {}
|
||||
for (const canonicalID of Object.keys(registry)) {
|
||||
const entry = registry[canonicalID]
|
||||
const model = {
|
||||
id: entry.canonicalID,
|
||||
name: entry.displayLabel,
|
||||
providerID: "sap-aicore",
|
||||
api: { id: entry.canonicalID, npm: entry.apiNpm },
|
||||
capabilities: {
|
||||
toolcall: entry.capabilities.functionTool === true,
|
||||
attachment: entry.capabilities.image === true,
|
||||
input: { text: true, image: entry.capabilities.image === true, audio: false, video: false, pdf: false },
|
||||
output: { text: true, image: false, audio: false, video: false, pdf: false },
|
||||
},
|
||||
}
|
||||
const contextLength = entry.metadata?.contextLength
|
||||
const maxOutput = entry.requestPolicy?.maxOutputTokens
|
||||
if (contextLength !== undefined || maxOutput !== undefined) {
|
||||
model.limit = {}
|
||||
if (contextLength !== undefined) model.limit.context = contextLength
|
||||
if (maxOutput !== undefined) model.limit.output = maxOutput
|
||||
}
|
||||
catalog[canonicalID] = model
|
||||
}
|
||||
return catalog
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Canonical Claude model identity resolution.
|
||||
//
|
||||
// This module is deliberately independent of transport, authentication and
|
||||
// capability policy (the single "metadata-first identity resolver" the spec
|
||||
// calls for). Discovery uses it to derive a stable, conventional agent-facing
|
||||
// model ID and a human display label from authoritative model metadata — the
|
||||
// catalog display name and provider — with a documented SAP-identity-format
|
||||
// fallback. The raw SAP identity stays opaque to transport, which never parses
|
||||
// it.
|
||||
//
|
||||
// A SAP prefix/delimiter/order or opaque-key change must not rename a model
|
||||
// when metadata still establishes the same underlying model; genuinely
|
||||
// ambiguous or conflicting evidence is reported (resolve returns null) rather
|
||||
// than guessed.
|
||||
|
||||
const VARIANTS = new Set(["opus", "sonnet", "haiku"])
|
||||
// Hyphenated numeric release segments normalize to dots. An eight-digit trailing
|
||||
// date remains a suffix rather than becoming another release segment.
|
||||
const VERSION = "\\d+(?:\\.\\d+|-(?!\\d{8}(?:[\\s_-]|$))\\d+)*"
|
||||
const VARIANT = "opus|sonnet|haiku"
|
||||
// "Claude 4.8 Opus [suffix]" and "Claude Opus 4.8 [suffix]". The separator is
|
||||
// whitespace, hyphen or underscore so both display names and SAP identities
|
||||
// (after their provider prefix is stripped) run through the same recognizer.
|
||||
const VERSION_FIRST = new RegExp(`^claude[\\s_-]+(${VERSION})[\\s_-]+(${VARIANT})((?:[\\s_-]+[a-z0-9]+)*)$`, "i")
|
||||
const VARIANT_FIRST = new RegExp(`^claude[\\s_-]+(${VARIANT})[\\s_-]+(${VERSION})((?:[\\s_-]+[a-z0-9]+)*)$`, "i")
|
||||
// Observed current SAP identity format: an opaque provider prefix joined by a
|
||||
// delimiter, e.g. "anthropic--claude-4.8-opus". The prefix is opaque and
|
||||
// optional; only the Claude remainder is parsed.
|
||||
const PROVIDER_PREFIX = /^[a-z0-9]+(?:--|__|::|\/)/i
|
||||
|
||||
const capitalize = word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
|
||||
|
||||
/**
|
||||
* Normalize extra trailing tokens (date/preview/variant suffixes) captured
|
||||
* after the variant+version. Returns lowercase tokens for the ID and the
|
||||
* original-cased tokens for the label.
|
||||
* @param {string} rest
|
||||
*/
|
||||
function suffixTokens(rest) {
|
||||
return rest.split(/[\s_-]+/).filter(Boolean)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the canonical ID and display label from a parsed (variant, version,
|
||||
* suffix tokens) tuple. Version dots become hyphens; family, full release and
|
||||
* any meaningful suffix are preserved.
|
||||
* @param {string} variant
|
||||
* @param {string} version
|
||||
* @param {string[]} suffix
|
||||
*/
|
||||
function compose(variant, version, suffix) {
|
||||
const v = variant.toLowerCase()
|
||||
if (!VARIANTS.has(v)) return null
|
||||
const release = version.replace(/\./g, "-")
|
||||
const dotted = version.replace(/-/g, ".")
|
||||
const idSuffix = suffix.map(t => t.toLowerCase())
|
||||
const canonicalID = ["claude", v, release, ...idSuffix].join("-")
|
||||
const labelSuffix = suffix.length ? " " + suffix.join(" ") : ""
|
||||
const displayLabel = `Claude ${capitalize(v)} ${dotted}${labelSuffix}`
|
||||
return { canonicalID, displayLabel }
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a Claude label/identity remainder in either version-first or
|
||||
* variant-first order.
|
||||
* @param {string} text
|
||||
*/
|
||||
function parse(text) {
|
||||
const m = VERSION_FIRST.exec(text) ?? null
|
||||
if (m) return compose(m[2], m[1], suffixTokens(m[3]))
|
||||
const n = VARIANT_FIRST.exec(text)
|
||||
if (n) return compose(n[1], n[2], suffixTokens(n[3]))
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this deployment's metadata identify it as an Anthropic Claude model?
|
||||
* Provider or an unambiguous Claude identity/label qualifies; executable alone
|
||||
* does not (Titan/Nova are also aws-bedrock and out of scope).
|
||||
* @param {{ provider?: unknown, sapIdentity?: unknown, displayName?: unknown }} evidence
|
||||
*/
|
||||
export function claudeFamily({ provider, sapIdentity, displayName } = {}) {
|
||||
if (provider !== undefined) {
|
||||
if (typeof provider !== "string" || provider.trim().toLowerCase() !== "anthropic") return false
|
||||
}
|
||||
if (displayName !== undefined && typeof displayName !== "string") return false
|
||||
if (sapIdentity !== undefined && typeof sapIdentity !== "string") return false
|
||||
if (provider !== undefined) return true
|
||||
if (typeof sapIdentity === "string" && /(?:^|[^a-z])claude(?:[^a-z]|$)/i.test(sapIdentity)) return true
|
||||
if (typeof displayName === "string" && /(?:^|[^a-z])claude(?:[^a-z]|$)/i.test(displayName)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
// Two resolutions describe the same model when their canonical ID matches; a
|
||||
// formatting-only label difference (token order, spacing) is not a conflict.
|
||||
const resultsAgree = (a, b) => a.canonicalID === b.canonicalID
|
||||
|
||||
|
||||
/**
|
||||
* Resolve the canonical agent-facing ID and display label for a Claude model.
|
||||
* The catalog display name is authoritative metadata; the SAP identity format
|
||||
* is a documented fallback used only when no display name is present. A present
|
||||
* but non-empty display name that cannot be parsed, non-string evidence, or a
|
||||
* display/identity canonical-ID disagreement is ambiguous and resolves to null
|
||||
* rather than a guess.
|
||||
* @param {{ sapIdentity?: unknown, displayName?: unknown }} evidence
|
||||
* @returns {{ canonicalID: string, displayLabel: string } | null}
|
||||
*/
|
||||
export function resolveCanonicalClaude({ sapIdentity, displayName } = {}) {
|
||||
if (displayName !== undefined && typeof displayName !== "string") return null
|
||||
if (sapIdentity !== undefined && typeof sapIdentity !== "string") return null
|
||||
|
||||
const displayText = typeof displayName === "string" ? displayName.trim() : ""
|
||||
const fromDisplay = displayText ? parse(displayText) : null
|
||||
if (displayText && fromDisplay === null) return null
|
||||
|
||||
let fromIdentity = null
|
||||
if (typeof sapIdentity === "string" && sapIdentity.trim()) {
|
||||
fromIdentity = parse(sapIdentity.trim().replace(PROVIDER_PREFIX, ""))
|
||||
}
|
||||
|
||||
if (fromDisplay) {
|
||||
if (fromIdentity && !resultsAgree(fromDisplay, fromIdentity)) return null
|
||||
return fromDisplay
|
||||
}
|
||||
if (fromIdentity) return fromIdentity
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,724 @@
|
||||
import fs from "node:fs"
|
||||
import { open } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { createHash } from "node:crypto"
|
||||
import { discover, projectModels, isPermittedModel, parseDate } from "./discovery.js"
|
||||
import { validateRequest, dispatch, responseError } from "./responses.js"
|
||||
import { validateRequest as validateMessagesRequest, dispatch as messagesDispatch } from "./messages.js"
|
||||
import { readJSONRequest } from "./transport.js"
|
||||
import { pluginRevision } from "./revision.js"
|
||||
|
||||
// Per-protocol transports keyed by the registry entry's protocol. The account
|
||||
// lifecycle, discovery, token ownership and cancellation around them are shared;
|
||||
// only request parsing and dispatch differ per native protocol.
|
||||
const TRANSPORTS = {
|
||||
responses: { validateRequest, dispatch },
|
||||
anthropic: { validateRequest: validateMessagesRequest, dispatch: messagesDispatch },
|
||||
}
|
||||
// Account-root client routes the host rewrites to, mapped to their protocol.
|
||||
const ROUTES = { "/responses": "responses", "/messages": "anthropic" }
|
||||
// Recognition for unavailable-model errors only; eligibility remains discovery's.
|
||||
const KNOWN_CLAUDE_MODELS = new Set(["claude-opus-4-8", "claude-sonnet-4-6"])
|
||||
|
||||
const PROVIDER_ID = "sap-aicore"
|
||||
const LABEL = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
|
||||
const AUTH_HOST = new RegExp(`^${LABEL}\\.authentication\\.${LABEL}\\.hana\\.ondemand\\.com$`)
|
||||
const AI_HOST = new RegExp(`^api\\.ai\\.${LABEL}(?:\\.${LABEL})*\\.hana\\.ondemand\\.com$`)
|
||||
const MAX_BYTES = 65536
|
||||
const TIMEOUT_MS = 15000
|
||||
const DEFAULT_IDLE_TIMEOUT_MS = 120000
|
||||
const DEFAULT_TOTAL_TIMEOUT_MS = 900000
|
||||
const MAX_TOTAL_TIMEOUT_MS = 3600000
|
||||
const ERRORS = {
|
||||
input: "SAP AI Core: invalid credential file path.",
|
||||
file: "SAP AI Core: credential file could not be read.",
|
||||
credentials: "SAP AI Core: credential file is invalid.",
|
||||
destination: "SAP AI Core: unsafe request destination.",
|
||||
"oauth-response": "SAP AI Core: token endpoint returned an unexpected response.",
|
||||
"oauth-refused": "SAP AI Core: sign-in was refused by the token endpoint.",
|
||||
network: "SAP AI Core: token endpoint could not be reached.",
|
||||
timeout: "SAP AI Core: token acquisition timed out.",
|
||||
cancelled: "SAP AI Core: token acquisition was cancelled.",
|
||||
superseded: "SAP AI Core: account was replaced before this operation completed.",
|
||||
"inference-timeout": "SAP AI Core: the inference request timed out.",
|
||||
"inference-idle-timeout": "SAP AI Core: the inference stream timed out while waiting for data.",
|
||||
"inference-cancelled": "SAP AI Core: the inference request was cancelled.",
|
||||
"unknown-model": "SAP AI Core: requested model has no verified available deployment.",
|
||||
"unavailable-model": "SAP AI Core: requested model has no verified running deployment.",
|
||||
}
|
||||
|
||||
const DISCOVERY_ERRORS = {
|
||||
destination: "SAP AI Core: model discovery used an unsafe destination.",
|
||||
response: "SAP AI Core: model discovery returned an unexpected response.",
|
||||
network: "SAP AI Core: model discovery could not be reached.",
|
||||
timeout: "SAP AI Core: model discovery timed out.",
|
||||
cancelled: "SAP AI Core: model discovery was cancelled.",
|
||||
exhausted: "SAP AI Core: model discovery exceeded its bounds.",
|
||||
identity: "SAP AI Core: a Claude deployment's model identity could not be resolved.",
|
||||
conflict: "SAP AI Core: distinct Claude deployments resolved to the same model identity.",
|
||||
}
|
||||
const OWNED_ERRORS = new WeakSet()
|
||||
|
||||
|
||||
/** @returns {Error & {code: string, status?: number, retryAfter?: string}} */
|
||||
function failure(code) {
|
||||
const error = Object.assign(new Error(ERRORS[code]), { code })
|
||||
OWNED_ERRORS.add(error)
|
||||
return error
|
||||
}
|
||||
|
||||
function discoveryFailure(error) {
|
||||
const code = Object.hasOwn(DISCOVERY_ERRORS, error?.code) ? error.code : "response"
|
||||
/** @type {Error & {code: string, status?: number, retryAfter?: string}} */
|
||||
const safe = Object.assign(new Error(DISCOVERY_ERRORS[code]), { code: "discovery-" + code, status: code === "cancelled" ? 499 : code === "timeout" ? 504 : 502 })
|
||||
if (Number.isInteger(error?.status) && error.status >= 400 && error.status <= 599) safe.status = error.status
|
||||
if (/^\d{1,10}$/.test(error?.retryAfter ?? "")) safe.retryAfter = error.retryAfter
|
||||
OWNED_ERRORS.add(safe)
|
||||
return safe
|
||||
}
|
||||
|
||||
function safeFailure(error) {
|
||||
return OWNED_ERRORS.has(error) ? error : failure("network")
|
||||
}
|
||||
|
||||
const DISCOVERY_TTL_MS = 300000
|
||||
|
||||
function retireAtOf(entries) {
|
||||
let soonest
|
||||
for (const name of Object.keys(entries)) {
|
||||
const at = parseDate(entries[name]?.metadata?.retirementDate ?? "")
|
||||
if (at === null) continue
|
||||
if (soonest === undefined || at < soonest) soonest = at
|
||||
}
|
||||
return soonest
|
||||
}
|
||||
|
||||
function credentialPath(value) {
|
||||
if (typeof value !== "string" || !value || value.includes("\0") || !path.isAbsolute(value)) {
|
||||
throw failure("input")
|
||||
}
|
||||
return path.normalize(value)
|
||||
}
|
||||
|
||||
function reference(credentialFile) {
|
||||
const normalized = credentialPath(credentialFile)
|
||||
return {
|
||||
credentialFile: normalized,
|
||||
key: "sap-aicore:path:" + createHash("sha256").update("sap-aicore:path:" + normalized).digest("hex"),
|
||||
}
|
||||
}
|
||||
|
||||
function storedReference(auth) {
|
||||
if (auth?.type !== "api") throw failure("credentials")
|
||||
const ref = reference(auth.metadata?.credentialFile)
|
||||
if (auth.key !== ref.key) throw failure("credentials")
|
||||
return ref
|
||||
}
|
||||
|
||||
function serviceURL(raw) {
|
||||
if (typeof raw !== "string" || !/^https:\/\//i.test(raw) || /[\x00-\x20\x7f-\x9f\\\s?#]/.test(raw)) {
|
||||
throw failure("destination")
|
||||
}
|
||||
if (/%(?:2f|5c|2e)/i.test(raw) || /\/(?:\.|\.\.)(?:\/|$)/.test(raw)) throw failure("destination")
|
||||
let url
|
||||
try { url = new URL(raw) } catch { throw failure("destination") }
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.port || url.search || url.hash) {
|
||||
throw failure("destination")
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
function root(raw, auth) {
|
||||
const url = serviceURL(raw)
|
||||
if (!(auth ? AUTH_HOST : AI_HOST).test(url.hostname)) throw failure("credentials")
|
||||
const suffix = auth ? "/oauth/token" : "/v2"
|
||||
if (!["/", suffix].includes(url.pathname)) throw failure("credentials")
|
||||
return url.origin
|
||||
}
|
||||
|
||||
function credentials(bytes) {
|
||||
let value
|
||||
try { value = JSON.parse(bytes) } catch { throw failure("credentials") }
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw failure("credentials")
|
||||
for (const field of ["authUrl", "baseUrl", "clientId", "clientSecret", "resourceGroup"]) {
|
||||
if (typeof value[field] !== "string" || !value[field].trim()) throw failure("credentials")
|
||||
}
|
||||
for (const field of ["clientId", "clientSecret"]) {
|
||||
// Limit raw Basic credentials to the supported unambiguous subset.
|
||||
if (/[:\x00-\x1f\x7f-\x9f]/.test(value[field]) || !value[field].isWellFormed()) throw failure("credentials")
|
||||
}
|
||||
if (!/^[\x21-\x7e]+$/.test(value.resourceGroup)) throw failure("credentials")
|
||||
try {
|
||||
return {
|
||||
tokenURL: root(value.authUrl, true) + "/oauth/token",
|
||||
aiRoot: root(value.baseUrl, false),
|
||||
clientId: value.clientId,
|
||||
clientSecret: value.clientSecret,
|
||||
resourceGroup: value.resourceGroup,
|
||||
}
|
||||
} catch { throw failure("credentials") }
|
||||
}
|
||||
|
||||
async function bounded(operation, controller) {
|
||||
let timer
|
||||
let onAbort
|
||||
const stop = new Promise((_, reject) => {
|
||||
onAbort = () => reject(controller.signal.reason?.code ? controller.signal.reason : failure("cancelled"))
|
||||
controller.signal.addEventListener("abort", onAbort, { once: true })
|
||||
timer = setTimeout(() => controller.abort(failure("timeout")), TIMEOUT_MS)
|
||||
})
|
||||
try {
|
||||
if (controller.signal.aborted) throw controller.signal.reason ?? failure("cancelled")
|
||||
return await Promise.race([Promise.resolve().then(operation), stop])
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
controller.signal.removeEventListener("abort", onAbort)
|
||||
}
|
||||
}
|
||||
|
||||
async function readCredentials(file, controller) {
|
||||
return bounded(async () => {
|
||||
let handle
|
||||
try {
|
||||
// Nonblocking open prevents a FIFO from occupying an fs worker before its type is checked.
|
||||
handle = await open(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0))
|
||||
if (controller.signal.aborted) throw failure("cancelled")
|
||||
const stat = await handle.stat()
|
||||
if (!stat.isFile() || stat.size > MAX_BYTES) throw failure("file")
|
||||
const bytes = Buffer.alloc(MAX_BYTES + 1)
|
||||
let size = 0
|
||||
while (size < bytes.length) {
|
||||
if (controller.signal.aborted) throw failure("cancelled")
|
||||
const { bytesRead } = await handle.read(bytes, size, bytes.length - size, size)
|
||||
if (!bytesRead) break
|
||||
size += bytesRead
|
||||
}
|
||||
if (size > MAX_BYTES) throw failure("file")
|
||||
return credentials(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size)))
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) throw controller.signal.reason ?? failure("cancelled")
|
||||
throw error?.code && Object.hasOwn(ERRORS, error.code) ? error : failure("file")
|
||||
} finally {
|
||||
if (handle) await handle.close().catch(() => {})
|
||||
}
|
||||
}, controller)
|
||||
}
|
||||
|
||||
async function responseJSON(response, signal) {
|
||||
const reader = response.body?.getReader()
|
||||
if (!reader) throw failure("oauth-response")
|
||||
const chunks = []
|
||||
let size = 0
|
||||
const cancel = () => { void reader.cancel().catch(() => {}) }
|
||||
signal.addEventListener("abort", cancel, { once: true })
|
||||
try {
|
||||
for (;;) {
|
||||
if (signal.aborted) throw signal.reason ?? failure("cancelled")
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
size += value.byteLength
|
||||
if (size > MAX_BYTES) throw failure("oauth-response")
|
||||
chunks.push(value)
|
||||
}
|
||||
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)))
|
||||
} catch (error) {
|
||||
cancel()
|
||||
if (signal.aborted) throw signal.reason ?? failure("cancelled")
|
||||
throw failure("oauth-response")
|
||||
} finally {
|
||||
signal.removeEventListener("abort", cancel)
|
||||
reader.releaseLock()
|
||||
}
|
||||
}
|
||||
|
||||
async function exchange(creds, controller) {
|
||||
return bounded(async () => {
|
||||
const started = performance.now()
|
||||
// Bun's macOS monotonic clock pauses during sleep; SAP token lifetime does not.
|
||||
const wallStarted = Date.now()
|
||||
let response
|
||||
try {
|
||||
response = await globalThis.fetch(creds.tokenURL, {
|
||||
method: "POST",
|
||||
redirect: "error",
|
||||
headers: {
|
||||
Authorization: "Basic " + Buffer.from(`${creds.clientId}:${creds.clientSecret}`, "utf8").toString("base64"),
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: "grant_type=client_credentials",
|
||||
signal: controller.signal,
|
||||
})
|
||||
} catch {
|
||||
if (controller.signal.aborted) throw controller.signal.reason ?? failure("cancelled")
|
||||
throw failure("network")
|
||||
}
|
||||
if (controller.signal.aborted) {
|
||||
void response.body?.cancel().catch(() => {})
|
||||
throw controller.signal.reason ?? failure("cancelled")
|
||||
}
|
||||
if (response.redirected || (response.url && response.url !== creds.tokenURL) || (response.status >= 300 && response.status < 400)) {
|
||||
void response.body?.cancel().catch(() => {})
|
||||
throw failure("oauth-response")
|
||||
}
|
||||
const oauthFailure = () => {
|
||||
const error = failure("oauth-response")
|
||||
if (response.status >= 400 && response.status <= 599) error.status = response.status
|
||||
const retryAfter = response.headers.get("retry-after")
|
||||
if (/^\d{1,10}$/.test(retryAfter ?? "")) error.retryAfter = retryAfter
|
||||
return error
|
||||
}
|
||||
let body
|
||||
try { body = await responseJSON(response, controller.signal) }
|
||||
catch (error) {
|
||||
if (controller.signal.aborted || response.ok) throw error
|
||||
throw oauthFailure()
|
||||
}
|
||||
if (response.status === 401 && body?.error === "invalid_client" && /^Basic(?:\s|$)/i.test(response.headers.get("www-authenticate") ?? "")) {
|
||||
throw Object.assign(failure("oauth-refused"), { status: 401 })
|
||||
}
|
||||
const lifetime = body?.expires_in * 1000
|
||||
if (!response.ok || typeof body?.access_token !== "string" || !/^[\x21-\x7e]+$/.test(body.access_token) ||
|
||||
typeof body.expires_in !== "number" || !Number.isFinite(lifetime) || lifetime <= 0 || lifetime > Number.MAX_SAFE_INTEGER ||
|
||||
(body.token_type !== undefined && (typeof body.token_type !== "string" || body.token_type.toLowerCase() !== "bearer"))) {
|
||||
throw oauthFailure()
|
||||
}
|
||||
const expiresAt = started + lifetime
|
||||
const wallExpiresAt = wallStarted + lifetime
|
||||
if (!Number.isFinite(expiresAt) || !Number.isFinite(wallExpiresAt) ||
|
||||
performance.now() >= expiresAt || Date.now() >= wallExpiresAt) throw failure("oauth-response")
|
||||
const margin = Math.min(60000, lifetime / 2)
|
||||
return { value: body.access_token, expiresAt, wallExpiresAt, renewAt: expiresAt - margin, wallRenewAt: wallExpiresAt - margin }
|
||||
}, controller)
|
||||
}
|
||||
|
||||
function requestTarget(input, init) {
|
||||
const request = input instanceof Request ? input : null
|
||||
const url = serviceURL(request ? request.url : String(input))
|
||||
const method = init?.method ?? request?.method ?? "GET"
|
||||
const protocol = Object.hasOwn(ROUTES, url.pathname) ? ROUTES[url.pathname] : undefined
|
||||
if (typeof method !== "string" || method.toUpperCase() !== "POST" ||
|
||||
!AI_HOST.test(url.hostname) || protocol === undefined) throw failure("destination")
|
||||
return { origin: url.origin, signal: init?.signal ?? request?.signal, protocol }
|
||||
}
|
||||
|
||||
const CREDENTIAL_HEADERS = new Set(["api-key", "x-api-key", "x-goog-api-key", "openai-api-key", "x-auth-token", "x-access-token", "client-secret", "x-client-secret"])
|
||||
|
||||
function incomingSecrets(input, init) {
|
||||
const secrets = []
|
||||
const headers = new Headers(input instanceof Request ? input.headers : undefined)
|
||||
new Headers(init?.headers).forEach((value, key) => headers.set(key, value))
|
||||
headers.forEach((value, key) => {
|
||||
if (key === "authorization" || key === "proxy-authorization") secrets.push(value, value.replace(/^\S+\s+/, ""))
|
||||
else if (CREDENTIAL_HEADERS.has(key)) secrets.push(value)
|
||||
})
|
||||
return secrets
|
||||
}
|
||||
|
||||
function clampTimeout(value, fallback) {
|
||||
if (typeof value !== "number" || Number.isNaN(value) || value <= 0) return fallback
|
||||
return Math.min(MAX_TOTAL_TIMEOUT_MS, Math.max(1, Math.floor(value)))
|
||||
}
|
||||
|
||||
export async function SAPAICorePlugin(input) {
|
||||
const generations = new Map()
|
||||
const candidates = new Map()
|
||||
let idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS
|
||||
let totalTimeoutMs = DEFAULT_TOTAL_TIMEOUT_MS
|
||||
|
||||
function applyTimeouts(source) {
|
||||
if (!source || typeof source !== "object") return
|
||||
for (const candidate of [source.options, source]) {
|
||||
if (!candidate || typeof candidate !== "object") continue
|
||||
const rawIdle = candidate.idleTimeoutMs ?? candidate.streamIdleTimeoutMs
|
||||
const rawTotal = candidate.totalTimeoutMs ?? candidate.inferenceTimeoutMs ?? candidate.timeoutMs
|
||||
if (rawIdle !== undefined) idleTimeoutMs = clampTimeout(rawIdle, idleTimeoutMs)
|
||||
if (rawTotal !== undefined) totalTimeoutMs = clampTimeout(rawTotal, totalTimeoutMs)
|
||||
else if (rawIdle !== undefined && totalTimeoutMs < idleTimeoutMs) totalTimeoutMs = idleTimeoutMs
|
||||
}
|
||||
}
|
||||
applyTimeouts(input?.config?.provider?.[PROVIDER_ID])
|
||||
applyTimeouts(input)
|
||||
|
||||
if (typeof input?.client?.app?.log === "function") {
|
||||
void pluginRevision().then(version => input.client.app.log({
|
||||
body: { service: PROVIDER_ID, level: "info", message: `version ${version}` },
|
||||
})).catch(() => {})
|
||||
}
|
||||
|
||||
function generation(ref) {
|
||||
return { ref, credentials: null, token: null, flight: null, load: null, snapshot: null, discovery: null, retired: false, controller: new AbortController() }
|
||||
}
|
||||
|
||||
function retire(gen) {
|
||||
gen.retired = true
|
||||
gen.controller.abort(failure("superseded"))
|
||||
gen.flight?.controller.abort(failure("superseded"))
|
||||
gen.discovery?.controller.abort(failure("superseded"))
|
||||
gen.credentials = gen.token = gen.load = gen.flight = gen.snapshot = gen.discovery = null
|
||||
}
|
||||
|
||||
function current(gen) {
|
||||
if (gen.retired || (generations.get(gen.ref.key) !== gen && candidates.get(gen.ref.key) !== gen)) throw failure("superseded")
|
||||
}
|
||||
|
||||
function initialize(ref) {
|
||||
if (!generations.has(ref.key)) generations.set(ref.key, generation(ref))
|
||||
return generations.get(ref.key)
|
||||
}
|
||||
|
||||
async function loaded(gen) {
|
||||
current(gen)
|
||||
if (!gen.credentials) {
|
||||
if (!gen.load) {
|
||||
const load = readCredentials(gen.ref.credentialFile, gen.controller).then(creds => {
|
||||
current(gen)
|
||||
gen.credentials = creds
|
||||
})
|
||||
gen.load = load
|
||||
load.catch(() => {
|
||||
if (gen.load === load) {
|
||||
gen.load = null
|
||||
if (!gen.retired) gen.controller = new AbortController()
|
||||
}
|
||||
})
|
||||
}
|
||||
await gen.load
|
||||
current(gen)
|
||||
}
|
||||
}
|
||||
|
||||
async function tokenFor(gen, signal, check = async () => current(gen)) {
|
||||
current(gen)
|
||||
if (signal?.aborted) throw failure("cancelled")
|
||||
await check()
|
||||
if (gen.token && performance.now() < gen.token.renewAt && Date.now() < gen.token.wallRenewAt) return gen.token
|
||||
if (!gen.flight) {
|
||||
const flight = { controller: new AbortController(), owners: new Set(), result: null }
|
||||
gen.flight = flight
|
||||
flight.result = exchange(gen.credentials, flight.controller)
|
||||
// Observe rejection even if every request owner leaves before the exchange settles.
|
||||
flight.result.catch(() => {})
|
||||
}
|
||||
const flight = gen.flight
|
||||
const owner = Symbol()
|
||||
flight.owners.add(owner)
|
||||
let rejectAbort
|
||||
const aborted = new Promise((_, reject) => { rejectAbort = reject })
|
||||
const release = () => {
|
||||
flight.owners.delete(owner)
|
||||
if (!flight.owners.size && gen.flight === flight) {
|
||||
gen.flight = null
|
||||
flight.controller.abort(failure("cancelled"))
|
||||
}
|
||||
}
|
||||
const cancel = () => { release(); rejectAbort(failure("cancelled")) }
|
||||
signal?.addEventListener("abort", cancel, { once: true })
|
||||
try {
|
||||
if (signal?.aborted) throw failure("cancelled")
|
||||
const token = await Promise.race([flight.result, aborted])
|
||||
await check()
|
||||
current(gen)
|
||||
if (signal?.aborted) throw failure("cancelled")
|
||||
if (gen.flight !== flight || performance.now() >= token.expiresAt || Date.now() >= token.wallExpiresAt) throw failure("superseded")
|
||||
gen.token = token
|
||||
return token
|
||||
} catch (error) {
|
||||
await check()
|
||||
throw safeFailure(error)
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", cancel)
|
||||
release()
|
||||
}
|
||||
}
|
||||
|
||||
async function authorize(inputs) {
|
||||
let ref
|
||||
try {
|
||||
if (!inputs || typeof inputs !== "object" || Array.isArray(inputs) || Object.keys(inputs).length !== 1 || !Object.hasOwn(inputs, "credentialFile")) throw failure("input")
|
||||
ref = reference(inputs.credentialFile)
|
||||
} catch { return { type: "failed", error: ERRORS.input } }
|
||||
if (candidates.has(ref.key)) retire(candidates.get(ref.key))
|
||||
const gen = generation(ref)
|
||||
candidates.set(ref.key, gen)
|
||||
try {
|
||||
await loaded(gen)
|
||||
await tokenFor(gen)
|
||||
current(gen)
|
||||
if (generations.has(ref.key)) retire(generations.get(ref.key))
|
||||
generations.set(ref.key, gen)
|
||||
candidates.delete(ref.key)
|
||||
return { type: "success", key: ref.key, metadata: { credentialFile: ref.credentialFile } }
|
||||
} catch (error) {
|
||||
if (candidates.get(ref.key) === gen) candidates.delete(ref.key)
|
||||
retire(gen)
|
||||
return { type: "failed", error: safeFailure(error).message }
|
||||
}
|
||||
}
|
||||
|
||||
async function registryFor(gen, signal, check = async () => current(gen)) {
|
||||
current(gen)
|
||||
if (signal?.aborted) throw failure("cancelled")
|
||||
await loaded(gen)
|
||||
await tokenFor(gen, signal, check)
|
||||
await check()
|
||||
if (signal?.aborted) throw failure("cancelled")
|
||||
const cached = gen.snapshot
|
||||
if (cached && performance.now() - cached.completedAt < DISCOVERY_TTL_MS &&
|
||||
Date.now() - cached.wallCompletedAt < DISCOVERY_TTL_MS &&
|
||||
(cached.retireAt === undefined || Date.now() < cached.retireAt)) {
|
||||
return cached.entries
|
||||
}
|
||||
if (!gen.discovery) {
|
||||
const flight = { controller: new AbortController(), owners: new Set(), result: null }
|
||||
let authError = null
|
||||
let usedToken
|
||||
flight.result = discover({
|
||||
aiRoot: gen.credentials.aiRoot,
|
||||
resourceGroup: gen.credentials.resourceGroup,
|
||||
bearer: async () => {
|
||||
try { usedToken = await tokenFor(gen, flight.controller.signal); return usedToken.value }
|
||||
catch (error) { authError = safeFailure(error); throw error }
|
||||
},
|
||||
signal: flight.controller.signal,
|
||||
rejectedToken: () => { if (gen.token === usedToken) gen.token = null },
|
||||
}).then(
|
||||
entries => {
|
||||
current(gen)
|
||||
if (gen.discovery === flight && !flight.controller.signal.aborted && flight.owners.size) {
|
||||
gen.snapshot = { entries, completedAt: performance.now(), wallCompletedAt: Date.now(), retireAt: retireAtOf(entries) }
|
||||
}
|
||||
return entries
|
||||
},
|
||||
error => {
|
||||
current(gen)
|
||||
throw authError ?? discoveryFailure(error)
|
||||
},
|
||||
)
|
||||
gen.discovery = flight
|
||||
flight.result.catch(() => {})
|
||||
}
|
||||
const flight = gen.discovery
|
||||
const owner = Symbol()
|
||||
flight.owners.add(owner)
|
||||
let rejectAbort
|
||||
const aborted = new Promise((_, reject) => { rejectAbort = reject })
|
||||
const release = () => {
|
||||
flight.owners.delete(owner)
|
||||
if (!flight.owners.size && gen.discovery === flight) {
|
||||
gen.discovery = null
|
||||
flight.controller.abort(failure("cancelled"))
|
||||
}
|
||||
}
|
||||
const cancel = () => { release(); rejectAbort(failure("cancelled")) }
|
||||
signal?.addEventListener("abort", cancel, { once: true })
|
||||
try {
|
||||
if (signal?.aborted) throw failure("cancelled")
|
||||
const entries = await Promise.race([flight.result, aborted])
|
||||
await check()
|
||||
current(gen)
|
||||
if (signal?.aborted) throw failure("cancelled")
|
||||
return entries
|
||||
} catch (error) {
|
||||
await check()
|
||||
throw error
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", cancel)
|
||||
release()
|
||||
}
|
||||
}
|
||||
|
||||
async function models(given, context) {
|
||||
if (!context?.auth) return {}
|
||||
const gen = initialize(storedReference(context.auth))
|
||||
try { return projectModels(await registryFor(gen)) }
|
||||
catch (error) {
|
||||
current(gen)
|
||||
error.signIn = error?.code === "oauth-refused" ? "expired" : "kept"
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function loader(getAuth) {
|
||||
let ref
|
||||
try { ref = storedReference(await getAuth()) } catch (error) { throw safeFailure(error) }
|
||||
const gen = initialize(ref)
|
||||
await loaded(gen)
|
||||
let revoked = false
|
||||
async function selected() {
|
||||
if (revoked) throw failure("superseded")
|
||||
let now
|
||||
try { now = storedReference(await getAuth()) } catch { revoked = true; throw failure("superseded") }
|
||||
if (now.key !== ref.key || now.credentialFile !== ref.credentialFile || generations.get(ref.key) !== gen || gen.retired) {
|
||||
revoked = true
|
||||
throw failure("superseded")
|
||||
}
|
||||
}
|
||||
await selected()
|
||||
try { await registryFor(gen, undefined, selected) }
|
||||
catch {
|
||||
// Discovery failure is surfaced by the active fetch as an HTTP response;
|
||||
// throwing from the loader would let the host flatten status and headers.
|
||||
await selected()
|
||||
}
|
||||
await selected()
|
||||
const aiRoot = gen.credentials.aiRoot
|
||||
return {
|
||||
baseURL: gen.credentials.aiRoot,
|
||||
fetch: async (input, init) => {
|
||||
let target
|
||||
try {
|
||||
target = requestTarget(input, init)
|
||||
if (target.origin !== aiRoot) throw failure("destination")
|
||||
} catch (error) { return responseError(safeFailure(error), true) }
|
||||
const controller = new AbortController()
|
||||
const cancel = () => controller.abort(failure("inference-cancelled"))
|
||||
const replace = () => controller.abort(failure("superseded"))
|
||||
target.signal?.addEventListener("abort", cancel, { once: true })
|
||||
gen.controller.signal.addEventListener("abort", replace, { once: true })
|
||||
if (target.signal?.aborted) cancel()
|
||||
if (gen.controller.signal.aborted) replace()
|
||||
let handedOff = false
|
||||
let cleaned = false
|
||||
const totalTimer = setTimeout(() => controller.abort(failure("inference-timeout")), totalTimeoutMs)
|
||||
let idleTimer
|
||||
const touchIdle = () => {
|
||||
if (cleaned || controller.signal.aborted) return
|
||||
clearTimeout(idleTimer)
|
||||
idleTimer = setTimeout(() => controller.abort(failure(handedOff ? "inference-idle-timeout" : "inference-timeout")), idleTimeoutMs)
|
||||
}
|
||||
touchIdle()
|
||||
let rejectAbort
|
||||
const aborted = new Promise((_, reject) => { rejectAbort = reject })
|
||||
const onAbort = () => rejectAbort(controller.signal.reason)
|
||||
controller.signal.addEventListener("abort", onAbort, { once: true })
|
||||
let disposeBody = () => {}
|
||||
const cleanup = () => {
|
||||
if (cleaned) return
|
||||
cleaned = true
|
||||
disposeBody()
|
||||
clearTimeout(totalTimer)
|
||||
clearTimeout(idleTimer)
|
||||
controller.signal.removeEventListener("abort", onAbort)
|
||||
target.signal?.removeEventListener("abort", cancel)
|
||||
gen.controller.signal.removeEventListener("abort", replace)
|
||||
if (!controller.signal.aborted) controller.abort(failure("inference-cancelled"))
|
||||
}
|
||||
try {
|
||||
if (controller.signal.aborted) throw controller.signal.reason
|
||||
const check = async () => {
|
||||
await Promise.race([selected(), aborted])
|
||||
if (controller.signal.aborted) throw controller.signal.reason
|
||||
}
|
||||
const work = (async () => {
|
||||
await check()
|
||||
const transport = TRANSPORTS[target.protocol]
|
||||
const request = await readJSONRequest(input, init, controller.signal)
|
||||
const entries = await registryFor(gen, controller.signal, check)
|
||||
await check()
|
||||
const entry = entries[request.model]
|
||||
if (!entry) {
|
||||
const code = isPermittedModel(request.model) || KNOWN_CLAUDE_MODELS.has(request.model) ? "unavailable-model" : "unknown-model"
|
||||
throw Object.assign(failure(code), { status: 404 })
|
||||
}
|
||||
// The client route must match the selected model's native protocol:
|
||||
// a model is never dispatched through another protocol's transport.
|
||||
if (entry.protocol !== target.protocol) throw Object.assign(failure("destination"), { status: 400 })
|
||||
const body = transport.validateRequest(request, entry)
|
||||
const token = await tokenFor(gen, controller.signal, check)
|
||||
await check()
|
||||
if (controller.signal.aborted) throw controller.signal.reason
|
||||
const response = await transport.dispatch({
|
||||
entry, body, credentials: gen.credentials, token, signal: controller.signal,
|
||||
extraSecrets: incomingSecrets(input, init),
|
||||
rejectedToken: () => { if (gen.token === token) gen.token = null },
|
||||
})
|
||||
await check()
|
||||
return response
|
||||
})()
|
||||
const response = await Promise.race([work, aborted])
|
||||
if (!response.body || !response.headers.get("content-type")?.startsWith("text/event-stream")) return response
|
||||
|
||||
// A streamed fetch owns its deadline and account/request listeners
|
||||
// until the consumer finishes or cancels, not merely until headers.
|
||||
const reader = response.body.getReader()
|
||||
let ended = false
|
||||
const cancelBody = () => {
|
||||
void reader.cancel().catch(() => {})
|
||||
reader.releaseLock()
|
||||
}
|
||||
const body = new ReadableStream({
|
||||
start(output) {
|
||||
const abort = () => {
|
||||
if (ended) return
|
||||
ended = true
|
||||
output.error(controller.signal.reason)
|
||||
cancelBody()
|
||||
cleanup()
|
||||
}
|
||||
disposeBody = () => controller.signal.removeEventListener("abort", abort)
|
||||
controller.signal.addEventListener("abort", abort, { once: true })
|
||||
if (controller.signal.aborted) abort()
|
||||
},
|
||||
async pull(output) {
|
||||
try {
|
||||
const chunk = await reader.read()
|
||||
if (ended) return
|
||||
if (chunk.done) {
|
||||
ended = true
|
||||
output.close()
|
||||
reader.releaseLock()
|
||||
cleanup()
|
||||
} else {
|
||||
touchIdle()
|
||||
output.enqueue(chunk.value)
|
||||
}
|
||||
} catch (error) {
|
||||
if (ended) return
|
||||
ended = true
|
||||
// dispatch exposes only locally sanitized stream errors.
|
||||
output.error(controller.signal.aborted ? controller.signal.reason : error)
|
||||
cancelBody()
|
||||
cleanup()
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
ended = true
|
||||
controller.abort(failure("inference-cancelled"))
|
||||
cancelBody()
|
||||
cleanup()
|
||||
},
|
||||
}, { highWaterMark: 0 })
|
||||
const streamed = new Response(body, { status: response.status, headers: response.headers })
|
||||
handedOff = true
|
||||
touchIdle()
|
||||
return streamed
|
||||
} catch (error) {
|
||||
return responseError(error, OWNED_ERRORS.has(error))
|
||||
} finally {
|
||||
if (!handedOff) cleanup()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async config(config) {
|
||||
config.provider ??= {}
|
||||
config.provider[PROVIDER_ID] = {
|
||||
name: "SAP AI Core", npm: "@ai-sdk/openai", models: {},
|
||||
...config.provider[PROVIDER_ID],
|
||||
}
|
||||
applyTimeouts(config.provider[PROVIDER_ID])
|
||||
},
|
||||
auth: {
|
||||
provider: PROVIDER_ID,
|
||||
methods: [{
|
||||
type: "api", keyless: true, label: "SAP AI Core credential file",
|
||||
prompts: [{ key: "credentialFile", message: "Absolute path to your SAP AI Core credential file", type: "text" }],
|
||||
authorize,
|
||||
}],
|
||||
loader,
|
||||
},
|
||||
provider: { id: PROVIDER_ID, models },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,550 @@
|
||||
// Native Anthropic Messages transport for SAP AI Core Bedrock deployments.
|
||||
//
|
||||
// Sibling to the GPT Responses transport: it adapts the native Anthropic
|
||||
// Messages routing envelope (strip the routing model, supply anthropic_version,
|
||||
// choose the invoke route) without touching conversation semantics, and relays
|
||||
// SAP's data-only Anthropic SSE. All credential-safe HTTP, redaction, bounded
|
||||
// framing and error rendering are shared through ./transport.js.
|
||||
|
||||
import {
|
||||
AI_HOST, SAFE_TEXT, MAX_BODY_BYTES, isObject,
|
||||
safeError, invalid, abortReason, drain, secretsOf,
|
||||
redactError, bearerRejected, safeHeaders, streamHeaders,
|
||||
sseRelay as relay, messageFor, owns,
|
||||
} from "./transport.js"
|
||||
|
||||
export { responseError } from "./transport.js"
|
||||
|
||||
const DEPLOYMENT_PATH = /^\/v2\/inference\/deployments\/[A-Za-z0-9_-]+$/
|
||||
const ANTHROPIC_VERSION = "bedrock-2023-05-31"
|
||||
|
||||
// --- strict native request validation -------------------------------------
|
||||
|
||||
// Fields the plugin authoritatively rejects as out of scope (hosted, stateful,
|
||||
// or non-Messages) with a specific message. Every other top-level field must be
|
||||
// in ALLOWED: an unrecognized field is rejected rather than forwarded, so an
|
||||
// unsupported parameter fails explicitly instead of silently reaching upstream.
|
||||
const REJECTED = {
|
||||
metadata: "The \"metadata\" parameter is not supported.",
|
||||
service_tier: "The \"service_tier\" parameter is not supported.",
|
||||
container: "The \"container\" parameter is not supported.",
|
||||
mcp_servers: "Hosted MCP servers are not supported.",
|
||||
input: "Use the native Anthropic \"messages\" parameter.",
|
||||
prompt: "Use the native Anthropic \"messages\" parameter.",
|
||||
messages_history: "Use the native Anthropic \"messages\" parameter.",
|
||||
}
|
||||
// The recognized top-level native Messages fields. `output_config` (reasoning
|
||||
// effort) and `thinking` display/block_binding controls are explicitly
|
||||
// recognized; `model`/`stream` are the routing envelope consumed by dispatch.
|
||||
const ALLOWED = new Set([
|
||||
"model", "messages", "system", "max_tokens", "stop_sequences",
|
||||
"temperature", "top_p", "top_k", "tools", "tool_choice", "thinking",
|
||||
"output_config", "anthropic_version", "stream",
|
||||
])
|
||||
const ROLES = new Set(["user", "assistant"])
|
||||
const TOOL_CHOICE_TYPES = new Set(["auto", "any", "tool", "none"])
|
||||
const STREAM_EVENTS = new Set([
|
||||
"message_start", "content_block_start", "content_block_delta",
|
||||
"content_block_stop", "message_delta", "message_stop", "ping", "error",
|
||||
])
|
||||
|
||||
// Client-only per-tool hints (pi): eager tool-input streaming and deferred tool
|
||||
// loading. Bedrock rejects them, so they are validated as booleans here and
|
||||
// stripped during envelope adaptation; they are the only unenumerated tool
|
||||
// fields tolerated — every other unknown tool field is rejected.
|
||||
const CLIENT_TOOL_HINTS = new Set(["eager_input_streaming", "defer_loading"])
|
||||
|
||||
function validateCacheControl(cc) {
|
||||
if (cc === undefined) return
|
||||
if (!isObject(cc) || cc.type !== "ephemeral") throw invalid("Unsupported \"cache_control\"; only {\"type\":\"ephemeral\"} is accepted.")
|
||||
for (const key of Object.keys(cc)) if (key !== "type" && key !== "ttl") throw invalid("Unsupported field in \"cache_control\".")
|
||||
if ("ttl" in cc && typeof cc.ttl !== "string") throw invalid("A \"cache_control\" \"ttl\" must be a string.")
|
||||
}
|
||||
|
||||
const TEXT_KEYS = new Set(["type", "text", "cache_control"])
|
||||
|
||||
function validateTextBlock(block) {
|
||||
if (!isObject(block) || block.type !== "text" || typeof block.text !== "string") throw invalid("A text block requires a string \"text\".")
|
||||
for (const key of Object.keys(block)) if (!TEXT_KEYS.has(key)) throw invalid("Unsupported field in a text block.")
|
||||
validateCacheControl(block.cache_control)
|
||||
}
|
||||
|
||||
function allowedKeys(obj, keys, where) {
|
||||
for (const key of Object.keys(obj)) if (!keys.has(key)) throw invalid("Unsupported field in " + where + ".")
|
||||
}
|
||||
|
||||
const TOOL_USE_KEYS = new Set(["type", "id", "name", "input", "cache_control"])
|
||||
const TOOL_RESULT_KEYS = new Set(["type", "tool_use_id", "content", "is_error", "cache_control"])
|
||||
const THINKING_KEYS = new Set(["type", "thinking", "signature"])
|
||||
const REDACTED_KEYS = new Set(["type", "data"])
|
||||
|
||||
const IMAGE_KEYS = new Set(["type", "source", "cache_control"])
|
||||
const IMAGE_SOURCE_KEYS = new Set(["type", "media_type", "data"])
|
||||
|
||||
// Supported content blocks: text, agent tool_use/tool_result, genuine
|
||||
// signed/opaque thinking history, and — when the selected model advertises image
|
||||
// input — base64 image blocks. Non-base64 sources, documents and other
|
||||
// multimodal blocks are out of scope and rejected rather than silently dropped.
|
||||
function validateContentBlock(block, allowImage) {
|
||||
if (!isObject(block) || typeof block.type !== "string") throw invalid("Each content block must have a string \"type\".")
|
||||
switch (block.type) {
|
||||
case "text":
|
||||
validateTextBlock(block)
|
||||
return
|
||||
case "tool_use":
|
||||
allowedKeys(block, TOOL_USE_KEYS, "a tool_use block")
|
||||
if (typeof block.id !== "string" || !block.id) throw invalid("A tool_use block requires a string \"id\".")
|
||||
if (typeof block.name !== "string" || !block.name) throw invalid("A tool_use block requires a string \"name\".")
|
||||
if (!isObject(block.input)) throw invalid("A tool_use block requires an \"input\" object.")
|
||||
validateCacheControl(block.cache_control)
|
||||
return
|
||||
case "tool_result": {
|
||||
allowedKeys(block, TOOL_RESULT_KEYS, "a tool_result block")
|
||||
if (typeof block.tool_use_id !== "string" || !block.tool_use_id) throw invalid("A tool_result block requires a string \"tool_use_id\".")
|
||||
if ("is_error" in block && typeof block.is_error !== "boolean") throw invalid("A tool_result \"is_error\" must be a boolean.")
|
||||
const content = block.content
|
||||
if (typeof content !== "string") {
|
||||
if (!Array.isArray(content)) throw invalid("A tool_result \"content\" must be a string or an array of text blocks.")
|
||||
for (const part of content) validateTextBlock(part)
|
||||
}
|
||||
validateCacheControl(block.cache_control)
|
||||
return
|
||||
}
|
||||
case "thinking":
|
||||
allowedKeys(block, THINKING_KEYS, "a thinking block")
|
||||
// Empty thinking text is still a genuine signed history block.
|
||||
if (typeof block.thinking !== "string") throw invalid("A thinking block requires a string \"thinking\".")
|
||||
if (typeof block.signature !== "string" || !block.signature) throw invalid("A thinking block requires a non-empty \"signature\".")
|
||||
return
|
||||
case "redacted_thinking":
|
||||
allowedKeys(block, REDACTED_KEYS, "a redacted_thinking block")
|
||||
if (typeof block.data !== "string" || !block.data) throw invalid("A redacted_thinking block requires a string \"data\".")
|
||||
return
|
||||
case "image": {
|
||||
if (!allowImage) throw invalid("Image blocks are not supported for this model.")
|
||||
allowedKeys(block, IMAGE_KEYS, "an image block")
|
||||
const source = block.source
|
||||
if (!isObject(source) || source.type !== "base64") throw invalid("An image block requires a \"source\" with type \"base64\".")
|
||||
allowedKeys(source, IMAGE_SOURCE_KEYS, "an image source")
|
||||
if (typeof source.media_type !== "string" || !source.media_type) throw invalid("An image source requires a string \"media_type\".")
|
||||
if (typeof source.data !== "string" || !source.data) throw invalid("An image source requires string \"data\".")
|
||||
validateCacheControl(block.cache_control)
|
||||
return
|
||||
}
|
||||
default:
|
||||
throw invalid("Unsupported content block type.")
|
||||
}
|
||||
}
|
||||
|
||||
function validateMessages(messages, allowImage) {
|
||||
if (!Array.isArray(messages) || messages.length === 0) throw invalid("The \"messages\" parameter must be a non-empty array.")
|
||||
for (const message of messages) {
|
||||
if (!isObject(message) || typeof message.role !== "string" || !ROLES.has(message.role)) throw invalid("Each message requires role \"user\" or \"assistant\".")
|
||||
for (const key of Object.keys(message)) if (key !== "role" && key !== "content") throw invalid("Unsupported field in a message.")
|
||||
const content = message.content
|
||||
if (typeof content === "string") continue
|
||||
if (!Array.isArray(content)) throw invalid("Message \"content\" must be a string or an array of content blocks.")
|
||||
for (const block of content) validateContentBlock(block, allowImage)
|
||||
}
|
||||
}
|
||||
|
||||
function validateSystem(system) {
|
||||
if (typeof system === "string") return
|
||||
if (!Array.isArray(system)) throw invalid("The \"system\" parameter must be a string or an array of text blocks.")
|
||||
for (const block of system) validateTextBlock(block)
|
||||
}
|
||||
|
||||
const TOOL_KEYS = new Set([
|
||||
"type", "name", "description", "input_schema", "strict", "cache_control",
|
||||
...CLIENT_TOOL_HINTS,
|
||||
])
|
||||
|
||||
function validateTool(tool) {
|
||||
if (!isObject(tool)) throw invalid("Each tool must be an object.")
|
||||
// Every tool field must be enumerated; the only tolerated unenumerated fields
|
||||
// are the boolean pi hints (eager_input_streaming, defer_loading), which are
|
||||
// validated here and stripped at dispatch. Any other field is rejected.
|
||||
allowedKeys(tool, TOOL_KEYS, "a tool")
|
||||
for (const hint of CLIENT_TOOL_HINTS) {
|
||||
if (hint in tool && typeof tool[hint] !== "boolean") throw invalid(`A tool "${hint}" hint must be a boolean.`)
|
||||
}
|
||||
if ("type" in tool && tool.type !== "custom") throw invalid("Only custom function tools are supported.")
|
||||
if (typeof tool.name !== "string" || !tool.name) throw invalid("A tool requires a non-empty string \"name\".")
|
||||
if ("description" in tool && typeof tool.description !== "string") throw invalid("A tool \"description\" must be a string.")
|
||||
if (!isObject(tool.input_schema)) throw invalid("A tool requires an \"input_schema\" object.")
|
||||
if ("strict" in tool && typeof tool.strict !== "boolean") throw invalid("A tool \"strict\" must be a boolean.")
|
||||
validateCacheControl(tool.cache_control)
|
||||
}
|
||||
|
||||
const TOOL_CHOICE_KEYS = new Set(["type", "name", "disable_parallel_tool_use"])
|
||||
|
||||
function validateToolChoice(tc, tools) {
|
||||
if (!isObject(tc) || typeof tc.type !== "string" || !TOOL_CHOICE_TYPES.has(tc.type)) throw invalid("The \"tool_choice\" must be an object with type \"auto\", \"any\", \"tool\" or \"none\".")
|
||||
allowedKeys(tc, TOOL_CHOICE_KEYS, "\"tool_choice\"")
|
||||
if ("disable_parallel_tool_use" in tc && typeof tc.disable_parallel_tool_use !== "boolean") throw invalid("A \"tool_choice\" \"disable_parallel_tool_use\" must be a boolean.")
|
||||
if (tc.type === "tool") {
|
||||
if (typeof tc.name !== "string" || !tc.name) throw invalid("A forced tool choice requires a \"name\".")
|
||||
if (!Array.isArray(tools) || !tools.some(tool => tool.name === tc.name)) throw invalid("The selected tool must match a declared tool.")
|
||||
} else if ("name" in tc) {
|
||||
throw invalid("Only a \"tool\" tool_choice may name a tool.")
|
||||
}
|
||||
if ((tc.type === "any" || tc.type === "tool") && (!Array.isArray(tools) || !tools.length)) throw invalid("A forced tool choice requires declared tools.")
|
||||
}
|
||||
|
||||
const THINKING_TYPES = new Set(["enabled", "disabled", "adaptive"])
|
||||
const THINKING_PARAM_KEYS = new Set(["type", "budget_tokens", "display", "block_binding"])
|
||||
const BLOCK_BINDING_KEYS = new Set(["prefix_mismatch_behavior"])
|
||||
const OUTPUT_CONFIG_KEYS = new Set(["effort"])
|
||||
|
||||
function validateThinking(thinking) {
|
||||
if (!isObject(thinking)) throw invalid("The \"thinking\" parameter must be an object.")
|
||||
// Recognized native thinking modes only; an unrecognized type is rejected
|
||||
// rather than advertised as supported. display/block_binding are recognized
|
||||
// structural controls; model-specific acceptance stays with dispatch policy.
|
||||
allowedKeys(thinking, THINKING_PARAM_KEYS, "\"thinking\"")
|
||||
if (typeof thinking.type !== "string" || !THINKING_TYPES.has(thinking.type)) throw invalid("A \"thinking\" \"type\" must be \"enabled\", \"disabled\" or \"adaptive\".")
|
||||
const budget = thinking.budget_tokens
|
||||
const hasBudget = "budget_tokens" in thinking
|
||||
if (thinking.type === "enabled") {
|
||||
// Enabled thinking requires a positive integer token budget.
|
||||
if (!hasBudget || typeof budget !== "number" || !Number.isInteger(budget) || budget <= 0) throw invalid("Enabled \"thinking\" requires a positive integer \"budget_tokens\".")
|
||||
} else if (hasBudget) {
|
||||
// adaptive/disabled thinking takes no token budget.
|
||||
throw invalid("A \"budget_tokens\" applies only to enabled \"thinking\".")
|
||||
}
|
||||
if ("display" in thinking && typeof thinking.display !== "string") throw invalid("A \"thinking\" \"display\" must be a string.")
|
||||
if ("block_binding" in thinking) {
|
||||
const binding = thinking.block_binding
|
||||
if (!isObject(binding)) throw invalid("A \"thinking\" \"block_binding\" must be an object.")
|
||||
// The known client control is a free-form string; its value stays with upstream.
|
||||
allowedKeys(binding, BLOCK_BINDING_KEYS, "\"block_binding\"")
|
||||
if ("prefix_mismatch_behavior" in binding && typeof binding.prefix_mismatch_behavior !== "string") throw invalid("A \"block_binding\" \"prefix_mismatch_behavior\" must be a string.")
|
||||
}
|
||||
}
|
||||
|
||||
function validateOutputConfig(oc) {
|
||||
if (!isObject(oc)) throw invalid("The \"output_config\" parameter must be an object.")
|
||||
// Reasoning effort is the only recognized control; its value stays with upstream.
|
||||
allowedKeys(oc, OUTPUT_CONFIG_KEYS, "\"output_config\"")
|
||||
if ("effort" in oc && (typeof oc.effort !== "string" || !oc.effort)) throw invalid("An \"output_config\" \"effort\" must be a non-empty string.")
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a parsed native Anthropic Messages body. Structure and the recognized
|
||||
* field allowlist are enforced; model/version-specific restrictions (sampling,
|
||||
* thinking, output ceiling) stay with dispatch policy and the upstream. The
|
||||
* routing `model` and the `stream` selector are retained here and handled by
|
||||
* dispatch. Returns the validated body verbatim.
|
||||
* @param {unknown} body
|
||||
*/
|
||||
export function validateRequest(body, entry) {
|
||||
const allowImage = entry?.capabilities?.image === true
|
||||
if (!isObject(body)) throw invalid("The request body must be a JSON object.")
|
||||
const b = /** @type {Record<string, unknown>} */ (body)
|
||||
for (const key of Object.keys(b)) {
|
||||
if (Object.hasOwn(REJECTED, key)) throw invalid(REJECTED[key])
|
||||
if (!ALLOWED.has(key)) throw invalid("The request includes an unsupported parameter.")
|
||||
}
|
||||
|
||||
const model = b.model
|
||||
if (typeof model !== "string" || model.length < 1 || /[\x00-\x1f\x7f]/.test(model)) throw invalid("The \"model\" parameter must be a non-empty string.")
|
||||
|
||||
validateMessages(b.messages, allowImage)
|
||||
if ("system" in b) validateSystem(b.system)
|
||||
|
||||
if (!("max_tokens" in b)) throw invalid("The \"max_tokens\" parameter is required.")
|
||||
// Zero was accepted by both baselines; negative and non-integer are rejected.
|
||||
if (typeof b.max_tokens !== "number" || !Number.isInteger(b.max_tokens) || b.max_tokens < 0) throw invalid("The \"max_tokens\" parameter must be a non-negative integer.")
|
||||
|
||||
if ("stop_sequences" in b) {
|
||||
if (!Array.isArray(b.stop_sequences) || !b.stop_sequences.every(s => typeof s === "string")) throw invalid("The \"stop_sequences\" parameter must be an array of strings.")
|
||||
}
|
||||
for (const key of ["temperature", "top_p"]) {
|
||||
if (key in b && (typeof b[key] !== "number" || !Number.isFinite(b[key]))) throw invalid(`The "${key}" parameter must be a number.`)
|
||||
}
|
||||
const topK = b.top_k
|
||||
if ("top_k" in b && (typeof topK !== "number" || !Number.isInteger(topK) || topK < 0)) throw invalid("The \"top_k\" parameter must be a non-negative integer.")
|
||||
|
||||
if ("tools" in b) {
|
||||
if (!Array.isArray(b.tools)) throw invalid("The \"tools\" parameter must be an array of tools.")
|
||||
for (const tool of b.tools) validateTool(tool)
|
||||
}
|
||||
if ("tool_choice" in b) validateToolChoice(b.tool_choice, b.tools)
|
||||
if ("thinking" in b) validateThinking(b.thinking)
|
||||
if ("output_config" in b) validateOutputConfig(b.output_config)
|
||||
|
||||
// Client version header is input metadata; a conflicting body version is
|
||||
// rejected rather than forwarded. Dispatch always supplies the Bedrock value.
|
||||
if ("anthropic_version" in b && b.anthropic_version !== ANTHROPIC_VERSION) throw invalid(`The "anthropic_version" must be "${ANTHROPIC_VERSION}".`)
|
||||
if ("stream" in b && typeof b.stream !== "boolean") throw invalid("The \"stream\" parameter must be a boolean.")
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
// --- dispatch --------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The exact Bedrock invoke route for the eligible deployment. The whole-reply
|
||||
* route is /invoke; streaming is /invoke-with-response-stream. No API-version
|
||||
* query is ever appended.
|
||||
* @param {*} entry
|
||||
* @param {string | undefined} aiRoot
|
||||
* @param {boolean} streaming
|
||||
*/
|
||||
function targetURL(entry, aiRoot, streaming) {
|
||||
const raw = entry?.deploymentURL
|
||||
const reject = () => safeError("inference-destination", { status: 502 })
|
||||
if (typeof raw !== "string" || !/^https:\/\//i.test(raw) ||
|
||||
/[\x00-\x20\x7f-\x9f\\\s?#]/.test(raw) || /%(?:2f|5c|2e)/i.test(raw)) throw reject()
|
||||
let url
|
||||
try { url = new URL(raw) } catch { throw reject() }
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.port || url.search || url.hash) throw reject()
|
||||
if (!AI_HOST.test(url.hostname)) throw reject()
|
||||
if (typeof aiRoot === "string" && aiRoot && url.origin !== aiRoot) throw reject()
|
||||
if (!DEPLOYMENT_PATH.test(url.pathname) || raw !== url.origin + url.pathname) throw reject()
|
||||
return raw + (streaming ? "/invoke-with-response-stream" : "/invoke")
|
||||
}
|
||||
|
||||
// Adapt the routing envelope only: drop the canonical routing model and the
|
||||
// stream selector, strip the validated non-native client tool hints
|
||||
// (eager_input_streaming, defer_loading), supply the Bedrock anthropic_version.
|
||||
// Conversation semantics are preserved verbatim.
|
||||
|
||||
function stripToolHints(tools) {
|
||||
if (!Array.isArray(tools)) return tools
|
||||
let changed = false
|
||||
const out = tools.map(tool => {
|
||||
if (!isObject(tool) || !Object.keys(tool).some(k => CLIENT_TOOL_HINTS.has(k))) return tool
|
||||
changed = true
|
||||
const clean = {}
|
||||
for (const k of Object.keys(tool)) if (!CLIENT_TOOL_HINTS.has(k)) clean[k] = tool[k]
|
||||
return clean
|
||||
})
|
||||
return changed ? out : tools
|
||||
}
|
||||
|
||||
function bedrockBody(body) {
|
||||
const out = {}
|
||||
for (const key of Object.keys(body)) {
|
||||
if (key === "model" || key === "stream") continue
|
||||
out[key] = body[key]
|
||||
}
|
||||
if ("tools" in out) out.tools = stripToolHints(out.tools)
|
||||
out.anthropic_version = ANTHROPIC_VERSION
|
||||
return out
|
||||
}
|
||||
|
||||
const isNonNegInt = n => typeof n === "number" && Number.isInteger(n) && n >= 0
|
||||
|
||||
// A native Anthropic message envelope: an assistant message with a non-empty id,
|
||||
// a content array, and a usage object carrying non-negative integer input/output
|
||||
// token counts. `opener` selects the streaming message_start form (initial
|
||||
// stop_reason strictly null) versus a completed whole reply (a non-empty stop
|
||||
// reason string, so a future native reason is preserved, not restricted).
|
||||
function isMessageEnvelope(m, opener) {
|
||||
if (!isObject(m) || m.type !== "message") return false
|
||||
if (typeof m.id !== "string" || !m.id) return false
|
||||
if (m.role !== "assistant") return false
|
||||
if (!Array.isArray(m.content)) return false
|
||||
if (opener ? m.stop_reason !== null : (typeof m.stop_reason !== "string" || !m.stop_reason)) return false
|
||||
const usage = m.usage
|
||||
return isObject(usage) && isNonNegInt(usage.input_tokens) && isNonNegInt(usage.output_tokens)
|
||||
}
|
||||
|
||||
function isMessageShape(native) {
|
||||
return isMessageEnvelope(native, false)
|
||||
}
|
||||
|
||||
// Native Anthropic success output is immutable; a failure's descriptive fields
|
||||
// are redacted while native category fields (ERROR_PROTOCOL_FIELDS) are kept, so
|
||||
// a secret echoed in any sibling field — not just under `error` — is scrubbed.
|
||||
function redactFailure(native, secrets) {
|
||||
if (isMessageShape(native)) return native
|
||||
const redacted = redactError(native, secrets)
|
||||
if (isObject(native) && "error" in native) redacted.error = redactError(native.error, secrets)
|
||||
return redacted
|
||||
}
|
||||
|
||||
function redactStreamError(event, secrets) {
|
||||
return redactFailure(event, secrets)
|
||||
}
|
||||
|
||||
function errorEvent(code) {
|
||||
return `event: error\ndata: ${JSON.stringify({ type: "error", error: { type: "api_error", message: messageFor(code) } })}\n\n`
|
||||
}
|
||||
|
||||
// Validate the native event stream's shape and ordering without accumulating
|
||||
// content. A valid stream opens with one message_start whose message carries an
|
||||
// initial null stop_reason, surfaces a message_delta carrying a non-null
|
||||
// stop_reason before the terminal message_stop, and never repeats or reorders
|
||||
// those markers. An error frame may terminate the stream at any point.
|
||||
function sseRelay(upstream, signal, secrets) {
|
||||
let started = false
|
||||
let stopReasonSeen = false
|
||||
const malformed = () => safeError("inference-response")
|
||||
const classify = (event, name) => {
|
||||
if (!isObject(event) || typeof event.type !== "string" || (name && name !== event.type)) throw malformed()
|
||||
if (!STREAM_EVENTS.has(event.type)) throw malformed()
|
||||
switch (event.type) {
|
||||
case "ping":
|
||||
break
|
||||
case "message_start":
|
||||
// Exactly one opener, a valid assistant envelope with a null stop reason.
|
||||
if (started || !isMessageEnvelope(event.message, true)) throw malformed()
|
||||
started = true
|
||||
break
|
||||
case "message_delta": {
|
||||
if (!started) throw malformed()
|
||||
const delta = event.delta
|
||||
if (!isObject(delta)) throw malformed()
|
||||
// A delta either omits stop_reason (null included) or resolves it exactly
|
||||
// once with a non-empty string; a malformed or duplicate reason is invalid.
|
||||
if ("stop_reason" in delta && delta.stop_reason !== null) {
|
||||
if (typeof delta.stop_reason !== "string" || !delta.stop_reason || stopReasonSeen) throw malformed()
|
||||
stopReasonSeen = true
|
||||
}
|
||||
break
|
||||
}
|
||||
case "content_block_start":
|
||||
case "content_block_delta":
|
||||
case "content_block_stop":
|
||||
if (!started) throw malformed()
|
||||
break
|
||||
case "message_stop":
|
||||
// A terminal is valid only after the opener and a resolved stop reason.
|
||||
if (!started || !stopReasonSeen) throw malformed()
|
||||
break
|
||||
}
|
||||
const terminal = event.type === "message_stop" || event.type === "error"
|
||||
const redacted = event.type === "error" ? redactStreamError(event, secrets) : event
|
||||
// SAP relays data-only frames; emit the native `event:` name so clients that
|
||||
// dispatch on it (e.g. pi) see message_delta/message_stop and the stop reason.
|
||||
return { terminal, redacted, name: event.type }
|
||||
}
|
||||
return relay(upstream, signal, { classify, errorEvent })
|
||||
}
|
||||
|
||||
async function readNative(response, signal) {
|
||||
if (!response.body) throw safeError("inference-response")
|
||||
let bytes
|
||||
try {
|
||||
bytes = await drain(response.body, signal, MAX_BODY_BYTES, () => safeError("inference-response", { status: 502, message: messageFor("inference-response") }))
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
if (owns(error)) throw error
|
||||
throw safeError("inference-response")
|
||||
}
|
||||
try {
|
||||
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))
|
||||
} catch {
|
||||
throw safeError("inference-response")
|
||||
}
|
||||
}
|
||||
|
||||
// Apply the selected deployment's established request restrictions before any
|
||||
// inference credential is sent. The frozen `entry.requestPolicy` is present only
|
||||
// for the verified baseline versions; a newer deployment carries none, so its
|
||||
// request passes through to upstream validation unchanged ("no newer inference"
|
||||
// restriction is invented here).
|
||||
function applyPolicy(entry, body, streaming) {
|
||||
// Streaming is relayed only when the matched version reports it supported.
|
||||
if (streaming && entry?.capabilities?.streaming !== true) throw invalid("Streaming is not supported for this model.")
|
||||
const policy = entry?.requestPolicy
|
||||
if (!isObject(policy)) return
|
||||
if (typeof policy.maxOutputTokens === "number" && typeof body.max_tokens === "number" && body.max_tokens > policy.maxOutputTokens) {
|
||||
throw invalid(`The "max_tokens" parameter must not exceed ${policy.maxOutputTokens} for this model.`)
|
||||
}
|
||||
const hasTemperature = "temperature" in body
|
||||
const hasTopP = "top_p" in body
|
||||
if (policy.rejectTemperature && hasTemperature) throw invalid("This model does not support the \"temperature\" parameter.")
|
||||
if (policy.rejectTopP && hasTopP) throw invalid("This model does not support the \"top_p\" parameter.")
|
||||
if (policy.rejectCombinedSampling && hasTemperature && hasTopP) throw invalid("This model does not support \"temperature\" and \"top_p\" together.")
|
||||
const thinkingEnabled = isObject(body.thinking) && body.thinking.type === "enabled"
|
||||
if (policy.rejectEnabledThinking && thinkingEnabled) throw invalid("This model does not support enabled thinking with a fixed budget.")
|
||||
const tc = body.tool_choice
|
||||
const forcedTool = isObject(tc) && (tc.type === "any" || tc.type === "tool")
|
||||
if (policy.rejectForcedToolThinking && thinkingEnabled && forcedTool) throw invalid("This model does not support forced tool use with enabled thinking.")
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform exactly one account-authenticated Bedrock invoke and return native
|
||||
* Anthropic JSON or incremental SSE. Never retries; never forwards incoming
|
||||
* headers.
|
||||
* @param {{ entry: *, body: Record<string, unknown>, credentials: *, token: *, signal?: AbortSignal, extraSecrets?: string[], rejectedToken?: () => void }} args
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
export async function dispatch({ entry, body, credentials, token, signal, extraSecrets, rejectedToken: onRejectedToken } = /** @type {*} */ ({})) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
|
||||
const streaming = body.stream === true
|
||||
applyPolicy(entry, body, streaming)
|
||||
const url = targetURL(entry, credentials?.aiRoot, streaming)
|
||||
|
||||
const bearer = token?.value
|
||||
if (typeof bearer !== "string" || !SAFE_TEXT.test(bearer)) throw safeError("internal", { status: 500 })
|
||||
const resourceGroup = credentials?.resourceGroup
|
||||
if (typeof resourceGroup !== "string" || !SAFE_TEXT.test(resourceGroup)) throw safeError("internal", { status: 500 })
|
||||
|
||||
const headers = {
|
||||
"content-type": "application/json",
|
||||
accept: streaming ? "text/event-stream" : "application/json",
|
||||
authorization: "Bearer " + bearer,
|
||||
"AI-Resource-Group": resourceGroup,
|
||||
}
|
||||
const payload = JSON.stringify(bedrockBody(body))
|
||||
|
||||
const fetchImpl = globalThis.fetch
|
||||
let response
|
||||
try {
|
||||
response = await fetchImpl(url, { method: "POST", redirect: "error", headers, body: payload, signal })
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
throw safeError("inference-network")
|
||||
}
|
||||
|
||||
if (signal?.aborted) {
|
||||
void response.body?.cancel().catch(() => {})
|
||||
throw abortReason(signal)
|
||||
}
|
||||
|
||||
if (response.redirected || response.type === "opaqueredirect" ||
|
||||
(response.status >= 300 && response.status < 400) ||
|
||||
(response.url && response.url !== url)) {
|
||||
void response.body?.cancel().catch(() => {})
|
||||
throw safeError("inference-redirect")
|
||||
}
|
||||
|
||||
const rejectedToken = response.status === 401 && bearerRejected(response.headers.get("www-authenticate"))
|
||||
if (rejectedToken && typeof onRejectedToken === "function") onRejectedToken()
|
||||
|
||||
if (streaming && response.ok) {
|
||||
const contentType = response.headers.get("content-type") || ""
|
||||
if (!response.body || !/^text\/event-stream(?:\s*;|\s*$)/i.test(contentType)) {
|
||||
void response.body?.cancel().catch(() => {})
|
||||
throw safeError("inference-response")
|
||||
}
|
||||
const stream = sseRelay(response.body, signal, secretsOf(credentials, token, extraSecrets))
|
||||
return new Response(stream, { status: response.status, headers: streamHeaders() })
|
||||
}
|
||||
|
||||
let native
|
||||
try {
|
||||
native = await readNative(response, signal)
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
if (!response.ok) {
|
||||
const fallback = JSON.stringify({ type: "error", error: { type: "api_error", message: messageFor("inference-response") } })
|
||||
return new Response(fallback, { status: response.status, headers: safeHeaders(response) })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
if (response.ok && !isMessageShape(native)) throw safeError("inference-response")
|
||||
|
||||
const failed = !response.ok || (isObject(native) && native.type === "error")
|
||||
const serialized = failed
|
||||
? JSON.stringify(redactFailure(native, secretsOf(credentials, token, extraSecrets)))
|
||||
: JSON.stringify(native)
|
||||
|
||||
return new Response(serialized, { status: response.status, headers: safeHeaders(response) })
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
import {
|
||||
AI_HOST, SAFE_TEXT, MAX_BODY_BYTES, isObject,
|
||||
safeError, invalid, abortReason, drain, secretsOf,
|
||||
redactError, redactErrorDetails, ERROR_PROTOCOL_FIELDS,
|
||||
bearerRejected, safeHeaders, streamHeaders, sseRelay as relay, messageFor, owns,
|
||||
} from "./transport.js"
|
||||
|
||||
export { responseError } from "./transport.js"
|
||||
|
||||
const DEPLOYMENT_PATH = /^\/v2\/inference\/deployments\/[A-Za-z0-9_-]+$/
|
||||
|
||||
const ALLOWED = new Set([
|
||||
"model", "input", "instructions", "max_output_tokens", "prompt_cache_key",
|
||||
"reasoning", "include", "tools", "tool_choice",
|
||||
"store", "stream", "background",
|
||||
])
|
||||
|
||||
// --- strict stateless parameter validation --------------------------------
|
||||
|
||||
const MESSAGE_PART = new Set(["input_text", "output_text"])
|
||||
|
||||
/**
|
||||
* Validate message content: a string or an array of parts. Text parts are
|
||||
* always accepted; `input_image` parts are accepted only when the selected
|
||||
* model advertises image input. Other multimodal parts are rejected.
|
||||
* @param {unknown} content
|
||||
* @param {boolean} allowImage
|
||||
*/
|
||||
function validateMessageContent(content, allowImage) {
|
||||
if (typeof content === "string") return
|
||||
if (!Array.isArray(content)) throw invalid("Message content must be a string or an array of text parts.")
|
||||
for (const part of content) {
|
||||
if (!isObject(part) || typeof part.type !== "string") throw invalid("Only text message content is supported.")
|
||||
if (part.type === "input_image") {
|
||||
if (!allowImage) throw invalid("Image content is not supported for this model.")
|
||||
validateInputImage(part)
|
||||
continue
|
||||
}
|
||||
if (!MESSAGE_PART.has(part.type) || typeof part.text !== "string") throw invalid("Only text message content is supported.")
|
||||
}
|
||||
}
|
||||
|
||||
const IMAGE_DETAIL = new Set(["auto", "low", "high"])
|
||||
const INPUT_IMAGE_KEYS = new Set(["type", "image_url", "detail"])
|
||||
|
||||
/**
|
||||
* Validate an `input_image` part: a data or https `image_url` string with an
|
||||
* optional `detail`. Stateful file references and unknown fields are rejected.
|
||||
* @param {Record<string, unknown>} part
|
||||
*/
|
||||
function validateInputImage(part) {
|
||||
for (const key of Object.keys(part)) if (!INPUT_IMAGE_KEYS.has(key)) throw invalid("Unsupported field in an input_image part.")
|
||||
if (typeof part.image_url !== "string" || !/^(?:data:|https:\/\/)/i.test(part.image_url)) throw invalid("An input_image requires an \"image_url\" data or https URL string.")
|
||||
if ("detail" in part && (typeof part.detail !== "string" || !IMAGE_DETAIL.has(part.detail))) throw invalid("An input_image \"detail\" must be \"auto\", \"low\" or \"high\".")
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate one input item: supported stateless message / function_call /
|
||||
* function_call_output / reasoning history only. Stateful references and
|
||||
* unverified item types are rejected.
|
||||
* @param {unknown} item
|
||||
* @param {boolean} allowImage
|
||||
*/
|
||||
function validateInputItem(item, allowImage) {
|
||||
if (!isObject(item)) throw invalid("Each input item must be an object.")
|
||||
const type = item.type
|
||||
if (type === undefined || type === "message") {
|
||||
if (!["user", "assistant", "system", "developer"].includes(String(item.role))) throw invalid("A message requires a supported role.")
|
||||
validateMessageContent(item.content, allowImage)
|
||||
return
|
||||
}
|
||||
if (type === "function_call") {
|
||||
if (typeof item.call_id !== "string" || !item.call_id || typeof item.name !== "string" || !item.name || typeof item.arguments !== "string") throw invalid("A function call requires call_id, name and string arguments.")
|
||||
return
|
||||
}
|
||||
if (type === "function_call_output") {
|
||||
if (typeof item.call_id !== "string" || !item.call_id || typeof item.output !== "string") throw invalid("A function result requires call_id and string output.")
|
||||
return
|
||||
}
|
||||
if (type === "reasoning") {
|
||||
if (!Array.isArray(item.summary) || !item.summary.every(part => isObject(part) && part.type === "summary_text" && typeof part.text === "string") ||
|
||||
(item.encrypted_content !== undefined && typeof item.encrypted_content !== "string")) throw invalid("A reasoning item requires a native summary and optional encrypted content.")
|
||||
return
|
||||
}
|
||||
throw invalid("Unsupported input item type.")
|
||||
}
|
||||
|
||||
const TOOL_KEYS = new Set(["type", "name", "description", "parameters", "strict"])
|
||||
|
||||
/**
|
||||
* Validate a function tool definition. Hosted tools and unverified fields are
|
||||
* rejected; parameter schema contents are left to upstream validation.
|
||||
* @param {unknown} tool
|
||||
*/
|
||||
function validateTool(tool) {
|
||||
if (!isObject(tool) || tool.type !== "function") throw invalid("Only function tools are supported in the \"tools\" parameter.")
|
||||
for (const key of Object.keys(tool)) if (!TOOL_KEYS.has(key)) throw invalid("Unsupported field in a function tool definition.")
|
||||
if (typeof tool.name !== "string" || !tool.name) throw invalid("A function tool requires a non-empty string \"name\".")
|
||||
if ("description" in tool && typeof tool.description !== "string") throw invalid("A function tool \"description\" must be a string.")
|
||||
if ("parameters" in tool && !isObject(tool.parameters)) throw invalid("A function tool \"parameters\" must be an object.")
|
||||
if ("strict" in tool && typeof tool.strict !== "boolean") throw invalid("A function tool \"strict\" must be a boolean.")
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {unknown} body
|
||||
* @param {*} [entry] selected deployment entry; its capabilities gate image input.
|
||||
* @returns {{ model: string, store: false, stream?: boolean } & Record<string, unknown>}
|
||||
*/
|
||||
export function validateRequest(body, entry) {
|
||||
const allowImage = entry?.capabilities?.image === true
|
||||
if (!isObject(body)) throw invalid("The request body must be a JSON object.")
|
||||
const b = /** @type {Record<string, unknown>} */ (body)
|
||||
|
||||
// Stateful / unsupported keys get specific, non-echoing messages.
|
||||
if ("previous_response_id" in b) throw invalid("The \"previous_response_id\" parameter is not supported; responses are stateless.")
|
||||
if ("conversation" in b) throw invalid("The \"conversation\" parameter is not supported; responses are stateless.")
|
||||
|
||||
for (const key of Object.keys(b)) {
|
||||
if (ALLOWED.has(key)) continue
|
||||
if (key === "messages" || key === "prompt" || key === "functions" || key === "function_call") {
|
||||
throw invalid("Chat Completions fields are not supported; use the Responses \"input\" parameter.")
|
||||
}
|
||||
throw invalid("The request includes an unsupported parameter.")
|
||||
}
|
||||
|
||||
// model — structural only; identity (verified vs unavailable) is owned by discovery.
|
||||
const model = b.model
|
||||
if (typeof model !== "string" || model.length < 1 || /[\x00-\x1f\x7f]/.test(model)) {
|
||||
throw invalid("The \"model\" parameter must be a non-empty string.")
|
||||
}
|
||||
|
||||
// input — a string or an array of supported stateless history items.
|
||||
const input = b.input
|
||||
let reasoningHistory = false
|
||||
if (typeof input !== "string") {
|
||||
if (!Array.isArray(input)) throw invalid("The \"input\" parameter must be a string or an array of input items.")
|
||||
for (const item of input) {
|
||||
validateInputItem(item, allowImage)
|
||||
if (item.type === "reasoning") reasoningHistory = true
|
||||
}
|
||||
}
|
||||
|
||||
if ("instructions" in b && typeof b.instructions !== "string") {
|
||||
throw invalid("The \"instructions\" parameter must be a string.")
|
||||
}
|
||||
|
||||
if ("max_output_tokens" in b) {
|
||||
const n = b.max_output_tokens
|
||||
// Positive integer only. No invented minimum — upstream validates values (1 failed live).
|
||||
if (typeof n !== "number" || !Number.isInteger(n) || n <= 0) {
|
||||
throw invalid("The \"max_output_tokens\" parameter must be a positive integer.")
|
||||
}
|
||||
}
|
||||
|
||||
if ("prompt_cache_key" in b && typeof b.prompt_cache_key !== "string") {
|
||||
throw invalid("The \"prompt_cache_key\" parameter must be a string.")
|
||||
}
|
||||
|
||||
if ("reasoning" in b) {
|
||||
const r = b.reasoning
|
||||
// Live GPT-6 probes verified low/medium/high with optional summary:"auto".
|
||||
const bad = () => invalid("The \"reasoning\" parameter requires \"effort\" set to \"low\", \"medium\" or \"high\", with optional \"summary\" set to \"auto\".")
|
||||
if (!isObject(r)) throw bad()
|
||||
for (const key of Object.keys(r)) if (key !== "effort" && key !== "summary") throw bad()
|
||||
if ((r.effort !== "low" && r.effort !== "medium" && r.effort !== "high") || ("summary" in r && r.summary !== "auto")) throw bad()
|
||||
}
|
||||
|
||||
if ("include" in b) {
|
||||
const inc = b.include
|
||||
// Only the verified encrypted-reasoning include is supported.
|
||||
if (!Array.isArray(inc) || !inc.every(v => v === "reasoning.encrypted_content")) {
|
||||
throw invalid("The \"include\" parameter may only contain \"reasoning.encrypted_content\".")
|
||||
}
|
||||
}
|
||||
|
||||
if ("tools" in b) {
|
||||
const tools = b.tools
|
||||
if (!Array.isArray(tools)) throw invalid("The \"tools\" parameter must be an array of function tools.")
|
||||
for (const tool of tools) validateTool(tool)
|
||||
}
|
||||
|
||||
if ("tool_choice" in b) {
|
||||
const tc = b.tool_choice
|
||||
const ok = tc === "auto" || tc === "none" || tc === "required" || (isObject(tc) && tc.type === "function")
|
||||
if (!ok) throw invalid("The \"tool_choice\" parameter must be \"auto\", \"none\", \"required\" or a function tool choice.")
|
||||
if (tc === "required" || isObject(tc)) {
|
||||
if (!Array.isArray(b.tools) || !b.tools.length) throw invalid("A forced function choice requires declared tools.")
|
||||
if (isObject(tc) && (Object.keys(tc).some(key => key !== "type" && key !== "name") || typeof tc.name !== "string" || !b.tools.some(tool => tool.name === tc.name))) throw invalid("The selected function must match a declared tool.")
|
||||
}
|
||||
}
|
||||
|
||||
// Installed magpie may force stream true/false before the plugin sees the
|
||||
// request. The native boolean is preserved verbatim (true → incremental SSE,
|
||||
// false/omitted → whole JSON); only its type is checked.
|
||||
if ("stream" in b && typeof b.stream !== "boolean") {
|
||||
throw invalid("The \"stream\" parameter must be a boolean.")
|
||||
}
|
||||
if ("background" in b && b.background !== false) {
|
||||
throw invalid("The \"background\" parameter must be false; background responses are not supported.")
|
||||
}
|
||||
if ("store" in b && b.store !== false) {
|
||||
throw invalid("The \"store\" parameter must be false; stateful responses are not supported.")
|
||||
}
|
||||
|
||||
// Preserve supported fields; this transport forces stateless responses and
|
||||
// relays the native stream flag unchanged.
|
||||
/** @type {Record<string, unknown>} */
|
||||
const out = {}
|
||||
for (const key of ALLOWED) {
|
||||
if (key === "store") continue
|
||||
if (key in b) out[key] = b[key]
|
||||
}
|
||||
out.store = false
|
||||
// Stateless reasoning continuity: when the caller omits "include", request the
|
||||
// opaque encrypted reasoning that keeps function-tool and reasoning history
|
||||
// replayable across stateless turns. An explicit include (even []) is kept.
|
||||
if (!("include" in b) && (reasoningHistory || "reasoning" in b || (Array.isArray(b.tools) && b.tools.length > 0))) {
|
||||
out.include = ["reasoning.encrypted_content"]
|
||||
}
|
||||
return /** @type {{ model: string, store: false, stream?: boolean } & Record<string, unknown>} */ (out)
|
||||
}
|
||||
|
||||
|
||||
// --- dispatch --------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Validate the eligible deployment and resolve the exact /responses route.
|
||||
* @param {*} entry
|
||||
* @param {string} [aiRoot]
|
||||
* @returns {string}
|
||||
*/
|
||||
function targetURL(entry, aiRoot) {
|
||||
const raw = entry?.deploymentURL
|
||||
const reject = () => safeError("inference-destination", { status: 502 })
|
||||
if (typeof raw !== "string" || !/^https:\/\//i.test(raw) ||
|
||||
/[\x00-\x20\x7f-\x9f\\\s?#]/.test(raw) || /%(?:2f|5c|2e)/i.test(raw)) throw reject()
|
||||
let url
|
||||
try { url = new URL(raw) } catch { throw reject() }
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.port || url.search || url.hash) throw reject()
|
||||
if (!AI_HOST.test(url.hostname)) throw reject()
|
||||
if (typeof aiRoot === "string" && aiRoot && url.origin !== aiRoot) throw reject()
|
||||
if (!DEPLOYMENT_PATH.test(url.pathname) || raw !== url.origin + url.pathname) throw reject()
|
||||
return raw + "/responses"
|
||||
}
|
||||
|
||||
function redactFailure(native, secrets) {
|
||||
if (isObject(native) && native.object === "response") {
|
||||
// Native output/history, identity, usage and terminal status are immutable.
|
||||
return native.error == null ? native : { ...native, error: redactError(native.error, secrets) }
|
||||
}
|
||||
if (isObject(native) && "error" in native) {
|
||||
const out = Object.create(null)
|
||||
for (const key of Object.keys(native)) out[key] = key === "error" ? redactError(native.error, secrets) : ERROR_PROTOCOL_FIELDS.has(key) ? native[key] : redactErrorDetails(native[key], secrets)
|
||||
return out
|
||||
}
|
||||
return redactError(native, secrets)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the whole native JSON reply, bounded and cancellable.
|
||||
* @param {Response} response
|
||||
* @param {AbortSignal} [signal]
|
||||
*/
|
||||
async function readNative(response, signal) {
|
||||
if (!response.body) throw safeError("inference-response")
|
||||
let bytes
|
||||
try {
|
||||
bytes = await drain(response.body, signal, MAX_BODY_BYTES, () => safeError("inference-response", { status: 502, message: messageFor("inference-response") }))
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
if (owns(error)) throw error
|
||||
throw safeError("inference-response")
|
||||
}
|
||||
try {
|
||||
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))
|
||||
} catch {
|
||||
throw safeError("inference-response")
|
||||
}
|
||||
}
|
||||
|
||||
const TERMINAL_STATUS = new Set(["completed", "incomplete", "failed"])
|
||||
|
||||
/**
|
||||
* A terminal native Responses object — never a scalar, Chat completion,
|
||||
* in-progress or otherwise malformed body.
|
||||
* @param {*} native
|
||||
*/
|
||||
function isResponseShape(native) {
|
||||
return isObject(native) && native.object === "response" &&
|
||||
typeof native.id === "string" && Array.isArray(native.output) &&
|
||||
typeof native.status === "string" && TERMINAL_STATUS.has(native.status)
|
||||
}
|
||||
|
||||
const RESPONSE_TERMINALS = new Map([
|
||||
["response.completed", "completed"],
|
||||
["response.incomplete", "incomplete"],
|
||||
["response.failed", "failed"],
|
||||
])
|
||||
|
||||
/**
|
||||
* Serialize a safe, locally-owned SSE error event. The type is always "error";
|
||||
* a terminal success is never fabricated.
|
||||
* @param {string} code
|
||||
*/
|
||||
function errorEvent(code) {
|
||||
return `data: ${JSON.stringify({ type: "error", error: { code, message: messageFor(code) } })}\n\n`
|
||||
}
|
||||
|
||||
/**
|
||||
* Redact only descriptive error fields. Native output/history and response
|
||||
* identity are immutable, even when they overlap a credential string.
|
||||
* @param {Record<string, unknown>} event
|
||||
* @param {string[]} secrets
|
||||
*/
|
||||
function redactEvent(event, secrets) {
|
||||
if (isObject(event.response) && event.response.object === "response") {
|
||||
const response = redactFailure(event.response, secrets)
|
||||
return response === event.response ? event : { ...event, response }
|
||||
}
|
||||
if (event.type === "error" || event.type === "response.error") {
|
||||
if (!("error" in event)) return redactError(event, secrets)
|
||||
const { error, ...fields } = event
|
||||
return { ...redactError(fields, secrets), error: redactError(error, secrets) }
|
||||
}
|
||||
return event.error == null ? event : { ...event, error: redactError(event.error, secrets) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Relay native Responses SSE: classify each frame's terminal/redaction and hand
|
||||
* the bounded framing to the shared relay.
|
||||
* @param {ReadableStream<Uint8Array>} upstream
|
||||
* @param {AbortSignal | undefined} signal
|
||||
* @param {string[]} secrets
|
||||
* @returns {ReadableStream<Uint8Array>}
|
||||
*/
|
||||
function sseRelay(upstream, signal, secrets) {
|
||||
const classify = (event, name) => {
|
||||
if (!isObject(event) || typeof event.type !== "string" || (name && name !== event.type)) throw safeError("inference-response")
|
||||
const status = RESPONSE_TERMINALS.get(event.type)
|
||||
if (status && (!isObject(event.response) || !isResponseShape(event.response) || event.response.status !== status)) throw safeError("inference-response")
|
||||
const terminal = Boolean(status) || event.type === "error" || event.type === "response.error"
|
||||
return { terminal, redacted: redactEvent(event, secrets) }
|
||||
}
|
||||
return relay(upstream, signal, { classify, errorEvent })
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform exactly one account-authenticated upstream call and return native
|
||||
* JSON or incremental SSE. Never retries; never forwards incoming headers.
|
||||
* @param {{ entry: *, body: Record<string, unknown>, credentials: *, token: *, signal?: AbortSignal, extraSecrets?: string[], rejectedToken?: () => void }} args
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
export async function dispatch({ entry, body, credentials, token, signal, extraSecrets, rejectedToken: onRejectedToken } = /** @type {*} */ ({})) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
|
||||
const url = targetURL(entry, credentials?.aiRoot)
|
||||
|
||||
const bearer = token?.value
|
||||
if (typeof bearer !== "string" || !SAFE_TEXT.test(bearer)) throw safeError("internal", { status: 500 })
|
||||
const resourceGroup = credentials?.resourceGroup
|
||||
if (typeof resourceGroup !== "string" || !SAFE_TEXT.test(resourceGroup)) throw safeError("internal", { status: 500 })
|
||||
|
||||
// Outgoing allowlist only — incoming SDK tokens/headers never propagate.
|
||||
const streaming = body.stream === true
|
||||
const headers = {
|
||||
"content-type": "application/json",
|
||||
accept: streaming ? "text/event-stream" : "application/json",
|
||||
authorization: "Bearer " + bearer,
|
||||
"AI-Resource-Group": resourceGroup,
|
||||
}
|
||||
const payload = JSON.stringify(body)
|
||||
|
||||
// Exactly one fetch, captured at call time.
|
||||
const fetchImpl = globalThis.fetch
|
||||
let response
|
||||
try {
|
||||
response = await fetchImpl(url, { method: "POST", redirect: "error", headers, body: payload, signal })
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
throw safeError("inference-network")
|
||||
}
|
||||
|
||||
if (signal?.aborted) {
|
||||
void response.body?.cancel().catch(() => {})
|
||||
throw abortReason(signal)
|
||||
}
|
||||
|
||||
if (response.redirected || response.type === "opaqueredirect" ||
|
||||
(response.status >= 300 && response.status < 400) ||
|
||||
(response.url && response.url !== url)) {
|
||||
void response.body?.cancel().catch(() => {})
|
||||
throw safeError("inference-redirect")
|
||||
}
|
||||
|
||||
// Verified invalid/expired Bearer: drop the token immediately (before any read)
|
||||
// so recovery never reuses it. The upstream status/code are preserved.
|
||||
const rejectedToken = response.status === 401 && bearerRejected(response.headers.get("www-authenticate"))
|
||||
if (rejectedToken && typeof onRejectedToken === "function") onRejectedToken()
|
||||
|
||||
// A successful streaming request yields a native text/event-stream the plugin
|
||||
// relays incrementally; anything else from a 2xx reply is a safe failure.
|
||||
if (streaming && response.ok) {
|
||||
const contentType = response.headers.get("content-type") || ""
|
||||
if (!response.body || !/^text\/event-stream(?:\s*;|\s*$)/i.test(contentType)) {
|
||||
void response.body?.cancel().catch(() => {})
|
||||
throw safeError("inference-response")
|
||||
}
|
||||
const stream = sseRelay(response.body, signal, secretsOf(credentials, token, extraSecrets))
|
||||
return new Response(stream, { status: response.status, headers: streamHeaders() })
|
||||
}
|
||||
|
||||
let native
|
||||
try {
|
||||
native = await readNative(response, signal)
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
if (!response.ok) {
|
||||
// Malformed error body: keep the HTTP status and Retry-After, surface a safe
|
||||
// fallback code. The request is never replayed.
|
||||
const fallback = JSON.stringify({ error: { code: "inference-response", message: messageFor("inference-response") } })
|
||||
return new Response(fallback, { status: response.status, headers: safeHeaders(response) })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
// A 2xx reply must be a terminal native Responses object.
|
||||
if (response.ok && !isResponseShape(native)) throw safeError("inference-response")
|
||||
|
||||
// Preserve native output verbatim; redact secrets only from failed responses.
|
||||
const failed = !response.ok || (isObject(native) && (native.error != null || native.status === "failed"))
|
||||
const serialized = failed
|
||||
? JSON.stringify(redactFailure(native, secretsOf(credentials, token, extraSecrets)))
|
||||
: JSON.stringify(native)
|
||||
|
||||
return new Response(serialized, { status: response.status, headers: safeHeaders(response) })
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { readFile } from "node:fs/promises"
|
||||
|
||||
const ROOT = new URL("..", import.meta.url)
|
||||
|
||||
async function readVersion() {
|
||||
try {
|
||||
const pkg = JSON.parse(await readFile(new URL("package.json", ROOT), "utf8"))
|
||||
return typeof pkg.version === "string" ? pkg.version : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
let cached
|
||||
|
||||
/** Package version only, computed once without Git or child processes. */
|
||||
export function pluginRevision() {
|
||||
cached ??= readVersion().then(version => version ?? "unknown")
|
||||
return cached
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
// Shared, protocol-agnostic transport primitives.
|
||||
//
|
||||
// Both the GPT Responses transport and the Claude Messages transport build on
|
||||
// these: credential-safe bounded body reading, secret redaction, locally-owned
|
||||
// safe errors, and standard response rendering. Token management stays in the
|
||||
// plugin factory and protocol semantics stay in each transport; this module
|
||||
// never converts between protocols.
|
||||
|
||||
const LABEL = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
|
||||
export const AI_HOST = new RegExp(`^api\\.ai\\.${LABEL}(?:\\.${LABEL})*\\.hana\\.ondemand\\.com$`)
|
||||
export const SAFE_TEXT = /^[\x21-\x7e]+$/
|
||||
|
||||
// Request/whole-reply and per-SSE-frame byte bound. A streaming reply is never
|
||||
// accumulated as a whole; encrypted history can still make one frame large.
|
||||
export const MAX_BODY_BYTES = 16 * 1024 * 1024
|
||||
|
||||
// Default safe statuses used only when a safe error carries no explicit status.
|
||||
const STATUS = {
|
||||
"invalid-request": 400,
|
||||
destination: 400,
|
||||
"unknown-model": 404,
|
||||
"oauth-refused": 401,
|
||||
"inference-destination": 502,
|
||||
"inference-redirect": 502,
|
||||
"inference-network": 502,
|
||||
"inference-response": 502,
|
||||
"inference-timeout": 504,
|
||||
"inference-idle-timeout": 504,
|
||||
"inference-cancelled": 499,
|
||||
cancelled: 499,
|
||||
timeout: 504,
|
||||
network: 502,
|
||||
superseded: 503,
|
||||
internal: 500,
|
||||
}
|
||||
|
||||
const MESSAGES = {
|
||||
"inference-destination": "SAP AI Core: the deployment target was unsafe.",
|
||||
"inference-redirect": "SAP AI Core: the deployment redirected the request.",
|
||||
"inference-network": "SAP AI Core: the deployment could not be reached.",
|
||||
"inference-response": "SAP AI Core: the deployment returned an unexpected response.",
|
||||
"inference-timeout": "SAP AI Core: the inference request timed out.",
|
||||
"inference-idle-timeout": "SAP AI Core: the inference stream timed out while waiting for data.",
|
||||
"inference-cancelled": "SAP AI Core: the inference request was cancelled.",
|
||||
"invalid-request": "SAP AI Core: the request was rejected.",
|
||||
internal: "The request could not be completed.",
|
||||
}
|
||||
|
||||
export const GENERIC_MESSAGE = "The request could not be completed."
|
||||
|
||||
// Errors this module (and the transports that reuse it) construct are trusted
|
||||
// for echoing by responseError. Anything not in this set (or not flagged
|
||||
// trusted by the parent) is sanitized.
|
||||
const OWNED = new WeakSet()
|
||||
|
||||
/** Safe descriptive text for a locally-owned error code. */
|
||||
export function messageFor(code) {
|
||||
return MESSAGES[code] ?? GENERIC_MESSAGE
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a branded, locally-owned safe error.
|
||||
* @param {string} code
|
||||
* @param {{ status?: number, retryAfter?: string, message?: string }} [options]
|
||||
* @returns {Error & { code: string, status?: number, retryAfter?: string }}
|
||||
*/
|
||||
export function safeError(code, options = {}) {
|
||||
const error = /** @type {Error & { code: string, status?: number, retryAfter?: string }} */ (
|
||||
new Error(options.message ?? MESSAGES[code] ?? GENERIC_MESSAGE)
|
||||
)
|
||||
error.code = code
|
||||
if (options.status !== undefined) error.status = options.status
|
||||
if (options.retryAfter !== undefined) error.retryAfter = options.retryAfter
|
||||
OWNED.add(error)
|
||||
return error
|
||||
}
|
||||
|
||||
export const invalid = (message, status = 400) => safeError("invalid-request", { status, message })
|
||||
|
||||
/** @returns {boolean} */
|
||||
export function owns(error) {
|
||||
return OWNED.has(error)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {unknown} v
|
||||
* @returns {v is Record<string, unknown>}
|
||||
*/
|
||||
export function isObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer the parent-owned abort reason (it carries inference-timeout /
|
||||
* inference-cancelled) and fall back to our own cancellation error.
|
||||
* @param {AbortSignal} [signal]
|
||||
*/
|
||||
export function abortReason(signal) {
|
||||
return signal?.reason ?? safeError("inference-cancelled")
|
||||
}
|
||||
|
||||
/**
|
||||
* Drain a byte stream up to `limit`, racing the abort signal so cancellation
|
||||
* wins even when a (mocked) reader ignores reader.cancel().
|
||||
* @param {ReadableStream<Uint8Array>} stream
|
||||
* @param {AbortSignal | undefined} signal
|
||||
* @param {number} limit
|
||||
* @param {() => Error} oversize
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
export async function drain(stream, signal, limit, oversize) {
|
||||
if (!stream || typeof stream.getReader !== "function") throw oversize()
|
||||
const reader = stream.getReader()
|
||||
/** @type {Buffer[]} */
|
||||
const chunks = []
|
||||
let size = 0
|
||||
/** @type {(() => void) | undefined} */
|
||||
let onAbort
|
||||
const aborted = new Promise((_, reject) => {
|
||||
if (!signal) return
|
||||
onAbort = () => reject(abortReason(signal))
|
||||
signal.addEventListener("abort", onAbort, { once: true })
|
||||
})
|
||||
const cancel = () => { void reader.cancel().catch(() => {}) }
|
||||
try {
|
||||
for (;;) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
const { done, value } = signal ? await Promise.race([reader.read(), aborted]) : await reader.read()
|
||||
if (done) break
|
||||
size += value.byteLength
|
||||
if (size > limit) throw oversize()
|
||||
chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength))
|
||||
}
|
||||
return Buffer.concat(chunks, size)
|
||||
} catch (error) {
|
||||
cancel()
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
throw error
|
||||
} finally {
|
||||
if (signal && onAbort) signal.removeEventListener("abort", onAbort)
|
||||
try { reader.releaseLock() } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the raw bytes of a Fetch-compatible body (init.body if present, else
|
||||
* the Request body), bounded and cancellable.
|
||||
* @param {string | Request} input
|
||||
* @param {*} init
|
||||
* @param {AbortSignal} [signal]
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
export async function readBytes(input, init, signal) {
|
||||
// Fetch semantics: init.body wins only when defined; otherwise consume the Request.
|
||||
const source = init?.body !== undefined ? init.body : (input instanceof Request ? input : undefined)
|
||||
if (source === undefined || source === null) throw invalid("A request body is required.")
|
||||
|
||||
const tooLarge = () => invalid("The request body exceeds the maximum allowed size.", 413)
|
||||
|
||||
if (typeof source === "string") {
|
||||
if (source.length > MAX_BODY_BYTES) throw tooLarge()
|
||||
const bytes = Buffer.from(source, "utf8")
|
||||
if (bytes.byteLength > MAX_BODY_BYTES) throw tooLarge()
|
||||
return bytes
|
||||
}
|
||||
if (source instanceof ArrayBuffer) {
|
||||
if (source.byteLength > MAX_BODY_BYTES) throw tooLarge()
|
||||
return Buffer.from(source)
|
||||
}
|
||||
if (ArrayBuffer.isView(source)) {
|
||||
if (source.byteLength > MAX_BODY_BYTES) throw tooLarge()
|
||||
return Buffer.from(source.buffer, source.byteOffset, source.byteLength)
|
||||
}
|
||||
if (typeof Blob !== "undefined" && source instanceof Blob) {
|
||||
if (source.size > MAX_BODY_BYTES) throw tooLarge()
|
||||
return drain(source.stream(), signal, MAX_BODY_BYTES, tooLarge)
|
||||
}
|
||||
if (source instanceof Request) {
|
||||
if (source.bodyUsed) throw invalid("The request body has already been consumed.")
|
||||
if (!source.body) throw invalid("A request body is required.")
|
||||
return drain(source.body, signal, MAX_BODY_BYTES, tooLarge)
|
||||
}
|
||||
if (source instanceof ReadableStream || (source && typeof source.getReader === "function")) {
|
||||
return drain(source, signal, MAX_BODY_BYTES, tooLarge)
|
||||
}
|
||||
throw invalid("The request body type is not supported.")
|
||||
}
|
||||
|
||||
/** Parse the bounded JSON routing envelope before protocol-specific validation. */
|
||||
export async function readJSONRequest(input, init, signal) {
|
||||
if (signal?.aborted) throw abortReason(signal)
|
||||
const bytes = await readBytes(input, init, signal)
|
||||
let text
|
||||
try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes) }
|
||||
catch { throw invalid("The request body is not valid UTF-8.") }
|
||||
let body
|
||||
try { body = JSON.parse(text) }
|
||||
catch { throw invalid("The request body is not valid JSON.") }
|
||||
if (!isObject(body)) throw invalid("The request body must be a JSON object.")
|
||||
if (typeof body.model !== "string" || !body.model || /[\x00-\x1f\x7f]/.test(body.model)) throw invalid("The \"model\" parameter must be a non-empty string.")
|
||||
return /** @type {{model: string} & Record<string, unknown>} */ (body)
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect every credential substring to redact, longest first.
|
||||
* @param {*} credentials
|
||||
* @param {*} token
|
||||
* @param {string[]} [extraSecrets]
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function secretsOf(credentials, token, extraSecrets) {
|
||||
const out = []
|
||||
if (token && typeof token.value === "string" && token.value) out.push(token.value)
|
||||
if (credentials) {
|
||||
const clientId = credentials.clientId
|
||||
const clientSecret = credentials.clientSecret
|
||||
if (typeof clientId === "string" && clientId) out.push(clientId)
|
||||
if (typeof clientSecret === "string" && clientSecret) out.push(clientSecret)
|
||||
if (typeof clientId === "string" && clientId && typeof clientSecret === "string" && clientSecret) {
|
||||
const raw = clientId + ":" + clientSecret
|
||||
const basic = Buffer.from(raw, "utf8").toString("base64")
|
||||
out.push(raw, basic, "Basic " + basic)
|
||||
}
|
||||
}
|
||||
// resourceGroup is actionable identity, not a secret — never redacted.
|
||||
if (Array.isArray(extraSecrets)) {
|
||||
for (const secret of extraSecrets) if (typeof secret === "string" && secret) out.push(secret)
|
||||
}
|
||||
return out.sort((a, b) => b.length - a.length)
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace every secret substring in a single string.
|
||||
* @param {string} value
|
||||
* @param {string[]} secrets
|
||||
*/
|
||||
export function redactString(value, secrets) {
|
||||
let out = value
|
||||
for (const secret of secrets) if (secret) out = out.split(secret).join("[redacted]")
|
||||
return out
|
||||
}
|
||||
|
||||
export const ERROR_PROTOCOL_FIELDS = new Set(["code", "type", "param", "status"])
|
||||
|
||||
/**
|
||||
* Redact credential echoes in descriptive error details. Native error category
|
||||
* fields are preserved by the caller, not by arbitrary nested key names.
|
||||
* @param {*} value
|
||||
* @param {string[]} secrets
|
||||
* @returns {*}
|
||||
*/
|
||||
export function redactErrorDetails(value, secrets) {
|
||||
if (typeof value === "string") return redactString(value, secrets)
|
||||
if (Array.isArray(value)) return value.map(v => redactErrorDetails(v, secrets))
|
||||
if (isObject(value)) {
|
||||
const out = Object.create(null)
|
||||
for (const key of Object.keys(value)) out[key] = redactErrorDetails(value[key], secrets)
|
||||
return out
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} error
|
||||
* @param {string[]} secrets
|
||||
*/
|
||||
export function redactError(error, secrets) {
|
||||
if (!isObject(error)) return redactErrorDetails(error, secrets)
|
||||
const out = Object.create(null)
|
||||
for (const key of Object.keys(error)) out[key] = ERROR_PROTOCOL_FIELDS.has(key) ? error[key] : redactErrorDetails(error[key], secrets)
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* True only for a verified invalid/expired Bearer rejection.
|
||||
* @param {string | null} header
|
||||
*/
|
||||
export function bearerRejected(header) {
|
||||
if (!header || !/^Bearer\b/i.test(header)) return false
|
||||
return /\berror\s*=\s*(?:"(?:invalid_token|expired_token)"|(?:invalid_token|expired_token))(?=\s|,|$)/i.test(header)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the safe, local-only JSON response headers: drop every upstream header,
|
||||
* keep a numeric-seconds Retry-After only.
|
||||
* @param {Response} upstream
|
||||
*/
|
||||
export function safeHeaders(upstream) {
|
||||
const headers = new Headers({ "content-type": "application/json", "x-magpie-sign-in": "kept" })
|
||||
const retryAfter = upstream.headers.get("retry-after")
|
||||
if (retryAfter && /^\d{1,10}$/.test(retryAfter)) headers.set("retry-after", retryAfter)
|
||||
return headers
|
||||
}
|
||||
|
||||
export function streamHeaders() {
|
||||
return new Headers({ "content-type": "text/event-stream", "x-magpie-sign-in": "kept" })
|
||||
}
|
||||
|
||||
export const SSE_ENCODER = new TextEncoder()
|
||||
|
||||
/**
|
||||
* Generic bounded, data-only SSE relay. Emits at most one frame per pull with
|
||||
* no read-ahead or whole-reply accumulation; byte framing precedes UTF-8
|
||||
* decoding so split code points and split frames are harmless. Protocol
|
||||
* specifics are supplied by callbacks:
|
||||
* classify(event, eventName) -> { terminal, redacted } or throws a safe error
|
||||
* for a malformed/mislabelled frame. `redacted === event` means unchanged.
|
||||
* errorEvent(code) -> the serialized protocol error frame for a local failure.
|
||||
* @param {ReadableStream<Uint8Array>} upstream
|
||||
* @param {AbortSignal | undefined} signal
|
||||
* @param {{ classify: (event: any, name: string) => { terminal: boolean, redacted: any, name?: string }, errorEvent: (code: string) => string }} hooks
|
||||
* @returns {ReadableStream<Uint8Array>}
|
||||
*/
|
||||
export function sseRelay(upstream, signal, { classify, errorEvent }) {
|
||||
const reader = upstream.getReader()
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true })
|
||||
let chunk = new Uint8Array(0)
|
||||
let cursor = 0
|
||||
let skipLF = false
|
||||
let lineEmpty = true
|
||||
let frameBytes = 0
|
||||
/** @type {Uint8Array[]} */
|
||||
let parts = []
|
||||
let finished = false
|
||||
let released = false
|
||||
let onAbort = () => {}
|
||||
|
||||
const release = () => {
|
||||
if (released) return
|
||||
released = true
|
||||
signal?.removeEventListener("abort", onAbort)
|
||||
void reader.cancel().catch(() => {})
|
||||
reader.releaseLock()
|
||||
chunk = new Uint8Array(0)
|
||||
parts = []
|
||||
}
|
||||
const fail = (output, code) => {
|
||||
finished = true
|
||||
release()
|
||||
output.enqueue(SSE_ENCODER.encode(errorEvent(code)))
|
||||
output.close()
|
||||
}
|
||||
|
||||
// Scan bytes only up to the next blank line. A CR completes a line
|
||||
// immediately; a following LF is consumed as part of the same newline.
|
||||
const takeFrame = () => {
|
||||
let start = cursor
|
||||
while (cursor < chunk.length) {
|
||||
const byte = chunk[cursor++]
|
||||
if (skipLF) {
|
||||
skipLF = false
|
||||
if (byte === 10) {
|
||||
if (!frameBytes) start = cursor
|
||||
else if (++frameBytes > MAX_BODY_BYTES) throw safeError("inference-response")
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (++frameBytes > MAX_BODY_BYTES) throw safeError("inference-response")
|
||||
if (byte !== 10 && byte !== 13) { lineEmpty = false; continue }
|
||||
skipLF = byte === 13
|
||||
if (lineEmpty) {
|
||||
parts.push(chunk.subarray(start, cursor))
|
||||
const text = parts.map(part => decoder.decode(part, { stream: true })).join("") + decoder.decode()
|
||||
parts = []
|
||||
frameBytes = 0
|
||||
return text
|
||||
}
|
||||
lineEmpty = true
|
||||
}
|
||||
if (cursor > start) parts.push(chunk.subarray(start, cursor))
|
||||
return null
|
||||
}
|
||||
|
||||
return new ReadableStream({
|
||||
start(output) {
|
||||
onAbort = () => {
|
||||
if (finished) return
|
||||
finished = true
|
||||
release()
|
||||
output.error(safeError("inference-cancelled"))
|
||||
}
|
||||
signal?.addEventListener("abort", onAbort, { once: true })
|
||||
if (signal?.aborted) onAbort()
|
||||
},
|
||||
async pull(output) {
|
||||
if (finished) { output.close(); return }
|
||||
try {
|
||||
for (;;) {
|
||||
const raw = takeFrame()
|
||||
if (raw !== null) {
|
||||
const lines = raw.split(/\r\n|\r|\n/)
|
||||
const data = []
|
||||
let name = ""
|
||||
for (const line of lines) {
|
||||
const colon = line.indexOf(":")
|
||||
const field = colon < 0 ? line : line.slice(0, colon)
|
||||
let value = colon < 0 ? "" : line.slice(colon + 1)
|
||||
if (value.startsWith(" ")) value = value.slice(1)
|
||||
if (field === "data") data.push(value)
|
||||
else if (field === "event") name = value
|
||||
}
|
||||
if (!data.length) continue // comment / keep-alive / metadata only
|
||||
let event
|
||||
try { event = JSON.parse(data.join("\n")) } catch { throw safeError("inference-response") }
|
||||
const { terminal, redacted, name: emitName } = classify(event, name)
|
||||
let text
|
||||
if (redacted === event) {
|
||||
text = raw.replace(/\r\n|\r/g, "\n")
|
||||
} else {
|
||||
// Rebuild a redacted frame without a leading blank line, preserving any
|
||||
// non-data lines (e.g. an existing `event:`) ahead of the new data.
|
||||
const kept = lines.filter(line => line && !line.startsWith("data:"))
|
||||
text = [...kept, "data: " + JSON.stringify(redacted)].join("\n") + "\n\n"
|
||||
}
|
||||
// Some upstreams (SAP) relay data-only frames; clients that dispatch on
|
||||
// the SSE `event:` name need it synthesized from the event type.
|
||||
if (emitName && !/^event:/m.test(text)) text = "event: " + emitName + "\n" + text
|
||||
output.enqueue(SSE_ENCODER.encode(text))
|
||||
if (terminal) {
|
||||
finished = true
|
||||
release()
|
||||
output.close()
|
||||
}
|
||||
return
|
||||
}
|
||||
let next
|
||||
try { next = await reader.read() }
|
||||
catch {
|
||||
if (!finished) fail(output, "inference-network")
|
||||
return
|
||||
}
|
||||
if (finished) return
|
||||
if (next.done) {
|
||||
// EOF without a valid, fully framed terminal is truncation, not
|
||||
// completion. This also rejects any trailing partial UTF-8/frame.
|
||||
fail(output, "inference-response")
|
||||
return
|
||||
}
|
||||
chunk = next.value
|
||||
cursor = 0
|
||||
}
|
||||
} catch {
|
||||
if (!finished) fail(output, "inference-response")
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
finished = true
|
||||
release()
|
||||
},
|
||||
}, { highWaterMark: 0 })
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a locally-owned safe error into a standard JSON Response. Only errors
|
||||
* created here (or by a transport reusing this module) or flagged `trusted` by
|
||||
* the parent are echoed; everything else is sanitized to a generic internal
|
||||
* error.
|
||||
* @param {*} error
|
||||
* @param {boolean} [trusted]
|
||||
* @returns {Response}
|
||||
*/
|
||||
export function responseError(error, trusted = false) {
|
||||
const safe = (trusted === true || OWNED.has(error)) &&
|
||||
error && typeof error.code === "string" && typeof error.message === "string"
|
||||
|
||||
const code = safe ? error.code : "internal"
|
||||
const message = safe ? error.message : GENERIC_MESSAGE
|
||||
const status = safe && Number.isInteger(error.status) && error.status >= 400 && error.status <= 599
|
||||
? error.status
|
||||
: (STATUS[code] ?? 500)
|
||||
|
||||
const headers = new Headers({ "content-type": "application/json" })
|
||||
if (safe && /^\d{1,10}$/.test(String(error.retryAfter ?? ""))) {
|
||||
headers.set("retry-after", String(error.retryAfter))
|
||||
}
|
||||
|
||||
// X-Magpie-Sign-In: "expired" only for a locally verified oauth-refused; every
|
||||
// other response keeps the session ("kept") so the host never lapses it falsely.
|
||||
headers.set("x-magpie-sign-in", code === "oauth-refused" ? "expired" : "kept")
|
||||
|
||||
return new Response(JSON.stringify({ error: { code, message } }), { status, headers })
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const urlFor = id => ROOT + "/v2/inference/deployments/" + id
|
||||
|
||||
// Two accounts/resource groups with overlapping canonical GPT and Claude names
|
||||
// but distinct raw SAP identities and deployments for the same canonical Claude
|
||||
// model (version-first vs variant-first SAP format, both -> claude-opus-4-8).
|
||||
const GROUPS = {
|
||||
"group-a": {
|
||||
client: "client-a",
|
||||
gpt: { did: "deploy-a-gpt", cid: "cfg-a-gpt" },
|
||||
opus: { sap: "anthropic--claude-4.8-opus", display: "Claude 4.8 Opus", did: "deploy-a-opus", cid: "cfg-a-opus" },
|
||||
},
|
||||
"group-b": {
|
||||
client: "client-b",
|
||||
gpt: { did: "deploy-b-gpt", cid: "cfg-b-gpt" },
|
||||
opus: { sap: "anthropic--claude-opus-4.8", display: "Claude Opus 4.8", did: "deploy-b-opus", cid: "cfg-b-opus" },
|
||||
},
|
||||
}
|
||||
|
||||
const message = model => ({ id: "msg_" + model, type: "message", role: "assistant", model, content: [{ type: "text", text: "OK:" + model }], stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 3, output_tokens: 2 } })
|
||||
|
||||
function backend(creds, group) {
|
||||
const json = body => new Response(JSON.stringify(body))
|
||||
const g = GROUPS[group]
|
||||
const deployments = [
|
||||
{ id: g.gpt.did, status: "RUNNING", deploymentUrl: urlFor(g.gpt.did), configurationId: g.gpt.cid, details: { resources: { backendDetails: { model: { name: "gpt-6-astra", version: "2026-09-03" } } } } },
|
||||
{ id: g.opus.did, status: "RUNNING", deploymentUrl: urlFor(g.opus.did), configurationId: g.opus.cid, details: { resources: { backendDetails: { model: { name: g.opus.sap, version: "1" } } } } },
|
||||
]
|
||||
const configs = {
|
||||
[g.gpt.cid]: { id: g.gpt.cid, scenarioId: "foundation-models", executableId: "azure-openai", parameterBindings: [{ key: "modelName", value: "gpt-6-astra" }, { key: "modelVersion", value: "2026-09-03" }] },
|
||||
[g.opus.cid]: { id: g.opus.cid, scenarioId: "foundation-models", executableId: "aws-bedrock", parameterBindings: [{ key: "modelName", value: g.opus.sap }, { key: "modelVersion", value: "1" }] },
|
||||
}
|
||||
const catalog = { count: 2, resources: [
|
||||
{ model: "gpt-6-astra", executableId: "azure-openai", allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }], versions: [{ name: "2026-09-03", contextLength: 1050000, inputTypes: ["text"], streamingSupported: true }] },
|
||||
{ model: g.opus.sap, executableId: "aws-bedrock", provider: "Anthropic", displayName: g.opus.display, allowedScenarios: [{ scenarioId: "foundation-models", executableId: "aws-bedrock" }], versions: [{ name: "1", contextLength: 1000000, inputTypes: ["text"], streamingSupported: true }] },
|
||||
] }
|
||||
return { json, deployments, configs, catalog }
|
||||
}
|
||||
|
||||
function install(counters) {
|
||||
const original = globalThis.fetch
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
const inference = []
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = new URL(String(input))
|
||||
const json = body => new Response(JSON.stringify(body))
|
||||
if (url.pathname === "/oauth/token") {
|
||||
const basic = Buffer.from((init.headers.Authorization || "").replace(/^Basic\s+/, ""), "base64").toString("utf8")
|
||||
const client = basic.split(":")[0]
|
||||
counters.oauth[client] = (counters.oauth[client] ?? 0) + 1
|
||||
return json({ access_token: "token-" + client, token_type: "bearer", expires_in: 3600 })
|
||||
}
|
||||
const group = init.headers?.["AI-Resource-Group"]
|
||||
const b = backend(null, group)
|
||||
if (url.pathname === "/v2/lm/deployments") return b.json({ resources: url.searchParams.get("$skip") === "0" ? b.deployments : [] })
|
||||
if (url.pathname.startsWith("/v2/lm/configurations/")) return b.json(b.configs[url.pathname.slice("/v2/lm/configurations/".length)])
|
||||
if (url.pathname === "/v2/lm/scenarios/foundation-models/models") return b.json(b.catalog)
|
||||
// inference
|
||||
inference.push({ url: url.href, group, auth: init.headers.authorization })
|
||||
const model = url.pathname.includes("-opus") ? "claude-opus-4-8" : "gpt-6-astra"
|
||||
if (url.pathname.endsWith("/responses")) return new Response(JSON.stringify({ id: "resp", object: "response", model, status: "completed", output: [{ id: "m", type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text: "OK:" + model, annotations: [] }] }], usage: {}, error: null, incomplete_details: null }))
|
||||
return new Response(JSON.stringify(message(model)))
|
||||
}
|
||||
return inference
|
||||
}
|
||||
|
||||
function writeCreds(dir, name, group) {
|
||||
const file = path.join(dir, name)
|
||||
fs.writeFileSync(file, JSON.stringify({
|
||||
authUrl: "https://t.authentication.eu10.hana.ondemand.com",
|
||||
baseUrl: ROOT + "/v2",
|
||||
clientId: GROUPS[group].client,
|
||||
clientSecret: "secret-" + group,
|
||||
resourceGroup: group,
|
||||
}), { mode: 0o600 })
|
||||
return file
|
||||
}
|
||||
|
||||
async function account(plugin, credentialFile) {
|
||||
const signed = await plugin.auth.methods[0].authorize({ credentialFile })
|
||||
assert.equal(signed.type, "success")
|
||||
const auth = { type: "api", key: signed.key, metadata: signed.metadata }
|
||||
const loader = await plugin.auth.loader(async () => auth)
|
||||
return { auth, loader }
|
||||
}
|
||||
|
||||
test("two accounts expose the same canonical Claude ID yet dispatch never crosses identity, group or protocol", async () => {
|
||||
const counters = { oauth: {} }
|
||||
const inference = install(counters)
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-accounts-"))
|
||||
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }))
|
||||
const fileA = writeCreds(dir, "a.json", "group-a")
|
||||
const fileB = writeCreds(dir, "b.json", "group-b")
|
||||
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const a = await account(plugin, fileA)
|
||||
const b = await account(plugin, fileB)
|
||||
|
||||
// Both accounts list the same canonical IDs with canonical (never raw SAP) api.id.
|
||||
for (const acc of [a, b]) {
|
||||
const models = await plugin.provider.models({ models: {} }, { auth: acc.auth })
|
||||
assert.deepEqual(Object.keys(models).sort(), ["claude-opus-4-8", "gpt-6-astra"])
|
||||
assert.deepEqual(models["claude-opus-4-8"].api, { id: "claude-opus-4-8", npm: "@ai-sdk/anthropic" })
|
||||
}
|
||||
|
||||
// Claude dispatch on each account reaches that account's own deployment/group.
|
||||
const ra = await a.loader.fetch(ROOT + "/messages", { method: "POST", body: JSON.stringify({ model: "claude-opus-4-8", messages: [{ role: "user", content: "hi" }], max_tokens: 16 }) })
|
||||
const rb = await b.loader.fetch(ROOT + "/messages", { method: "POST", body: JSON.stringify({ model: "claude-opus-4-8", messages: [{ role: "user", content: "hi" }], max_tokens: 16 }) })
|
||||
assert.equal(ra.status, 200)
|
||||
assert.equal(rb.status, 200)
|
||||
|
||||
const opusCalls = inference.filter(c => c.url.includes("-opus/invoke"))
|
||||
assert.deepEqual(opusCalls.map(c => c.url).sort(), [urlFor("deploy-a-opus") + "/invoke", urlFor("deploy-b-opus") + "/invoke"])
|
||||
const a1 = opusCalls.find(c => c.group === "group-a")
|
||||
const b1 = opusCalls.find(c => c.group === "group-b")
|
||||
assert.equal(a1.url, urlFor("deploy-a-opus") + "/invoke")
|
||||
assert.equal(a1.auth, "Bearer token-client-a")
|
||||
assert.equal(b1.url, urlFor("deploy-b-opus") + "/invoke")
|
||||
assert.equal(b1.auth, "Bearer token-client-b")
|
||||
})
|
||||
|
||||
test("GPT and Claude share one account-scoped token without extra OAuth exchanges or crossing accounts", async () => {
|
||||
const counters = { oauth: {} }
|
||||
const inference = install(counters)
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-accounts-tok-"))
|
||||
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }))
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const a = await account(plugin, writeCreds(dir, "a.json", "group-a"))
|
||||
|
||||
await a.loader.fetch(ROOT + "/responses", { method: "POST", body: JSON.stringify({ model: "gpt-6-astra", input: "hi" }) })
|
||||
await a.loader.fetch(ROOT + "/messages", { method: "POST", body: JSON.stringify({ model: "claude-opus-4-8", messages: [{ role: "user", content: "hi" }], max_tokens: 16 }) })
|
||||
|
||||
assert.equal(counters.oauth["client-a"], 1, "a single OAuth exchange serves both protocols")
|
||||
assert.equal(counters.oauth["client-b"], undefined, "no cross-account token work")
|
||||
assert.deepEqual(inference.map(c => c.group), ["group-a", "group-a"])
|
||||
})
|
||||
|
||||
test("after a restart a fresh plugin rebuilds discovery and dispatch from the credential file alone", async () => {
|
||||
const counters = { oauth: {} }
|
||||
const inference = install(counters)
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-accounts-restart-"))
|
||||
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }))
|
||||
const file = writeCreds(dir, "b.json", "group-b")
|
||||
|
||||
// First process: sign in and dispatch.
|
||||
const first = await SAPAICorePlugin()
|
||||
const a1 = await account(first, file)
|
||||
assert.equal((await a1.loader.fetch(ROOT + "/messages", { method: "POST", body: JSON.stringify({ model: "claude-opus-4-8", messages: [{ role: "user", content: "hi" }], max_tokens: 16 }) })).status, 200)
|
||||
|
||||
// Restart: a brand-new plugin instance with no prior in-memory state, only the
|
||||
// stored credential-file reference, rebuilds the same canonical mapping.
|
||||
const second = await SAPAICorePlugin()
|
||||
const stored = { type: "api", key: a1.auth.key, metadata: a1.auth.metadata }
|
||||
const loader = await second.auth.loader(async () => stored)
|
||||
const models = await second.provider.models({ models: {} }, { auth: stored })
|
||||
assert.equal(models["claude-opus-4-8"].api.id, "claude-opus-4-8")
|
||||
const response = await loader.fetch(ROOT + "/messages", { method: "POST", body: JSON.stringify({ model: "claude-opus-4-8", messages: [{ role: "user", content: "hi" }], max_tokens: 16 }) })
|
||||
assert.equal(response.status, 200)
|
||||
assert.equal(inference.at(-1).url, urlFor("deploy-b-opus") + "/invoke", "restart rebuilds the group-b raw identity/deployment mapping")
|
||||
})
|
||||
@@ -0,0 +1,203 @@
|
||||
import { it, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdtemp, writeFile, rm } from "node:fs/promises"
|
||||
import { existsSync } from "node:fs"
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
|
||||
// Resolve mkfifo from absolute candidates at load, independent of process.env.PATH:
|
||||
// under the monorepo's shared bun-test process a sibling package may narrow PATH,
|
||||
// and no preload freezes it anymore.
|
||||
const MKFIFO = ["/usr/bin/mkfifo", "/bin/mkfifo", "/usr/local/bin/mkfifo"].find(existsSync)
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const creds = {
|
||||
authUrl: "https://synthetic.authentication.eu10.hana.ondemand.com",
|
||||
baseUrl: "https://api.ai.prod.eu10.hana.ondemand.com",
|
||||
clientId: "synthetic-id",
|
||||
clientSecret: "synthetic-secret",
|
||||
resourceGroup: "default",
|
||||
}
|
||||
const target = creds.baseUrl + "/responses"
|
||||
const body = JSON.stringify({ model: "gpt-6-astra", input: "hello" })
|
||||
const reply = (expires_in = 120) => new Response(JSON.stringify({ access_token: "synthetic-token", expires_in }))
|
||||
function gate() {
|
||||
let resolve
|
||||
const promise = new Promise(ok => { resolve = ok })
|
||||
return { promise, resolve }
|
||||
}
|
||||
async function sandbox(run) {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "aicore-regression-"))
|
||||
const file = path.join(dir, "credentials.json")
|
||||
await writeFile(file, JSON.stringify(creds), { mode: 0o600 })
|
||||
const fetch = globalThis.fetch
|
||||
const clock = performance.now
|
||||
const timers = globalThis.setTimeout
|
||||
try {
|
||||
globalThis.fetch = async (href) => {
|
||||
if (new URL(String(href)).pathname === "/v2/lm/deployments") return new Response(JSON.stringify({ resources: [] }))
|
||||
return reply()
|
||||
}
|
||||
await run({ dir, file })
|
||||
} finally {
|
||||
globalThis.fetch = fetch
|
||||
performance.now = clock
|
||||
globalThis.setTimeout = timers
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
async function signed(file) {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const result = await plugin.auth.methods[0].authorize({ credentialFile: file })
|
||||
assert.equal(result.type, "success")
|
||||
const auth = { type: "api", key: result.key, metadata: result.metadata }
|
||||
return { plugin, auth }
|
||||
}
|
||||
|
||||
it("wrong method, route and SAP account origin cannot acquire a token", () => sandbox(async ({ file }) => {
|
||||
let now = 0
|
||||
performance.now = () => now
|
||||
const { plugin, auth } = await signed(file)
|
||||
const opts = await plugin.auth.loader(async () => auth)
|
||||
now = 61000
|
||||
let calls = 0
|
||||
globalThis.fetch = async () => { calls++; return reply() }
|
||||
for (const [url, method] of [[target, "GET"], [target, 42], [target + "/cancel", "POST"], ["https://api.ai.other.eu10.hana.ondemand.com/responses", "POST"], [target + "?", "POST"]]) {
|
||||
const response = await opts.fetch(url, { method })
|
||||
assert.equal(response.status, 400)
|
||||
assert.equal((await response.json()).error.code, "destination")
|
||||
}
|
||||
assert.equal(calls, 0)
|
||||
}))
|
||||
|
||||
it("model initialization failure throws instead of reporting an empty catalog", () => sandbox(async ({ file }) => {
|
||||
const { auth } = await signed(file)
|
||||
await writeFile(file, "not-json")
|
||||
const restored = await SAPAICorePlugin()
|
||||
await assert.rejects(restored.provider.models({}, { auth }), { code: "credentials" })
|
||||
await writeFile(file, JSON.stringify(creds))
|
||||
assert.deepEqual(await restored.provider.models({}, { auth }), {})
|
||||
assert.deepEqual(await restored.provider.models({}, {}), {})
|
||||
}))
|
||||
|
||||
it("shared waiter abort rejects before upstream completion and does not abort survivor", () => sandbox(async ({ file }) => {
|
||||
let now = 0
|
||||
performance.now = () => now
|
||||
const { plugin, auth } = await signed(file)
|
||||
const opts = await plugin.auth.loader(async () => auth)
|
||||
now = 61000
|
||||
const started = gate()
|
||||
const finish = gate()
|
||||
let calls = 0
|
||||
let upstream
|
||||
globalThis.fetch = async (_, init) => {
|
||||
calls++
|
||||
upstream = init.signal
|
||||
started.resolve()
|
||||
await finish.promise
|
||||
return reply()
|
||||
}
|
||||
const controller = new AbortController()
|
||||
const first = opts.fetch(target, { method: "POST", body, signal: controller.signal })
|
||||
const second = opts.fetch(target, { method: "POST", body })
|
||||
await started.promise
|
||||
await new Promise(ok => setImmediate(ok))
|
||||
controller.abort()
|
||||
assert.equal((await first).status, 499)
|
||||
assert.equal(upstream.aborted, false)
|
||||
assert.equal(calls, 1)
|
||||
finish.resolve()
|
||||
assert.equal((await second).status, 404)
|
||||
}))
|
||||
|
||||
it("ignored-abort late acquisition cannot warm token cache and next operation recovers", () => sandbox(async ({ file }) => {
|
||||
let now = 0
|
||||
performance.now = () => now
|
||||
const { plugin, auth } = await signed(file)
|
||||
const opts = await plugin.auth.loader(async () => auth)
|
||||
now = 61000
|
||||
const started = gate()
|
||||
const finish = gate()
|
||||
let upstream
|
||||
globalThis.fetch = async (_, init) => { upstream = init.signal; started.resolve(); await finish.promise; return reply() }
|
||||
const controller = new AbortController()
|
||||
const request = opts.fetch(target, { method: "POST", body, signal: controller.signal })
|
||||
await started.promise
|
||||
controller.abort()
|
||||
assert.equal((await request).status, 499)
|
||||
assert.equal(upstream.aborted, true)
|
||||
finish.resolve()
|
||||
await new Promise(ok => setImmediate(ok))
|
||||
let calls = 0
|
||||
globalThis.fetch = async () => { calls++; return reply() }
|
||||
assert.equal((await opts.fetch(target, { method: "POST", body })).status, 404)
|
||||
assert.equal(calls, 1)
|
||||
}))
|
||||
|
||||
it("late OAuth refusal cannot expire an explicitly replaced slot", () => sandbox(async ({ file, dir }) => {
|
||||
let now = 0
|
||||
performance.now = () => now
|
||||
const { plugin, auth } = await signed(file)
|
||||
let selected = auth
|
||||
const opts = await plugin.auth.loader(async () => selected)
|
||||
now = 61000
|
||||
const started = gate()
|
||||
const finish = gate()
|
||||
globalThis.fetch = async () => {
|
||||
started.resolve()
|
||||
await finish.promise
|
||||
return new Response(JSON.stringify({ error: "invalid_client" }), { status: 401, headers: { "www-authenticate": "Basic realm=OAuth" } })
|
||||
}
|
||||
const pending = opts.fetch(target, { method: "POST", body })
|
||||
await started.promise
|
||||
const other = path.join(dir, "other.json")
|
||||
await writeFile(other, JSON.stringify(creds))
|
||||
globalThis.fetch = async () => reply()
|
||||
const replacement = await plugin.auth.methods[0].authorize({ credentialFile: other })
|
||||
assert.equal(replacement.type, "success")
|
||||
selected = { type: "api", key: replacement.key, metadata: replacement.metadata }
|
||||
finish.resolve()
|
||||
const response = await pending
|
||||
assert.equal(response.headers.get("x-magpie-sign-in"), "kept")
|
||||
assert.equal((await response.json()).error.code, "superseded")
|
||||
}))
|
||||
|
||||
it("token deadline bounds fetch that ignores abort", () => sandbox(async ({ file }) => {
|
||||
const original = setTimeout
|
||||
globalThis.setTimeout = (fn, ms, ...args) => original(fn, ms === 15000 ? 20 : ms, ...args)
|
||||
let upstream
|
||||
globalThis.fetch = async (_, init) => { upstream = init.signal; return new Promise(() => {}) }
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const result = await plugin.auth.methods[0].authorize({ credentialFile: file })
|
||||
assert.equal(result.type, "failed")
|
||||
assert.match(result.error, /timed out/)
|
||||
assert.equal(upstream.aborted, true)
|
||||
}))
|
||||
|
||||
it.skipIf(process.platform === "win32" || !MKFIFO)("FIFO credentials reject without waiting for a writer", () => sandbox(async ({ dir }) => {
|
||||
const file = path.join(dir, "fifo")
|
||||
execFileSync(MKFIFO, [file])
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const result = await plugin.auth.methods[0].authorize({ credentialFile: file })
|
||||
assert.equal(result.type, "failed")
|
||||
assert.match(result.error, /could not be read/)
|
||||
}))
|
||||
|
||||
it("malformed and wrong OAuth response URLs fail closed", () => sandbox(async ({ file }) => {
|
||||
for (const url of ["not-url", creds.authUrl + "/oauth/token?secret=synthetic", creds.authUrl + "/oauth/token#x"]) {
|
||||
globalThis.fetch = async () => {
|
||||
const response = reply()
|
||||
Object.defineProperty(response, "url", { value: url })
|
||||
return response
|
||||
}
|
||||
const plugin = await SAPAICorePlugin()
|
||||
assert.equal((await plugin.auth.methods[0].authorize({ credentialFile: file })).type, "failed")
|
||||
}
|
||||
}))
|
||||
@@ -0,0 +1,406 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { resolveDeployment, projectModels, discover } from "../src/discovery.js"
|
||||
import { claudeFamily, resolveCanonicalClaude } from "../src/identity.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const AI_ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const GROUP = "default"
|
||||
const OPUS_ID = "d9df30a64cef44d6"
|
||||
const SONNET_ID = "d41e534c5ac13dbf"
|
||||
const OPUS_SAP = "anthropic--claude-4.8-opus"
|
||||
const SONNET_SAP = "anthropic--claude-4.6-sonnet"
|
||||
|
||||
// --- canonical identity resolver ------------------------------------------
|
||||
|
||||
test("resolver maps the baseline display names to conventional canonical IDs", () => {
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: OPUS_SAP, displayName: "Claude 4.8 Opus" }),
|
||||
{ canonicalID: "claude-opus-4-8", displayLabel: "Claude Opus 4.8" })
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: SONNET_SAP, displayName: "Claude 4.6 Sonnet" }),
|
||||
{ canonicalID: "claude-sonnet-4-6", displayLabel: "Claude Sonnet 4.6" })
|
||||
})
|
||||
|
||||
test("resolver falls back to the SAP identity format when no display name is present", () => {
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: OPUS_SAP }),
|
||||
{ canonicalID: "claude-opus-4-8", displayLabel: "Claude Opus 4.8" })
|
||||
})
|
||||
|
||||
test("resolver is stable across changed prefix, delimiter and token order", () => {
|
||||
for (const id of ["aws__claude-4.8-opus", "bedrock::claude-4.8-opus", "anthropic--claude-opus-4.8"]) {
|
||||
assert.equal(resolveCanonicalClaude({ sapIdentity: id }).canonicalID, "claude-opus-4-8", id)
|
||||
}
|
||||
})
|
||||
|
||||
test("resolver derives newer models from metadata without a code change", () => {
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: "anthropic--claude-4.9-opus", displayName: "Claude 4.9 Opus" }),
|
||||
{ canonicalID: "claude-opus-4-9", displayLabel: "Claude Opus 4.9" })
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: "x", displayName: "Claude Haiku 5" }),
|
||||
{ canonicalID: "claude-haiku-5", displayLabel: "Claude Haiku 5" })
|
||||
})
|
||||
|
||||
test("resolver preserves meaningful suffixes rather than collapsing releases", () => {
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: "z", displayName: "Claude 3.5 Sonnet 20241022" }),
|
||||
{ canonicalID: "claude-sonnet-3-5-20241022", displayLabel: "Claude Sonnet 3.5 20241022" })
|
||||
})
|
||||
|
||||
test("resolver reads hyphenated numeric versions in either token order and case", () => {
|
||||
for (const id of ["anthropic--claude-opus-4-8", "anthropic--claude-4-8-opus", "AWS__Claude-OPUS-4-8"]) {
|
||||
const r = resolveCanonicalClaude({ sapIdentity: id })
|
||||
assert.equal(r.canonicalID, "claude-opus-4-8", id)
|
||||
assert.equal(r.displayLabel, "Claude Opus 4.8", id)
|
||||
}
|
||||
})
|
||||
|
||||
test("resolver keeps a long numeric date suffix out of the hyphenated version", () => {
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: "anthropic--claude-sonnet-3-5-20241022" }),
|
||||
{ canonicalID: "claude-sonnet-3-5-20241022", displayLabel: "Claude Sonnet 3.5 20241022" })
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: "anthropic--claude-opus-4-8-preview", displayName: "Claude 4.8 Opus PREVIEW" }),
|
||||
{ canonicalID: "claude-opus-4-8-preview", displayLabel: "Claude Opus 4.8 PREVIEW" })
|
||||
})
|
||||
|
||||
test("resolver rejects non-string evidence and present-but-unparseable display names", () => {
|
||||
assert.equal(resolveCanonicalClaude({ sapIdentity: OPUS_SAP, displayName: { foo: 1 } }), null)
|
||||
assert.equal(resolveCanonicalClaude({ sapIdentity: 42, displayName: "Claude 4.8 Opus" }), null)
|
||||
assert.equal(resolveCanonicalClaude({ sapIdentity: OPUS_SAP, displayName: "Totally Bogus" }), null)
|
||||
})
|
||||
|
||||
test("resolver reports conflicting display vs identity evidence instead of guessing", () => {
|
||||
assert.equal(resolveCanonicalClaude({ sapIdentity: OPUS_SAP, displayName: "Claude 4.6 Sonnet" }), null)
|
||||
})
|
||||
|
||||
test("resolver returns null for genuinely opaque, unrecognized evidence", () => {
|
||||
assert.equal(resolveCanonicalClaude({ sapIdentity: "opaque-key-1234", displayName: "Mystery Model" }), null)
|
||||
assert.equal(resolveCanonicalClaude({}), null)
|
||||
})
|
||||
|
||||
test("resolver falls back to the SAP identity format for an absent (whitespace) display name", () => {
|
||||
assert.deepEqual(resolveCanonicalClaude({ sapIdentity: OPUS_SAP, displayName: " " }),
|
||||
{ canonicalID: "claude-opus-4-8", displayLabel: "Claude Opus 4.8" })
|
||||
})
|
||||
|
||||
test("claudeFamily recognizes Anthropic by provider or Claude identity, not executable alone", () => {
|
||||
assert.equal(claudeFamily({ provider: "Anthropic" }), true)
|
||||
assert.equal(claudeFamily({ sapIdentity: OPUS_SAP }), true)
|
||||
assert.equal(claudeFamily({ displayName: "Claude 4.8 Opus" }), true)
|
||||
assert.equal(claudeFamily({ provider: "Amazon", sapIdentity: "amazon--titan-text", displayName: "Titan Text" }), false)
|
||||
assert.equal(claudeFamily({}), false)
|
||||
})
|
||||
|
||||
test("explicit non-Anthropic or malformed family metadata overrides Claude-like names", () => {
|
||||
for (const provider of ["Amazon", "OpenAI", "", 42, null, {}]) {
|
||||
assert.equal(claudeFamily({ provider, sapIdentity: OPUS_SAP, displayName: "Claude 4.8 Opus" }), false)
|
||||
}
|
||||
assert.equal(claudeFamily({ provider: "Anthropic", sapIdentity: 42 }), false)
|
||||
assert.equal(claudeFamily({ provider: "Anthropic", displayName: {} }), false)
|
||||
assert.equal(claudeFamily({ sapIdentity: OPUS_SAP, displayName: null }), false)
|
||||
})
|
||||
|
||||
// --- Claude eligibility (resolveDeployment) --------------------------------
|
||||
|
||||
function urlFor(id) { return AI_ROOT + "/v2/inference/deployments/" + id }
|
||||
|
||||
function bedrockDeployment(id, sapModel, version, cid) {
|
||||
return {
|
||||
id,
|
||||
status: "RUNNING",
|
||||
deploymentUrl: urlFor(id),
|
||||
configurationId: cid,
|
||||
details: { resources: { backendDetails: { model: { name: sapModel, version } } } },
|
||||
}
|
||||
}
|
||||
|
||||
function bedrockConfig(sapModel, version, cid) {
|
||||
return {
|
||||
id: cid,
|
||||
scenarioId: "foundation-models",
|
||||
executableId: "aws-bedrock",
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: sapModel },
|
||||
...(version === undefined ? [] : [{ key: "modelVersion", value: version }]),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function bedrockCatalog(sapModel, version, { displayName, provider = "Anthropic", contextLength = 1000000, inputTypes = ["text", "image"] } = {}) {
|
||||
return {
|
||||
count: 1,
|
||||
resources: [{
|
||||
model: sapModel,
|
||||
executableId: "aws-bedrock",
|
||||
provider,
|
||||
displayName,
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: "aws-bedrock" }],
|
||||
versions: [{ name: version, contextLength, inputTypes, deprecated: false, retirementDate: "", streamingSupported: true }],
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
function opus(over = {}) {
|
||||
return {
|
||||
deployment: bedrockDeployment(OPUS_ID, OPUS_SAP, "1", "cfg-opus"),
|
||||
configuration: bedrockConfig(OPUS_SAP, "1", "cfg-opus"),
|
||||
catalog: bedrockCatalog(OPUS_SAP, "1", { displayName: "Claude 4.8 Opus" }),
|
||||
aiRoot: AI_ROOT,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
test("a running Bedrock Claude deployment resolves to a frozen anthropic entry with canonical identity", () => {
|
||||
const entry = resolveDeployment(opus())
|
||||
assert.equal(entry.protocol, "anthropic")
|
||||
assert.equal(entry.canonicalID, "claude-opus-4-8")
|
||||
assert.equal(entry.displayLabel, "Claude Opus 4.8")
|
||||
assert.equal(entry.apiNpm, "@ai-sdk/anthropic")
|
||||
assert.equal(entry.modelName, OPUS_SAP, "raw SAP identity retained for account-local routing")
|
||||
assert.equal(entry.deploymentID, OPUS_ID)
|
||||
assert.equal(entry.deploymentURL, urlFor(OPUS_ID))
|
||||
assert.equal(entry.activeVersion, "1")
|
||||
assert.equal(entry.executableID, "aws-bedrock")
|
||||
assert.deepEqual(entry.routePolicy, { invoke: "/invoke", stream: "/invoke-with-response-stream", query: false })
|
||||
assert.deepEqual(entry.capabilities, { text: true, functionTool: true, streaming: true, image: true })
|
||||
assert.equal(entry.metadata.contextLength, 1000000)
|
||||
assert.ok(Object.isFrozen(entry) && Object.isFrozen(entry.routePolicy))
|
||||
assert.deepEqual(entry.requestPolicy,
|
||||
{ maxOutputTokens: 128000, rejectTemperature: true, rejectTopP: true, rejectEnabledThinking: true })
|
||||
assert.ok(Object.isFrozen(entry.requestPolicy))
|
||||
})
|
||||
|
||||
test("a newer Claude model/version is eligible by contract with version-specific metadata, no allowlist", () => {
|
||||
const entry = resolveDeployment({
|
||||
deployment: bedrockDeployment(OPUS_ID, "anthropic--claude-4.9-opus", "2", "cfg-x"),
|
||||
configuration: bedrockConfig("anthropic--claude-4.9-opus", "latest", "cfg-x"),
|
||||
catalog: bedrockCatalog("anthropic--claude-4.9-opus", "2", { displayName: "Claude 4.9 Opus", contextLength: 2000000 }),
|
||||
aiRoot: AI_ROOT,
|
||||
})
|
||||
assert.equal(entry.canonicalID, "claude-opus-4-9")
|
||||
assert.equal(entry.activeVersion, "2")
|
||||
assert.equal(entry.metadata.contextLength, 2000000, "limits come from its own version, not a baseline")
|
||||
assert.equal(entry.requestPolicy, undefined, "a newer version never inherits the baseline request policy")
|
||||
})
|
||||
|
||||
test("a Claude backend latest selector is unresolved even with matching catalog metadata", () => {
|
||||
for (const configuredVersion of [undefined, "latest"]) {
|
||||
assert.equal(resolveDeployment(opus({
|
||||
deployment: bedrockDeployment(OPUS_ID, OPUS_SAP, "latest", "cfg-opus"),
|
||||
configuration: bedrockConfig(OPUS_SAP, configuredVersion, "cfg-opus"),
|
||||
catalog: bedrockCatalog(OPUS_SAP, "latest", { displayName: "Claude 4.8 Opus" }),
|
||||
})), null)
|
||||
}
|
||||
})
|
||||
|
||||
test("a newer active version of a baseline release does not inherit its output or sampling policy", () => {
|
||||
const entry = resolveDeployment({
|
||||
deployment: bedrockDeployment(OPUS_ID, OPUS_SAP, "2", "cfg-x"),
|
||||
configuration: bedrockConfig(OPUS_SAP, "latest", "cfg-x"),
|
||||
catalog: bedrockCatalog(OPUS_SAP, "2", { displayName: "Claude 4.8 Opus" }),
|
||||
aiRoot: AI_ROOT,
|
||||
})
|
||||
assert.equal(entry.activeVersion, "2")
|
||||
assert.equal(entry.requestPolicy, undefined)
|
||||
assert.equal(projectModels({ [entry.canonicalID]: entry })[entry.canonicalID].limit.output, undefined)
|
||||
})
|
||||
|
||||
test("a non-Claude Bedrock model (Titan) is silently skipped, not an error", () => {
|
||||
const entry = resolveDeployment({
|
||||
deployment: bedrockDeployment(OPUS_ID, "amazon--titan-text", "1", "cfg-t"),
|
||||
configuration: bedrockConfig("amazon--titan-text", "1", "cfg-t"),
|
||||
catalog: bedrockCatalog("amazon--titan-text", "1", { displayName: "Titan Text", provider: "Amazon" }),
|
||||
aiRoot: AI_ROOT,
|
||||
})
|
||||
assert.equal(entry, null)
|
||||
})
|
||||
|
||||
test("a Claude deployment whose identity cannot be resolved throws an observable discovery error", () => {
|
||||
assert.throws(() => resolveDeployment({
|
||||
deployment: bedrockDeployment(OPUS_ID, "opaque-key-9", "1", "cfg-o"),
|
||||
configuration: bedrockConfig("opaque-key-9", "1", "cfg-o"),
|
||||
catalog: bedrockCatalog("opaque-key-9", "1", { displayName: "Mystery", provider: "Anthropic" }),
|
||||
aiRoot: AI_ROOT,
|
||||
}), { code: "identity" })
|
||||
})
|
||||
|
||||
test("a Bedrock catalog that omits the running version is not eligible", () => {
|
||||
assert.equal(resolveDeployment(opus({ catalog: bedrockCatalog(OPUS_SAP, "2", { displayName: "Claude 4.8 Opus" }) })), null)
|
||||
})
|
||||
|
||||
test("the Sonnet baseline carries its own request policy and projected output limit", () => {
|
||||
const entry = resolveDeployment({
|
||||
deployment: bedrockDeployment(SONNET_ID, SONNET_SAP, "1", "cfg-s"),
|
||||
configuration: bedrockConfig(SONNET_SAP, "1", "cfg-s"),
|
||||
catalog: bedrockCatalog(SONNET_SAP, "1", { displayName: "Claude 4.6 Sonnet" }),
|
||||
aiRoot: AI_ROOT,
|
||||
})
|
||||
assert.equal(entry.canonicalID, "claude-sonnet-4-6")
|
||||
assert.deepEqual(entry.requestPolicy,
|
||||
{ maxOutputTokens: 128000, rejectCombinedSampling: true, rejectForcedToolThinking: true })
|
||||
const model = projectModels({ [entry.canonicalID]: entry })["claude-sonnet-4-6"]
|
||||
assert.equal(model.limit.output, 128000)
|
||||
})
|
||||
|
||||
test("a Claude version without explicit streaming support remains available for whole requests only", () => {
|
||||
for (const supported of [undefined, false]) {
|
||||
const catalog = bedrockCatalog(OPUS_SAP, "1", { displayName: "Claude 4.8 Opus" })
|
||||
if (supported === undefined) delete catalog.resources[0].versions[0].streamingSupported
|
||||
else catalog.resources[0].versions[0].streamingSupported = supported
|
||||
const entry = resolveDeployment(opus({ catalog }))
|
||||
assert.equal(entry.canonicalID, "claude-opus-4-8")
|
||||
assert.equal(entry.capabilities.streaming, false)
|
||||
}
|
||||
})
|
||||
|
||||
test("malformed or conflicting provider metadata cannot qualify through a Claude identity", () => {
|
||||
for (const [field, value] of [["provider", "Amazon"], ["provider", 42], ["provider", null], ["displayName", { unexpected: true }], ["displayName", null]]) {
|
||||
const catalog = bedrockCatalog(OPUS_SAP, "1", { displayName: "Claude 4.8 Opus" })
|
||||
catalog.resources[0][field] = value
|
||||
assert.equal(resolveDeployment(opus({ catalog })), null)
|
||||
}
|
||||
})
|
||||
|
||||
// --- projection ------------------------------------------------------------
|
||||
|
||||
test("projectModels publishes Claude under @ai-sdk/anthropic and enables image/attachment from the catalog", () => {
|
||||
const entry = resolveDeployment(opus())
|
||||
const model = projectModels({ [entry.canonicalID]: entry })["claude-opus-4-8"]
|
||||
assert.deepEqual(model.api, { id: "claude-opus-4-8", npm: "@ai-sdk/anthropic" })
|
||||
assert.equal(model.name, "Claude Opus 4.8")
|
||||
assert.equal(model.capabilities.attachment, true)
|
||||
assert.equal(model.capabilities.input.image, true)
|
||||
assert.equal(model.limit.context, 1000000)
|
||||
assert.equal(model.limit.output, 128000)
|
||||
})
|
||||
|
||||
// --- discover(): both families, collisions, duplicates ---------------------
|
||||
|
||||
function installFetch(handler) {
|
||||
const original = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (href, init) => { calls.push({ href: String(href), init }); return handler(String(href), init) }
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
return calls
|
||||
}
|
||||
|
||||
function ok(payload) {
|
||||
return { ok: true, status: 200, redirected: false, url: "", body: new Response(JSON.stringify(payload)).body }
|
||||
}
|
||||
|
||||
function gptConfig(model, version, cid) {
|
||||
return { id: cid, scenarioId: "foundation-models", executableId: "azure-openai", parameterBindings: [{ key: "modelName", value: model }, { key: "modelVersion", value: version }] }
|
||||
}
|
||||
|
||||
function gptCatalogResource(model, version) {
|
||||
return { model, executableId: "azure-openai", allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }], versions: [{ name: version, contextLength: 1050000, inputTypes: ["text"], deprecated: false, retirementDate: "", streamingSupported: true }] }
|
||||
}
|
||||
|
||||
function mixedRouter({ deployments, configs, catalog }) {
|
||||
return href => {
|
||||
const url = new URL(href)
|
||||
if (url.pathname === "/v2/lm/deployments") return url.searchParams.get("$skip") === "0" ? ok({ resources: deployments }) : ok({ resources: [] })
|
||||
if (url.pathname === "/v2/lm/scenarios/foundation-models/models") return ok(catalog)
|
||||
if (url.pathname.startsWith("/v2/lm/configurations/")) return ok(configs[url.pathname.slice("/v2/lm/configurations/".length)])
|
||||
throw new Error("unexpected path " + url.pathname)
|
||||
}
|
||||
}
|
||||
|
||||
const base = { aiRoot: AI_ROOT, resourceGroup: GROUP, bearer: async () => "tok" }
|
||||
|
||||
test("discovery lists GPT and Claude together, each under its own protocol identity", async () => {
|
||||
installFetch(mixedRouter({
|
||||
deployments: [
|
||||
{ id: "d02212989ca345a2", status: "RUNNING", deploymentUrl: urlFor("d02212989ca345a2"), configurationId: "cfg-gpt", details: { resources: { backendDetails: { model: { name: "gpt-6-astra", version: "2026-09-03" } } } } },
|
||||
bedrockDeployment(OPUS_ID, OPUS_SAP, "1", "cfg-opus"),
|
||||
bedrockDeployment(SONNET_ID, SONNET_SAP, "1", "cfg-sonnet"),
|
||||
],
|
||||
configs: { "cfg-gpt": gptConfig("gpt-6-astra", "2026-09-03", "cfg-gpt"), "cfg-opus": bedrockConfig(OPUS_SAP, "1", "cfg-opus"), "cfg-sonnet": bedrockConfig(SONNET_SAP, "1", "cfg-sonnet") },
|
||||
catalog: {
|
||||
count: 3,
|
||||
resources: [
|
||||
gptCatalogResource("gpt-6-astra", "2026-09-03"),
|
||||
bedrockCatalog(OPUS_SAP, "1", { displayName: "Claude 4.8 Opus" }).resources[0],
|
||||
bedrockCatalog(SONNET_SAP, "1", { displayName: "Claude 4.6 Sonnet" }).resources[0],
|
||||
],
|
||||
},
|
||||
}))
|
||||
const registry = await discover(base)
|
||||
assert.deepEqual(Object.keys(registry), ["claude-opus-4-8", "claude-sonnet-4-6", "gpt-6-astra"])
|
||||
assert.equal(registry["claude-opus-4-8"].protocol, "anthropic")
|
||||
assert.equal(registry["claude-opus-4-8"].modelName, OPUS_SAP)
|
||||
assert.equal(registry["gpt-6-astra"].protocol, "responses")
|
||||
const models = projectModels(registry)
|
||||
assert.equal(models["claude-sonnet-4-6"].api.npm, "@ai-sdk/anthropic")
|
||||
assert.equal(models["gpt-6-astra"].api.npm, "@ai-sdk/openai")
|
||||
})
|
||||
|
||||
test("distinct Claude identities colliding only via SAP-format fallback fail discovery with a conflict", async () => {
|
||||
installFetch(mixedRouter({
|
||||
deployments: [
|
||||
bedrockDeployment(OPUS_ID, OPUS_SAP, "1", "cfg-a"),
|
||||
bedrockDeployment(SONNET_ID, "anthropic--claude-opus-4.8", "1", "cfg-b"),
|
||||
],
|
||||
configs: { "cfg-a": bedrockConfig(OPUS_SAP, "1", "cfg-a"), "cfg-b": bedrockConfig("anthropic--claude-opus-4.8", "1", "cfg-b") },
|
||||
catalog: {
|
||||
count: 2,
|
||||
resources: [
|
||||
bedrockCatalog(OPUS_SAP, "1").resources[0],
|
||||
bedrockCatalog("anthropic--claude-opus-4.8", "1").resources[0],
|
||||
],
|
||||
},
|
||||
}))
|
||||
await assert.rejects(discover(base), e => e.code === "discovery-conflict" || e.code === "conflict")
|
||||
})
|
||||
|
||||
test("distinct SAP identities with authoritative, equivalent display metadata dedup to the lowest ID", async () => {
|
||||
const lowId = "d0000000000000b2"
|
||||
installFetch(mixedRouter({
|
||||
deployments: [
|
||||
bedrockDeployment(OPUS_ID, OPUS_SAP, "1", "cfg-a"),
|
||||
bedrockDeployment(lowId, "anthropic--claude-opus-4.8", "1", "cfg-b"),
|
||||
],
|
||||
configs: { "cfg-a": bedrockConfig(OPUS_SAP, "1", "cfg-a"), "cfg-b": bedrockConfig("anthropic--claude-opus-4.8", "1", "cfg-b") },
|
||||
catalog: {
|
||||
count: 2,
|
||||
resources: [
|
||||
bedrockCatalog(OPUS_SAP, "1", { displayName: "Claude 4.8 Opus" }).resources[0],
|
||||
bedrockCatalog("anthropic--claude-opus-4.8", "1", { displayName: "Claude Opus 4.8" }).resources[0],
|
||||
],
|
||||
},
|
||||
}))
|
||||
const registry = await discover(base)
|
||||
assert.deepEqual(Object.keys(registry), ["claude-opus-4-8"])
|
||||
assert.equal(registry["claude-opus-4-8"].deploymentID, lowId)
|
||||
assert.equal(registry["claude-opus-4-8"].modelName, "anthropic--claude-opus-4.8")
|
||||
})
|
||||
|
||||
test("authoritative equivalent names still conflict when version or capability metadata differs", async () => {
|
||||
for (const difference of ["version", "streaming"]) {
|
||||
const other = "opaque-opus-key"
|
||||
const version = difference === "version" ? "2" : "1"
|
||||
const otherCatalog = bedrockCatalog(other, version, { displayName: "Claude Opus 4.8" }).resources[0]
|
||||
if (difference === "streaming") otherCatalog.versions[0].streamingSupported = false
|
||||
installFetch(mixedRouter({
|
||||
deployments: [bedrockDeployment(OPUS_ID, OPUS_SAP, "1", "cfg-a"), bedrockDeployment(SONNET_ID, other, version, "cfg-b")],
|
||||
configs: { "cfg-a": bedrockConfig(OPUS_SAP, "1", "cfg-a"), "cfg-b": bedrockConfig(other, version, "cfg-b") },
|
||||
catalog: { count: 2, resources: [bedrockCatalog(OPUS_SAP, "1", { displayName: "Claude 4.8 Opus" }).resources[0], otherCatalog] },
|
||||
}))
|
||||
await assert.rejects(discover(base), { code: "conflict" })
|
||||
}
|
||||
})
|
||||
|
||||
test("duplicate deployments of the same Claude model/version select deterministically by lowest ID", async () => {
|
||||
const lowId = "d0000000000000a1"
|
||||
installFetch(mixedRouter({
|
||||
deployments: [
|
||||
bedrockDeployment(OPUS_ID, OPUS_SAP, "1", "cfg-opus"),
|
||||
bedrockDeployment(lowId, OPUS_SAP, "1", "cfg-opus"),
|
||||
],
|
||||
configs: { "cfg-opus": bedrockConfig(OPUS_SAP, "1", "cfg-opus") },
|
||||
catalog: bedrockCatalog(OPUS_SAP, "1", { displayName: "Claude 4.8 Opus" }),
|
||||
}))
|
||||
const registry = await discover(base)
|
||||
assert.deepEqual(Object.keys(registry), ["claude-opus-4-8"])
|
||||
assert.equal(registry["claude-opus-4-8"].deploymentID, lowId)
|
||||
})
|
||||
@@ -0,0 +1,313 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { discover } from "../src/discovery.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const AI_ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const GROUP = "default"
|
||||
const TIMEOUT_MS = 15000
|
||||
|
||||
const LIST = "/v2/lm/deployments"
|
||||
const DETAIL = "/v2/lm/deployments/"
|
||||
const CATALOG = "/v2/lm/scenarios/foundation-models/models"
|
||||
const CONFIG = "/v2/lm/configurations/"
|
||||
|
||||
function body(text) {
|
||||
return new Response(text).body
|
||||
}
|
||||
|
||||
function streamBody(hooks) {
|
||||
return new ReadableStream({ start() { hooks.onStart?.() }, cancel() { hooks.onCancel?.() } })
|
||||
}
|
||||
|
||||
function ok(payload) {
|
||||
return { ok: true, status: 200, redirected: false, url: "", body: body(JSON.stringify(payload)) }
|
||||
}
|
||||
|
||||
function urlFor(id) {
|
||||
return AI_ROOT + "/v2/inference/deployments/" + id
|
||||
}
|
||||
|
||||
function backend(model, version) {
|
||||
return { details: { resources: { backendDetails: { model: { name: model, version } } } } }
|
||||
}
|
||||
|
||||
function config(model, version, id) {
|
||||
return {
|
||||
id,
|
||||
scenarioId: "foundation-models",
|
||||
executableId: "azure-openai",
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: model },
|
||||
{ key: "modelVersion", value: version },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function catalogFor(...entries) {
|
||||
return {
|
||||
count: entries.length,
|
||||
resources: entries.map(([model, version]) => ({
|
||||
model,
|
||||
executableId: "azure-openai",
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }],
|
||||
versions: [{ name: version, contextLength: 1050000, inputTypes: ["text"], deprecated: false, retirementDate: "", streamingSupported: true }],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function wrap(value) {
|
||||
if (value === undefined) throw new Error("no route")
|
||||
return value && value.body !== undefined ? value : ok(value)
|
||||
}
|
||||
|
||||
function router(routes) {
|
||||
return (href) => {
|
||||
const url = new URL(href)
|
||||
if (url.pathname === LIST) {
|
||||
if (url.searchParams.get("$skip") !== "0") return ok({ resources: [] })
|
||||
return wrap(routes.deployments)
|
||||
}
|
||||
if (url.pathname.startsWith(DETAIL)) return wrap((routes.details || {})[url.pathname.slice(DETAIL.length)])
|
||||
if (url.pathname === CATALOG) return wrap(routes.catalog)
|
||||
if (url.pathname.startsWith(CONFIG)) return wrap(routes.configs[url.pathname.slice(CONFIG.length)])
|
||||
throw new Error("unexpected path " + url.pathname)
|
||||
}
|
||||
}
|
||||
|
||||
function installFetch(handler) {
|
||||
const original = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (href, init) => {
|
||||
calls.push({ href, init })
|
||||
return handler(href, init, calls.length - 1)
|
||||
}
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
return calls
|
||||
}
|
||||
|
||||
function base(overrides = {}) {
|
||||
return { aiRoot: AI_ROOT, resourceGroup: GROUP, bearer: async () => "tok", ...overrides }
|
||||
}
|
||||
|
||||
const detailPaths = calls => calls.filter(c => new URL(c.href).pathname.startsWith(DETAIL)).map(c => new URL(c.href).pathname)
|
||||
|
||||
test("a running row missing url and backend is repaired from matching detail into an eligible entry", async () => {
|
||||
const id = "d02212989ca345a2"
|
||||
const cid = "c" + "0".repeat(15)
|
||||
const calls = installFetch(router({
|
||||
deployments: { resources: [{ id, status: "RUNNING", configurationId: cid }] },
|
||||
details: { [id]: { id, status: "RUNNING", deploymentUrl: urlFor(id), ...backend("gpt-6-astra", "2026-09-03") } },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
|
||||
const registry = await discover(base())
|
||||
|
||||
assert.deepEqual(Object.keys(registry), ["gpt-6-astra"])
|
||||
const entry = registry["gpt-6-astra"]
|
||||
assert.equal(entry.deploymentID, id)
|
||||
assert.equal(entry.deploymentURL, urlFor(id))
|
||||
assert.equal(entry.activeVersion, "2026-09-03")
|
||||
assert.equal(entry.configurationID, cid)
|
||||
assert.deepEqual(detailPaths(calls), [DETAIL + id])
|
||||
})
|
||||
|
||||
test("a running row missing only configurationId is repaired from detail", async () => {
|
||||
const id = "d0bdd146b3138906"
|
||||
const cid = "c" + "1".repeat(15)
|
||||
installFetch(router({
|
||||
deployments: { resources: [{ id, status: "RUNNING", deploymentUrl: urlFor(id), ...backend("gpt-6.1-sol", "2026-09-29") }] },
|
||||
details: { [id]: { id, status: "RUNNING", configurationId: cid } },
|
||||
configs: { [cid]: config("gpt-6.1-sol", "2026-09-29", cid) },
|
||||
catalog: catalogFor(["gpt-6.1-sol", "2026-09-29"]),
|
||||
}))
|
||||
|
||||
const registry = await discover(base())
|
||||
|
||||
assert.deepEqual(Object.keys(registry), ["gpt-6.1-sol"])
|
||||
assert.equal(registry["gpt-6.1-sol"].deploymentID, id)
|
||||
assert.equal(registry["gpt-6.1-sol"].configurationID, cid)
|
||||
})
|
||||
|
||||
test("a lower id whose detail configurationId conflicts is hidden and never displaces the valid higher id", async () => {
|
||||
const lower = "d0000000000000aa"
|
||||
const higher = "d0000000000000bb"
|
||||
const lowCid = "c" + "2".repeat(15)
|
||||
const detailCid = "c" + "3".repeat(15)
|
||||
const highCid = "c" + "4".repeat(15)
|
||||
const calls = installFetch(router({
|
||||
deployments: { resources: [
|
||||
{ id: lower, status: "RUNNING", configurationId: lowCid, ...backend("gpt-6-astra", "2026-09-03") },
|
||||
{ id: higher, status: "RUNNING", deploymentUrl: urlFor(higher), configurationId: highCid, ...backend("gpt-6-astra", "2026-09-03") },
|
||||
] },
|
||||
details: { [lower]: { id: lower, status: "RUNNING", deploymentUrl: urlFor(lower), configurationId: detailCid } },
|
||||
configs: {
|
||||
[lowCid]: config("gpt-6-astra", "2026-09-03", lowCid),
|
||||
[highCid]: config("gpt-6-astra", "2026-09-03", highCid),
|
||||
},
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
|
||||
const registry = await discover(base())
|
||||
|
||||
assert.deepEqual(Object.keys(registry), ["gpt-6-astra"])
|
||||
assert.equal(registry["gpt-6-astra"].deploymentID, higher)
|
||||
assert.ok(calls.every(c => new URL(c.href).pathname !== CONFIG + lowCid))
|
||||
})
|
||||
|
||||
test("a mismatched id, a malformed envelope, or an http failure on detail rejects the whole discovery", async () => {
|
||||
const id = "d02212989ca345a2"
|
||||
const cid = "c" + "5".repeat(15)
|
||||
const incomplete = { resources: [{ id, status: "RUNNING", configurationId: cid, ...backend("gpt-6-astra", "2026-09-03") }] }
|
||||
|
||||
installFetch(router({ deployments: incomplete, details: { [id]: { id: "d0000000000000zz", status: "RUNNING", deploymentUrl: urlFor(id) } } }))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
|
||||
installFetch(router({ deployments: incomplete, details: { [id]: { id, status: 7, deploymentUrl: urlFor(id) } } }))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
|
||||
installFetch(router({ deployments: incomplete, details: { [id]: { ok: false, status: 500, redirected: false, url: "", body: body("{}") } } }))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("a present but unsafe deployment url hides the row and issues zero detail request", async () => {
|
||||
const id = "d02212989ca345a2"
|
||||
const cid = "c" + "6".repeat(15)
|
||||
const calls = installFetch(router({
|
||||
deployments: { resources: [{ id, status: "RUNNING", deploymentUrl: "https://evil.example.com/v2/inference/deployments/" + id, configurationId: cid, ...backend("gpt-6-astra", "2026-09-03") }] },
|
||||
details: { [id]: { id, status: "RUNNING", deploymentUrl: urlFor(id) } },
|
||||
configs: {},
|
||||
catalog: catalogFor(),
|
||||
}))
|
||||
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
assert.deepEqual(detailPaths(calls), [])
|
||||
})
|
||||
|
||||
test("a row whose backend stays absent after detail remains hidden without throwing", async () => {
|
||||
const id = "d02212989ca345a2"
|
||||
const cid = "c" + "7".repeat(15)
|
||||
const calls = installFetch(router({
|
||||
deployments: { resources: [{ id, status: "RUNNING", deploymentUrl: urlFor(id), configurationId: cid }] },
|
||||
details: { [id]: { id, status: "RUNNING" } },
|
||||
configs: {},
|
||||
catalog: catalogFor(),
|
||||
}))
|
||||
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
assert.deepEqual(detailPaths(calls), [DETAIL + id])
|
||||
})
|
||||
|
||||
test("a running row with a malformed list backend container is hidden and never repaired from detail", async () => {
|
||||
const id = "d02212989ca345a2"
|
||||
const cid = "c" + "9".repeat(15)
|
||||
const calls = installFetch(router({
|
||||
deployments: { resources: [{
|
||||
id, status: "RUNNING", deploymentUrl: urlFor(id), configurationId: cid,
|
||||
details: { resources: { backendDetails: { model: { name: 7, version: "2026-09-03" } } } },
|
||||
}] },
|
||||
details: { [id]: { id, status: "RUNNING", ...backend("gpt-6-astra", "2026-09-03") } },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
assert.deepEqual(detailPaths(calls), [])
|
||||
})
|
||||
|
||||
test("a partial list model missing version is filled from detail, while a conflicting version hides the row", async () => {
|
||||
const id = "d0bdd146b3138906"
|
||||
const cid = "c" + "a".repeat(15)
|
||||
const partialList = {
|
||||
id, status: "RUNNING", deploymentUrl: urlFor(id), configurationId: cid,
|
||||
details: { resources: { backendDetails: { model: { name: "gpt-6.1-sol" } } } },
|
||||
}
|
||||
|
||||
installFetch(router({
|
||||
deployments: { resources: [{ ...partialList }] },
|
||||
details: { [id]: { id, status: "RUNNING", configurationId: cid, ...backend("gpt-6.1-sol", "2026-09-29") } },
|
||||
configs: { [cid]: config("gpt-6.1-sol", "2026-09-29", cid) },
|
||||
catalog: catalogFor(["gpt-6.1-sol", "2026-09-29"]),
|
||||
}))
|
||||
const registry = await discover(base())
|
||||
assert.deepEqual(Object.keys(registry), ["gpt-6.1-sol"])
|
||||
assert.equal(registry["gpt-6.1-sol"].activeVersion, "2026-09-29")
|
||||
|
||||
installFetch(router({
|
||||
deployments: { resources: [{ ...partialList, configurationId: undefined, details: { resources: { backendDetails: { model: { name: "gpt-6.1-sol", version: "2026-01-01" } } } } }] },
|
||||
details: { [id]: { id, status: "RUNNING", configurationId: cid, ...backend("gpt-6.1-sol", "2026-09-29") } },
|
||||
configs: { [cid]: config("gpt-6.1-sol", "2026-09-29", cid) },
|
||||
catalog: catalogFor(["gpt-6.1-sol", "2026-09-29"]),
|
||||
}))
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
})
|
||||
|
||||
test("a malformed detail backend rejects the whole refresh while a well-typed empty detail only hides the row", async () => {
|
||||
const id = "d02212989ca345a2"
|
||||
const cid = "c" + "b".repeat(15)
|
||||
const incomplete = { resources: [{ id, status: "RUNNING", deploymentUrl: urlFor(id), configurationId: cid }] }
|
||||
|
||||
installFetch(router({
|
||||
deployments: incomplete,
|
||||
details: { [id]: { id, status: "RUNNING", details: { resources: { backendDetails: { model: { name: "gpt-6-astra", version: 9 } } } } } },
|
||||
}))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
|
||||
const calls = installFetch(router({
|
||||
deployments: incomplete,
|
||||
details: { [id]: { id, status: "RUNNING", details: { resources: {} } } },
|
||||
configs: {},
|
||||
catalog: catalogFor(),
|
||||
}))
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
assert.deepEqual(detailPaths(calls), [DETAIL + id])
|
||||
})
|
||||
|
||||
test("an earlier eligible row does not survive a malformed detail on a later row", async () => {
|
||||
const good = "d0000000000000aa"
|
||||
const later = "d0000000000000bb"
|
||||
const goodCid = "c" + "c".repeat(15)
|
||||
const laterCid = "c" + "d".repeat(15)
|
||||
installFetch(router({
|
||||
deployments: { resources: [
|
||||
{ id: good, status: "RUNNING", deploymentUrl: urlFor(good), configurationId: goodCid, ...backend("gpt-6-astra", "2026-09-03") },
|
||||
{ id: later, status: "RUNNING", deploymentUrl: urlFor(later), configurationId: laterCid },
|
||||
] },
|
||||
details: { [later]: { id: later, status: "RUNNING", details: { resources: { backendDetails: { model: { name: 5 } } } } } },
|
||||
configs: { [goodCid]: config("gpt-6-astra", "2026-09-03", goodCid) },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("the deadline still bounds a hanging detail lookup and cancels its reader", async () => {
|
||||
jest.useFakeTimers()
|
||||
const id = "d02212989ca345a2"
|
||||
const cid = "c" + "8".repeat(15)
|
||||
let cancelled = false
|
||||
let reading
|
||||
const started = new Promise(r => { reading = r })
|
||||
installFetch((href) => {
|
||||
const url = new URL(href)
|
||||
if (url.pathname === LIST) {
|
||||
return url.searchParams.get("$skip") === "0"
|
||||
? ok({ resources: [{ id, status: "RUNNING", deploymentUrl: urlFor(id), configurationId: cid }] })
|
||||
: ok({ resources: [] })
|
||||
}
|
||||
return { ok: true, status: 200, redirected: false, url: "",
|
||||
body: streamBody({ onStart: () => reading(), onCancel: () => { cancelled = true } }) }
|
||||
})
|
||||
|
||||
const pending = discover(base())
|
||||
await started
|
||||
jest.advanceTimersByTime(TIMEOUT_MS)
|
||||
await assert.rejects(pending, { code: "timeout" })
|
||||
assert.equal(cancelled, true)
|
||||
})
|
||||
@@ -0,0 +1,333 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { listDeployments } from "../src/discovery.js"
|
||||
|
||||
const AI_ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const GROUP = "default"
|
||||
const TIMEOUT_MS = 15000
|
||||
|
||||
// Single process under `bun test`: restore every per-test global swap and real
|
||||
// timers after each test so fetch/PATH/timer state never leaks across files.
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
function body(text) {
|
||||
return new Response(text).body
|
||||
}
|
||||
|
||||
function bytesBody(bytes) {
|
||||
return new Response(Uint8Array.from(bytes)).body
|
||||
}
|
||||
|
||||
function streamBody(hooks) {
|
||||
return new ReadableStream({ start() { hooks.onStart?.() }, cancel() { hooks.onCancel?.() } })
|
||||
}
|
||||
|
||||
function jsonPage(resources, extra = {}) {
|
||||
const payload = extra.count === undefined ? { resources } : { resources, count: extra.count }
|
||||
return { ok: true, status: 200, redirected: false, url: "", body: body(JSON.stringify(payload)) }
|
||||
}
|
||||
|
||||
function installFetch(handler) {
|
||||
const original = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (href, init) => {
|
||||
calls.push({ href, init })
|
||||
return handler(href, init, calls.length - 1)
|
||||
}
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
return calls
|
||||
}
|
||||
|
||||
function base(overrides = {}) {
|
||||
return { aiRoot: AI_ROOT, resourceGroup: GROUP, bearer: async () => "tok", ...overrides }
|
||||
}
|
||||
|
||||
function skipOf(href) {
|
||||
return new URL(href).searchParams.get("$skip")
|
||||
}
|
||||
|
||||
function assertInvariants(call) {
|
||||
const url = new URL(call.href)
|
||||
assert.equal(url.origin, AI_ROOT)
|
||||
assert.equal(url.pathname, "/v2/lm/deployments")
|
||||
assert.equal(url.searchParams.get("scenarioId"), "foundation-models")
|
||||
assert.equal(url.searchParams.get("executableIds"), "azure-openai,aws-bedrock")
|
||||
assert.equal(url.searchParams.get("status"), "RUNNING")
|
||||
assert.equal(url.searchParams.get("$top"), "100")
|
||||
assert.equal(call.init.method, "GET")
|
||||
assert.equal(call.init.redirect, "error")
|
||||
assert.equal(call.init.headers.Authorization, "Bearer tok")
|
||||
assert.equal(call.init.headers["AI-Resource-Group"], GROUP)
|
||||
}
|
||||
|
||||
test("collects every page and stops on the empty page", async () => {
|
||||
const pages = [
|
||||
jsonPage([{ id: "a", url: "x" }, { id: "b" }], { count: 2 }),
|
||||
jsonPage([{ id: "c" }]),
|
||||
jsonPage([]),
|
||||
]
|
||||
const calls = installFetch((_h, _i, n) => pages[n])
|
||||
|
||||
const rows = await listDeployments(base())
|
||||
|
||||
assert.deepEqual(rows, [{ id: "a", url: "x" }, { id: "b" }, { id: "c" }])
|
||||
assert.equal(calls.length, 3)
|
||||
assert.deepEqual(calls.map(c => skipOf(c.href)), ["0", "2", "3"])
|
||||
calls.forEach(assertInvariants)
|
||||
})
|
||||
|
||||
test("a later-page HTTP error rejects without a partial result", async () => {
|
||||
const calls = installFetch((_h, _i, n) =>
|
||||
n === 0 ? jsonPage([{ id: "a" }]) : { ok: false, status: 500, redirected: false, url: "", body: body("{}") })
|
||||
|
||||
await assert.rejects(listDeployments(base()), err => {
|
||||
assert.equal(err.code, "response")
|
||||
return true
|
||||
})
|
||||
assert.equal(calls.length, 2)
|
||||
})
|
||||
|
||||
test("a management 401 is an ordinary discovery error", async () => {
|
||||
installFetch(() => ({ ok: false, status: 401, redirected: false, url: "", body: body("{}") }))
|
||||
await assert.rejects(listDeployments(base()), err => {
|
||||
assert.equal(err.code, "response")
|
||||
assert.ok(!("signIn" in err))
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
test("a malformed envelope rejects", async () => {
|
||||
installFetch(() => ({ ok: true, status: 200, redirected: false, url: "", body: body(JSON.stringify({ resources: {} })) }))
|
||||
await assert.rejects(listDeployments(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("a malformed count rejects", async () => {
|
||||
installFetch(() => jsonPage([{ id: "a" }], { count: -1 }))
|
||||
await assert.rejects(listDeployments(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("a row without a safe id rejects", async () => {
|
||||
installFetch(() => jsonPage([{ id: "" }]))
|
||||
await assert.rejects(listDeployments(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("repeated ids across pages reject", async () => {
|
||||
const pages = [jsonPage([{ id: "a" }]), jsonPage([{ id: "a" }])]
|
||||
installFetch((_h, _i, n) => pages[n])
|
||||
await assert.rejects(listDeployments(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("a redirected response rejects", async () => {
|
||||
installFetch(() => ({ ok: true, status: 200, redirected: true, url: "", body: body(JSON.stringify({ resources: [] })) }))
|
||||
await assert.rejects(listDeployments(base()), { code: "destination" })
|
||||
})
|
||||
|
||||
test("a final-URL mismatch rejects", async () => {
|
||||
installFetch(() => ({
|
||||
ok: true, status: 200, redirected: false,
|
||||
url: "https://api.ai.other.hana.ondemand.com/v2/lm/deployments",
|
||||
body: body(JSON.stringify({ resources: [] })),
|
||||
}))
|
||||
await assert.rejects(listDeployments(base()), { code: "destination" })
|
||||
})
|
||||
|
||||
test("a non-AI or non-HTTPS root rejects before any fetch", async () => {
|
||||
const calls = installFetch(() => jsonPage([]))
|
||||
await assert.rejects(listDeployments(base({ aiRoot: "http://api.ai.eu10.hana.ondemand.com" })), { code: "destination" })
|
||||
await assert.rejects(listDeployments(base({ aiRoot: "https://evil.example.com" })), { code: "destination" })
|
||||
assert.equal(calls.length, 0)
|
||||
})
|
||||
|
||||
test("row exhaustion rejects instead of truncating", async () => {
|
||||
let id = 0
|
||||
installFetch(() => jsonPage(Array.from({ length: 100 }, () => ({ id: "d" + id++ }))))
|
||||
await assert.rejects(listDeployments(base()), { code: "exhausted" })
|
||||
})
|
||||
|
||||
test("an oversized page body rejects", async () => {
|
||||
const huge = "p".repeat(1024 * 1024 + 16)
|
||||
installFetch(() => jsonPage([{ id: "a", pad: huge }]))
|
||||
await assert.rejects(listDeployments(base()), { code: "exhausted" })
|
||||
})
|
||||
|
||||
test("a pre-aborted caller signal rejects promptly", async () => {
|
||||
const calls = installFetch(() => jsonPage([]))
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
await assert.rejects(listDeployments(base({ signal: controller.signal })), { code: "cancelled" })
|
||||
assert.equal(calls.length, 0)
|
||||
})
|
||||
|
||||
test("caller cancellation rejects past a fetch that ignores the signal, then recovers", async () => {
|
||||
let called
|
||||
const seen = new Promise(r => { called = r })
|
||||
installFetch(() => { called(); return new Promise(() => {}) })
|
||||
|
||||
const controller = new AbortController()
|
||||
const pending = listDeployments(base({ signal: controller.signal }))
|
||||
await seen
|
||||
controller.abort()
|
||||
await assert.rejects(pending, { code: "cancelled" })
|
||||
|
||||
installFetch(() => jsonPage([]))
|
||||
assert.deepEqual(await listDeployments(base()), [])
|
||||
})
|
||||
|
||||
test("the 15s deadline wins even when fetch ignores the signal", async () => {
|
||||
jest.useFakeTimers()
|
||||
let called
|
||||
const seen = new Promise(r => { called = r })
|
||||
installFetch(() => { called(); return new Promise(() => {}) })
|
||||
|
||||
const pending = listDeployments(base())
|
||||
await seen
|
||||
jest.advanceTimersByTime(TIMEOUT_MS)
|
||||
await assert.rejects(pending, err => {
|
||||
assert.equal(err.code, "timeout")
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
test("error messages leak no tokens, hosts, or bodies", async () => {
|
||||
installFetch(() => ({ ok: false, status: 500, redirected: false, url: "", body: body(JSON.stringify({ secret: "leak" })) }))
|
||||
await assert.rejects(listDeployments(base()), err => {
|
||||
assert.doesNotMatch(err.message, /tok|eu10|hana|leak|Bearer/)
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
test("a deployment id that is not a bare path segment rejects", async () => {
|
||||
let current
|
||||
const calls = installFetch(() => jsonPage([{ id: current }]))
|
||||
const rejected = ["a/b", "../x", "a\\b", "a?b", "a#b", "a%2f", "a.b", ".", "..", "a".repeat(129), " a", "a b"]
|
||||
for (const id of rejected) {
|
||||
current = id
|
||||
await assert.rejects(listDeployments(base()), { code: "response" })
|
||||
}
|
||||
assert.equal(calls.length, rejected.length)
|
||||
})
|
||||
|
||||
test("a root that normalizes away a port, traversal, or encoded bytes rejects before any fetch", async () => {
|
||||
const calls = installFetch(() => jsonPage([]))
|
||||
const rejected = [
|
||||
"https://api.ai.eu10.hana.ondemand.com:443",
|
||||
"https://api.ai.eu10.hana.ondemand.com/../v2",
|
||||
"https://api.ai.eu10.hana.ondemand.com/%2e%2e",
|
||||
"https://api.ai.eu10.hana.ondemand.com\\@evil.example.com",
|
||||
"https://api.ai.eu10.hana.ondemand.com ",
|
||||
"https://api.ai.eu10.hana.ondemand.com/\x01",
|
||||
"https://api.ai.eu10.hana.ondemand.com/v2",
|
||||
]
|
||||
for (const aiRoot of rejected) {
|
||||
await assert.rejects(listDeployments(base({ aiRoot })), { code: "destination" })
|
||||
}
|
||||
assert.equal(calls.length, 0)
|
||||
})
|
||||
|
||||
test("a malicious bearer error is sanitized to a response error", async () => {
|
||||
installFetch(() => jsonPage([]))
|
||||
const bearer = async () => { throw Object.assign(new Error("tok=SECRET leak eu10 hana"), { code: "response" }) }
|
||||
await assert.rejects(listDeployments(base({ bearer })), err => {
|
||||
assert.equal(err.code, "response")
|
||||
assert.doesNotMatch(err.message, /SECRET|leak|eu10|hana/)
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
test("a malicious caller abort reason normalizes to a safe cancellation", async () => {
|
||||
const calls = installFetch(() => jsonPage([]))
|
||||
for (const code of ["timeout", "network"]) {
|
||||
const controller = new AbortController()
|
||||
controller.abort(Object.assign(new Error("tok=SECRET leak"), { code }))
|
||||
await assert.rejects(listDeployments(base({ signal: controller.signal })), err => {
|
||||
assert.equal(err.code, "cancelled")
|
||||
assert.doesNotMatch(err.message, /SECRET|leak/)
|
||||
return true
|
||||
})
|
||||
}
|
||||
assert.equal(calls.length, 0)
|
||||
})
|
||||
|
||||
test("caller cancellation while the bearer is pending rejects promptly before any fetch", async () => {
|
||||
const calls = installFetch(() => jsonPage([]))
|
||||
const controller = new AbortController()
|
||||
let asked
|
||||
const seen = new Promise(r => { asked = r })
|
||||
const pending = listDeployments(base({ signal: controller.signal, bearer: () => { asked(); return new Promise(() => {}) } }))
|
||||
await seen
|
||||
controller.abort()
|
||||
await assert.rejects(pending, { code: "cancelled" })
|
||||
assert.equal(calls.length, 0)
|
||||
})
|
||||
|
||||
test("the deadline wins while the bearer is pending", async () => {
|
||||
jest.useFakeTimers()
|
||||
let asked
|
||||
const seen = new Promise(r => { asked = r })
|
||||
installFetch(() => jsonPage([]))
|
||||
const pending = listDeployments(base({ bearer: () => { asked(); return new Promise(() => {}) } }))
|
||||
await seen
|
||||
jest.advanceTimersByTime(TIMEOUT_MS)
|
||||
await assert.rejects(pending, { code: "timeout" })
|
||||
})
|
||||
|
||||
test("caller cancellation during a pending body read rejects and cancels the reader", async () => {
|
||||
let cancelled = false
|
||||
let reading
|
||||
const started = new Promise(r => { reading = r })
|
||||
installFetch(() => ({
|
||||
ok: true, status: 200, redirected: false, url: "",
|
||||
body: streamBody({ onStart: () => reading(), onCancel: () => { cancelled = true } }),
|
||||
}))
|
||||
const controller = new AbortController()
|
||||
const pending = listDeployments(base({ signal: controller.signal }))
|
||||
await started
|
||||
controller.abort()
|
||||
await assert.rejects(pending, { code: "cancelled" })
|
||||
assert.equal(cancelled, true)
|
||||
})
|
||||
|
||||
test("the deadline wins during a pending body read and cancels the reader", async () => {
|
||||
jest.useFakeTimers()
|
||||
let cancelled = false
|
||||
let reading
|
||||
const started = new Promise(r => { reading = r })
|
||||
installFetch(() => ({
|
||||
ok: true, status: 200, redirected: false, url: "",
|
||||
body: streamBody({ onStart: () => reading(), onCancel: () => { cancelled = true } }),
|
||||
}))
|
||||
const pending = listDeployments(base())
|
||||
await started
|
||||
jest.advanceTimersByTime(TIMEOUT_MS)
|
||||
await assert.rejects(pending, { code: "timeout" })
|
||||
assert.equal(cancelled, true)
|
||||
})
|
||||
|
||||
test("page-count exhaustion rejects", async () => {
|
||||
let n = 0
|
||||
const calls = installFetch(() => jsonPage([{ id: "d" + n++ }]))
|
||||
await assert.rejects(listDeployments(base()), { code: "exhausted" })
|
||||
assert.equal(calls.length, 128)
|
||||
})
|
||||
|
||||
test("aggregate body size exhaustion rejects", async () => {
|
||||
const pad = "p".repeat(1000000)
|
||||
let n = 0
|
||||
const calls = installFetch(() => jsonPage([{ id: "d" + n++, pad }]))
|
||||
await assert.rejects(listDeployments(base()), { code: "exhausted" })
|
||||
assert.equal(calls.length, 17)
|
||||
})
|
||||
|
||||
test("a malformed JSON body rejects", async () => {
|
||||
installFetch(() => ({ ok: true, status: 200, redirected: false, url: "", body: body("not json at all") }))
|
||||
await assert.rejects(listDeployments(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("a malformed UTF-8 body rejects", async () => {
|
||||
installFetch(() => ({ ok: true, status: 200, redirected: false, url: "", body: bytesBody([0xff, 0xfe, 0xff]) }))
|
||||
await assert.rejects(listDeployments(base()), { code: "response" })
|
||||
})
|
||||
@@ -0,0 +1,427 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { resolveDeployment } from "../src/discovery.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const AI_ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const ASTRA_ID = "d02212989ca345a2"
|
||||
const SOL_ID = "d0bdd146b3138906"
|
||||
const FUTURE = "2099-01-01"
|
||||
|
||||
function urlFor(id) {
|
||||
return AI_ROOT + "/v2/inference/deployments/" + id
|
||||
}
|
||||
|
||||
function backend(name, version) {
|
||||
return { details: { resources: { backendDetails: { model: { name, version } } } } }
|
||||
}
|
||||
|
||||
function deployment(over = {}) {
|
||||
const id = over.id ?? ASTRA_ID
|
||||
return {
|
||||
id,
|
||||
status: "RUNNING",
|
||||
deploymentUrl: urlFor(id),
|
||||
...backend("gpt-6-astra", "2026-09-03"),
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function configuration(over = {}) {
|
||||
return {
|
||||
id: "c" + "0".repeat(15),
|
||||
scenarioId: "foundation-models",
|
||||
executableId: "azure-openai",
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: "gpt-6-astra" },
|
||||
{ key: "modelVersion", value: "2026-09-03" },
|
||||
],
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function catalogFor(model, version, versionOver = {}) {
|
||||
return {
|
||||
count: 1,
|
||||
resources: [{
|
||||
model,
|
||||
executableId: "azure-openai",
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }],
|
||||
versions: [{
|
||||
name: version,
|
||||
contextLength: 1050000,
|
||||
inputTypes: ["text"],
|
||||
deprecated: false,
|
||||
retirementDate: "",
|
||||
streamingSupported: true,
|
||||
...versionOver,
|
||||
}],
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
function astra(over = {}) {
|
||||
return {
|
||||
deployment: deployment(over.deployment),
|
||||
configuration: configuration(over.configuration),
|
||||
catalog: over.catalog ?? catalogFor("gpt-6-astra", "2026-09-03"),
|
||||
aiRoot: over.aiRoot ?? AI_ROOT,
|
||||
}
|
||||
}
|
||||
|
||||
function sol(over = {}) {
|
||||
return {
|
||||
deployment: deployment({
|
||||
id: SOL_ID,
|
||||
...backend("gpt-6.1-sol", "2026-09-29"),
|
||||
...over.deployment,
|
||||
}),
|
||||
configuration: configuration({
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: "gpt-6.1-sol" },
|
||||
{ key: "modelVersion", value: "2026-09-29" },
|
||||
],
|
||||
...over.configuration,
|
||||
}),
|
||||
catalog: over.catalog ?? catalogFor("gpt-6.1-sol", "2026-09-29"),
|
||||
aiRoot: AI_ROOT,
|
||||
}
|
||||
}
|
||||
|
||||
test("eligible gpt-6-astra yields a frozen entry with identity, URL, route, and capabilities", () => {
|
||||
const entry = resolveDeployment(astra())
|
||||
assert.equal(entry.modelName, "gpt-6-astra")
|
||||
assert.equal(entry.protocol, "responses")
|
||||
assert.equal(entry.canonicalID, "gpt-6-astra")
|
||||
assert.equal(entry.displayLabel, "gpt-6-astra")
|
||||
assert.equal(entry.apiNpm, "@ai-sdk/openai")
|
||||
assert.equal(entry.deploymentID, ASTRA_ID)
|
||||
assert.equal(entry.deploymentURL, urlFor(ASTRA_ID))
|
||||
assert.equal(entry.configuredVersion, "2026-09-03")
|
||||
assert.equal(entry.activeVersion, "2026-09-03")
|
||||
assert.equal(entry.scenarioID, "foundation-models")
|
||||
assert.equal(entry.executableID, "azure-openai")
|
||||
assert.deepEqual(entry.routePolicy, { path: "/responses", query: false })
|
||||
assert.deepEqual(entry.capabilities, { text: true, functionTool: true, streaming: true, image: false })
|
||||
assert.equal(entry.configurationID, "c" + "0".repeat(15))
|
||||
assert.equal(entry.metadata.contextLength, 1050000)
|
||||
assert.ok(Object.isFrozen(entry) && Object.isFrozen(entry.routePolicy) && Object.isFrozen(entry.metadata))
|
||||
})
|
||||
|
||||
test("eligible gpt-6.1-sol resolves its own identity and active version", () => {
|
||||
const entry = resolveDeployment(sol())
|
||||
assert.equal(entry.modelName, "gpt-6.1-sol")
|
||||
assert.equal(entry.deploymentID, SOL_ID)
|
||||
assert.equal(entry.activeVersion, "2026-09-29")
|
||||
assert.equal(entry.deploymentURL, urlFor(SOL_ID))
|
||||
})
|
||||
|
||||
test("configuration supplies fallback identity and executable when the deployment omits them", () => {
|
||||
const entry = resolveDeployment(astra({ deployment: {} }))
|
||||
assert.equal(entry.modelName, "gpt-6-astra")
|
||||
assert.equal(entry.executableID, "azure-openai")
|
||||
})
|
||||
|
||||
test("the latest selector resolves the active version from the concrete backend", () => {
|
||||
const entry = resolveDeployment(astra({
|
||||
configuration: { parameterBindings: [{ key: "modelName", value: "gpt-6-astra" }] },
|
||||
}))
|
||||
assert.equal(entry.configuredVersion, "latest")
|
||||
assert.equal(entry.activeVersion, "2026-09-03")
|
||||
})
|
||||
|
||||
test("a pinned version that disagrees with the backend is rejected", () => {
|
||||
const out = resolveDeployment(astra({
|
||||
configuration: {
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: "gpt-6-astra" },
|
||||
{ key: "modelVersion", value: "2026-08-01" },
|
||||
],
|
||||
},
|
||||
}))
|
||||
assert.equal(out, null)
|
||||
})
|
||||
|
||||
test("missing backend evidence hides the deployment", () => {
|
||||
assert.equal(resolveDeployment(astra({ deployment: { details: undefined } })), null)
|
||||
})
|
||||
|
||||
test("a pin alone without backend never proves active", () => {
|
||||
const dep = deployment()
|
||||
delete dep.details
|
||||
assert.equal(resolveDeployment({ ...astra(), deployment: dep }), null)
|
||||
})
|
||||
|
||||
test("GPT major versions 6 and above accept any catalog-matched active version", () => {
|
||||
for (const name of ["gpt-6", "gpt-6-mini", "gpt-6.2", "gpt-6.2-mini", "gpt-7-astra", "gpt-10", "gpt-10.1-mini"]) {
|
||||
const version = "2027-01-01"
|
||||
const entry = resolveDeployment(astra({
|
||||
deployment: backend(name, version),
|
||||
configuration: { parameterBindings: [{ key: "modelName", value: name }, { key: "modelVersion", value: version }] },
|
||||
catalog: catalogFor(name, version),
|
||||
}))
|
||||
assert.ok(entry, name)
|
||||
assert.equal(entry.canonicalID, name)
|
||||
assert.equal(entry.activeVersion, version)
|
||||
assert.equal(entry.protocol, "responses")
|
||||
}
|
||||
})
|
||||
|
||||
test("older GPT majors, non-GPT identities, malformed names, and stopped deployments stay hidden", () => {
|
||||
assert.equal(resolveDeployment(astra({ deployment: { status: "STOPPED" } })), null)
|
||||
for (const name of ["gpt-4o", "gpt-5", "gpt-5-turbo", "gpt-5.9-mini", "o6", "claude-6", "not-gpt-6", "gpt-six", "gpt-6x", "gpt-6.", "gpt-6-", "gpt-6\n"]) {
|
||||
assert.equal(resolveDeployment(astra({
|
||||
deployment: backend(name, "2027-01-01"),
|
||||
configuration: { parameterBindings: [{ key: "modelName", value: name }] },
|
||||
catalog: catalogFor(name, "2027-01-01"),
|
||||
})), null, name)
|
||||
}
|
||||
})
|
||||
|
||||
test("a wrong scenario or executable hides, in configuration, deployment, and catalog", () => {
|
||||
assert.equal(resolveDeployment(astra({ configuration: { scenarioId: "orchestration" } })), null)
|
||||
assert.equal(resolveDeployment(astra({ configuration: { executableId: "openai" } })), null)
|
||||
assert.equal(resolveDeployment(astra({ deployment: { scenarioId: "orchestration" } })), null)
|
||||
assert.equal(resolveDeployment(astra({ deployment: { executableId: "openai" } })), null)
|
||||
const wrongScenario = catalogFor("gpt-6-astra", "2026-09-03")
|
||||
wrongScenario.resources[0].allowedScenarios = [{ scenarioId: "orchestration", executableId: "orchestration" }]
|
||||
assert.equal(resolveDeployment(astra({ catalog: wrongScenario })), null)
|
||||
})
|
||||
|
||||
test("conflicting configuration id and duplicate identity bindings fail closed", () => {
|
||||
assert.equal(resolveDeployment(astra({
|
||||
deployment: { configurationId: "c" + "1".repeat(15) },
|
||||
})), null)
|
||||
assert.equal(resolveDeployment(astra({
|
||||
configuration: {
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: "gpt-6-astra" },
|
||||
{ key: "modelName", value: "gpt-6.1-sol" },
|
||||
{ key: "modelVersion", value: "2026-09-03" },
|
||||
],
|
||||
},
|
||||
})), null)
|
||||
assert.equal(resolveDeployment(astra({
|
||||
configuration: { parameterBindings: [] },
|
||||
})), null)
|
||||
})
|
||||
|
||||
test("a catalog duplicate model or version fails closed", () => {
|
||||
const dupModel = catalogFor("gpt-6-astra", "2026-09-03")
|
||||
dupModel.resources.push(dupModel.resources[0])
|
||||
assert.equal(resolveDeployment(astra({ catalog: dupModel })), null)
|
||||
const dupVersion = catalogFor("gpt-6-astra", "2026-09-03")
|
||||
dupVersion.resources[0].versions.push({ ...dupVersion.resources[0].versions[0] })
|
||||
assert.equal(resolveDeployment(astra({ catalog: dupVersion })), null)
|
||||
})
|
||||
|
||||
test("context metadata is included when valid and omitted when absent", () => {
|
||||
const withCtx = resolveDeployment(astra())
|
||||
assert.equal(withCtx.metadata.contextLength, 1050000)
|
||||
const noCtx = resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { contextLength: undefined }) }))
|
||||
assert.ok(!("contextLength" in (noCtx.metadata ?? {})))
|
||||
const badCtx = resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { contextLength: "big" }) }))
|
||||
assert.equal(badCtx, null)
|
||||
})
|
||||
|
||||
test("a deprecated, retired, or invalid-metadata version hides, future retirement is retained", () => {
|
||||
assert.equal(resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { deprecated: true }) })), null)
|
||||
assert.equal(resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { retirementDate: "2000-01-01" }) })), null)
|
||||
assert.equal(resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { retirementDate: "2026-13-40" }) })), null)
|
||||
assert.equal(resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { streamingSupported: false }) })), null)
|
||||
assert.equal(resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { inputTypes: ["image"] }) })), null)
|
||||
const retained = resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { retirementDate: FUTURE }) }))
|
||||
assert.equal(retained.metadata.retirementDate, FUTURE)
|
||||
// Boundary: a version retiring at exactly today's UTC date is already expired
|
||||
// (the cutoff is <=, not <), so it hides rather than being served its last day.
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
assert.equal(resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { retirementDate: today }) })), null)
|
||||
})
|
||||
|
||||
test("an image-advertising catalog adds image capability", () => {
|
||||
const entry = resolveDeployment(astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { inputTypes: ["text", "image"] }) }))
|
||||
assert.deepEqual(entry.capabilities, { text: true, functionTool: true, streaming: true, image: true })
|
||||
})
|
||||
|
||||
test("an unsafe deployment URL is rejected", () => {
|
||||
const unsafe = [
|
||||
undefined,
|
||||
"http://api.ai.eu10.hana.ondemand.com/v2/inference/deployments/" + ASTRA_ID,
|
||||
"https://user:pass@api.ai.eu10.hana.ondemand.com/v2/inference/deployments/" + ASTRA_ID,
|
||||
"https://api.ai.eu10.hana.ondemand.com:443/v2/inference/deployments/" + ASTRA_ID,
|
||||
urlFor(ASTRA_ID) + "?x=1",
|
||||
urlFor(ASTRA_ID) + "#f",
|
||||
urlFor(ASTRA_ID) + "/responses",
|
||||
urlFor(ASTRA_ID) + " ",
|
||||
"https://api.ai.eu10.hana.ondemand.com/v2/inference/deployments/" + ASTRA_ID + "/..",
|
||||
"https://api.ai.eu10.hana.ondemand.com/v2/inference/deployments/%2e%2e",
|
||||
"https://api.ai.eu10.hana.ondemand.com\\@evil.example.com/v2/inference/deployments/" + ASTRA_ID,
|
||||
"https://evil.example.com/v2/inference/deployments/" + ASTRA_ID,
|
||||
"https://api.ai.eu10.hana.ondemand.com/v2/lm/deployments/" + ASTRA_ID,
|
||||
]
|
||||
for (const deploymentUrl of unsafe) {
|
||||
assert.equal(resolveDeployment(astra({ deployment: { deploymentUrl } })), null, String(deploymentUrl))
|
||||
}
|
||||
})
|
||||
|
||||
test("the URL origin must match aiRoot, never a base reconstructed from the id", () => {
|
||||
const other = "https://api.ai.us10.hana.ondemand.com"
|
||||
assert.equal(resolveDeployment({ ...astra(), aiRoot: other }), null)
|
||||
})
|
||||
|
||||
test("catalog availability alone never generates a deployment", () => {
|
||||
assert.equal(resolveDeployment({ deployment: undefined, configuration: configuration(), catalog: catalogFor("gpt-6-astra", "2026-09-03"), aiRoot: AI_ROOT }), null)
|
||||
assert.equal(resolveDeployment({ ...astra(), catalog: undefined }), null)
|
||||
})
|
||||
|
||||
test("a malformed parameterBindings member fails closed, never silently ignored", () => {
|
||||
for (const bad of ["garbage", 42, null, { foo: 1 }, { key: "extra", value: 5 }, { key: 7, value: "x" }]) {
|
||||
assert.equal(resolveDeployment(astra({
|
||||
configuration: { parameterBindings: [
|
||||
{ key: "modelName", value: "gpt-6-astra" },
|
||||
{ key: "modelVersion", value: "2026-09-03" },
|
||||
bad,
|
||||
] },
|
||||
})), null, String(bad && bad.key))
|
||||
}
|
||||
})
|
||||
|
||||
test("a malformed modelVersion value never collapses to the latest selector", () => {
|
||||
assert.equal(resolveDeployment(astra({
|
||||
configuration: { parameterBindings: [
|
||||
{ key: "modelName", value: "gpt-6-astra" },
|
||||
{ key: "modelVersion", value: 20260903 },
|
||||
] },
|
||||
})), null)
|
||||
})
|
||||
|
||||
test("a duplicate modelVersion binding fails closed", () => {
|
||||
assert.equal(resolveDeployment(astra({
|
||||
configuration: { parameterBindings: [
|
||||
{ key: "modelName", value: "gpt-6-astra" },
|
||||
{ key: "modelVersion", value: "2026-09-03" },
|
||||
{ key: "modelVersion", value: "2026-09-03" },
|
||||
] },
|
||||
})), null)
|
||||
})
|
||||
|
||||
test("a backend identity that disagrees with the configured model fails closed", () => {
|
||||
assert.equal(resolveDeployment(astra({
|
||||
deployment: backend("gpt-6.1-sol", "2026-09-03"),
|
||||
})), null)
|
||||
})
|
||||
|
||||
test("an explicit latest selector resolves and labels the backend active version", () => {
|
||||
const entry = resolveDeployment(astra({
|
||||
configuration: { parameterBindings: [
|
||||
{ key: "modelName", value: "gpt-6-astra" },
|
||||
{ key: "modelVersion", value: "latest" },
|
||||
] },
|
||||
}))
|
||||
assert.equal(entry.configuredVersion, "latest")
|
||||
assert.equal(entry.activeVersion, "2026-09-03")
|
||||
assert.equal(entry.activeEvidence, "deployment-backend")
|
||||
})
|
||||
|
||||
test("latest accepts a new backend version only with matching catalog evidence", () => {
|
||||
const input = astra({
|
||||
deployment: backend("gpt-6-astra", "2027-01-01"),
|
||||
configuration: { parameterBindings: [{ key: "modelName", value: "gpt-6-astra" }] },
|
||||
catalog: catalogFor("gpt-6-astra", "2027-01-01", { contextLength: 200000 }),
|
||||
})
|
||||
const entry = resolveDeployment(input)
|
||||
assert.equal(entry.configuredVersion, "latest")
|
||||
assert.equal(entry.activeVersion, "2027-01-01")
|
||||
assert.equal(entry.metadata.contextLength, 200000)
|
||||
input.catalog = catalogFor("gpt-6-astra", "2026-09-03")
|
||||
assert.equal(resolveDeployment(input), null)
|
||||
})
|
||||
|
||||
test("a backend latest selector is unresolved even with matching catalog metadata", () => {
|
||||
for (const versionBindings of [[], [{ key: "modelVersion", value: "latest" }]]) {
|
||||
assert.equal(resolveDeployment(astra({
|
||||
deployment: backend("gpt-6-astra", "latest"),
|
||||
configuration: { parameterBindings: [{ key: "modelName", value: "gpt-6-astra" }, ...versionBindings] },
|
||||
catalog: catalogFor("gpt-6-astra", "latest"),
|
||||
})), null)
|
||||
}
|
||||
})
|
||||
|
||||
test("a non-nonnegative-integer catalog count fails closed", () => {
|
||||
for (const count of [-1, 1.5, "1", Number.NaN]) {
|
||||
const cat = catalogFor("gpt-6-astra", "2026-09-03")
|
||||
cat.count = count
|
||||
assert.equal(resolveDeployment(astra({ catalog: cat })), null, String(count))
|
||||
}
|
||||
})
|
||||
|
||||
test("a malformed model-level allowedScenarios member fails closed despite a valid row", () => {
|
||||
const cat = catalogFor("gpt-6-astra", "2026-09-03")
|
||||
cat.resources[0].allowedScenarios = [
|
||||
{ scenarioId: "foundation-models", executableId: "azure-openai" },
|
||||
{ scenarioId: 5 },
|
||||
]
|
||||
assert.equal(resolveDeployment(astra({ catalog: cat })), null)
|
||||
})
|
||||
|
||||
test("a version-level allowedScenarios is validated and must carry the required tuple", () => {
|
||||
const ok = resolveDeployment(astra({
|
||||
catalog: catalogFor("gpt-6-astra", "2026-09-03", {
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }],
|
||||
}),
|
||||
}))
|
||||
assert.equal(ok.activeVersion, "2026-09-03")
|
||||
assert.equal(resolveDeployment(astra({
|
||||
catalog: catalogFor("gpt-6-astra", "2026-09-03", {
|
||||
allowedScenarios: [{ scenarioId: "orchestration", executableId: "orchestration" }],
|
||||
}),
|
||||
})), null)
|
||||
assert.equal(resolveDeployment(astra({
|
||||
catalog: catalogFor("gpt-6-astra", "2026-09-03", {
|
||||
allowedScenarios: [{ scenarioId: 5, executableId: "azure-openai" }],
|
||||
}),
|
||||
})), null)
|
||||
})
|
||||
|
||||
test("a non-boolean version isLatest fails closed, a boolean never infers active", () => {
|
||||
assert.equal(resolveDeployment(astra({
|
||||
catalog: catalogFor("gpt-6-astra", "2026-09-03", { isLatest: "yes" }),
|
||||
})), null)
|
||||
const entry = resolveDeployment(astra({
|
||||
catalog: catalogFor("gpt-6-astra", "2026-09-03", { isLatest: true }),
|
||||
}))
|
||||
assert.equal(entry.activeVersion, "2026-09-03")
|
||||
assert.ok(!("isLatest" in entry.metadata))
|
||||
})
|
||||
|
||||
test("matched catalog capability and lifecycle metadata is retained as copied primitives and array", () => {
|
||||
const entry = resolveDeployment(astra())
|
||||
assert.equal(entry.metadata.streamingSupported, true)
|
||||
assert.equal(entry.metadata.deprecated, false)
|
||||
assert.deepEqual(entry.metadata.inputTypes, ["text"])
|
||||
assert.ok(Object.isFrozen(entry.metadata.inputTypes))
|
||||
})
|
||||
|
||||
test("retained inputTypes is a copy, not an alias of the catalog input array", () => {
|
||||
const input = astra({ catalog: catalogFor("gpt-6-astra", "2026-09-03", { inputTypes: ["text", "audio"] }) })
|
||||
const entry = resolveDeployment(input)
|
||||
assert.notEqual(entry.metadata.inputTypes, input.catalog.resources[0].versions[0].inputTypes)
|
||||
input.catalog.resources[0].versions[0].inputTypes.push("image")
|
||||
assert.deepEqual(entry.metadata.inputTypes, ["text", "audio"])
|
||||
})
|
||||
|
||||
test("the returned entry is isolated from later mutation of the inputs", () => {
|
||||
const input = astra()
|
||||
const entry = resolveDeployment(input)
|
||||
const before = { ...entry.metadata }
|
||||
input.catalog.resources[0].versions[0].contextLength = 7
|
||||
input.deployment.deploymentUrl = "https://evil.example.com"
|
||||
assert.deepEqual({ ...entry.metadata }, before)
|
||||
assert.equal(entry.deploymentURL, urlFor(ASTRA_ID))
|
||||
assert.throws(() => { entry.modelName = "x" })
|
||||
})
|
||||
@@ -0,0 +1,422 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { discover } from "../src/discovery.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const AI_ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const GROUP = "default"
|
||||
const TIMEOUT_MS = 15000
|
||||
|
||||
const DEPLOYMENTS = "/v2/lm/deployments"
|
||||
const CATALOG = "/v2/lm/scenarios/foundation-models/models"
|
||||
const CONFIG = "/v2/lm/configurations/"
|
||||
|
||||
function body(text) {
|
||||
return new Response(text).body
|
||||
}
|
||||
|
||||
function streamBody(hooks) {
|
||||
return new ReadableStream({ start() { hooks.onStart?.() }, cancel() { hooks.onCancel?.() } })
|
||||
}
|
||||
|
||||
function ok(payload) {
|
||||
return { ok: true, status: 200, redirected: false, url: "", body: body(JSON.stringify(payload)) }
|
||||
}
|
||||
|
||||
function urlFor(id) {
|
||||
return AI_ROOT + "/v2/inference/deployments/" + id
|
||||
}
|
||||
|
||||
function row(id, model, version, configurationId) {
|
||||
return {
|
||||
id,
|
||||
status: "RUNNING",
|
||||
deploymentUrl: urlFor(id),
|
||||
configurationId,
|
||||
details: { resources: { backendDetails: { model: { name: model, version } } } },
|
||||
}
|
||||
}
|
||||
|
||||
function config(model, version, id) {
|
||||
return {
|
||||
id,
|
||||
scenarioId: "foundation-models",
|
||||
executableId: "azure-openai",
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: model },
|
||||
{ key: "modelVersion", value: version },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function catalogFor(...entries) {
|
||||
return {
|
||||
count: entries.length,
|
||||
resources: entries.map(([model, version]) => ({
|
||||
model,
|
||||
executableId: "azure-openai",
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }],
|
||||
versions: [{
|
||||
name: version,
|
||||
contextLength: 1050000,
|
||||
inputTypes: ["text"],
|
||||
deprecated: false,
|
||||
retirementDate: "",
|
||||
streamingSupported: true,
|
||||
}],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function catalogStreaming(model, version, streaming) {
|
||||
const catalog = catalogFor([model, version])
|
||||
if (streaming === undefined) delete catalog.resources[0].versions[0].streamingSupported
|
||||
else catalog.resources[0].versions[0].streamingSupported = streaming
|
||||
return catalog
|
||||
}
|
||||
|
||||
function router(routes) {
|
||||
return (href) => {
|
||||
const url = new URL(href)
|
||||
if (url.pathname === DEPLOYMENTS) {
|
||||
if (url.searchParams.get("$skip") !== "0") return ok({ resources: [] })
|
||||
return wrap(routes.deployments)
|
||||
}
|
||||
if (url.pathname === CATALOG) return wrap(routes.catalog)
|
||||
if (url.pathname.startsWith(CONFIG)) return wrap(routes.configs[url.pathname.slice(CONFIG.length)])
|
||||
throw new Error("unexpected path " + url.pathname)
|
||||
}
|
||||
}
|
||||
|
||||
function wrap(value) {
|
||||
if (value === undefined) throw new Error("no route")
|
||||
return value && value.body !== undefined ? value : ok(value)
|
||||
}
|
||||
|
||||
function installFetch(handler) {
|
||||
const original = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (href, init) => {
|
||||
calls.push({ href, init })
|
||||
return handler(href, init, calls.length - 1)
|
||||
}
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
return calls
|
||||
}
|
||||
|
||||
function base(overrides = {}) {
|
||||
return { aiRoot: AI_ROOT, resourceGroup: GROUP, bearer: async () => "tok", ...overrides }
|
||||
}
|
||||
|
||||
test("a complete row resolves to a concrete frozen registry entry with authorized config and catalog lookups", async () => {
|
||||
const cid = "c" + "0".repeat(15)
|
||||
const calls = installFetch(router({
|
||||
deployments: { resources: [row("d02212989ca345a2", "gpt-6-astra", "2026-09-03", cid)] },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
|
||||
const registry = await discover(base())
|
||||
|
||||
assert.deepEqual(Object.keys(registry), ["gpt-6-astra"])
|
||||
assert.equal(Object.getPrototypeOf(registry), null)
|
||||
assert.ok(Object.isFrozen(registry))
|
||||
const entry = registry["gpt-6-astra"]
|
||||
assert.equal(entry.deploymentID, "d02212989ca345a2")
|
||||
assert.equal(entry.deploymentURL, urlFor("d02212989ca345a2"))
|
||||
assert.equal(entry.activeVersion, "2026-09-03")
|
||||
assert.equal(entry.configurationID, cid)
|
||||
assert.equal(entry.metadata.contextLength, 1050000)
|
||||
assert.ok(Object.isFrozen(entry))
|
||||
|
||||
const config_call = calls.find(c => new URL(c.href).pathname === CONFIG + cid)
|
||||
const catalog_call = calls.find(c => new URL(c.href).pathname === CATALOG)
|
||||
for (const call of [config_call, catalog_call]) {
|
||||
assert.equal(call.init.method, "GET")
|
||||
assert.equal(call.init.redirect, "error")
|
||||
assert.equal(call.init.headers.Authorization, "Bearer tok")
|
||||
assert.equal(call.init.headers["AI-Resource-Group"], GROUP)
|
||||
}
|
||||
})
|
||||
|
||||
test("after eligibility the lexicographically smallest id wins and an invalid lower id never does", async () => {
|
||||
const lower = "d0000000000000aa"
|
||||
const higher = "d0000000000000bb"
|
||||
const lowConfig = "c" + "1".repeat(15)
|
||||
const highConfig = "c" + "2".repeat(15)
|
||||
installFetch(router({
|
||||
deployments: { resources: [
|
||||
row(higher, "gpt-6-astra", "2026-09-03", highConfig),
|
||||
row(lower, "gpt-6-astra", "2026-09-03", lowConfig),
|
||||
] },
|
||||
configs: {
|
||||
[lowConfig]: config("gpt-6-astra", "2026-08-01", lowConfig),
|
||||
[highConfig]: config("gpt-6-astra", "2026-09-03", highConfig),
|
||||
},
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
|
||||
const registry = await discover(base())
|
||||
|
||||
assert.deepEqual(Object.keys(registry), ["gpt-6-astra"])
|
||||
assert.equal(registry["gpt-6-astra"].deploymentID, higher)
|
||||
})
|
||||
|
||||
test("eligible GPT versions share the lowest-id selection without mixing version metadata", async () => {
|
||||
const model = "gpt-6.2-mini"
|
||||
const catalog = catalogFor([model, "2027-01-01"])
|
||||
catalog.resources[0].versions.push({ name: "2027-02-01", contextLength: 200000 })
|
||||
const deployments = { resources: [
|
||||
row("deployment-b", model, "2027-01-01", "config-b"),
|
||||
row("deployment-a", model, "2027-02-01", "config-a"),
|
||||
] }
|
||||
installFetch(router({
|
||||
deployments,
|
||||
configs: {
|
||||
"config-a": config(model, "2027-02-01", "config-a"),
|
||||
"config-b": config(model, "2027-01-01", "config-b"),
|
||||
},
|
||||
catalog,
|
||||
}))
|
||||
const registry = await discover(base())
|
||||
assert.deepEqual(Object.keys(registry), [model])
|
||||
assert.equal(registry[model].deploymentID, "deployment-a")
|
||||
assert.equal(registry[model].activeVersion, "2027-02-01")
|
||||
assert.deepEqual(registry[model].metadata, { contextLength: 200000 })
|
||||
deployments.resources.reverse()
|
||||
assert.deepEqual(await discover(base()), registry)
|
||||
})
|
||||
|
||||
test("a later configuration failure rejects the whole result with no partial registry", async () => {
|
||||
const first = "c" + "3".repeat(15)
|
||||
const second = "c" + "4".repeat(15)
|
||||
installFetch(router({
|
||||
deployments: { resources: [
|
||||
row("d0000000000000aa", "gpt-6-astra", "2026-09-03", first),
|
||||
row("d0bdd146b3138906", "gpt-6.1-sol", "2026-09-29", second),
|
||||
] },
|
||||
configs: {
|
||||
[first]: config("gpt-6-astra", "2026-09-03", first),
|
||||
[second]: { ok: false, status: 500, redirected: false, url: "", body: body("{}") },
|
||||
},
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"], ["gpt-6.1-sol", "2026-09-29"]),
|
||||
}))
|
||||
|
||||
await assert.rejects(discover(base()), err => {
|
||||
assert.equal(err.code, "response")
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
test("a structurally malformed catalog or configuration envelope rejects rather than returning empty", async () => {
|
||||
const cid = "c" + "5".repeat(15)
|
||||
const deployments = { resources: [row("d02212989ca345a2", "gpt-6-astra", "2026-09-03", cid)] }
|
||||
|
||||
installFetch(router({
|
||||
deployments,
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: { count: 1, resources: {} },
|
||||
}))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
|
||||
installFetch(router({
|
||||
deployments,
|
||||
configs: { [cid]: "not-an-object-envelope" },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("two resource groups with the same model stay isolated in tokens and selected ids", async () => {
|
||||
const cidA = "c" + "6".repeat(15)
|
||||
const cidB = "c" + "7".repeat(15)
|
||||
const idA = "d0000000000000a1"
|
||||
const idB = "d0000000000000b1"
|
||||
const routes = {
|
||||
A: router({
|
||||
deployments: { resources: [row(idA, "gpt-6-astra", "2026-09-03", cidA)] },
|
||||
configs: { [cidA]: config("gpt-6-astra", "2026-09-03", cidA) },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}),
|
||||
B: router({
|
||||
deployments: { resources: [row(idB, "gpt-6-astra", "2026-09-03", cidB)] },
|
||||
configs: { [cidB]: config("gpt-6-astra", "2026-09-03", cidB) },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}),
|
||||
}
|
||||
const calls = installFetch((href, init) => {
|
||||
const group = init.headers["AI-Resource-Group"]
|
||||
return routes[group](href, init)
|
||||
})
|
||||
|
||||
const registryA = await discover(base({ resourceGroup: "A", bearer: async () => "tokA" }))
|
||||
const registryB = await discover(base({ resourceGroup: "B", bearer: async () => "tokB" }))
|
||||
|
||||
assert.equal(registryA["gpt-6-astra"].deploymentID, idA)
|
||||
assert.equal(registryB["gpt-6-astra"].deploymentID, idB)
|
||||
const tokensFor = group => new Set(calls.filter(c => c.init.headers["AI-Resource-Group"] === group).map(c => c.init.headers.Authorization))
|
||||
assert.deepEqual([...tokensFor("A")], ["Bearer tokA"])
|
||||
assert.deepEqual([...tokensFor("B")], ["Bearer tokB"])
|
||||
})
|
||||
|
||||
test("two eligible duplicates in shuffled order resolve to the smaller deployment id", async () => {
|
||||
const lower = "d0000000000000aa"
|
||||
const higher = "d0000000000000bb"
|
||||
const lowConfig = "c" + "a".repeat(15)
|
||||
const highConfig = "c" + "b".repeat(15)
|
||||
installFetch(router({
|
||||
deployments: { resources: [
|
||||
row(higher, "gpt-6-astra", "2026-09-03", highConfig),
|
||||
row(lower, "gpt-6-astra", "2026-09-03", lowConfig),
|
||||
] },
|
||||
configs: {
|
||||
[lowConfig]: config("gpt-6-astra", "2026-09-03", lowConfig),
|
||||
[highConfig]: config("gpt-6-astra", "2026-09-03", highConfig),
|
||||
},
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
|
||||
const registry = await discover(base())
|
||||
|
||||
assert.deepEqual(Object.keys(registry), ["gpt-6-astra"])
|
||||
assert.equal(registry["gpt-6-astra"].deploymentID, lower)
|
||||
})
|
||||
|
||||
test("a bare {} configuration, malformed bindings, and a bad catalog count each reject instead of yielding an empty registry", async () => {
|
||||
const cid = "c" + "d".repeat(15)
|
||||
const deployments = { resources: [row("d02212989ca345a2", "gpt-6-astra", "2026-09-03", cid)] }
|
||||
const goodCatalog = catalogFor(["gpt-6-astra", "2026-09-03"])
|
||||
|
||||
installFetch(router({ deployments, configs: { [cid]: {} }, catalog: goodCatalog }))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
|
||||
installFetch(router({
|
||||
deployments,
|
||||
configs: { [cid]: {
|
||||
scenarioId: "foundation-models",
|
||||
executableId: "azure-openai",
|
||||
parameterBindings: [{ key: "modelName", value: 7 }],
|
||||
} },
|
||||
catalog: goodCatalog,
|
||||
}))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
|
||||
installFetch(router({
|
||||
deployments,
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: { count: -1, resources: [] },
|
||||
}))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
})
|
||||
|
||||
test("empty and stopped deployments yield an empty registry without any configuration or catalog lookup", async () => {
|
||||
const stopped = { id: "d0000000000000cc", status: "STOPPED", deploymentUrl: urlFor("d0000000000000cc"), configurationId: "c" + "e".repeat(15) }
|
||||
|
||||
const emptyCalls = installFetch(router({ deployments: { resources: [] }, configs: {}, catalog: catalogFor() }))
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
assert.ok(emptyCalls.every(c => new URL(c.href).pathname === DEPLOYMENTS))
|
||||
|
||||
const stoppedCalls = installFetch(router({ deployments: { resources: [stopped] }, configs: {}, catalog: catalogFor() }))
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
assert.ok(stoppedCalls.every(c => new URL(c.href).pathname === DEPLOYMENTS))
|
||||
})
|
||||
|
||||
test("caller cancellation during a configuration lookup rejects and a fresh call recovers", async () => {
|
||||
const cid = "c" + "9".repeat(15)
|
||||
let reading
|
||||
const started = new Promise(r => { reading = r })
|
||||
installFetch((href) => {
|
||||
const url = new URL(href)
|
||||
if (url.pathname === DEPLOYMENTS) {
|
||||
return url.searchParams.get("$skip") === "0"
|
||||
? ok({ resources: [row("d02212989ca345a2", "gpt-6-astra", "2026-09-03", cid)] })
|
||||
: ok({ resources: [] })
|
||||
}
|
||||
return { ok: true, status: 200, redirected: false, url: "", body: streamBody({ onStart: () => reading() }) }
|
||||
})
|
||||
|
||||
const controller = new AbortController()
|
||||
const pending = discover(base({ signal: controller.signal }))
|
||||
await started
|
||||
controller.abort()
|
||||
await assert.rejects(pending, { code: "cancelled" })
|
||||
|
||||
installFetch(router({
|
||||
deployments: { resources: [row("d02212989ca345a2", "gpt-6-astra", "2026-09-03", cid)] },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
assert.deepEqual(Object.keys(await discover(base())), ["gpt-6-astra"])
|
||||
})
|
||||
|
||||
test("a malformed deployment status rejects the whole discovery and never yields a partial registry", async () => {
|
||||
const MISSING = Symbol("missing")
|
||||
const good = "c" + "f".repeat(15)
|
||||
for (const value of [MISSING, null, 7, ""]) {
|
||||
const bad = row("d0000000000000bb", "gpt-6.1-sol", "2026-09-29", "c" + "0".repeat(15))
|
||||
if (value === MISSING) delete bad.status
|
||||
else bad.status = value
|
||||
installFetch(router({
|
||||
deployments: { resources: [
|
||||
row("d0000000000000aa", "gpt-6-astra", "2026-09-03", good),
|
||||
bad,
|
||||
] },
|
||||
configs: { [good]: config("gpt-6-astra", "2026-09-03", good) },
|
||||
catalog: catalogFor(["gpt-6-astra", "2026-09-03"]),
|
||||
}))
|
||||
await assert.rejects(discover(base()), { code: "response" })
|
||||
}
|
||||
})
|
||||
|
||||
test("a valid non-RUNNING status string is excluded without a lookup and never throws", async () => {
|
||||
for (const status of ["STOPPED", "PENDING", "UNKNOWN"]) {
|
||||
const only = row("d0000000000000cc", "gpt-6-astra", "2026-09-03", "c" + "e".repeat(15))
|
||||
only.status = status
|
||||
const calls = installFetch(router({ deployments: { resources: [only] }, configs: {}, catalog: catalogFor() }))
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
assert.ok(calls.every(c => new URL(c.href).pathname === DEPLOYMENTS))
|
||||
}
|
||||
})
|
||||
|
||||
test("missing catalog streaming keeps the verified capability true while an explicit false hides the deployment", async () => {
|
||||
const cid = "c" + "3".repeat(15)
|
||||
const deployments = { resources: [row("d02212989ca345a2", "gpt-6-astra", "2026-09-03", cid)] }
|
||||
const configs = { [cid]: config("gpt-6-astra", "2026-09-03", cid) }
|
||||
|
||||
installFetch(router({ deployments, configs, catalog: catalogStreaming("gpt-6-astra", "2026-09-03", undefined) }))
|
||||
const entry = (await discover(base()))["gpt-6-astra"]
|
||||
assert.equal(entry.capabilities.streaming, true)
|
||||
assert.ok(!("streamingSupported" in (entry.metadata ?? {})))
|
||||
|
||||
installFetch(router({ deployments, configs, catalog: catalogStreaming("gpt-6-astra", "2026-09-03", false) }))
|
||||
assert.deepEqual(Object.keys(await discover(base())), [])
|
||||
})
|
||||
|
||||
test("the deadline wins while a configuration lookup hangs and cancels its reader", async () => {
|
||||
jest.useFakeTimers()
|
||||
const cid = "c" + "8".repeat(15)
|
||||
let cancelled = false
|
||||
let reading
|
||||
const started = new Promise(r => { reading = r })
|
||||
installFetch((href) => {
|
||||
const url = new URL(href)
|
||||
if (url.pathname === DEPLOYMENTS) {
|
||||
return url.searchParams.get("$skip") === "0"
|
||||
? ok({ resources: [row("d02212989ca345a2", "gpt-6-astra", "2026-09-03", cid)] })
|
||||
: ok({ resources: [] })
|
||||
}
|
||||
return { ok: true, status: 200, redirected: false, url: "",
|
||||
body: streamBody({ onStart: () => reading(), onCancel: () => { cancelled = true } }) }
|
||||
})
|
||||
|
||||
const pending = discover(base())
|
||||
await started
|
||||
jest.advanceTimersByTime(TIMEOUT_MS)
|
||||
await assert.rejects(pending, { code: "timeout" })
|
||||
assert.equal(cancelled, true)
|
||||
})
|
||||
@@ -0,0 +1,347 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const CREDS = {
|
||||
authUrl: "https://synthetic.authentication.eu10.hana.ondemand.com",
|
||||
baseUrl: "https://api.ai.eu10.hana.ondemand.com",
|
||||
clientId: "synthetic-id",
|
||||
clientSecret: "synthetic-secret",
|
||||
resourceGroup: "default",
|
||||
}
|
||||
const AI_ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const TARGET = AI_ROOT + "/responses"
|
||||
const DEPLOYMENTS = "/v2/lm/deployments"
|
||||
const CATALOG = "/v2/lm/scenarios/foundation-models/models"
|
||||
const CONFIG = "/v2/lm/configurations/"
|
||||
const TOKEN = "/oauth/token"
|
||||
const ASTRA = ["gpt-6-astra", "2026-09-03"]
|
||||
|
||||
function tmpDir() {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), "magpie-fetch-discovery-"))
|
||||
}
|
||||
|
||||
function writeCreds(dir, name, overrides = {}) {
|
||||
const p = path.join(dir, name)
|
||||
fs.writeFileSync(p, JSON.stringify({ ...CREDS, ...overrides }), { mode: 0o600 })
|
||||
return p
|
||||
}
|
||||
|
||||
function json(payload, init = {}) {
|
||||
return new Response(JSON.stringify(payload), init)
|
||||
}
|
||||
|
||||
function tokenReply(overrides = {}) {
|
||||
return json({ access_token: "synthetic-token", token_type: "bearer", expires_in: 43199, ...overrides })
|
||||
}
|
||||
|
||||
function pathOf(href) {
|
||||
return new URL(String(href instanceof Request ? href.url : href)).pathname
|
||||
}
|
||||
|
||||
function urlFor(id) {
|
||||
return AI_ROOT + "/v2/inference/deployments/" + id
|
||||
}
|
||||
|
||||
function row(id, model, version, configurationId) {
|
||||
return {
|
||||
id,
|
||||
status: "RUNNING",
|
||||
deploymentUrl: urlFor(id),
|
||||
configurationId,
|
||||
details: { resources: { backendDetails: { model: { name: model, version } } } },
|
||||
}
|
||||
}
|
||||
|
||||
function config(model, version, id) {
|
||||
return {
|
||||
id,
|
||||
scenarioId: "foundation-models",
|
||||
executableId: "azure-openai",
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: model },
|
||||
{ key: "modelVersion", value: version },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function catalogFor(...entries) {
|
||||
return {
|
||||
count: entries.length,
|
||||
resources: entries.map(([model, version]) => ({
|
||||
model,
|
||||
executableId: "azure-openai",
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }],
|
||||
versions: [{
|
||||
name: version,
|
||||
contextLength: 1050000,
|
||||
inputTypes: ["text"],
|
||||
deprecated: false,
|
||||
retirementDate: "",
|
||||
streamingSupported: true,
|
||||
}],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function router(routes) {
|
||||
return (href) => {
|
||||
const url = new URL(String(href instanceof Request ? href.url : href))
|
||||
if (url.pathname === TOKEN) return tokenReply()
|
||||
if (url.pathname === DEPLOYMENTS) {
|
||||
return url.searchParams.get("$skip") === "0" ? json(routes.deployments) : json({ resources: [] })
|
||||
}
|
||||
if (url.pathname === CATALOG) return json(routes.catalog)
|
||||
if (url.pathname.startsWith(CONFIG)) return json(routes.configs[url.pathname.slice(CONFIG.length)])
|
||||
if (url.pathname.includes("/inference/") && url.pathname.endsWith("/responses")) return json({ id: "resp_a", object: "response", status: "completed", output: [], usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 }, error: null, incomplete_details: null })
|
||||
throw new Error("unexpected path " + url.pathname)
|
||||
}
|
||||
}
|
||||
|
||||
function astraRoutes(cid) {
|
||||
return {
|
||||
deployments: { resources: [row("d0000000000000a1", "gpt-6-astra", "2026-09-03", cid)] },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: catalogFor(ASTRA),
|
||||
}
|
||||
}
|
||||
const BODY = JSON.stringify({ model: "gpt-6-astra", input: "hello" })
|
||||
|
||||
async function fetchResponse(opts, init = {}) {
|
||||
return opts.fetch(TARGET, { method: "POST", body: BODY, ...init })
|
||||
}
|
||||
|
||||
|
||||
function withFetch(mock, fn) {
|
||||
const real = globalThis.fetch
|
||||
globalThis.fetch = mock
|
||||
return Promise.resolve().then(fn).finally(() => { globalThis.fetch = real })
|
||||
}
|
||||
|
||||
function withClock(start, fn) {
|
||||
const real = performance.now
|
||||
let t = start
|
||||
performance.now = () => t
|
||||
return Promise.resolve().then(() => fn(v => { t = v })).finally(() => { performance.now = real })
|
||||
}
|
||||
|
||||
function counting(mock) {
|
||||
const state = { management: 0, firstPage: 0 }
|
||||
const wrapped = (href, init) => {
|
||||
const p = pathOf(href)
|
||||
if (p !== TOKEN) state.management++
|
||||
if (p === DEPLOYMENTS && new URL(String(href instanceof Request ? href.url : href)).searchParams.get("$skip") === "0") state.firstPage++
|
||||
return mock(href, init)
|
||||
}
|
||||
return { wrapped, state }
|
||||
}
|
||||
|
||||
async function sign(plugin, mock, credentialFile) {
|
||||
const result = await withFetch(mock, () => plugin.auth.methods[0].authorize({ credentialFile }))
|
||||
assert.equal(result.type, "success")
|
||||
return { type: "api", key: result.key, metadata: result.metadata }
|
||||
}
|
||||
|
||||
const cid = n => "c" + String(n).repeat(15).slice(0, 15)
|
||||
|
||||
test("routing rejects mismatched native bodies before protocol validation and recognizes undeployed Claude baselines", async () => {
|
||||
const dir = tmpDir()
|
||||
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }))
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const good = router(astraRoutes(cid(3)))
|
||||
let inferenceCalls = 0
|
||||
const mock = (href, init) => {
|
||||
if (pathOf(href).includes("/inference/")) inferenceCalls++
|
||||
return good(href, init)
|
||||
}
|
||||
const auth = await sign(plugin, mock, writeCreds(dir, "routing.json"))
|
||||
const opts = await withFetch(mock, () => plugin.auth.loader(async () => auth))
|
||||
await withFetch(mock, async () => {
|
||||
const wrongRoute = await opts.fetch(AI_ROOT + "/messages", { method: "POST", body: BODY })
|
||||
assert.equal(wrongRoute.status, 400)
|
||||
assert.equal((await wrongRoute.json()).error.code, "destination")
|
||||
for (const model of ["claude-opus-4-8", "claude-sonnet-4-6", "claude-ghost-9-9"]) {
|
||||
const response = await opts.fetch(AI_ROOT + "/messages", { method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }], max_tokens: 16 }) })
|
||||
assert.equal(response.status, 404)
|
||||
assert.equal((await response.json()).error.code, model === "claude-ghost-9-9" ? "unknown-model" : "unavailable-model")
|
||||
}
|
||||
})
|
||||
assert.equal(inferenceCalls, 0)
|
||||
})
|
||||
|
||||
|
||||
test("a failed expired discovery never dispatches from the stale deployment, then recovers", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const good = router(astraRoutes(cid(3)))
|
||||
let fail = false
|
||||
const mock = (href, init) => {
|
||||
if (pathOf(href) === TOKEN) return tokenReply()
|
||||
if (fail && pathOf(href) === DEPLOYMENTS) return json({ resources: {} })
|
||||
return good(href, init)
|
||||
}
|
||||
await withClock(0, async set => {
|
||||
const auth = await sign(plugin, mock, writeCreds(dir, "fetch-refresh.json"))
|
||||
const opts = await withFetch(mock, () => plugin.auth.loader(async () => auth))
|
||||
|
||||
set(300000)
|
||||
fail = true
|
||||
const response = await withFetch(mock, () => fetchResponse(opts))
|
||||
assert.equal(response.status, 502)
|
||||
assert.equal(response.headers.get("x-magpie-sign-in"), "kept")
|
||||
assert.equal((await response.json()).error.code, "discovery-response")
|
||||
|
||||
fail = false
|
||||
assert.equal((await withFetch(mock, () => fetchResponse(opts))).status, 200)
|
||||
})
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("cancelling one expired-discovery caller leaves the other able to generate", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const good = router(astraRoutes(cid(4)))
|
||||
let gate = null
|
||||
const { wrapped, state } = counting((href, init) => {
|
||||
if (gate && pathOf(href) === DEPLOYMENTS) return gate.then(() => good(href, init))
|
||||
return good(href, init)
|
||||
})
|
||||
await withClock(0, async set => {
|
||||
const auth = await sign(plugin, wrapped, writeCreds(dir, "concurrent.json"))
|
||||
const opts = await withFetch(wrapped, () => plugin.auth.loader(async () => auth))
|
||||
const afterLoaderFirstPage = state.firstPage
|
||||
|
||||
set(300000)
|
||||
let release
|
||||
gate = new Promise(r => { release = r })
|
||||
await withFetch(wrapped, async () => {
|
||||
const ctl = new AbortController()
|
||||
const cancelled = fetchResponse(opts, { signal: ctl.signal })
|
||||
const survivor = fetchResponse(opts)
|
||||
await new Promise(r => setImmediate(r))
|
||||
ctl.abort()
|
||||
release()
|
||||
const [c, s] = await Promise.all([cancelled, survivor])
|
||||
assert.equal(c.status, 499)
|
||||
assert.equal(s.status, 200)
|
||||
})
|
||||
assert.equal(state.firstPage, afterLoaderFirstPage + 1, "both fetches coalesce into one deployment listing")
|
||||
})
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("the last owner's cancel aborts the management signal and a late scan cannot warm the snapshot", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const good = router(astraRoutes(cid(5)))
|
||||
let seenSignal = null
|
||||
let gate = null
|
||||
const { wrapped, state } = counting((href, init) => {
|
||||
if (gate && pathOf(href) === DEPLOYMENTS) {
|
||||
seenSignal = init.signal
|
||||
return gate.then(() => good(href, init))
|
||||
}
|
||||
return good(href, init)
|
||||
})
|
||||
await withClock(0, async set => {
|
||||
const auth = await sign(plugin, wrapped, writeCreds(dir, "last-owner.json"))
|
||||
const opts = await withFetch(wrapped, () => plugin.auth.loader(async () => auth))
|
||||
|
||||
set(300000)
|
||||
let release
|
||||
gate = new Promise(r => { release = r })
|
||||
await withFetch(wrapped, async () => {
|
||||
const ctl = new AbortController()
|
||||
const cancelled = fetchResponse(opts, { signal: ctl.signal })
|
||||
await new Promise(r => setImmediate(r))
|
||||
assert.ok(seenSignal && !seenSignal.aborted, "the scan reaches the management request")
|
||||
|
||||
ctl.abort()
|
||||
const c = await cancelled
|
||||
assert.equal(c.status, 499)
|
||||
assert.equal(seenSignal.aborted, true, "the sole owner's cancel aborts the underlying management request")
|
||||
|
||||
release()
|
||||
await new Promise(r => setImmediate(r))
|
||||
const before = state.firstPage
|
||||
const next = await fetchResponse(opts)
|
||||
assert.equal(next.status, 200)
|
||||
assert.ok(state.firstPage > before, "the abandoned scan warmed nothing, so the next fetch rescans")
|
||||
})
|
||||
})
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a token refresh under a fresh snapshot preserves flight ownership across a cancel", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const good = router(astraRoutes(cid(6)))
|
||||
let tokenGate = null
|
||||
const { wrapped, state } = counting((href, init) => {
|
||||
if (pathOf(href) === TOKEN) return tokenGate ? tokenGate.then(() => tokenReply({ expires_in: 120 })) : tokenReply({ expires_in: 120 })
|
||||
return good(href, init)
|
||||
})
|
||||
await withClock(0, async set => {
|
||||
const auth = await sign(plugin, wrapped, writeCreds(dir, "token-refresh.json"))
|
||||
const opts = await withFetch(wrapped, () => plugin.auth.loader(async () => auth))
|
||||
const afterLoaderFirstPage = state.firstPage
|
||||
|
||||
set(60000)
|
||||
let release
|
||||
tokenGate = new Promise(r => { release = r })
|
||||
await withFetch(wrapped, async () => {
|
||||
const ctl = new AbortController()
|
||||
const cancelled = fetchResponse(opts, { signal: ctl.signal })
|
||||
const survivor = fetchResponse(opts)
|
||||
await new Promise(r => setImmediate(r))
|
||||
ctl.abort()
|
||||
release()
|
||||
const [c, s] = await Promise.all([cancelled, survivor])
|
||||
assert.equal(c.status, 499)
|
||||
assert.equal(s.status, 200)
|
||||
})
|
||||
assert.equal(state.firstPage, afterLoaderFirstPage, "a fresh snapshot means the token refresh triggers no rescan")
|
||||
})
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("an old loader closure refuses a fetch after the account is reauthorized and publishes nothing", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const good = router(astraRoutes(cid(7)))
|
||||
const p = writeCreds(dir, "reauth.json")
|
||||
const auth = await sign(plugin, good, p)
|
||||
const opts = await withFetch(good, () => plugin.auth.loader(async () => auth))
|
||||
|
||||
const reauth = await withFetch(good, () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(reauth.type, "success")
|
||||
|
||||
const response = await withFetch(good, () => fetchResponse(opts))
|
||||
assert.equal(response.headers.get("x-magpie-sign-in"), "kept")
|
||||
assert.equal((await response.json()).error.code, "superseded")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const CREDS = {
|
||||
authUrl: "https://synthetic.authentication.eu10.hana.ondemand.com",
|
||||
baseUrl: ROOT + "/v2",
|
||||
clientId: "sentinel-client",
|
||||
clientSecret: "sentinel-client-secret",
|
||||
resourceGroup: "group-a",
|
||||
}
|
||||
const TOKEN = "sentinel-bearer-token"
|
||||
|
||||
// canonical -> [sapIdentity, displayName, version, deploymentId, configId]
|
||||
const MODELS = {
|
||||
"claude-opus-4-8": ["anthropic--claude-4.8-opus", "Claude 4.8 Opus", "1", "deployment-opus", "cfg-opus"],
|
||||
"claude-sonnet-4-6": ["anthropic--claude-4.6-sonnet", "Claude 4.6 Sonnet", "1", "deployment-sonnet", "cfg-sonnet"],
|
||||
"claude-opus-4-9": ["anthropic--claude-4.9-opus", "Claude 4.9 Opus", "2", "deployment-newer", "cfg-newer"],
|
||||
}
|
||||
const urlFor = id => ROOT + "/v2/inference/deployments/" + id
|
||||
const frame = obj => `data: ${JSON.stringify(obj)}\n\n`
|
||||
|
||||
function wholeMessage(model, content, stop_reason = "end_turn") {
|
||||
return { id: "msg_" + stop_reason, type: "message", role: "assistant", model, content, stop_reason, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 8 } }
|
||||
}
|
||||
|
||||
function anthropicError(status, message) {
|
||||
return new Response(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message } }), { status })
|
||||
}
|
||||
|
||||
function streamOf(model, content) {
|
||||
const chunks = [
|
||||
{ type: "message_start", message: { ...wholeMessage(model, []), content: [], stop_reason: null } },
|
||||
{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
|
||||
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: content[0].text } },
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 8 } },
|
||||
{ type: "message_stop" },
|
||||
]
|
||||
return new Response(new ReadableStream({
|
||||
start(c) { for (const ch of chunks) c.enqueue(new TextEncoder().encode(frame(ch))); c.close() },
|
||||
}), { status: 200, headers: { "content-type": "text/event-stream" } })
|
||||
}
|
||||
|
||||
async function fixture(respond) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-cont-"))
|
||||
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }))
|
||||
const credentialFile = path.join(dir, "credentials.json")
|
||||
fs.writeFileSync(credentialFile, JSON.stringify(CREDS), { mode: 0o600 })
|
||||
const original = globalThis.fetch
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
const bodies = []
|
||||
const json = body => new Response(JSON.stringify(body))
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = new URL(String(input))
|
||||
if (url.pathname === "/oauth/token") return json({ access_token: TOKEN, token_type: "bearer", expires_in: 3600 })
|
||||
if (url.pathname === "/v2/lm/deployments") {
|
||||
return json({ resources: url.searchParams.get("$skip") === "0" ? Object.values(MODELS).map(([sap, , version, did, cid]) =>
|
||||
({ id: did, status: "RUNNING", deploymentUrl: urlFor(did), configurationId: cid, details: { resources: { backendDetails: { model: { name: sap, version } } } } })) : [] })
|
||||
}
|
||||
if (url.pathname.startsWith("/v2/lm/configurations/")) {
|
||||
const cid = url.pathname.slice("/v2/lm/configurations/".length)
|
||||
const entry = Object.values(MODELS).find(m => m[4] === cid)
|
||||
return json({ id: cid, scenarioId: "foundation-models", executableId: "aws-bedrock", parameterBindings: [{ key: "modelName", value: entry[0] }, { key: "modelVersion", value: entry[2] }] })
|
||||
}
|
||||
if (url.pathname === "/v2/lm/scenarios/foundation-models/models") {
|
||||
return json({ count: 3, resources: Object.values(MODELS).map(([sap, displayName, version]) =>
|
||||
({ model: sap, executableId: "aws-bedrock", provider: "Anthropic", displayName, allowedScenarios: [{ scenarioId: "foundation-models", executableId: "aws-bedrock" }], versions: [{ name: version, contextLength: 1000000, inputTypes: ["text"], streamingSupported: true }] })) })
|
||||
}
|
||||
const body = JSON.parse(init.body)
|
||||
bodies.push({ url: url.href, body })
|
||||
return respond(body, url)
|
||||
}
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const signed = await plugin.auth.methods[0].authorize({ credentialFile })
|
||||
assert.equal(signed.type, "success")
|
||||
const loader = await plugin.auth.loader(async () => ({ type: "api", key: signed.key, metadata: signed.metadata }))
|
||||
const post = (model, body, init = {}) => loader.fetch(ROOT + "/messages", { method: "POST", body: JSON.stringify({ model, max_tokens: 512, ...body }), ...init })
|
||||
return { post, bodies }
|
||||
}
|
||||
|
||||
function readStream(response) {
|
||||
return (async () => {
|
||||
const reader = response.body.getReader()
|
||||
const dec = new TextDecoder()
|
||||
let buf = ""
|
||||
const events = []
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buf += dec.decode(value, { stream: true })
|
||||
let i
|
||||
while ((i = buf.indexOf("\n\n")) >= 0) {
|
||||
const data = buf.slice(0, i).split("\n").filter(l => l.startsWith("data:")).map(l => l.slice(5).trimStart()).join("\n")
|
||||
buf = buf.slice(i + 2)
|
||||
if (data) events.push(JSON.parse(data))
|
||||
}
|
||||
}
|
||||
return events
|
||||
})()
|
||||
}
|
||||
|
||||
// A request-validating upstream for the agent tool loop. Turn 1 emits a signed
|
||||
// (empty-text) thinking block, text, and a tool_use. The continuation must
|
||||
// replay the complete assistant content in order with the authentic signature
|
||||
// and a tool_result paired by the original tool_use id, otherwise 400.
|
||||
const SIGNATURE = "SIG-scenario-7f3a"
|
||||
const TOOL_ID = "toolu_01CITY"
|
||||
|
||||
function toolLoopUpstream({ streamTurn2 = false } = {}) {
|
||||
return (body, url) => {
|
||||
const assistant = body.messages.find(m => m.role === "assistant")
|
||||
if (!assistant) {
|
||||
// Turn 1.
|
||||
return new Response(JSON.stringify(wholeMessage(body.messages[0]?.content ? "claude-x" : "claude-x", [
|
||||
{ type: "thinking", thinking: "", signature: SIGNATURE },
|
||||
{ type: "text", text: "Looking that up." },
|
||||
{ type: "tool_use", id: TOOL_ID, name: "lookup", input: { city: "Zürich" } },
|
||||
], "tool_use")))
|
||||
}
|
||||
// Continuation: validate full ordered history and signature/id pairing.
|
||||
const order = assistant.content.map(b => b.type)
|
||||
const thinking = assistant.content.find(b => b.type === "thinking")
|
||||
const toolUse = assistant.content.find(b => b.type === "tool_use")
|
||||
const last = body.messages[body.messages.length - 1]
|
||||
const toolResult = Array.isArray(last.content) ? last.content.find(b => b.type === "tool_result") : null
|
||||
if (order[0] !== "thinking" || order[order.length - 1] !== "tool_use") return anthropicError(400, "assistant content order not replayed")
|
||||
if (!thinking || thinking.signature !== SIGNATURE) return anthropicError(400, "invalid or missing thinking signature " + CREDS.clientSecret)
|
||||
if (!toolResult || toolResult.tool_use_id !== toolUse.id) return anthropicError(400, "mismatched tool_result")
|
||||
const content = [{ type: "text", text: "AICORE_TOOL_OK:Zürich" }]
|
||||
return streamTurn2 && url.pathname.endsWith("/invoke-with-response-stream")
|
||||
? streamOf("claude-x", content)
|
||||
: new Response(JSON.stringify(wholeMessage("claude-x", content)))
|
||||
}
|
||||
}
|
||||
|
||||
function continuation(first, extra = {}) {
|
||||
return {
|
||||
messages: [
|
||||
{ role: "user", content: "weather in Zürich?" },
|
||||
{ role: "assistant", content: first.content },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: TOOL_ID, content: "12°C" }] },
|
||||
],
|
||||
tools: [{ name: "lookup", input_schema: { type: "object" } }],
|
||||
tool_choice: { type: "auto" },
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
|
||||
const TOOL_TURN1 = { messages: [{ role: "user", content: "weather in Zürich?" }], tools: [{ name: "lookup", input_schema: { type: "object" } }] }
|
||||
|
||||
test("a whole agent tool loop replays signed (empty-text) thinking and pairs tool_result by id", async () => {
|
||||
const { post, bodies } = await fixture(toolLoopUpstream())
|
||||
const first = await (await post("claude-opus-4-8", TOOL_TURN1)).json()
|
||||
assert.equal(first.stop_reason, "tool_use")
|
||||
assert.equal(first.content.find(b => b.type === "tool_use").id, TOOL_ID)
|
||||
|
||||
const final = await post("claude-opus-4-8", continuation(first))
|
||||
assert.equal(final.status, 200)
|
||||
assert.equal((await final.json()).content[0].text, "AICORE_TOOL_OK:Zürich")
|
||||
|
||||
// The forwarded continuation body carried the full ordered history verbatim.
|
||||
const sent = bodies.at(-1).body
|
||||
assert.deepEqual(sent.messages[1].content.map(b => b.type), ["thinking", "text", "tool_use"])
|
||||
assert.equal(sent.messages[1].content[0].signature, SIGNATURE)
|
||||
assert.equal(sent.messages[1].content[0].thinking, "")
|
||||
assert.equal("model" in sent, false)
|
||||
})
|
||||
|
||||
test("a streamed continuation turn completes the tool loop", async () => {
|
||||
const { post } = await fixture(toolLoopUpstream({ streamTurn2: true }))
|
||||
const first = await (await post("claude-opus-4-8", TOOL_TURN1)).json()
|
||||
const events = await readStream(await post("claude-opus-4-8", continuation(first, { stream: true })))
|
||||
const text = events.filter(e => e.type === "content_block_delta").map(e => e.delta.text).join("")
|
||||
assert.equal(text, "AICORE_TOOL_OK:Zürich")
|
||||
assert.equal(events.at(-1).type, "message_stop")
|
||||
})
|
||||
|
||||
test("a tampered thinking signature is surfaced as an upstream error, never repaired", async () => {
|
||||
const { post } = await fixture(toolLoopUpstream())
|
||||
const first = await (await post("claude-opus-4-8", TOOL_TURN1)).json()
|
||||
const tampered = structuredClone(first)
|
||||
tampered.content.find(b => b.type === "thinking").signature = "FORGED"
|
||||
const response = await post("claude-opus-4-8", continuation(tampered))
|
||||
assert.equal(response.status, 400)
|
||||
const text = await response.text()
|
||||
assert.equal(text.includes(CREDS.clientSecret), false, "credential echo in the native error is redacted")
|
||||
})
|
||||
|
||||
test("a mismatched tool_result id is surfaced as an upstream error, never repaired", async () => {
|
||||
const { post } = await fixture(toolLoopUpstream())
|
||||
const first = await (await post("claude-opus-4-8", TOOL_TURN1)).json()
|
||||
const bad = {
|
||||
messages: [
|
||||
{ role: "user", content: "weather?" },
|
||||
{ role: "assistant", content: first.content },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_WRONG", content: "x" }] },
|
||||
],
|
||||
tools: [{ name: "lookup", input_schema: { type: "object" } }],
|
||||
}
|
||||
assert.equal((await post("claude-opus-4-8", bad)).status, 400)
|
||||
})
|
||||
|
||||
test("redacted_thinking and cache_control are forwarded verbatim for upstream validation", async () => {
|
||||
const seen = {}
|
||||
const { post } = await fixture((body) => {
|
||||
const assistant = body.messages.find(m => m.role === "assistant")
|
||||
seen.redacted = assistant?.content.some(b => b.type === "redacted_thinking" && b.data === "opaque-blob")
|
||||
seen.cache = body.system?.[0]?.cache_control?.type === "ephemeral"
|
||||
return new Response(JSON.stringify(wholeMessage("claude-x", [{ type: "text", text: "ok" }])))
|
||||
})
|
||||
await post("claude-opus-4-8", {
|
||||
system: [{ type: "text", text: "sys", cache_control: { type: "ephemeral" } }],
|
||||
messages: [
|
||||
{ role: "user", content: "hi" },
|
||||
{ role: "assistant", content: [{ type: "redacted_thinking", data: "opaque-blob" }, { type: "text", text: "prior" }] },
|
||||
{ role: "user", content: "again" },
|
||||
],
|
||||
})
|
||||
assert.equal(seen.redacted, true)
|
||||
assert.equal(seen.cache, true)
|
||||
})
|
||||
|
||||
|
||||
test("the generic newer model runs the same whole tool loop by contract", async () => {
|
||||
const { post } = await fixture(toolLoopUpstream())
|
||||
const first = await (await post("claude-opus-4-9", TOOL_TURN1)).json()
|
||||
assert.equal(first.stop_reason, "tool_use")
|
||||
const final = await post("claude-opus-4-9", continuation(first))
|
||||
assert.equal((await final.json()).content[0].text, "AICORE_TOOL_OK:Zürich")
|
||||
})
|
||||
@@ -0,0 +1,309 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const CREDS = {
|
||||
authUrl: "https://synthetic.authentication.eu10.hana.ondemand.com",
|
||||
baseUrl: ROOT + "/v2",
|
||||
clientId: "sentinel-client",
|
||||
clientSecret: "sentinel-client-secret",
|
||||
resourceGroup: "group-a",
|
||||
}
|
||||
const TOKEN = "sentinel-bearer-token"
|
||||
const OPUS_SAP = "anthropic--claude-4.8-opus"
|
||||
const OPUS = "claude-opus-4-8"
|
||||
const OPUS_URL = ROOT + "/v2/inference/deployments/deployment-opus"
|
||||
|
||||
const frame = obj => `data: ${JSON.stringify(obj)}\n\n`
|
||||
|
||||
// A text + tool_use streamed turn, terminated by message_stop.
|
||||
const STREAM = [
|
||||
{ type: "message_start", message: { id: "msg_s1", type: "message", role: "assistant", model: OPUS, content: [], stop_reason: null, usage: { input_tokens: 9, output_tokens: 0 } } },
|
||||
{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
|
||||
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Grüß " } },
|
||||
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "dich🙂" } },
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{ type: "content_block_start", index: 1, content_block: { type: "tool_use", id: "toolu_1", name: "lookup", input: {} } },
|
||||
{ type: "content_block_delta", index: 1, delta: { type: "input_json_delta", partial_json: "{\"city\":" } },
|
||||
{ type: "content_block_delta", index: 1, delta: { type: "input_json_delta", partial_json: "\"Zürich🙂\"}" } },
|
||||
{ type: "content_block_stop", index: 1 },
|
||||
{ type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 12 } },
|
||||
{ type: "message_stop" },
|
||||
]
|
||||
|
||||
function streamResponse(chunks, { onPull } = {}) {
|
||||
let i = 0
|
||||
const enc = new TextEncoder()
|
||||
const stream = new ReadableStream({
|
||||
pull(controller) {
|
||||
onPull?.(i)
|
||||
if (i >= chunks.length) { controller.close(); return }
|
||||
const chunk = chunks[i++]
|
||||
controller.enqueue(typeof chunk === "string" ? enc.encode(chunk) : chunk)
|
||||
},
|
||||
}, { highWaterMark: 0 })
|
||||
return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } })
|
||||
}
|
||||
|
||||
async function fixture(inference, pluginOptions) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-stream-"))
|
||||
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }))
|
||||
const credentialFile = path.join(dir, "credentials.json")
|
||||
fs.writeFileSync(credentialFile, JSON.stringify(CREDS), { mode: 0o600 })
|
||||
const original = globalThis.fetch
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
const json = body => new Response(JSON.stringify(body))
|
||||
const calls = []
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = new URL(String(input))
|
||||
if (url.pathname === "/oauth/token") return json({ access_token: TOKEN, token_type: "bearer", expires_in: 3600 })
|
||||
if (url.pathname === "/v2/lm/deployments") {
|
||||
return json({ resources: url.searchParams.get("$skip") === "0" ? [
|
||||
{ id: "deployment-opus", status: "RUNNING", deploymentUrl: OPUS_URL, configurationId: "cfg-opus", details: { resources: { backendDetails: { model: { name: OPUS_SAP, version: "1" } } } } },
|
||||
] : [] })
|
||||
}
|
||||
if (url.pathname === "/v2/lm/configurations/cfg-opus") return json({ id: "cfg-opus", scenarioId: "foundation-models", executableId: "aws-bedrock", parameterBindings: [{ key: "modelName", value: OPUS_SAP }, { key: "modelVersion", value: "1" }] })
|
||||
if (url.pathname === "/v2/lm/scenarios/foundation-models/models") return json({ count: 1, resources: [
|
||||
{ model: OPUS_SAP, executableId: "aws-bedrock", provider: "Anthropic", displayName: "Claude 4.8 Opus", allowedScenarios: [{ scenarioId: "foundation-models", executableId: "aws-bedrock" }], versions: [{ name: "1", contextLength: 1000000, inputTypes: ["text"], streamingSupported: true }] },
|
||||
] })
|
||||
calls.push({ url: url.href, init })
|
||||
return inference(url, init)
|
||||
}
|
||||
const plugin = await SAPAICorePlugin(pluginOptions)
|
||||
const signed = await plugin.auth.methods[0].authorize({ credentialFile })
|
||||
assert.equal(signed.type, "success")
|
||||
const loader = await plugin.auth.loader(async () => ({ type: "api", key: signed.key, metadata: signed.metadata }))
|
||||
const post = (body, init = {}) => loader.fetch(ROOT + "/messages", { method: "POST", body: JSON.stringify({ model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 256, stream: true, ...body }), ...init })
|
||||
return { plugin, loader, post, calls }
|
||||
}
|
||||
|
||||
function consumer(response) {
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ""
|
||||
const events = []
|
||||
const next = async () => {
|
||||
for (;;) {
|
||||
const split = buffer.indexOf("\n\n")
|
||||
if (split >= 0) {
|
||||
const block = buffer.slice(0, split); buffer = buffer.slice(split + 2)
|
||||
const data = block.split("\n").filter(l => l.startsWith("data:")).map(l => l.slice(5).trimStart()).join("\n")
|
||||
if (data) { const event = JSON.parse(data); events.push(event); return event }
|
||||
continue
|
||||
}
|
||||
const chunk = await reader.read()
|
||||
if (chunk.done) return null
|
||||
buffer += decoder.decode(chunk.value, { stream: true })
|
||||
}
|
||||
}
|
||||
return { reader, events, next, async finish() { while (await next()) {} return events } }
|
||||
}
|
||||
|
||||
test("a streamed request routes to /invoke-with-response-stream and relays text then tool-arg deltas before the terminal", async () => {
|
||||
const { post, calls } = await fixture(() => streamResponse(STREAM.map(frame)))
|
||||
const response = await post()
|
||||
assert.equal(response.status, 200)
|
||||
assert.equal(response.headers.get("content-type"), "text/event-stream")
|
||||
assert.equal(calls.at(-1).url, OPUS_URL + "/invoke-with-response-stream")
|
||||
|
||||
const c = consumer(response)
|
||||
const events = await c.finish()
|
||||
const text = events.filter(e => e.type === "content_block_delta" && e.delta.type === "text_delta").map(e => e.delta.text).join("")
|
||||
assert.equal(text, "Grüß dich🙂")
|
||||
const toolJson = events.filter(e => e.type === "content_block_delta" && e.delta.type === "input_json_delta").map(e => e.delta.partial_json).join("")
|
||||
assert.deepEqual(JSON.parse(toolJson), { city: "Zürich🙂" })
|
||||
assert.equal(events.find(e => e.type === "content_block_start" && e.index === 1).content_block.id, "toolu_1")
|
||||
assert.equal(events.at(-1).type, "message_stop")
|
||||
})
|
||||
|
||||
test("each relayed frame carries the native SSE event name, including the error frame", async () => {
|
||||
// SAP relays data-only frames; clients such as pi dispatch on the `event:` name
|
||||
// and skip nameless frames, so they must be synthesized from the event type.
|
||||
const { post } = await fixture(() => streamResponse([
|
||||
frame(STREAM[0]), frame(STREAM[9]), frame(STREAM[10]), // message_start, message_delta, message_stop
|
||||
]))
|
||||
const raw = await new Response((await post()).body).text()
|
||||
const frames = raw.split("\n\n").filter(Boolean)
|
||||
for (const block of frames) {
|
||||
const name = block.split("\n").find(l => l.startsWith("event:"))?.slice(6).trim()
|
||||
const data = JSON.parse(block.split("\n").find(l => l.startsWith("data:")).slice(5).trim())
|
||||
assert.equal(name, data.type, "each frame names its event type")
|
||||
}
|
||||
assert.ok(frames.some(b => b.includes("event: message_delta")), "stop reason frame is named")
|
||||
assert.ok(frames.some(b => b.includes("event: message_stop")))
|
||||
|
||||
// A local truncation failure frame is also a named error event.
|
||||
const { post: post2 } = await fixture(() => streamResponse([frame(STREAM[0])]))
|
||||
const raw2 = await new Response((await post2()).body).text()
|
||||
assert.ok(raw2.includes("event: error"), "truncation yields a named error frame")
|
||||
})
|
||||
|
||||
test("the relay pulls one frame per read and does not reach the terminal until consumed", async () => {
|
||||
let pulls = 0
|
||||
const { post } = await fixture(() => streamResponse(STREAM.map(frame), { onPull: () => { pulls++ } }))
|
||||
const c = consumer(await post())
|
||||
// Read only the first text delta.
|
||||
let first
|
||||
do { first = await c.next() } while (first && !(first.type === "content_block_delta" && first.delta.type === "text_delta"))
|
||||
assert.equal(first.delta.text, "Grüß ")
|
||||
assert.ok(pulls < STREAM.length, `stopped consumer must not drain the whole reply (pulls=${pulls})`)
|
||||
const rest = await c.finish()
|
||||
assert.equal(rest.at(-1).type, "message_stop")
|
||||
})
|
||||
|
||||
test("fragmented bytes across frame and multibyte boundaries reassemble without corruption", async () => {
|
||||
const bytes = Buffer.from(STREAM.map(frame).join(""), "utf8")
|
||||
const chunks = []
|
||||
for (let i = 0; i < bytes.length; i += 3) chunks.push(bytes.subarray(i, i + 3))
|
||||
const { post } = await fixture(() => streamResponse(chunks))
|
||||
const events = await consumer(await post()).finish()
|
||||
const text = events.filter(e => e.type === "content_block_delta" && e.delta.type === "text_delta").map(e => e.delta.text).join("")
|
||||
assert.equal(text, "Grüß dich🙂")
|
||||
assert.equal(events.at(-1).type, "message_stop")
|
||||
})
|
||||
|
||||
test("a native stream error frame surfaces and redacts credential echoes", async () => {
|
||||
const chunks = [frame(STREAM[0]), frame({ type: "error", message: "fail " + CREDS.clientSecret, details: { echo: CREDS.clientSecret }, error: { type: "overloaded_error", message: "native failure" } })]
|
||||
const { post } = await fixture(() => streamResponse(chunks))
|
||||
const raw = await new Response((await post()).body).text()
|
||||
// The redacted error frame must be a single well-formed event: the data line
|
||||
// immediately follows the name, with no blank line splitting them.
|
||||
assert.ok(/event: error\ndata: \{/.test(raw), "redacted error frame keeps data adjacent to its event name")
|
||||
const parsed = await consumer({ body: new Response(raw).body }).finish()
|
||||
const error = parsed.find(e => e.type === "error")
|
||||
assert.ok(error && error.error.type === "overloaded_error")
|
||||
assert.equal(raw.includes(CREDS.clientSecret), false)
|
||||
assert.equal(error.error.message, "native failure")
|
||||
})
|
||||
|
||||
test("a stream truncated before message_stop ends in a safe error, never a fabricated completion", async () => {
|
||||
const chunks = [frame(STREAM[0]), frame(STREAM[2])] // message_start + a text delta, then EOF
|
||||
const { post } = await fixture(() => streamResponse(chunks))
|
||||
const events = await consumer(await post()).finish()
|
||||
assert.equal(events.some(e => e.type === "message_stop"), false)
|
||||
assert.equal(events.at(-1).type, "error")
|
||||
})
|
||||
|
||||
test("an unknown stream event type is rejected as a safe error", async () => {
|
||||
const chunks = [frame(STREAM[0]), frame({ type: "totally_unknown_event" })]
|
||||
const { post } = await fixture(() => streamResponse(chunks))
|
||||
const events = await consumer(await post()).finish()
|
||||
assert.equal(events.at(-1).type, "error")
|
||||
})
|
||||
|
||||
test("cancelling a streamed consumer aborts the owned upstream and an independent request recovers", async () => {
|
||||
let cancelled = false
|
||||
const gated = () => new Response(new ReadableStream({
|
||||
start(c) { c.enqueue(new TextEncoder().encode(frame(STREAM[0]) + frame(STREAM[2]))) },
|
||||
cancel() { cancelled = true },
|
||||
}, { highWaterMark: 0 }), { status: 200, headers: { "content-type": "text/event-stream" } })
|
||||
const { post } = await fixture((url) => url.pathname.endsWith("/invoke-with-response-stream") ? gated() : new Response(JSON.stringify({ id: "m", type: "message", role: "assistant", model: OPUS, content: [{ type: "text", text: "ok" }], stop_reason: "end_turn", usage: { input_tokens: 1, output_tokens: 1 } })))
|
||||
const abort = new AbortController()
|
||||
const response = await post({}, { signal: abort.signal })
|
||||
const c = consumer(response)
|
||||
await c.next() // message_start
|
||||
abort.abort()
|
||||
await assert.rejects(c.finish())
|
||||
await new Promise(r => setTimeout(r, 20))
|
||||
assert.equal(cancelled, true, "owned upstream body was cancelled")
|
||||
// An independent non-streaming request recovers.
|
||||
const recovered = await post({ stream: false })
|
||||
assert.equal(recovered.status, 200)
|
||||
assert.equal((await recovered.json()).content[0].text, "ok")
|
||||
})
|
||||
|
||||
test("malformed terminal states (bare, missing stop reason, out-of-order, bad or duplicate opener) end in a safe error", async () => {
|
||||
const cases = {
|
||||
"bare terminal": [frame({ type: "message_stop" })],
|
||||
"terminal without a resolved stop reason": [frame(STREAM[0]), frame({ type: "message_stop" })],
|
||||
"content before the opener": [frame(STREAM[1]), frame(STREAM[0])],
|
||||
"opener without an initial null stop_reason": [frame({ type: "message_start", message: { ...STREAM[0].message, stop_reason: "end_turn" } })],
|
||||
"duplicate opener": [frame(STREAM[0]), frame(STREAM[0])],
|
||||
"opener without identity": [frame({ type: "message_start", message: { ...STREAM[0].message, id: "" } })],
|
||||
"opener with wrong role": [frame({ type: "message_start", message: { ...STREAM[0].message, role: "user" } })],
|
||||
"opener without usage": [frame({ type: "message_start", message: { ...STREAM[0].message, usage: undefined } })],
|
||||
"malformed stop reason": [frame(STREAM[0]), frame({ type: "message_delta", delta: { stop_reason: "" } }), frame(STREAM[10])],
|
||||
"duplicate stop reason": [frame(STREAM[0]), frame(STREAM[9]), frame(STREAM[9]), frame(STREAM[10])],
|
||||
}
|
||||
for (const [label, chunks] of Object.entries(cases)) {
|
||||
const { post } = await fixture(() => streamResponse(chunks))
|
||||
const events = await consumer(await post()).finish()
|
||||
assert.equal(events.some(e => e.type === "message_stop"), false, label)
|
||||
assert.equal(events.at(-1).type, "error", label)
|
||||
}
|
||||
})
|
||||
|
||||
test("a valid message_start, resolved message_delta and message_stop sequence is relayed as a completion", async () => {
|
||||
const { post } = await fixture(() => streamResponse([frame(STREAM[0]), frame(STREAM[9]), frame(STREAM[10])]))
|
||||
const events = await consumer(await post()).finish()
|
||||
assert.equal(events.at(-1).type, "message_stop")
|
||||
assert.equal(events.find(e => e.type === "message_delta").delta.stop_reason, "tool_use")
|
||||
})
|
||||
|
||||
test("arriving stream chunks reset the idle timeout so active Claude turns exceed a single idle window", async () => {
|
||||
const chunks = [frame(STREAM[0]), frame(STREAM[1]), frame(STREAM[2]), frame(STREAM[3]), frame(STREAM[4]), frame(STREAM[9]), frame(STREAM[10])]
|
||||
let i = 0
|
||||
const enc = new TextEncoder()
|
||||
const paced = () => new Response(new ReadableStream({
|
||||
async pull(controller) {
|
||||
if (i >= chunks.length) { controller.close(); return }
|
||||
await new Promise(r => setTimeout(r, 20))
|
||||
controller.enqueue(enc.encode(chunks[i++]))
|
||||
},
|
||||
}, { highWaterMark: 0 }), { status: 200, headers: { "content-type": "text/event-stream" } })
|
||||
// Total duration (~140ms) exceeds the 55ms idle window, but each chunk arrives within 20ms.
|
||||
const { post } = await fixture(paced, { idleTimeoutMs: 55, totalTimeoutMs: 500 })
|
||||
const events = await consumer(await post()).finish()
|
||||
assert.equal(events.at(-1).type, "message_stop")
|
||||
})
|
||||
|
||||
test("a stalled Claude stream rejects with inference-idle-timeout while an active stream exceeding totalTimeoutMs rejects with inference-timeout", async () => {
|
||||
let stalledCancelled = false
|
||||
const stalled = () => new Response(new ReadableStream({
|
||||
start(controller) { controller.enqueue(new TextEncoder().encode(frame(STREAM[0]))) },
|
||||
cancel() { stalledCancelled = true },
|
||||
}, { highWaterMark: 0 }), { status: 200, headers: { "content-type": "text/event-stream" } })
|
||||
const { post: postStalled } = await fixture(stalled, { idleTimeoutMs: 25, totalTimeoutMs: 500 })
|
||||
const c1 = consumer(await postStalled())
|
||||
assert.equal((await c1.next()).type, "message_start")
|
||||
let idleErr
|
||||
await assert.rejects(c1.finish(), err => { idleErr = err; return true })
|
||||
assert.equal(idleErr.code, "inference-idle-timeout")
|
||||
await new Promise(r => setImmediate(r))
|
||||
assert.equal(stalledCancelled, true)
|
||||
|
||||
// Continuous ping chunks keep resetting the 50ms idle timer, but the 70ms total ceiling still terminates the stream.
|
||||
let activeCancelled = false
|
||||
let opened = false
|
||||
const enc = new TextEncoder()
|
||||
const endless = () => new Response(new ReadableStream({
|
||||
async pull(controller) {
|
||||
if (!opened) {
|
||||
opened = true
|
||||
controller.enqueue(enc.encode(frame(STREAM[0])))
|
||||
return
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 15))
|
||||
controller.enqueue(enc.encode(frame({ type: "ping" })))
|
||||
},
|
||||
cancel() { activeCancelled = true },
|
||||
}, { highWaterMark: 0 }), { status: 200, headers: { "content-type": "text/event-stream" } })
|
||||
const { plugin, post: postEndless } = await fixture(endless)
|
||||
await plugin.config({ provider: { "sap-aicore": { options: { idleTimeoutMs: 50, totalTimeoutMs: 70 } } } })
|
||||
const c2 = consumer(await postEndless())
|
||||
let totalErr
|
||||
await assert.rejects(c2.finish(), err => { totalErr = err; return true })
|
||||
assert.equal(totalErr.code, "inference-timeout")
|
||||
await new Promise(r => setImmediate(r))
|
||||
assert.equal(activeCancelled, true)
|
||||
})
|
||||
@@ -0,0 +1,368 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
import { validateRequest, dispatch } from "../src/messages.js"
|
||||
import { readJSONRequest } from "../src/transport.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const CREDS = {
|
||||
authUrl: "https://synthetic.authentication.eu10.hana.ondemand.com",
|
||||
baseUrl: ROOT + "/v2",
|
||||
clientId: "sentinel-client",
|
||||
clientSecret: "sentinel-client-secret",
|
||||
resourceGroup: "group-a",
|
||||
}
|
||||
const TOKEN = "sentinel-bearer-token"
|
||||
const OPUS_SAP = "anthropic--claude-4.8-opus"
|
||||
const OPUS = "claude-opus-4-8"
|
||||
const OPUS_URL = ROOT + "/v2/inference/deployments/deployment-opus"
|
||||
const SONNET = "claude-sonnet-4-6"
|
||||
const SONNET_URL = ROOT + "/v2/inference/deployments/deployment-sonnet"
|
||||
const GPT = "gpt-6-astra"
|
||||
const GPT_VERSION = "2026-09-03"
|
||||
const GPT_URL = ROOT + "/v2/inference/deployments/deployment-gpt"
|
||||
|
||||
const MESSAGE = {
|
||||
id: "msg_01ABC", type: "message", role: "assistant", model: OPUS,
|
||||
content: [{ type: "text", text: "AICORE_CLAUDE_OK" }],
|
||||
stop_reason: "end_turn", stop_sequence: null,
|
||||
usage: { input_tokens: 12, output_tokens: 6 },
|
||||
}
|
||||
|
||||
// --- native request validation (direct) ------------------------------------
|
||||
|
||||
const base = (over = {}) => ({ model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 1024, ...over })
|
||||
const parse = async body => validateRequest(await readJSONRequest(ROOT + "/messages", { body: JSON.stringify(body) }))
|
||||
|
||||
test("a valid native Messages body passes and is returned verbatim", async () => {
|
||||
const body = base({ system: "be terse", stop_sequences: ["STOP"], temperature: 0.4 })
|
||||
const out = await parse(body)
|
||||
assert.deepEqual(out, body)
|
||||
})
|
||||
|
||||
test("max_tokens is required; zero is accepted; negative and non-integer are rejected", async () => {
|
||||
await assert.rejects(parse({ model: OPUS, messages: [{ role: "user", content: "hi" }] }), { code: "invalid-request" })
|
||||
assert.equal((await parse(base({ max_tokens: 0 }))).max_tokens, 0)
|
||||
await assert.rejects(parse(base({ max_tokens: -1 })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ max_tokens: 1.5 })), { code: "invalid-request" })
|
||||
})
|
||||
|
||||
test("out-of-scope parameters, multimodal content, and unrecognized fields are rejected", async () => {
|
||||
await assert.rejects(parse(base({ metadata: { user_id: "u" } })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ mcp_servers: [] })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ messages: [{ role: "user", content: [{ type: "image", source: {} }] }] })), { code: "invalid-request" })
|
||||
// Unrecognized top-level fields fail explicitly rather than reaching upstream.
|
||||
for (const field of ["anthropic_beta", "top_logprobs", "functions", "tool_Calls", "stream_options"]) {
|
||||
await assert.rejects(parse(base({ [field]: field === "top_logprobs" ? 1 : [] })), { code: "invalid-request" }, field)
|
||||
}
|
||||
})
|
||||
|
||||
const IMAGE_CAPABLE = { capabilities: { image: true } }
|
||||
const parseWith = async (body, entry) => validateRequest(await readJSONRequest(ROOT + "/messages", { body: JSON.stringify(body) }), entry)
|
||||
const imageBlock = { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgo=" } }
|
||||
const withImage = block => base({ messages: [{ role: "user", content: [block, { type: "text", text: "describe" }] }] })
|
||||
|
||||
test("a base64 image block is accepted only for an image-capable model", async () => {
|
||||
// No capability (default) and an explicitly image-off model both reject.
|
||||
await assert.rejects(parseWith(withImage(imageBlock)), { code: "invalid-request" })
|
||||
await assert.rejects(parseWith(withImage(imageBlock), { capabilities: { image: false } }), { code: "invalid-request" })
|
||||
// An image-capable model accepts it and forwards the block verbatim.
|
||||
const out = await parseWith(withImage(imageBlock), IMAGE_CAPABLE)
|
||||
assert.deepEqual(out.messages[0].content[0], imageBlock)
|
||||
})
|
||||
|
||||
test("an image-capable model still rejects non-base64 sources and malformed image blocks", async () => {
|
||||
const bad = [
|
||||
{ type: "image", source: { type: "url", url: "https://example.invalid/i.png" } },
|
||||
{ type: "image", source: { type: "base64", media_type: "image/png" } },
|
||||
{ type: "image", source: { type: "base64", data: "iVBORw0KGgo=" } },
|
||||
{ type: "image" },
|
||||
{ type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgo=" }, detail: "high" },
|
||||
]
|
||||
for (const block of bad) await assert.rejects(parseWith(withImage(block), IMAGE_CAPABLE), { code: "invalid-request" }, JSON.stringify(block))
|
||||
})
|
||||
|
||||
test("tools, tool_choice and a forced tool name are validated against declared tools", async () => {
|
||||
const tools = [{ name: "lookup", input_schema: { type: "object" } }]
|
||||
assert.ok(await parse(base({ tools, tool_choice: { type: "tool", name: "lookup" } })))
|
||||
await assert.rejects(parse(base({ tools, tool_choice: { type: "tool", name: "missing" } })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ tool_choice: { type: "any" } })), { code: "invalid-request" })
|
||||
})
|
||||
|
||||
test("pi's boolean tool hints pass validation; other unknown and malformed tool fields are rejected", async () => {
|
||||
// pi attaches eager_input_streaming (and defer_loading on its deferred placeholder
|
||||
// tool); these boolean hints pass validation unchanged and are stripped at dispatch.
|
||||
const tools = [{ name: "lookup", description: "d", eager_input_streaming: true, strict: true, input_schema: { type: "object" } }]
|
||||
assert.deepEqual((await parse(base({ tools }))).tools, tools)
|
||||
assert.ok(await parse(base({ tools: [{ name: "__pi_deferred_placeholder__", input_schema: { type: "object" }, defer_loading: true }] })))
|
||||
// A malformed (non-boolean) pi hint is rejected.
|
||||
await assert.rejects(parse(base({ tools: [{ name: "x", input_schema: { type: "object" }, eager_input_streaming: "yes" }] })), { code: "invalid-request" })
|
||||
// Any other unknown tool field is rejected, not forwarded.
|
||||
await assert.rejects(parse(base({ tools: [{ name: "x", input_schema: { type: "object" }, unknown_tool_field: 1 }] })), { code: "invalid-request" })
|
||||
// Structural validation of enumerated fields still applies.
|
||||
await assert.rejects(parse(base({ tools: [{ name: "x", input_schema: { type: "object" }, strict: "yes" }] })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ tools: [{ name: "x" }] })), { code: "invalid-request" })
|
||||
})
|
||||
|
||||
test("signed thinking blocks (including empty text) and a conflicting anthropic_version", async () => {
|
||||
const thinking = { role: "assistant", content: [{ type: "thinking", thinking: "", signature: "sig-abc" }] }
|
||||
assert.ok(await parse(base({ messages: [thinking, { role: "user", content: "go" }] })))
|
||||
await assert.rejects(parse(base({ messages: [{ role: "assistant", content: [{ type: "thinking", thinking: "x" }] }] })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ anthropic_version: "2023-06-01" })), { code: "invalid-request" })
|
||||
})
|
||||
|
||||
test("native thinking controls validate structurally: enabled budget, adaptive/disabled, display/block_binding, output_config effort", async () => {
|
||||
// Enabled thinking requires a positive integer budget; adaptive/disabled take none.
|
||||
assert.ok(await parse(base({ thinking: { type: "enabled", budget_tokens: 1024 } })))
|
||||
assert.ok(await parse(base({ thinking: { type: "adaptive" } })))
|
||||
assert.ok(await parse(base({ thinking: { type: "disabled" } })))
|
||||
// display/block_binding and output_config.effort are recognized structural controls.
|
||||
assert.ok(await parse(base({ thinking: { type: "adaptive", display: "summarized", block_binding: { prefix_mismatch_behavior: "drop_block" } }, output_config: { effort: "high" } })))
|
||||
// Malformed: unknown type, missing/non-positive enabled budget, budget on adaptive/disabled.
|
||||
await assert.rejects(parse(base({ thinking: { type: "auto" } })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ thinking: { type: "enabled" } })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ thinking: { type: "enabled", budget_tokens: 0 } })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ thinking: { type: "enabled", budget_tokens: -1 } })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ thinking: { type: "adaptive", budget_tokens: 1024 } })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ thinking: { type: "enabled", budget_tokens: 1024, unknown: 1 } })), { code: "invalid-request" })
|
||||
await assert.rejects(parse(base({ output_config: { effort: 5 } })), { code: "invalid-request" })
|
||||
})
|
||||
|
||||
// --- whole-reply dispatch through the plugin loader ------------------------
|
||||
|
||||
async function fixture(inference = () => new Response(JSON.stringify(MESSAGE)), options = {}) {
|
||||
const opusStreaming = Object.hasOwn(options, "opusStreaming") ? options.opusStreaming : true
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-messages-"))
|
||||
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }))
|
||||
const credentialFile = path.join(dir, "credentials.json")
|
||||
fs.writeFileSync(credentialFile, JSON.stringify(CREDS), { mode: 0o600 })
|
||||
const original = globalThis.fetch
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
const sent = []
|
||||
const json = body => new Response(JSON.stringify(body))
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = new URL(String(input))
|
||||
if (url.pathname === "/oauth/token") return json({ access_token: TOKEN, token_type: "bearer", expires_in: 3600 })
|
||||
if (url.pathname === "/v2/lm/deployments") {
|
||||
return json({ resources: url.searchParams.get("$skip") === "0" ? [
|
||||
{ id: "deployment-gpt", status: "RUNNING", deploymentUrl: GPT_URL, configurationId: "cfg-gpt", details: { resources: { backendDetails: { model: { name: GPT, version: GPT_VERSION } } } } },
|
||||
{ id: "deployment-opus", status: "RUNNING", deploymentUrl: OPUS_URL, configurationId: "cfg-opus", details: { resources: { backendDetails: { model: { name: OPUS_SAP, version: "1" } } } } },
|
||||
] : [] })
|
||||
}
|
||||
if (url.pathname === "/v2/lm/configurations/cfg-gpt") return json({ id: "cfg-gpt", scenarioId: "foundation-models", executableId: "azure-openai", parameterBindings: [{ key: "modelName", value: GPT }, { key: "modelVersion", value: GPT_VERSION }] })
|
||||
if (url.pathname === "/v2/lm/configurations/cfg-opus") return json({ id: "cfg-opus", scenarioId: "foundation-models", executableId: "aws-bedrock", parameterBindings: [{ key: "modelName", value: OPUS_SAP }, { key: "modelVersion", value: "1" }] })
|
||||
if (url.pathname === "/v2/lm/scenarios/foundation-models/models") return json({ count: 2, resources: [
|
||||
{ model: GPT, executableId: "azure-openai", allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }], versions: [{ name: GPT_VERSION, contextLength: 1050000, inputTypes: ["text"], streamingSupported: true }] },
|
||||
{ model: OPUS_SAP, executableId: "aws-bedrock", provider: "Anthropic", displayName: "Claude 4.8 Opus", allowedScenarios: [{ scenarioId: "foundation-models", executableId: "aws-bedrock" }], versions: [{ name: "1", contextLength: 1000000, inputTypes: ["text", "image"], ...(opusStreaming === undefined ? {} : { streamingSupported: opusStreaming }) }] },
|
||||
] })
|
||||
sent.push({ url: url.href, init, body: JSON.parse(init.body) })
|
||||
return inference(input, init)
|
||||
}
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const signed = await plugin.auth.methods[0].authorize({ credentialFile })
|
||||
assert.equal(signed.type, "success")
|
||||
const auth = { type: "api", key: signed.key, metadata: signed.metadata }
|
||||
const loader = await plugin.auth.loader(async () => auth)
|
||||
const post = (route, body, init = {}) => loader.fetch(ROOT + route, { method: "POST", body: JSON.stringify(body), ...init })
|
||||
const models = () => plugin.provider.models({}, { auth })
|
||||
return { loader, post, sent, plugin, auth, models }
|
||||
}
|
||||
|
||||
test("a whole Claude reply reaches /invoke and returns native Anthropic JSON", async () => {
|
||||
const { post, sent } = await fixture()
|
||||
const response = await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 256, stop_sequences: ["STOP"] })
|
||||
assert.equal(response.status, 200)
|
||||
assert.deepEqual(await response.json(), MESSAGE)
|
||||
assert.equal(response.headers.get("x-magpie-sign-in"), "kept")
|
||||
|
||||
const call = sent.at(-1)
|
||||
assert.equal(call.url, OPUS_URL + "/invoke")
|
||||
assert.equal(call.init.method, "POST")
|
||||
assert.equal(call.init.headers.authorization, "Bearer " + TOKEN)
|
||||
assert.equal(call.init.headers["AI-Resource-Group"], "group-a")
|
||||
assert.equal(call.body.anthropic_version, "bedrock-2023-05-31")
|
||||
assert.equal("model" in call.body, false, "routing model is removed from the Bedrock body")
|
||||
assert.equal("stream" in call.body, false, "stream selector is omitted from the body")
|
||||
assert.deepEqual(call.body.stop_sequences, ["STOP"], "explicit native fields are forwarded, not dropped")
|
||||
assert.deepEqual(call.body.messages, [{ role: "user", content: "hi" }])
|
||||
})
|
||||
|
||||
test("pi's non-native tool hints are stripped from the Bedrock invoke body", async () => {
|
||||
const { post, sent } = await fixture()
|
||||
const tools = [
|
||||
{ name: "read_file", description: "d", eager_input_streaming: true, strict: true, input_schema: { type: "object", properties: {} } },
|
||||
{ name: "__pi_deferred_placeholder__", input_schema: { type: "object", properties: {}, required: [] }, defer_loading: true },
|
||||
]
|
||||
const response = await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 64, tools })
|
||||
assert.equal(response.status, 200)
|
||||
assert.deepEqual(sent.at(-1).body.tools, [
|
||||
{ name: "read_file", description: "d", strict: true, input_schema: { type: "object", properties: {} } },
|
||||
{ name: "__pi_deferred_placeholder__", input_schema: { type: "object", properties: {}, required: [] } },
|
||||
])
|
||||
})
|
||||
|
||||
test("pi's adaptive thinking and output_config reach the Bedrock invoke body verbatim", async () => {
|
||||
const { post, sent } = await fixture()
|
||||
const thinking = { type: "adaptive", display: "summarized", block_binding: { prefix_mismatch_behavior: "drop_block" } }
|
||||
const output_config = { effort: "high" }
|
||||
const response = await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 64, thinking, output_config })
|
||||
assert.equal(response.status, 200)
|
||||
assert.deepEqual(sent.at(-1).body.thinking, thinking)
|
||||
assert.deepEqual(sent.at(-1).body.output_config, output_config)
|
||||
})
|
||||
|
||||
test("no sampling default is injected for Claude when the client omits it", async () => {
|
||||
const { post, sent } = await fixture()
|
||||
await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 64 })
|
||||
const call = sent.at(-1)
|
||||
assert.equal("temperature" in call.body, false)
|
||||
assert.equal("top_p" in call.body, false)
|
||||
})
|
||||
|
||||
test("a model addressed through the wrong protocol route fails before inference", async () => {
|
||||
const { post, sent } = await fixture()
|
||||
const mark = sent.length
|
||||
// Claude model on the Responses route.
|
||||
const a = await post("/responses", { model: OPUS, input: "hi" })
|
||||
assert.equal(a.status, 400)
|
||||
// GPT model on the Messages route.
|
||||
const b = await post("/messages", { model: GPT, messages: [{ role: "user", content: "hi" }], max_tokens: 16 })
|
||||
assert.equal(b.status, 400)
|
||||
assert.equal(sent.length, mark, "no upstream inference call was made")
|
||||
})
|
||||
|
||||
test("a native Anthropic error reply preserves status and redacts credential echoes", async () => {
|
||||
const { post } = await fixture(() => new Response(JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "bad " + CREDS.clientSecret } }), { status: 400 }))
|
||||
const response = await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 16 })
|
||||
assert.equal(response.status, 400)
|
||||
const text = await response.text()
|
||||
assert.equal(text.includes(CREDS.clientSecret), false)
|
||||
assert.ok(text.includes("[redacted]"))
|
||||
})
|
||||
|
||||
test("an unknown model on the Messages route is a 404", async () => {
|
||||
const { post } = await fixture()
|
||||
const response = await post("/messages", { model: "claude-ghost-9-9", messages: [{ role: "user", content: "hi" }], max_tokens: 16 })
|
||||
assert.equal(response.status, 404)
|
||||
})
|
||||
|
||||
// --- dispatch request-policy and capability gates (direct) -----------------
|
||||
|
||||
const CREDENTIALS = { aiRoot: ROOT, resourceGroup: "group-a", clientId: CREDS.clientId, clientSecret: CREDS.clientSecret }
|
||||
const OPUS_POLICY = { maxOutputTokens: 128000, rejectTemperature: true, rejectTopP: true, rejectEnabledThinking: true }
|
||||
const SONNET_POLICY = { maxOutputTokens: 128000, rejectCombinedSampling: true, rejectForcedToolThinking: true }
|
||||
const entryFor = (url, policy, streaming = true) => ({
|
||||
deploymentURL: url, protocol: "anthropic",
|
||||
capabilities: { text: true, functionTool: true, streaming },
|
||||
...(policy ? { requestPolicy: policy } : {}),
|
||||
})
|
||||
const bodyFor = over => ({ model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 64, ...over })
|
||||
const invoke = (entry, body) => dispatch({ entry, body, credentials: CREDENTIALS, token: { value: TOKEN } })
|
||||
|
||||
function stubFetch(impl) {
|
||||
const original = globalThis.fetch
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
let calls = 0
|
||||
globalThis.fetch = async (input, init) => { calls++; return impl(input, init) }
|
||||
return { calls: () => calls }
|
||||
}
|
||||
|
||||
test("the Opus baseline policy rejects temperature, top_p, enabled thinking and the output ceiling before inference", async () => {
|
||||
const spy = stubFetch(() => new Response(JSON.stringify(MESSAGE)))
|
||||
const entry = entryFor(OPUS_URL, OPUS_POLICY)
|
||||
await assert.rejects(invoke(entry, bodyFor({ temperature: 0.2 })), { code: "invalid-request" })
|
||||
await assert.rejects(invoke(entry, bodyFor({ top_p: 0.5 })), { code: "invalid-request" })
|
||||
await assert.rejects(invoke(entry, bodyFor({ thinking: { type: "enabled", budget_tokens: 1024 } })), { code: "invalid-request" })
|
||||
await assert.rejects(invoke(entry, bodyFor({ max_tokens: 128001 })), { code: "invalid-request" })
|
||||
assert.equal(spy.calls(), 0, "no rejected request escaped the gate to inference")
|
||||
})
|
||||
|
||||
test("the Opus baseline accepts adaptive and disabled thinking and max_tokens at the ceiling", async () => {
|
||||
stubFetch(() => new Response(JSON.stringify(MESSAGE)))
|
||||
const entry = entryFor(OPUS_URL, OPUS_POLICY)
|
||||
assert.equal((await invoke(entry, bodyFor({ thinking: { type: "adaptive" } }))).status, 200)
|
||||
assert.equal((await invoke(entry, bodyFor({ thinking: { type: "disabled" } }))).status, 200)
|
||||
assert.equal((await invoke(entry, bodyFor({ max_tokens: 128000 }))).status, 200)
|
||||
})
|
||||
|
||||
test("the Sonnet baseline allows individual sampling and a fixed budget but rejects combined sampling and forced-tool thinking", async () => {
|
||||
const sonnetReply = { ...MESSAGE, model: SONNET }
|
||||
const spy = stubFetch(() => new Response(JSON.stringify(sonnetReply)))
|
||||
const entry = entryFor(SONNET_URL, SONNET_POLICY)
|
||||
assert.equal((await invoke(entry, bodyFor({ model: SONNET, temperature: 0.2 }))).status, 200)
|
||||
assert.equal((await invoke(entry, bodyFor({ model: SONNET, top_p: 0.5 }))).status, 200)
|
||||
assert.equal((await invoke(entry, bodyFor({ model: SONNET, thinking: { type: "enabled", budget_tokens: 1024 } }))).status, 200)
|
||||
const reached = spy.calls()
|
||||
await assert.rejects(invoke(entry, bodyFor({ model: SONNET, temperature: 0.2, top_p: 0.5 })), { code: "invalid-request" })
|
||||
const tools = [{ name: "lookup", input_schema: { type: "object" } }]
|
||||
await assert.rejects(invoke(entry, bodyFor({ model: SONNET, tools, tool_choice: { type: "any" }, thinking: { type: "enabled", budget_tokens: 1024 } })), { code: "invalid-request" })
|
||||
assert.equal(spy.calls(), reached, "rejected combinations never reached inference")
|
||||
})
|
||||
|
||||
test("a newer Claude deployment carries no policy, so structurally valid controls pass through and upstream validation is preserved", async () => {
|
||||
// No requestPolicy (not a verified baseline): the gate invents no restriction and
|
||||
// forwards combined sampling, enabled thinking and a large budget to upstream,
|
||||
// whose own validation verdict is preserved verbatim.
|
||||
const upstream = { type: "error", error: { type: "invalid_request_error", message: "unsupported by this version" } }
|
||||
const spy = stubFetch(() => new Response(JSON.stringify(upstream), { status: 400 }))
|
||||
const entry = entryFor(ROOT + "/v2/inference/deployments/deployment-next", null)
|
||||
const response = await invoke(entry, bodyFor({ model: "claude-opus-5-0", temperature: 0.2, top_p: 0.5, max_tokens: 400000, thinking: { type: "enabled", budget_tokens: 4096 } }))
|
||||
assert.equal(response.status, 400)
|
||||
assert.equal(spy.calls(), 1, "the request reached upstream unblocked")
|
||||
})
|
||||
|
||||
test("a streamed request to a model without streaming capability is rejected before inference", async () => {
|
||||
const spy = stubFetch(() => new Response(JSON.stringify(MESSAGE)))
|
||||
const entry = entryFor(OPUS_URL, OPUS_POLICY, false)
|
||||
await assert.rejects(invoke(entry, bodyFor({ stream: true })), { code: "invalid-request" })
|
||||
assert.equal(spy.calls(), 0, "the capability gate fires before any inference call")
|
||||
})
|
||||
|
||||
test("malformed whole message identity, role, stop reason, or usage is rejected as an upstream response failure", async () => {
|
||||
let reply = MESSAGE
|
||||
const { post } = await fixture(() => new Response(JSON.stringify(reply)))
|
||||
for (const invalid of [{ id: "" }, { role: "user" }, { stop_reason: "" }, { usage: undefined }, { usage: { input_tokens: -1, output_tokens: 2 } }]) {
|
||||
reply = { ...MESSAGE, ...invalid }
|
||||
const response = await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 16 })
|
||||
assert.equal(response.status, 502)
|
||||
assert.equal((await response.json()).error.code, "inference-response")
|
||||
}
|
||||
})
|
||||
|
||||
test("a whole error redacts top-level sibling credential echoes and preserves the native error category", async () => {
|
||||
const { post } = await fixture(() => new Response(JSON.stringify({
|
||||
type: "error", message: "oops " + CREDS.clientSecret, details: { echo: CREDS.clientSecret },
|
||||
error: { type: "overloaded_error", message: "native failure", details: { echo: CREDS.clientSecret } },
|
||||
}), { status: 529 }))
|
||||
const response = await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 16 })
|
||||
assert.equal(response.status, 529)
|
||||
const text = await response.text()
|
||||
assert.equal(text.includes(CREDS.clientSecret), false)
|
||||
assert.equal(JSON.parse(text).error.type, "overloaded_error", "native error category is preserved")
|
||||
})
|
||||
|
||||
test("Claude versions with absent or false catalog streaming support remain listed and whole-only", async () => {
|
||||
for (const opusStreaming of [undefined, false]) {
|
||||
const { post, sent, models } = await fixture(undefined, { opusStreaming })
|
||||
const listed = await models()
|
||||
assert.equal(listed[OPUS].limit.output, 128000)
|
||||
const whole = await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 16 })
|
||||
assert.equal(whole.status, 200)
|
||||
assert.deepEqual(await whole.json(), MESSAGE)
|
||||
assert.equal(sent.at(-1).url, OPUS_URL + "/invoke")
|
||||
const invokes = sent.length
|
||||
const streamed = await post("/messages", { model: OPUS, messages: [{ role: "user", content: "hi" }], max_tokens: 16, stream: true })
|
||||
assert.equal(streamed.status, 400)
|
||||
assert.equal((await streamed.json()).error.code, "invalid-request")
|
||||
assert.equal(sent.length, invokes)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,692 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { createHash } from "node:crypto"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const CREDS = {
|
||||
authUrl: "https://synthetic.authentication.eu10.hana.ondemand.com",
|
||||
baseUrl: "https://api.ai.eu10.hana.ondemand.com",
|
||||
clientId: "synthetic-id",
|
||||
clientSecret: "synthetic-secret",
|
||||
resourceGroup: "default",
|
||||
}
|
||||
const AI_ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
|
||||
const DEPLOYMENTS = "/v2/lm/deployments"
|
||||
const CATALOG = "/v2/lm/scenarios/foundation-models/models"
|
||||
const CONFIG = "/v2/lm/configurations/"
|
||||
const TOKEN = "/oauth/token"
|
||||
|
||||
function tmpDir() {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), "magpie-model-discovery-"))
|
||||
}
|
||||
|
||||
function writeCreds(dir, name, overrides = {}) {
|
||||
const p = path.join(dir, name)
|
||||
fs.writeFileSync(p, JSON.stringify({ ...CREDS, ...overrides }), { mode: 0o600 })
|
||||
return p
|
||||
}
|
||||
|
||||
function pathKey(normalized) {
|
||||
return "sap-aicore:path:" + createHash("sha256").update("sap-aicore:path:" + normalized).digest("hex")
|
||||
}
|
||||
|
||||
function authFor(credentialFile) {
|
||||
return { type: "api", key: pathKey(credentialFile), metadata: { credentialFile } }
|
||||
}
|
||||
|
||||
function json(payload, init = {}) {
|
||||
return new Response(JSON.stringify(payload), init)
|
||||
}
|
||||
|
||||
function tokenReply(overrides = {}) {
|
||||
return json({ access_token: "synthetic-token", token_type: "bearer", expires_in: 43199, ...overrides })
|
||||
}
|
||||
|
||||
function pathOf(href) {
|
||||
return new URL(String(href instanceof Request ? href.url : href)).pathname
|
||||
}
|
||||
|
||||
function urlFor(id) {
|
||||
return AI_ROOT + "/v2/inference/deployments/" + id
|
||||
}
|
||||
|
||||
function row(id, model, version, configurationId) {
|
||||
return {
|
||||
id,
|
||||
status: "RUNNING",
|
||||
deploymentUrl: urlFor(id),
|
||||
configurationId,
|
||||
details: { resources: { backendDetails: { model: { name: model, version } } } },
|
||||
}
|
||||
}
|
||||
|
||||
function config(model, version, id) {
|
||||
return {
|
||||
id,
|
||||
scenarioId: "foundation-models",
|
||||
executableId: "azure-openai",
|
||||
parameterBindings: [
|
||||
{ key: "modelName", value: model },
|
||||
{ key: "modelVersion", value: version },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function catalogFor(...entries) {
|
||||
return {
|
||||
count: entries.length,
|
||||
resources: entries.map(([model, version]) => ({
|
||||
model,
|
||||
executableId: "azure-openai",
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }],
|
||||
versions: [{
|
||||
name: version,
|
||||
contextLength: 1050000,
|
||||
inputTypes: ["text"],
|
||||
deprecated: false,
|
||||
retirementDate: "",
|
||||
streamingSupported: true,
|
||||
}],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function router(routes) {
|
||||
return (href) => {
|
||||
const url = new URL(String(href instanceof Request ? href.url : href))
|
||||
if (url.pathname === TOKEN) return tokenReply()
|
||||
if (url.pathname === DEPLOYMENTS) {
|
||||
return url.searchParams.get("$skip") === "0" ? json(routes.deployments) : json({ resources: [] })
|
||||
}
|
||||
if (url.pathname === CATALOG) return json(routes.catalog)
|
||||
if (url.pathname.startsWith(CONFIG)) {
|
||||
const body = routes.configs[url.pathname.slice(CONFIG.length)]
|
||||
return body && body.body !== undefined ? body : json(body)
|
||||
}
|
||||
throw new Error("unexpected path " + url.pathname)
|
||||
}
|
||||
}
|
||||
|
||||
function withFetch(mock, fn) {
|
||||
const real = globalThis.fetch
|
||||
globalThis.fetch = mock
|
||||
return Promise.resolve().then(fn).finally(() => { globalThis.fetch = real })
|
||||
}
|
||||
|
||||
async function authorize(plugin, mock, credentialFile) {
|
||||
const result = await withFetch(mock, () => plugin.auth.methods[0].authorize({ credentialFile }))
|
||||
assert.equal(result.type, "success")
|
||||
return { type: "api", key: result.key, metadata: result.metadata }
|
||||
}
|
||||
|
||||
const ASTRA = ["gpt-6-astra", "2026-09-03"]
|
||||
const SOL = ["gpt-6.1-sol", "2026-09-29"]
|
||||
|
||||
test("unsigned models performs no IO and returns an empty catalog", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
let called = false
|
||||
await withFetch(async () => { called = true; return json({}) }, async () => {
|
||||
assert.deepEqual(await plugin.provider.models({ models: {} }), {})
|
||||
assert.deepEqual(await plugin.provider.models({ models: {} }, {}), {})
|
||||
assert.deepEqual(await plugin.provider.models({ models: {} }, { auth: null }), {})
|
||||
})
|
||||
assert.equal(called, false)
|
||||
})
|
||||
|
||||
test("a signed account projects exactly the two verified models through the hook", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const cidA = "c" + "0".repeat(15)
|
||||
const cidB = "c" + "1".repeat(15)
|
||||
const mock = router({
|
||||
deployments: { resources: [
|
||||
row("d0000000000000a1", "gpt-6-astra", "2026-09-03", cidA),
|
||||
row("d0000000000000b1", "gpt-6.1-sol", "2026-09-29", cidB),
|
||||
] },
|
||||
configs: {
|
||||
[cidA]: config("gpt-6-astra", "2026-09-03", cidA),
|
||||
[cidB]: config("gpt-6.1-sol", "2026-09-29", cidB),
|
||||
},
|
||||
catalog: catalogFor(ASTRA, SOL),
|
||||
})
|
||||
const p = writeCreds(dir, "two.json")
|
||||
const auth = await authorize(plugin, mock, p)
|
||||
const catalog = await withFetch(mock, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
|
||||
assert.deepEqual(Object.keys(catalog).sort(), ["gpt-6-astra", "gpt-6.1-sol"])
|
||||
assert.deepEqual(catalog["gpt-6-astra"], {
|
||||
id: "gpt-6-astra",
|
||||
name: "gpt-6-astra",
|
||||
providerID: "sap-aicore",
|
||||
api: { id: "gpt-6-astra", npm: "@ai-sdk/openai" },
|
||||
capabilities: {
|
||||
toolcall: true,
|
||||
attachment: false,
|
||||
input: { text: true, image: false, audio: false, video: false, pdf: false },
|
||||
output: { text: true, image: false, audio: false, video: false, pdf: false },
|
||||
},
|
||||
limit: { context: 1050000 },
|
||||
})
|
||||
assert.equal(catalog["gpt-6.1-sol"].api.npm, "@ai-sdk/openai")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a newer GPT model is listed and dispatched through Responses without an allowlist entry", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const model = "gpt-7-mini"
|
||||
const version = "2027-01-01"
|
||||
const id = "deployment-new-gpt"
|
||||
const cid = "config-new-gpt"
|
||||
const discovery = router({
|
||||
deployments: { resources: [row(id, model, version, cid)] },
|
||||
configs: { [cid]: config(model, "latest", cid) },
|
||||
catalog: catalogFor([model, version]),
|
||||
})
|
||||
const sent = []
|
||||
const mock = (href, init) => {
|
||||
if (String(href) !== urlFor(id) + "/responses") return discovery(href)
|
||||
sent.push(JSON.parse(init.body))
|
||||
return json({ id: "resp_new", object: "response", model, status: "completed", output: [] })
|
||||
}
|
||||
const auth = await authorize(plugin, mock, writeCreds(dir, "new-gpt.json"))
|
||||
await withFetch(mock, async () => {
|
||||
const catalog = await plugin.provider.models({ models: {} }, { auth })
|
||||
assert.deepEqual(Object.keys(catalog), [model])
|
||||
assert.deepEqual(catalog[model].api, { id: model, npm: "@ai-sdk/openai" })
|
||||
const loader = await plugin.auth.loader(async () => auth)
|
||||
const response = await loader.fetch(AI_ROOT + "/responses", {
|
||||
method: "POST", body: JSON.stringify({ model, input: "hello" }),
|
||||
})
|
||||
assert.equal(response.status, 200)
|
||||
assert.equal((await response.json()).model, model)
|
||||
assert.deepEqual(sent, [{ model, input: "hello", store: false }])
|
||||
})
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a mixed GPT and Claude account lists both under their protocol identities through the hook", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const cidG = "c" + "0".repeat(15)
|
||||
const cidC = "c" + "3".repeat(15)
|
||||
const OPUS_SAP = "anthropic--claude-4.8-opus"
|
||||
const claudeConfig = { id: cidC, scenarioId: "foundation-models", executableId: "aws-bedrock", parameterBindings: [{ key: "modelName", value: OPUS_SAP }, { key: "modelVersion", value: "1" }] }
|
||||
const claudeResource = { model: OPUS_SAP, executableId: "aws-bedrock", provider: "Anthropic", displayName: "Claude 4.8 Opus", allowedScenarios: [{ scenarioId: "foundation-models", executableId: "aws-bedrock" }], versions: [{ name: "1", contextLength: 1000000, inputTypes: ["text", "image"], deprecated: false, retirementDate: "", streamingSupported: true }] }
|
||||
const mock = router({
|
||||
deployments: { resources: [
|
||||
row("d0000000000000a1", "gpt-6-astra", "2026-09-03", cidG),
|
||||
row("d9df30a64cef44d6", OPUS_SAP, "1", cidC),
|
||||
] },
|
||||
configs: { [cidG]: config("gpt-6-astra", "2026-09-03", cidG), [cidC]: claudeConfig },
|
||||
catalog: { count: 2, resources: [catalogFor(ASTRA).resources[0], claudeResource] },
|
||||
})
|
||||
const p = writeCreds(dir, "mixed.json")
|
||||
const auth = await authorize(plugin, mock, p)
|
||||
const catalog = await withFetch(mock, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
|
||||
assert.deepEqual(Object.keys(catalog).sort(), ["claude-opus-4-8", "gpt-6-astra"])
|
||||
assert.equal(catalog["gpt-6-astra"].api.npm, "@ai-sdk/openai")
|
||||
assert.deepEqual(catalog["claude-opus-4-8"].api, { id: "claude-opus-4-8", npm: "@ai-sdk/anthropic" })
|
||||
assert.equal(catalog["claude-opus-4-8"].name, "Claude Opus 4.8")
|
||||
assert.equal(catalog["claude-opus-4-8"].capabilities.input.image, true)
|
||||
assert.equal(catalog["claude-opus-4-8"].limit.context, 1000000)
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a configured given model is excluded and the given config is not mutated", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const cid = "c" + "2".repeat(15)
|
||||
const mock = router({
|
||||
deployments: { resources: [row("d0000000000000a1", "gpt-6-astra", "2026-09-03", cid)] },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: catalogFor(ASTRA),
|
||||
})
|
||||
const p = writeCreds(dir, "given.json")
|
||||
const auth = await authorize(plugin, mock, p)
|
||||
|
||||
const given = { models: { "ghost-model": { id: "ghost-model", npm: "@ai-sdk/anthropic" } } }
|
||||
const catalog = await withFetch(mock, () => plugin.provider.models(given, { auth }))
|
||||
|
||||
assert.deepEqual(Object.keys(catalog), ["gpt-6-astra"])
|
||||
assert.equal("ghost-model" in catalog, false)
|
||||
assert.deepEqual(given.models, { "ghost-model": { id: "ghost-model", npm: "@ai-sdk/anthropic" } })
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("successful empty discovery returns {} while a malformed response throws a prefixed discovery error", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const empty = router({ deployments: { resources: [] }, configs: {}, catalog: catalogFor() })
|
||||
const p = writeCreds(dir, "empty.json")
|
||||
const auth = await authorize(plugin, empty, p)
|
||||
assert.deepEqual(await withFetch(empty, () => plugin.provider.models({ models: {} }, { auth })), {})
|
||||
|
||||
const plugin2 = await SAPAICorePlugin()
|
||||
const malformed = (href) => pathOf(href) === TOKEN ? tokenReply() : json({ resources: {} })
|
||||
const p2 = writeCreds(dir, "malformed.json")
|
||||
const auth2 = await authorize(plugin2, malformed, p2)
|
||||
await assert.rejects(
|
||||
() => withFetch(malformed, () => plugin2.provider.models({ models: {} }, { auth: auth2 })),
|
||||
err => {
|
||||
assert.equal(err.code, "discovery-response")
|
||||
assert.match(err.message, /model discovery returned an unexpected response/)
|
||||
assert.doesNotMatch(err.message, /synthetic|eu10|hana|Bearer/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("model-hook OAuth refusal expires sign-in while a missing credential keeps it", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const missing = path.join(dir, "absent.json")
|
||||
const plugin = await SAPAICorePlugin()
|
||||
await assert.rejects(
|
||||
() => withFetch(() => { throw new Error("no network") }, () => plugin.provider.models({ models: {} }, { auth: authFor(missing) })),
|
||||
err => {
|
||||
assert.equal(err.code, "file")
|
||||
assert.equal(err.signIn, "kept")
|
||||
assert.doesNotMatch(err.message, /discovery/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
|
||||
const plugin2 = await SAPAICorePlugin()
|
||||
const p = writeCreds(dir, "refused.json")
|
||||
const refuse = (href) =>
|
||||
pathOf(href) === TOKEN
|
||||
? json({ error: "invalid_client" }, { status: 401, headers: { "www-authenticate": "Basic realm=OAuth" } })
|
||||
: json({ resources: [] })
|
||||
await assert.rejects(
|
||||
() => withFetch(refuse, () => plugin2.provider.models({ models: {} }, { auth: authFor(p) })),
|
||||
err => {
|
||||
assert.equal(err.code, "oauth-refused")
|
||||
assert.equal(err.signIn, "expired")
|
||||
assert.doesNotMatch(err.message, /discovery/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("two resource groups with the same model names issue distinct requests and stay isolated", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const cidA = "c" + "3".repeat(15)
|
||||
const cidB = "c" + "4".repeat(15)
|
||||
const routes = {
|
||||
groupA: router({
|
||||
deployments: { resources: [row("d0000000000000a1", "gpt-6-astra", "2026-09-03", cidA)] },
|
||||
configs: { [cidA]: config("gpt-6-astra", "2026-09-03", cidA) },
|
||||
catalog: catalogFor(ASTRA),
|
||||
}),
|
||||
groupB: router({
|
||||
deployments: { resources: [row("d0000000000000b1", "gpt-6-astra", "2026-09-03", cidB)] },
|
||||
configs: { [cidB]: config("gpt-6-astra", "2026-09-03", cidB) },
|
||||
catalog: catalogFor(ASTRA),
|
||||
}),
|
||||
}
|
||||
const groups = []
|
||||
const mock = async (href, init) => {
|
||||
if (pathOf(href) === TOKEN) return tokenReply()
|
||||
const group = init.headers["AI-Resource-Group"]
|
||||
groups.push(group)
|
||||
return routes[group](href, init)
|
||||
}
|
||||
const pA = writeCreds(dir, "group-a.json", { resourceGroup: "groupA" })
|
||||
const pB = writeCreds(dir, "group-b.json", { resourceGroup: "groupB" })
|
||||
const authA = await authorize(plugin, mock, pA)
|
||||
const authB = await authorize(plugin, mock, pB)
|
||||
|
||||
const catA = await withFetch(mock, () => plugin.provider.models({ models: {} }, { auth: authA }))
|
||||
const catB = await withFetch(mock, () => plugin.provider.models({ models: {} }, { auth: authB }))
|
||||
|
||||
assert.deepEqual(Object.keys(catA), ["gpt-6-astra"])
|
||||
assert.deepEqual(Object.keys(catB), ["gpt-6-astra"])
|
||||
assert.ok(groups.includes("groupA") && groups.includes("groupB"), "each account must request its own resource group")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a generation retired mid-discovery fails superseded and publishes nothing", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const cid = "c" + "5".repeat(15)
|
||||
const complete = router({
|
||||
deployments: { resources: [row("d0000000000000a1", "gpt-6-astra", "2026-09-03", cid)] },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: catalogFor(ASTRA),
|
||||
})
|
||||
const p = writeCreds(dir, "retire.json")
|
||||
const auth = await authorize(plugin, complete, p)
|
||||
|
||||
let started
|
||||
const seen = new Promise(r => { started = r })
|
||||
const hanging = (href, init) => {
|
||||
if (pathOf(href) === TOKEN) return tokenReply()
|
||||
if (pathOf(href) === DEPLOYMENTS) { started(); return new Promise(() => {}) }
|
||||
return complete(href, init)
|
||||
}
|
||||
|
||||
const real = globalThis.fetch
|
||||
globalThis.fetch = hanging
|
||||
try {
|
||||
const pending = plugin.provider.models({ models: {} }, { auth })
|
||||
const guarded = pending.catch(e => e)
|
||||
await seen
|
||||
const reauth = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(reauth.type, "success")
|
||||
const error = await guarded
|
||||
assert.ok(error instanceof Error)
|
||||
assert.equal(error.code, "superseded")
|
||||
assert.doesNotMatch(error.message, /discovery/)
|
||||
} finally {
|
||||
globalThis.fetch = real
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
function counting(mock) {
|
||||
const state = { management: 0, firstPage: 0 }
|
||||
const wrapped = (href, init) => {
|
||||
const p = pathOf(href)
|
||||
if (p !== TOKEN) state.management++
|
||||
if (p === DEPLOYMENTS && new URL(String(href instanceof Request ? href.url : href)).searchParams.get("$skip") === "0") state.firstPage++
|
||||
return mock(href, init)
|
||||
}
|
||||
return { wrapped, state }
|
||||
}
|
||||
|
||||
function withClock(start, fn) {
|
||||
const real = performance.now
|
||||
let t = start
|
||||
performance.now = () => t
|
||||
return Promise.resolve().then(() => fn(v => { t = v })).finally(() => { performance.now = real })
|
||||
}
|
||||
|
||||
function withDate(iso, fn) {
|
||||
const Real = Date
|
||||
const fixed = Real.parse(iso)
|
||||
class FakeDate extends Real {
|
||||
constructor(...args) { super(...(args.length ? args : [fixed])) }
|
||||
static now() { return fixed }
|
||||
}
|
||||
globalThis.Date = FakeDate
|
||||
return Promise.resolve().then(fn).finally(() => { globalThis.Date = Real })
|
||||
}
|
||||
|
||||
function astraRoutes(cid) {
|
||||
return {
|
||||
deployments: { resources: [row("d0000000000000a1", "gpt-6-astra", "2026-09-03", cid)] },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: catalogFor(ASTRA),
|
||||
}
|
||||
}
|
||||
|
||||
test("a fresh snapshot serves repeat scans with no further management requests", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const { wrapped, state } = counting(router(astraRoutes("c" + "6".repeat(15))))
|
||||
const auth = await authorize(plugin, wrapped, writeCreds(dir, "hit.json"))
|
||||
|
||||
const first = await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
const afterFirst = state.management
|
||||
assert.ok(afterFirst > 0, "the first scan performs discovery")
|
||||
const second = await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
|
||||
assert.equal(state.management, afterFirst, "a fresh snapshot issues no new management requests")
|
||||
assert.deepEqual(Object.keys(first), ["gpt-6-astra"])
|
||||
assert.deepEqual(Object.keys(second), ["gpt-6-astra"])
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a snapshot expires on equality with the 300000 ms TTL, not just before it", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const { wrapped, state } = counting(router(astraRoutes("c" + "7".repeat(15))))
|
||||
const auth = await authorize(plugin, wrapped, writeCreds(dir, "ttl.json"))
|
||||
|
||||
await withClock(0, async set => {
|
||||
await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
const afterFirst = state.management
|
||||
|
||||
set(299999)
|
||||
await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
assert.equal(state.management, afterFirst, "299999 ms is still within the TTL")
|
||||
|
||||
set(300000)
|
||||
const refreshed = await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
assert.ok(state.management > afterFirst, "equality with the TTL forces a refresh")
|
||||
assert.deepEqual(Object.keys(refreshed), ["gpt-6-astra"])
|
||||
})
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a successful empty discovery is cached and repeat scans stay empty without management", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const { wrapped, state } = counting(router({ deployments: { resources: [] }, configs: {}, catalog: catalogFor() }))
|
||||
const auth = await authorize(plugin, wrapped, writeCreds(dir, "empty-cache.json"))
|
||||
|
||||
assert.deepEqual(await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth })), {})
|
||||
const afterFirst = state.management
|
||||
assert.ok(afterFirst > 0, "the first empty scan still performs discovery")
|
||||
assert.deepEqual(await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth })), {})
|
||||
assert.equal(state.management, afterFirst, "a cached empty result issues no new management requests")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("an expired refresh that fails throws instead of serving the stale snapshot, then recovers", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const cid = "c" + "8".repeat(15)
|
||||
const good = router(astraRoutes(cid))
|
||||
let fail = false
|
||||
const mock = (href, init) => {
|
||||
if (pathOf(href) === TOKEN) return tokenReply()
|
||||
if (fail && pathOf(href) === DEPLOYMENTS) return json({ resources: {} })
|
||||
return good(href, init)
|
||||
}
|
||||
const auth = await authorize(plugin, mock, writeCreds(dir, "refresh.json"))
|
||||
|
||||
await withClock(0, async set => {
|
||||
assert.deepEqual(
|
||||
Object.keys(await withFetch(mock, () => plugin.provider.models({ models: {} }, { auth }))),
|
||||
["gpt-6-astra"],
|
||||
)
|
||||
set(300000)
|
||||
fail = true
|
||||
await assert.rejects(
|
||||
() => withFetch(mock, () => plugin.provider.models({ models: {} }, { auth })),
|
||||
err => {
|
||||
assert.equal(err.code, "discovery-response")
|
||||
assert.doesNotMatch(err.message, /synthetic|eu10|hana|Bearer/)
|
||||
return true
|
||||
},
|
||||
)
|
||||
fail = false
|
||||
const recovered = await withFetch(mock, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
assert.deepEqual(Object.keys(recovered), ["gpt-6-astra"])
|
||||
})
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("concurrent scans coalesce into a single discovery", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const good = router(astraRoutes("c" + "9".repeat(15)))
|
||||
let release
|
||||
const gate = new Promise(r => { release = r })
|
||||
const { wrapped, state } = counting(async (href, init) => {
|
||||
if (pathOf(href) === DEPLOYMENTS) await gate
|
||||
return good(href, init)
|
||||
})
|
||||
const auth = await authorize(plugin, wrapped, writeCreds(dir, "coalesce.json"))
|
||||
|
||||
await withFetch(wrapped, async () => {
|
||||
const a = plugin.provider.models({ models: {} }, { auth })
|
||||
const b = plugin.provider.models({ models: {} }, { auth })
|
||||
await new Promise(r => setImmediate(r))
|
||||
release()
|
||||
const [ra, rb] = await Promise.all([a, b])
|
||||
assert.deepEqual(Object.keys(ra), ["gpt-6-astra"])
|
||||
assert.deepEqual(Object.keys(rb), ["gpt-6-astra"])
|
||||
})
|
||||
assert.equal(state.firstPage, 1, "two concurrent scans share one deployment listing")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a retirement cutoff at UTC midnight expires a TTL-young snapshot", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const cid = "c" + "a".repeat(15)
|
||||
const retiring = {
|
||||
count: 1,
|
||||
resources: [{
|
||||
model: "gpt-6-astra",
|
||||
executableId: "azure-openai",
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }],
|
||||
versions: [{
|
||||
name: "2026-09-03",
|
||||
contextLength: 1050000,
|
||||
inputTypes: ["text"],
|
||||
deprecated: false,
|
||||
retirementDate: "2026-11-02",
|
||||
streamingSupported: true,
|
||||
}],
|
||||
}],
|
||||
}
|
||||
const { wrapped, state } = counting(router({
|
||||
deployments: { resources: [row("d0000000000000a1", "gpt-6-astra", "2026-09-03", cid)] },
|
||||
configs: { [cid]: config("gpt-6-astra", "2026-09-03", cid) },
|
||||
catalog: retiring,
|
||||
}))
|
||||
const p = writeCreds(dir, "retire-cutoff.json")
|
||||
let auth
|
||||
|
||||
await withDate("2026-11-01T12:00:00Z", async () => {
|
||||
auth = await authorize(plugin, wrapped, p)
|
||||
const before = await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
assert.deepEqual(Object.keys(before), ["gpt-6-astra"])
|
||||
})
|
||||
const afterFirst = state.management
|
||||
|
||||
await withDate("2026-11-02T00:00:00Z", async () => {
|
||||
const after = await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
assert.deepEqual(after, {}, "a model retired at UTC midnight is dropped despite a young TTL")
|
||||
})
|
||||
assert.ok(state.management > afterFirst, "crossing the retirement cutoff forces a refresh")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a cold loader with no prior scan initiates full discovery and exposes the account baseURL", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const { wrapped, state } = counting(router(astraRoutes("c" + "b".repeat(15))))
|
||||
const auth = await authorize(plugin, wrapped, writeCreds(dir, "cold-loader.json"))
|
||||
|
||||
const opts = await withFetch(wrapped, () => plugin.auth.loader(async () => auth))
|
||||
|
||||
assert.ok(state.management > 0, "a cold loader runs discovery during initialization")
|
||||
assert.equal(state.firstPage, 1, "the loader lists deployments exactly once")
|
||||
assert.equal(opts.baseURL, AI_ROOT)
|
||||
assert.equal(typeof opts.fetch, "function")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a prior models scan is reused by the loader with no further management requests", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const { wrapped, state } = counting(router(astraRoutes("c" + "c".repeat(15))))
|
||||
const auth = await authorize(plugin, wrapped, writeCreds(dir, "shared-cache.json"))
|
||||
|
||||
const catalog = await withFetch(wrapped, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
assert.deepEqual(Object.keys(catalog), ["gpt-6-astra"])
|
||||
const afterModels = state.management
|
||||
assert.ok(afterModels > 0, "the models scan performs discovery")
|
||||
|
||||
const opts = await withFetch(wrapped, () => plugin.auth.loader(async () => auth))
|
||||
assert.equal(state.management, afterModels, "the loader reuses the shared snapshot")
|
||||
assert.equal(opts.baseURL, AI_ROOT)
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
test("a fresh plugin rebuilds discovery from the stored auth reference without a prior scan", async () => {
|
||||
const dir = tmpDir()
|
||||
try {
|
||||
const plugin1 = await SAPAICorePlugin()
|
||||
const { wrapped, state } = counting(router(astraRoutes("c" + "d".repeat(15))))
|
||||
const auth = await authorize(plugin1, wrapped, writeCreds(dir, "restart.json"))
|
||||
|
||||
await withFetch(wrapped, () => plugin1.auth.loader(async () => auth))
|
||||
const afterFirst = state.management
|
||||
assert.ok(afterFirst > 0, "the first plugin's loader discovers")
|
||||
|
||||
const plugin2 = await SAPAICorePlugin()
|
||||
const opts = await withFetch(wrapped, () => plugin2.auth.loader(async () => auth))
|
||||
assert.ok(state.management > afterFirst, "a fresh plugin rebuilds discovery for the same auth reference")
|
||||
assert.equal(opts.baseURL, AI_ROOT)
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,157 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import definition from "../opencode2.mjs"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const ROOT = "https://api.ai.eu10.hana.ondemand.com"
|
||||
const GPT = "gpt-6-astra"
|
||||
const OPUS = "claude-opus-4-8"
|
||||
const OPUS_SAP = "anthropic--claude-4.8-opus"
|
||||
const TOKEN = "synthetic-opencode2-token"
|
||||
|
||||
function context() {
|
||||
const methods = []
|
||||
const transforms = []
|
||||
const sdkHooks = []
|
||||
const stored = new Map()
|
||||
const events = []
|
||||
let connection
|
||||
let credential
|
||||
let wake
|
||||
let refreshed
|
||||
const modelsRefreshed = new Promise(resolve => { refreshed = resolve })
|
||||
const ctx = {
|
||||
location: { directory: os.tmpdir() },
|
||||
integration: {
|
||||
transform: async transform => transform({ method: { update: method => methods.push(method) } }),
|
||||
connection: {
|
||||
active: async () => connection,
|
||||
resolve: async () => credential,
|
||||
},
|
||||
},
|
||||
provider: {
|
||||
transform: async transform => transforms.push(transform),
|
||||
reload: async () => refreshed(),
|
||||
},
|
||||
model: { reload: async () => {} },
|
||||
aisdk: { hook: async (name, callback, filter) => sdkHooks.push({ name, callback, filter }) },
|
||||
storage: { get: async key => stored.get(key), set: async (key, value) => stored.set(key, value) },
|
||||
event: {
|
||||
async *subscribe() {
|
||||
for (;;) {
|
||||
while (events.length) yield events.shift()
|
||||
await new Promise(resolve => { wake = resolve })
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
const providers = () => {
|
||||
const result = []
|
||||
for (const transform of transforms) transform({ add: provider => result.push(provider) })
|
||||
return result
|
||||
}
|
||||
const emit = event => { events.push(event); wake?.() }
|
||||
return {
|
||||
ctx, methods, providers, sdkHooks, modelsRefreshed, emit,
|
||||
use(value) {
|
||||
connection = { type: "credential", id: "synthetic-account" }
|
||||
credential = value
|
||||
emit({ type: "credential.switched", data: { integrationID: "sap-aicore" } })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function backend() {
|
||||
const original = globalThis.fetch
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
const calls = []
|
||||
const json = value => new Response(JSON.stringify(value), { headers: { "content-type": "application/json" } })
|
||||
const models = [
|
||||
{ id: "gpt", name: GPT, version: "2026-09-03", executable: "azure-openai" },
|
||||
{ id: "opus", name: OPUS_SAP, version: "1", executable: "aws-bedrock" },
|
||||
{ id: "old-gpt", name: "gpt-5.9", version: "1", executable: "azure-openai" },
|
||||
]
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = new URL(String(input))
|
||||
if (url.pathname === "/oauth/token") return json({ access_token: TOKEN, token_type: "bearer", expires_in: 3600 })
|
||||
if (url.pathname === "/v2/lm/deployments") return json({ resources: url.searchParams.get("$skip") === "0" ? models.map(model => ({
|
||||
id: model.id, status: "RUNNING", deploymentUrl: `${ROOT}/v2/inference/deployments/${model.id}`, configurationId: `cfg-${model.id}`,
|
||||
details: { resources: { backendDetails: { model: { name: model.name, version: model.version } } } },
|
||||
})) : [] })
|
||||
if (url.pathname.startsWith("/v2/lm/configurations/")) {
|
||||
const model = models.find(model => url.pathname === `/v2/lm/configurations/cfg-${model.id}`)
|
||||
assert.ok(model, `unexpected configuration request ${url}`)
|
||||
return json({ id: `cfg-${model.id}`, scenarioId: "foundation-models", executableId: model.executable, parameterBindings: [{ key: "modelName", value: model.name }, { key: "modelVersion", value: model.version }] })
|
||||
}
|
||||
if (url.pathname === "/v2/lm/scenarios/foundation-models/models") return json({ count: models.length, resources: models.map(model => ({
|
||||
model: model.name, executableId: model.executable, ...(model.executable === "aws-bedrock" ? { provider: "Anthropic", displayName: "Claude 4.8 Opus" } : {}),
|
||||
allowedScenarios: [{ scenarioId: "foundation-models", executableId: model.executable }],
|
||||
versions: [{ name: model.version, contextLength: 1000000, inputTypes: ["text", "image"], streamingSupported: true }],
|
||||
})) })
|
||||
calls.push({ url: url.href, headers: Object.fromEntries(new Headers(init.headers)), body: JSON.parse(init.body) })
|
||||
if (url.pathname === "/v2/inference/deployments/gpt/responses") return json({ id: "response-gpt", object: "response", model: GPT, status: "completed", output: [{ id: "message-gpt", type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text: "GPT_BRIDGE_OK", annotations: [] }] }], error: null, incomplete_details: null, usage: { input_tokens: 4, output_tokens: 3, total_tokens: 7 } })
|
||||
if (url.pathname === "/v2/inference/deployments/opus/invoke") return json({ id: "message-opus", type: "message", role: "assistant", model: OPUS, content: [{ type: "text", text: "CLAUDE_BRIDGE_OK" }], stop_reason: "end_turn", stop_sequence: null, usage: { input_tokens: 4, output_tokens: 3 } })
|
||||
throw new Error(`unexpected inference request ${url}`)
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
test("OpenCode 2 setup keeps the unsigned SAP catalog empty and does not fetch credentials", async () => {
|
||||
const original = globalThis.fetch
|
||||
cleanups.push(() => { globalThis.fetch = original })
|
||||
let requests = 0
|
||||
globalThis.fetch = async () => { requests++; throw new Error("unsigned setup must not request credentials") }
|
||||
const host = context()
|
||||
const stop = await definition.setup(host.ctx)
|
||||
cleanups.push(() => { stop(); host.emit({}) })
|
||||
assert.deepEqual(host.providers().map(provider => [provider.info.id, provider.models]), [["sap-aicore", []]])
|
||||
const signIn = host.methods.find(method => method.integrationID === "sap-aicore")
|
||||
assert.ok(signIn)
|
||||
assert.equal(signIn.method.form.find(field => field.key === "credentialFile").required, true)
|
||||
assert.equal(requests, 0)
|
||||
})
|
||||
|
||||
test("OpenCode 2 credential-file sign-in discovers both families and routes their SDK requests safely", async () => {
|
||||
const calls = backend()
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-opencode2-"))
|
||||
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }))
|
||||
const credentialFile = path.join(dir, "credentials.json")
|
||||
fs.writeFileSync(credentialFile, JSON.stringify({ authUrl: "https://synthetic.authentication.eu10.hana.ondemand.com", baseUrl: ROOT + "/v2", clientId: "synthetic-client", clientSecret: "synthetic-client-secret", resourceGroup: "bridge-group" }), { mode: 0o600 })
|
||||
const host = context()
|
||||
const stop = await definition.setup(host.ctx)
|
||||
cleanups.push(() => { stop(); host.emit({}) })
|
||||
const method = host.methods.find(method => method.integrationID === "sap-aicore")
|
||||
const signIn = await method.authorize({ credentialFile })
|
||||
host.use(await signIn.callback)
|
||||
await host.modelsRefreshed
|
||||
const provider = host.providers()[0]
|
||||
assert.deepEqual(provider.models.map(model => model.id).sort(), [OPUS, GPT])
|
||||
assert.deepEqual(provider.models.find(model => model.id === OPUS).capabilities.input, ["text", "image"])
|
||||
assert.equal(provider.models.find(model => model.id === OPUS).package, "aisdk:@ai-sdk/anthropic@ai-v6")
|
||||
const options = { baseURL: provider.info.settings.baseURL }
|
||||
await host.sdkHooks.find(hook => hook.name === "sdk" && hook.filter.providerID === "sap-aicore").callback({ options })
|
||||
const request = (route, body) => options.fetch(options.baseURL + route, { method: "POST", headers: { authorization: `Bearer ${options.apiKey}`, "x-api-key": "synthetic-caller-key" }, body: JSON.stringify(body) })
|
||||
const gpt = await request("/responses", { model: GPT, input: "hello", store: false })
|
||||
assert.equal(gpt.status, 200)
|
||||
assert.equal((await gpt.json()).output[0].content[0].text, "GPT_BRIDGE_OK")
|
||||
const claude = await request("/messages", { model: OPUS, messages: [{ role: "user", content: "hello" }], max_tokens: 64 })
|
||||
assert.equal(claude.status, 200)
|
||||
assert.equal((await claude.json()).content[0].text, "CLAUDE_BRIDGE_OK")
|
||||
assert.deepEqual(calls.map(call => call.url), [`${ROOT}/v2/inference/deployments/gpt/responses`, `${ROOT}/v2/inference/deployments/opus/invoke`])
|
||||
for (const call of calls) {
|
||||
assert.equal(call.headers.authorization, `Bearer ${TOKEN}`)
|
||||
assert.equal(call.headers["ai-resource-group"], "bridge-group")
|
||||
assert.equal(call.headers["x-api-key"], undefined)
|
||||
}
|
||||
assert.equal(calls[1].body.anthropic_version, "bedrock-2023-05-31")
|
||||
assert.equal(calls[1].body.model, undefined)
|
||||
assert.equal(calls[1].body.stream, undefined)
|
||||
}, 15000)
|
||||
@@ -0,0 +1,891 @@
|
||||
import { describe, it, beforeAll, afterAll, beforeEach, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { createHash } from "node:crypto"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
|
||||
let originalFetch
|
||||
let unstubbedFetchCalls = 0
|
||||
beforeAll(() => {
|
||||
originalFetch = globalThis.fetch
|
||||
globalThis.fetch = () => {
|
||||
unstubbedFetchCalls++
|
||||
throw new Error("Unstubbed fetch: use withFetch to mock HTTP.")
|
||||
}
|
||||
})
|
||||
afterAll(() => { globalThis.fetch = originalFetch })
|
||||
beforeEach(() => { unstubbedFetchCalls = 0 })
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
try {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
} finally {
|
||||
jest.useRealTimers()
|
||||
// The plugin catches fetch errors; assert outside that exception boundary.
|
||||
assert.equal(unstubbedFetchCalls, 0, "Unstubbed fetch: use withFetch to mock HTTP.")
|
||||
}
|
||||
})
|
||||
|
||||
function pathKey(normalizedPath) {
|
||||
const digest = createHash("sha256").update("sap-aicore:path:" + normalizedPath).digest("hex")
|
||||
return "sap-aicore:path:" + digest
|
||||
}
|
||||
|
||||
const VALID_CREDS = {
|
||||
authUrl: "https://mytenant.authentication.eu10.hana.ondemand.com",
|
||||
baseUrl: "https://api.ai.prod.eu10.hana.ondemand.com",
|
||||
clientId: "sb-abc123",
|
||||
clientSecret: "secret-value",
|
||||
resourceGroup: "default",
|
||||
}
|
||||
|
||||
const TOKEN_RESPONSE = {
|
||||
access_token: "eyJhbGciOiJSUzI1NiJ9.synthetic",
|
||||
token_type: "bearer",
|
||||
expires_in: 43199,
|
||||
}
|
||||
|
||||
function makeTokenResponse(overrides = {}) {
|
||||
return { ...TOKEN_RESPONSE, ...overrides }
|
||||
}
|
||||
|
||||
function makeTmpDir() {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), "magpie-aicore-test-"))
|
||||
}
|
||||
|
||||
function writeCredFile(dir, name, creds = VALID_CREDS) {
|
||||
const p = path.join(dir, name)
|
||||
fs.writeFileSync(p, JSON.stringify(creds), { mode: 0o600 })
|
||||
return p
|
||||
}
|
||||
|
||||
function withFetch(mockFn, fn) {
|
||||
const real = globalThis.fetch
|
||||
globalThis.fetch = mockFn
|
||||
return Promise.resolve().then(fn).finally(() => { globalThis.fetch = real })
|
||||
}
|
||||
|
||||
function makeOkResponse(body, requestUrl) {
|
||||
const resp = new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})
|
||||
if (requestUrl) Object.defineProperty(resp, "url", { value: String(requestUrl), configurable: true })
|
||||
Object.defineProperty(resp, "redirected", { value: false, configurable: true })
|
||||
return resp
|
||||
}
|
||||
|
||||
function makeErrResponse(status, body, requestUrl) {
|
||||
const resp = new Response(JSON.stringify(body ?? {}), {
|
||||
status,
|
||||
headers: { "content-type": "application/json", "www-authenticate": "Basic realm=\"OAuth\"" },
|
||||
})
|
||||
if (requestUrl) Object.defineProperty(resp, "url", { value: String(requestUrl), configurable: true })
|
||||
Object.defineProperty(resp, "redirected", { value: false, configurable: true })
|
||||
return resp
|
||||
}
|
||||
|
||||
function okFetch(body) {
|
||||
return async (url, init) => makeOkResponse(body, url)
|
||||
}
|
||||
|
||||
function routedFetch(tokenBody = TOKEN_RESPONSE, deployments = { resources: [] }) {
|
||||
return async (url, init) => {
|
||||
const target = url instanceof Request ? url.url : String(url)
|
||||
const pathname = new URL(target).pathname
|
||||
if (pathname === "/v2/lm/deployments") return makeOkResponse(deployments, url)
|
||||
return makeOkResponse(tokenBody, url)
|
||||
}
|
||||
}
|
||||
|
||||
function errFetch(status, body = {}) {
|
||||
return async (url, init) => makeErrResponse(status, body, url)
|
||||
}
|
||||
|
||||
function captureFetch(bodyOrFactory) {
|
||||
const calls = []
|
||||
const mock = async (url, init) => {
|
||||
calls.push({ url: String(url), method: init?.method, headers: Object.fromEntries(new Headers(init?.headers ?? {}).entries()), body: init?.body, redirect: init?.redirect, signal: init?.signal })
|
||||
const body = typeof bodyOrFactory === "function" ? bodyOrFactory(url) : bodyOrFactory
|
||||
return makeOkResponse(body, url)
|
||||
}
|
||||
mock.calls = calls
|
||||
return mock
|
||||
}
|
||||
|
||||
|
||||
describe("configuration", () => {
|
||||
it("preserves existing provider configuration", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const config = { provider: { "sap-aicore": { name: "My SAP", custom: true }, other: { name: "Other" } } }
|
||||
await plugin.config(config)
|
||||
assert.equal(config.provider["sap-aicore"].name, "My SAP")
|
||||
assert.equal(config.provider["sap-aicore"].custom, true)
|
||||
assert.equal(config.provider.other.name, "Other")
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("authorize input validation", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("rejects missing credentialFile", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize({})
|
||||
assert.equal(r.type, "failed")
|
||||
assert.ok(r.error)
|
||||
})
|
||||
|
||||
it("rejects non-string credentialFile", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: 42 })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects empty credentialFile", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: "" })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects relative path", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: "relative/path.json" })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects unknown input fields", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: "/tmp/x.json", extra: "bad" })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects path with NUL byte", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: "/tmp/x\x00.json" })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects array as input", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize(["/tmp/x.json"])
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects null input", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize(null)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("failed result has no key or metadata fields", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: "relative.json" })
|
||||
assert.equal(r.type, "failed")
|
||||
assert.equal("key" in r, false)
|
||||
assert.equal("metadata" in r, false)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("credential file validation", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("rejects nonexistent file", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: path.join(dir, "missing.json") })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects malformed JSON", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "bad.json")
|
||||
fs.writeFileSync(p, "{not valid json}")
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects missing authUrl", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "no-authurl.json")
|
||||
const { authUrl: _, ...creds } = VALID_CREDS
|
||||
fs.writeFileSync(p, JSON.stringify(creds))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects empty authUrl", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "empty-authurl.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, authUrl: "" }))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects missing clientSecret", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "no-secret.json")
|
||||
const { clientSecret: _, ...creds } = VALID_CREDS
|
||||
fs.writeFileSync(p, JSON.stringify(creds))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects clientId containing a colon", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "colon-clientid.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, clientId: "sb:bad" }))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects non-string clientId", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "num-clientid.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, clientId: 123 }))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects clientSecret with control characters", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "ctrl-secret.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, clientSecret: "secret\x01val" }))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects missing resourceGroup", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "no-rg.json")
|
||||
const { resourceGroup: _, ...creds } = VALID_CREDS
|
||||
fs.writeFileSync(p, JSON.stringify(creds))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("URL validation", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
async function tryUrl(authUrl, baseUrl) {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, `url-test-${Date.now()}-${Math.random()}.json`)
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, authUrl, baseUrl }))
|
||||
return plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
}
|
||||
|
||||
it("rejects http:// authUrl", async () => {
|
||||
const r = await tryUrl("http://mytenant.authentication.eu10.hana.ondemand.com", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with userinfo", async () => {
|
||||
const r = await tryUrl("https://user:pass@mytenant.authentication.eu10.hana.ondemand.com", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with query string", async () => {
|
||||
const r = await tryUrl("https://mytenant.authentication.eu10.hana.ondemand.com?foo=bar", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with fragment", async () => {
|
||||
const r = await tryUrl("https://mytenant.authentication.eu10.hana.ondemand.com#section", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with non-default port", async () => {
|
||||
const r = await tryUrl("https://mytenant.authentication.eu10.hana.ondemand.com:8443", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with IP literal", async () => {
|
||||
const r = await tryUrl("https://192.168.1.1", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with incomplete /oauth path", async () => {
|
||||
const r = await tryUrl("https://mytenant.authentication.eu10.hana.ondemand.com/oauth", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with extra path segments", async () => {
|
||||
const r = await tryUrl("https://mytenant.authentication.eu10.hana.ondemand.com/extra/path", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects baseUrl with unsupported /v1 suffix", async () => {
|
||||
const r = await tryUrl(VALID_CREDS.authUrl, "https://api.ai.prod.eu10.hana.ondemand.com/v1")
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl on unknown domain", async () => {
|
||||
const r = await tryUrl("https://attacker.evil.com", VALID_CREDS.baseUrl)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects baseUrl on unknown domain", async () => {
|
||||
const r = await tryUrl(VALID_CREDS.authUrl, "https://attacker.evil.com")
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("accepts /oauth/token and /v2 suffixes without duplicating the token path", async () => {
|
||||
const mock = captureFetch(TOKEN_RESPONSE)
|
||||
const r = await withFetch(mock, () => tryUrl(
|
||||
VALID_CREDS.authUrl + "/oauth/token",
|
||||
VALID_CREDS.baseUrl + "/v2",
|
||||
))
|
||||
assert.equal(r.type, "success")
|
||||
assert.equal(mock.calls.length, 1)
|
||||
assert.equal(mock.calls[0].method, "POST")
|
||||
assert.equal(mock.calls[0].url, VALID_CREDS.authUrl + "/oauth/token")
|
||||
})
|
||||
|
||||
it("accepts authUrl with trailing slash", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "trailing-slash.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, authUrl: VALID_CREDS.authUrl + "/" }))
|
||||
const r = await withFetch(okFetch(TOKEN_RESPONSE), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "success")
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("OAuth request contract", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("POSTs to normalized OAuth token URL", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "oauth-req.json")
|
||||
const mock = captureFetch(TOKEN_RESPONSE)
|
||||
const r = await withFetch(mock, () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "success")
|
||||
assert.equal(mock.calls.length, 1)
|
||||
assert.equal(mock.calls[0].url, VALID_CREDS.authUrl + "/oauth/token")
|
||||
assert.equal(mock.calls[0].method, "POST")
|
||||
})
|
||||
|
||||
it("uses raw UTF-8 Basic auth (not percent-encoded)", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "basic-raw.json", { ...VALID_CREDS, clientId: "sb-abc+def", clientSecret: "s3cr3t+val" })
|
||||
const mock = captureFetch(TOKEN_RESPONSE)
|
||||
await withFetch(mock, () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
const authHeader = mock.calls[0].headers["authorization"] ?? mock.calls[0].headers["Authorization"]
|
||||
assert.ok(authHeader, "Authorization header must be present")
|
||||
assert.ok(authHeader.startsWith("Basic "), "Must be Basic scheme")
|
||||
const encoded = authHeader.slice("Basic ".length)
|
||||
const decoded = Buffer.from(encoded, "base64").toString("utf8")
|
||||
assert.equal(decoded, "sb-abc+def:s3cr3t+val")
|
||||
})
|
||||
|
||||
it("sends only grant_type=client_credentials in body", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "grant-type.json")
|
||||
const mock = captureFetch(TOKEN_RESPONSE)
|
||||
await withFetch(mock, () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(mock.calls[0].body, "grant_type=client_credentials")
|
||||
})
|
||||
|
||||
it("sets Content-Type to application/x-www-form-urlencoded", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "content-type.json")
|
||||
const mock = captureFetch(TOKEN_RESPONSE)
|
||||
await withFetch(mock, () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
const ct = mock.calls[0].headers["content-type"] ?? mock.calls[0].headers["Content-Type"]
|
||||
assert.ok(ct?.includes("application/x-www-form-urlencoded"))
|
||||
})
|
||||
|
||||
it("sets redirect to error", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "redirect.json")
|
||||
const mock = captureFetch(TOKEN_RESPONSE)
|
||||
await withFetch(mock, () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(mock.calls[0].redirect, "error")
|
||||
})
|
||||
|
||||
it("rejects redirected response", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "redirected.json")
|
||||
const mock2 = async (url, init) => {
|
||||
const resp = makeOkResponse(TOKEN_RESPONSE, url)
|
||||
Object.defineProperty(resp, "redirected", { value: true, configurable: true })
|
||||
return resp
|
||||
}
|
||||
const r = await withFetch(mock2, () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("fails on network error", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "network-err.json")
|
||||
const r = await withFetch(async () => { throw new Error("network failure") }, () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
assert.ok(!r.error.includes("network failure"), "must not echo underlying error message")
|
||||
})
|
||||
|
||||
it("fails on empty access_token", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "empty-token.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, access_token: "" }), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("fails on missing access_token", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "no-token.json")
|
||||
const r = await withFetch(okFetch({ token_type: "bearer", expires_in: 43199 }), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("fails on non-finite expires_in", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "inf-exp.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, expires_in: Infinity }), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("fails on zero expires_in", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "zero-exp.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, expires_in: 0 }), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("fails on negative expires_in", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "neg-exp.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, expires_in: -1 }), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("fails on HTTP 500", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "5xx.json")
|
||||
const r = await withFetch(errFetch(500, {}), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("fails on unrelated 401 (no invalid_client body)", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "unrelated-401.json")
|
||||
const r = await withFetch(errFetch(401, { error: "unauthorized" }), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("accepts token_type bearer case-insensitively", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "bearer-upper.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, token_type: "Bearer" }), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "success")
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("authorize success result", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("returns type success with key and metadata on valid exchange", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "success.json")
|
||||
const r = await withFetch(okFetch(TOKEN_RESPONSE), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "success")
|
||||
assert.ok(typeof r.key === "string")
|
||||
assert.ok(r.key.startsWith("sap-aicore:path:"))
|
||||
assert.deepEqual(r.metadata, { credentialFile: p })
|
||||
})
|
||||
|
||||
it("key is deterministic SHA-256 of normalized path", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "det-key.json")
|
||||
const r = await withFetch(okFetch(TOKEN_RESPONSE), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.key, pathKey(p))
|
||||
})
|
||||
|
||||
it("result contains no access_token, clientSecret, or refresh", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "no-secrets.json")
|
||||
const r = await withFetch(okFetch(TOKEN_RESPONSE), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.type, "success")
|
||||
const text = JSON.stringify(r)
|
||||
assert.ok(!text.includes("access_token"))
|
||||
assert.ok(!text.includes("eyJhbGciOiJSUzI1NiJ9"))
|
||||
assert.ok(!text.includes("secret-value"))
|
||||
assert.ok(!text.includes("client_credentials"))
|
||||
assert.equal("refresh" in r, false)
|
||||
assert.equal("expires" in r, false)
|
||||
})
|
||||
|
||||
it("metadata normalizes credentialFile key regardless of input", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "norm-meta.json")
|
||||
const r = await withFetch(okFetch(TOKEN_RESPONSE), () => plugin.auth.methods[0].authorize({ credentialFile: p }))
|
||||
assert.equal(r.metadata.credentialFile, p)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("provider.models", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("returns empty object without auth (no file read or network)", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const r = await plugin.provider.models({ models: {} })
|
||||
assert.deepEqual(r, {})
|
||||
})
|
||||
|
||||
it("returns empty object with auth when discovery finds no eligible deployments", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "models-auth.json")
|
||||
let authorized
|
||||
await withFetch(okFetch(TOKEN_RESPONSE), async () => {
|
||||
authorized = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
})
|
||||
assert.equal(authorized.type, "success")
|
||||
const r = await withFetch(routedFetch(), () =>
|
||||
plugin.provider.models({ models: {} }, { auth: { type: "api", key: authorized.key, metadata: authorized.metadata } })
|
||||
)
|
||||
assert.deepEqual(r, {})
|
||||
})
|
||||
|
||||
it("does not fabricate models with plausible-looking auth", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
await assert.rejects(
|
||||
() => plugin.provider.models({ models: { "gpt-4o": {} } }, { auth: { type: "api", key: "fake-key", metadata: {} } }),
|
||||
(e) => { assert.ok(e instanceof Error); return true }
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("same-path reauthorization", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("sequential authorizations to same path return same key", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "same-path.json")
|
||||
const r1 = await withFetch(okFetch(TOKEN_RESPONSE), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
const r2 = await withFetch(okFetch({ ...TOKEN_RESPONSE, access_token: "token2" }), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r1.type, "success")
|
||||
assert.equal(r2.type, "success")
|
||||
assert.equal(r1.key, r2.key)
|
||||
})
|
||||
|
||||
it("concurrent same-path authorizations: newer candidate supersedes older", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "concurrent-same.json")
|
||||
const results = await withFetch(okFetch(TOKEN_RESPONSE), () =>
|
||||
Promise.all([
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p }),
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p }),
|
||||
])
|
||||
)
|
||||
const successes = results.filter(r => r.type === "success")
|
||||
assert.ok(successes.length >= 1, "at least one same-path concurrent authorize must succeed")
|
||||
const keys = new Set(successes.map(r => r.key))
|
||||
assert.equal(keys.size, 1)
|
||||
})
|
||||
|
||||
it("distinct paths yield distinct keys even with identical credential bytes", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p1 = writeCredFile(dir, "path-a.json")
|
||||
const p2 = writeCredFile(dir, "path-b.json")
|
||||
const [r1, r2] = await withFetch(okFetch(TOKEN_RESPONSE), () =>
|
||||
Promise.all([
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p1 }),
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p2 }),
|
||||
])
|
||||
)
|
||||
assert.equal(r1.type, "success")
|
||||
assert.equal(r2.type, "success")
|
||||
assert.notEqual(r1.key, r2.key)
|
||||
})
|
||||
|
||||
it("failed reauthorization does not retire current working account", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "fail-reauth.json")
|
||||
|
||||
const r1 = await withFetch(okFetch(TOKEN_RESPONSE), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r1.type, "success")
|
||||
|
||||
const r2 = await withFetch(errFetch(401, { error: "invalid_client" }), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r2.type, "failed")
|
||||
|
||||
const modelsResult = await withFetch(routedFetch(), () =>
|
||||
plugin.provider.models({ models: {} }, { auth: { type: "api", key: r1.key, metadata: r1.metadata } })
|
||||
)
|
||||
assert.deepEqual(modelsResult, {})
|
||||
})
|
||||
|
||||
it("successful same-path reauthorization replaces old generation", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "success-reauth.json")
|
||||
|
||||
const r1 = await withFetch(okFetch(TOKEN_RESPONSE), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r1.type, "success")
|
||||
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, resourceGroup: "new-rg" }))
|
||||
|
||||
const r2 = await withFetch(okFetch({ ...TOKEN_RESPONSE, access_token: "new-token" }), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r2.type, "success")
|
||||
assert.equal(r1.key, r2.key)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe("token renewal thresholds", () => {
|
||||
it("short-lived token is not re-exchanged while still within renewAt", async () => {
|
||||
const dir = makeTmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "short-lived.json")
|
||||
let authorized
|
||||
await withFetch(okFetch({ ...TOKEN_RESPONSE, expires_in: 120 }), async () => {
|
||||
authorized = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
})
|
||||
assert.equal(authorized.type, "success")
|
||||
|
||||
let tokenFetchCount = 0
|
||||
const trackFetch = async (url, init) => {
|
||||
if (new URL(String(url)).pathname === "/v2/lm/deployments") return makeOkResponse({ resources: [] }, url)
|
||||
tokenFetchCount++
|
||||
return makeOkResponse({ ...TOKEN_RESPONSE, expires_in: 120 }, url)
|
||||
}
|
||||
|
||||
const auth = { type: "api", key: authorized.key, metadata: authorized.metadata }
|
||||
await withFetch(trackFetch, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
const firstCount = tokenFetchCount
|
||||
await withFetch(trackFetch, () => plugin.provider.models({ models: {} }, { auth }))
|
||||
assert.equal(tokenFetchCount, firstCount, "second models call must not re-exchange a fresh token")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it("rejects already-expired token response", async () => {
|
||||
const dir = makeTmpDir()
|
||||
try {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "expired-resp.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, expires_in: -5 }), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r.type, "failed")
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
|
||||
|
||||
describe("credential file caching", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("does not re-read credential file after initialization", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "cache-test.json")
|
||||
let authorized
|
||||
await withFetch(okFetch(TOKEN_RESPONSE), async () => {
|
||||
authorized = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
})
|
||||
|
||||
fs.writeFileSync(p, "{invalid}")
|
||||
|
||||
const r = await withFetch(routedFetch({ ...TOKEN_RESPONSE, access_token: "refreshed" }), () =>
|
||||
plugin.provider.models({ models: {} }, { auth: { type: "api", key: authorized.key, metadata: authorized.metadata } })
|
||||
)
|
||||
assert.deepEqual(r, {})
|
||||
})
|
||||
|
||||
it("new factory invocation must re-read credential file", async () => {
|
||||
const p = writeCredFile(dir, "new-factory.json")
|
||||
|
||||
const plugin1 = await SAPAICorePlugin()
|
||||
let authorized
|
||||
await withFetch(okFetch(TOKEN_RESPONSE), async () => {
|
||||
authorized = await plugin1.auth.methods[0].authorize({ credentialFile: p })
|
||||
})
|
||||
assert.equal(authorized.type, "success")
|
||||
|
||||
fs.writeFileSync(p, "{bad json}")
|
||||
|
||||
const plugin2 = await SAPAICorePlugin()
|
||||
const r2 = await plugin2.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r2.type, "failed")
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
|
||||
describe("regression: malformed and edge responses", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("rejects token_type that is a number", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "numeric-type.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, token_type: 42 }), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects access_token that is whitespace-only", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "ws-token.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, access_token: " " }), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects expires_in arithmetic overflow (too large)", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "overflow-exp.json")
|
||||
const r = await withFetch(okFetch({ ...TOKEN_RESPONSE, expires_in: 9e15 }), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects credentials with unpaired surrogate in clientId", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "surrogate-id.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, clientId: "sb-\uD800bad" }))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects credentials with unpaired surrogate in clientSecret", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "surrogate-secret.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, clientSecret: "val\uDC00tail" }))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with raw whitespace", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "ws-authurl.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, authUrl: "https://mytenant.authentication.eu10.hana.ondemand.com " }))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("rejects authUrl with backslash", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "bs-authurl.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, authUrl: "https://mytenant.authentication.eu10.hana.ondemand.com\\" }))
|
||||
const r = await plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
assert.equal(r.type, "failed")
|
||||
})
|
||||
|
||||
it("late failure does not delete a newer candidate for the same path", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = writeCredFile(dir, "late-fail-newer.json")
|
||||
|
||||
let callCount = 0
|
||||
const racingFetch = async (url, init) => {
|
||||
callCount++
|
||||
const n = callCount
|
||||
if (n === 1) {
|
||||
await new Promise(r => setTimeout(r, 50))
|
||||
return makeErrResponse(500, {}, url)
|
||||
}
|
||||
return makeOkResponse(TOKEN_RESPONSE, url)
|
||||
}
|
||||
|
||||
const [r1, r2] = await withFetch(racingFetch, async () => {
|
||||
const p1 = plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
await new Promise(r => setTimeout(r, 10))
|
||||
const p2 = plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
return Promise.all([p1, p2])
|
||||
})
|
||||
|
||||
const successes = [r1, r2].filter(r => r.type === "success")
|
||||
assert.ok(successes.length >= 1, "newer candidate must succeed despite late first failure")
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
|
||||
describe("security boundaries", () => {
|
||||
let dir
|
||||
|
||||
beforeAll(() => { dir = makeTmpDir() })
|
||||
afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }) })
|
||||
|
||||
it("authorize result never contains credentials or token text", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const sentinelSecret = "secret-value"
|
||||
const sentinelToken = TOKEN_RESPONSE.access_token
|
||||
const p = writeCredFile(dir, "sec-check.json")
|
||||
const r = await withFetch(okFetch(TOKEN_RESPONSE), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r.type, "success")
|
||||
const text = JSON.stringify(r)
|
||||
assert.ok(!text.includes(sentinelSecret), "result must not contain clientSecret")
|
||||
assert.ok(!text.includes(sentinelToken), "result must not contain access_token")
|
||||
assert.ok(!text.includes("sb-abc123"), "result must not contain clientId")
|
||||
assert.ok(!text.includes("client_credentials"), "result must not contain grant type")
|
||||
assert.ok(!text.includes("basic "), "result must not contain Basic scheme (case insensitive)")
|
||||
assert.ok(!text.includes("Basic "), "result must not contain Basic scheme")
|
||||
})
|
||||
|
||||
it("failed authorize result never reveals path or JSON bytes", async () => {
|
||||
const plugin = await SAPAICorePlugin()
|
||||
const p = path.join(dir, "sec-fail.json")
|
||||
fs.writeFileSync(p, JSON.stringify({ ...VALID_CREDS, clientSecret: "ultra-secret" }))
|
||||
const r = await withFetch(errFetch(500), () =>
|
||||
plugin.auth.methods[0].authorize({ credentialFile: p })
|
||||
)
|
||||
assert.equal(r.type, "failed")
|
||||
const text = JSON.stringify(r)
|
||||
assert.ok(!text.includes("ultra-secret"), "error must not echo clientSecret")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { test, afterEach, jest } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { projectModels } from "../src/discovery.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
function entry(modelName, extra = {}) {
|
||||
return Object.freeze({
|
||||
protocol: "responses",
|
||||
canonicalID: modelName,
|
||||
displayLabel: modelName,
|
||||
apiNpm: "@ai-sdk/openai",
|
||||
modelName,
|
||||
deploymentID: "d-" + modelName,
|
||||
deploymentURL: "https://api.ai.eu10.hana.ondemand.com/v2/inference/deployments/d-" + modelName,
|
||||
configuredVersion: "latest",
|
||||
activeVersion: "2026-09-03",
|
||||
activeEvidence: "deployment-backend",
|
||||
scenarioID: "foundation-models",
|
||||
executableID: "azure-openai",
|
||||
configurationID: "c-" + modelName,
|
||||
routePolicy: Object.freeze({ path: "/responses", query: false }),
|
||||
capabilities: Object.freeze({ text: true, functionTool: true, streaming: true }),
|
||||
...extra,
|
||||
})
|
||||
}
|
||||
|
||||
test("projects a verified entry with context into the public catalog shape", () => {
|
||||
const registry = { "gpt-6-astra": entry("gpt-6-astra", { metadata: Object.freeze({ contextLength: 1050000, retirementDate: "2027-01-01", inputTypes: Object.freeze(["text"]) }) }) }
|
||||
assert.deepEqual(projectModels(registry), {
|
||||
"gpt-6-astra": {
|
||||
id: "gpt-6-astra",
|
||||
name: "gpt-6-astra",
|
||||
providerID: "sap-aicore",
|
||||
api: { id: "gpt-6-astra", npm: "@ai-sdk/openai" },
|
||||
capabilities: {
|
||||
toolcall: true,
|
||||
attachment: false,
|
||||
input: { text: true, image: false, audio: false, video: false, pdf: false },
|
||||
output: { text: true, image: false, audio: false, video: false, pdf: false },
|
||||
},
|
||||
limit: { context: 1050000 },
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("omits limit when context length is absent", () => {
|
||||
const noMeta = projectModels({ "gpt-6.1-sol": entry("gpt-6.1-sol") })["gpt-6.1-sol"]
|
||||
const retireOnly = projectModels({ "gpt-6.1-sol": entry("gpt-6.1-sol", { metadata: Object.freeze({ retirementDate: "2027-01-01" }) }) })["gpt-6.1-sol"]
|
||||
assert.equal("limit" in noMeta, false)
|
||||
assert.equal("limit" in retireOnly, false)
|
||||
})
|
||||
|
||||
test("leaks no deployment, configuration, or provenance state", () => {
|
||||
const model = projectModels({ "gpt-6-astra": entry("gpt-6-astra", { metadata: Object.freeze({ contextLength: 1050000, retirementDate: "2027-01-01" }) }) })["gpt-6-astra"]
|
||||
for (const key of ["deploymentID", "deploymentURL", "configurationID", "configuredVersion", "activeVersion", "activeEvidence", "scenarioID", "executableID", "routePolicy", "metadata", "retirementDate"]) {
|
||||
assert.equal(key in model, false, key)
|
||||
}
|
||||
assert.deepEqual(Object.keys(model.capabilities), ["toolcall", "attachment", "input", "output"])
|
||||
})
|
||||
|
||||
test("each projection owns fresh objects isolated from the registry and prior calls", () => {
|
||||
const source = entry("gpt-6-astra", { metadata: Object.freeze({ contextLength: 1050000 }) })
|
||||
const registry = { "gpt-6-astra": source }
|
||||
const first = projectModels(registry)
|
||||
first["gpt-6-astra"].capabilities.toolcall = false
|
||||
first["gpt-6-astra"].limit.context = 1
|
||||
first["gpt-6-astra"].capabilities.input.text = false
|
||||
const second = projectModels(registry)
|
||||
assert.equal(second["gpt-6-astra"].capabilities.toolcall, true)
|
||||
assert.equal(second["gpt-6-astra"].limit.context, 1050000)
|
||||
assert.equal(second["gpt-6-astra"].capabilities.input.text, true)
|
||||
assert.equal(source.capabilities.functionTool, true)
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,80 @@
|
||||
import { describe, it, afterEach, jest, spyOn } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import fs from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import os from "node:os"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { SAPAICorePlugin } from "../src/index.js"
|
||||
|
||||
const cleanups = []
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanups.splice(0).reverse()) await fn()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
const version = JSON.parse(await fs.readFile(new URL("../package.json", import.meta.url), "utf8")).version
|
||||
async function fixture() {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "aicore-revision-"))
|
||||
cleanups.push(() => fs.rm(dir, { recursive: true, force: true }))
|
||||
const root = path.join(dir, "plugin")
|
||||
await fs.mkdir(root)
|
||||
await fs.cp(new URL("../src", import.meta.url), path.join(root, "src"), { recursive: true })
|
||||
await fs.writeFile(path.join(root, "package.json"), JSON.stringify({ type: "module", version }))
|
||||
return { dir, root }
|
||||
}
|
||||
|
||||
|
||||
async function fakeGit(dir, command) {
|
||||
const bin = path.join(dir, "bin")
|
||||
await fs.mkdir(bin)
|
||||
await fs.writeFile(path.join(bin, "git"), `#!/bin/sh\n${command}\n`, { mode: 0o755 })
|
||||
const original = process.env.PATH
|
||||
process.env.PATH = bin
|
||||
cleanups.push(() => { process.env.PATH = original })
|
||||
}
|
||||
|
||||
describe("package version at startup", () => {
|
||||
it("does not execute Git even when a local package has Git metadata", async () => {
|
||||
const { dir, root } = await fixture()
|
||||
await fs.mkdir(path.join(root, ".git"))
|
||||
const invoked = path.join(dir, "git-invoked")
|
||||
await fakeGit(dir, `printf invoked > ${JSON.stringify(invoked)}\nprintf unexpected-git-revision`)
|
||||
const { SAPAICorePlugin } = await import(pathToFileURL(path.join(root, "src/index.js")).href)
|
||||
let finish
|
||||
const recorded = new Promise(resolve => { finish = resolve })
|
||||
const app = { log(options) { assert.equal(this, app); finish(options) } }
|
||||
await SAPAICorePlugin({ client: { app } })
|
||||
const record = await recorded
|
||||
assert.ok(record.body.message.includes(version))
|
||||
await assert.rejects(fs.access(invoked), { code: "ENOENT" })
|
||||
}, 15000)
|
||||
})
|
||||
|
||||
describe("startup host logging", () => {
|
||||
|
||||
for (const [name, log] of [
|
||||
["synchronous", () => {}],
|
||||
["throwing", () => { throw new Error("sync log failure") }],
|
||||
["rejecting", () => Promise.reject(new Error("async log failure"))],
|
||||
["pending", () => new Promise(() => {})],
|
||||
]) {
|
||||
it(`does not let a ${name} logger prevent initialization`, async () => {
|
||||
const hooks = await SAPAICorePlugin({ client: { app: { log } } })
|
||||
assert.equal(typeof hooks.config, "function")
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
})
|
||||
}
|
||||
|
||||
it("stays silent without a host logger", async () => {
|
||||
const logged = []
|
||||
const logSpy = spyOn(console, "log").mockImplementation((...args) => logged.push(args))
|
||||
cleanups.push(() => logSpy.mockRestore())
|
||||
const errorSpy = spyOn(console, "error").mockImplementation((...args) => logged.push(args))
|
||||
cleanups.push(() => errorSpy.mockRestore())
|
||||
for (const input of [undefined, {}, { client: {} }, { client: { app: {} } }]) {
|
||||
assert.equal(typeof (await SAPAICorePlugin(input)).config, "function")
|
||||
}
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
assert.deepEqual(logged, [])
|
||||
})
|
||||
})
|
||||
@@ -136,6 +136,8 @@
|
||||
"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-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,
|
||||
"summary": { "en": "Existing SAP AI Core deployments with client-secret credential-file sign-in, per-resource-group GPT Responses and Claude Messages discovery, streaming and agent tools. No deployment provisioning or quota reporting; Magpie only.", "zh": "用本机 client-secret 凭据文件连接已有 SAP AI Core 部署:按资源组发现 GPT Responses 与 Claude Messages 模型,支持流式回复和 agent 工具。不创建部署,不报告额度;仅验证 Magpie。" } },
|
||||
{ "package": "magpie-plugin-pink", "name": "PinK", "kind": "agent",
|
||||
"icon": "https://raw.githubusercontent.com/YuchenWell/magpie-plugin-pink/main/assets/pink.png",
|
||||
"summary": { "en": "Connect PinK to Magpie's models from the Agents page and track gateway usage and cost. Disconnecting restores the managed configuration.", "zh": "在 Agent 页面连接 PinK,使用 Magpie 中配置的模型并查看调用用量与费用;断开时恢复插件管理的配置。" } },
|
||||
|
||||
+4
-1
@@ -83,7 +83,10 @@ for (const name of readdirSync(root)) {
|
||||
if (p && !signInOnly && !usageOnly) {
|
||||
needsLoader = true
|
||||
servesModels = true
|
||||
if (!p.npm || !p.models || !Object.keys(p.models).length) problems.push(`${fn.name}: config gives ${auth.provider} no npm or models`)
|
||||
// Account-scoped catalogs may be empty before sign-in. Do not call
|
||||
// their models hook here: this check must stay credential/network-free.
|
||||
const dynamicModels = hooks.provider?.id === auth.provider && typeof hooks.provider.models === "function"
|
||||
if (!p.npm || (!Object.keys(p.models ?? {}).length && !dynamicModels)) problems.push(`${fn.name}: config gives ${auth.provider} no npm or models`)
|
||||
}
|
||||
}
|
||||
if ((needsLoader || auth.loader !== undefined) && typeof auth.loader !== "function") problems.push(`${fn.name}: auth.loader`)
|
||||
|
||||
@@ -61,6 +61,43 @@ test("check still requires loaders for providers, including providers with tools
|
||||
}
|
||||
})
|
||||
|
||||
test("check accepts account-scoped models without signing in or fetching them", () => {
|
||||
const result = check(`export const Plugin = async () => ({
|
||||
auth: {...${auth}, loader: async () => ({})},
|
||||
config: async (cfg) => { cfg.provider.fixture = {npm: "@ai-sdk/openai", models: {}} },
|
||||
provider: {id: "fixture", models() { throw new Error("must not ask for credentials") }}
|
||||
})`, okRegistry,
|
||||
{ main: "./index.mjs", exports: { ".": "./opencode2.mjs" }, files: ["index.mjs", "opencode.mjs", "opencode2.mjs"] },
|
||||
{ "opencode.mjs": 'export { Plugin } from "./index.mjs"\n', "opencode2.mjs": adapter })
|
||||
expect(result.code).toBe(0)
|
||||
expect(result.output).toContain("✓ fixture")
|
||||
})
|
||||
|
||||
test("check rejects missing, mismatched or non-callable account catalogs and still requires npm and a loader", () => {
|
||||
for (const provider of ["undefined", '{id: "wrong", models() {}}', '{id: "fixture", models: {}}']) {
|
||||
const result = check(`export const Plugin = async () => ({
|
||||
auth: {...${auth}, loader: async () => ({})},
|
||||
config: async (cfg) => { cfg.provider.fixture = {npm: "@ai-sdk/openai", models: {}} },
|
||||
provider: ${provider}
|
||||
})`)
|
||||
expect(result.code).toBe(1)
|
||||
expect(result.output).toContain("no npm or models")
|
||||
}
|
||||
for (const [npm, loader, problem] of [
|
||||
['"@ai-sdk/openai"', "undefined", "auth.loader"],
|
||||
["undefined", "async () => ({})", "no npm or models"],
|
||||
]) {
|
||||
const result = check(`export const Plugin = async () => ({
|
||||
auth: {...${auth}, loader: ${loader}},
|
||||
config: async (cfg) => { cfg.provider.fixture = {npm: ${npm}, models: {}} },
|
||||
provider: {id: "fixture", models() {}}
|
||||
})`)
|
||||
expect(result.code).toBe(1)
|
||||
expect(result.output).toContain(problem)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
const fine = `export const Plugin = async () => ({ tool: ${tool} })`
|
||||
|
||||
test("check accepts quota-only providers with a loader and no model transport", () => {
|
||||
|
||||
Reference in New Issue
Block a user