sap-aicore 0.3.2: accept session metadata, forward context_management with its beta (caikn, #851)

sap-aicore 0.3.1 refused two top-level Messages fields that real agents send:

- `metadata` (omp sends `metadata.user_id` on every request): now accepted and
  dropped in `bedrockBody`, the one builder both /invoke and
  /invoke-with-response-stream use, so it never reaches Bedrock.
- `context_management` (omp and Claude Code with thinking on send
  `{"edits":[{"type":"clear_thinking_20251015","keep":"all"}]}`), with
  `anthropic_beta`: both are accepted as opaque native fields and forwarded
  unchanged. When `context_management` comes without `anthropic_beta`, the body
  gets `anthropic_beta:["context-management-2025-06-27"]`, which SAP/Bedrock
  needs (without it SAP answers 400 "Extra inputs are not permitted"). An
  explicit `anthropic_beta` (including [] or null) is sent as given. SAP judges
  unknown edits and betas; its 400 surfaces once, redacted, with no retry. The
  author verified the literal directive against live SAP deployments (Opus 4.8,
  Opus 4.6, Sonnet 4.6, whole replies and streaming). Closes #864.

The test for #812 ("late failure does not delete a newer candidate") now waits
for the first token fetch to start instead of a 10ms sleep, and checks r1
failed, r2 succeeded and two fetches ran. Closes #812.

Version 0.3.1 -> 0.3.2 (the dist branch has 0.3.1; the package is not on npm).

Run at 76e1bfef2 (base 966cf717; origin/main 46fef953 has no sap-aicore change
since), on mote, HOME and TMPDIR under ~/runs, Bun 1.4.2:
- bun test packages/sap-aicore: 343 pass, 0 fail
- bun scripts/check.mjs sap-aicore: registry.json and sap-aicore ok
- bun test (repo root): 6895 tests, 6875 pass, 0 fail, 20 skip (HOME under TMPDIR; not through mote's suite lock, whose queue was hours long)
Broken by hand (messages.test.js + messages-stream.test.js, 46 tests):
- default beta line removed: 4 red (both agent-thinking tests, both defaulting tests)
- beta always set, overriding an explicit one: 4 red (override and novel-beta tests)
- context_management/anthropic_beta out of ALLOWED: 7 red
- main's messages.js: 9 red (adds both metadata tests)
The #812 test is unchanged since 19cabed44, where a 30ms delay injected in
authorize turned the old test red and the new one green.

Co-authored-by: Kanyin Cai <kanyin.cai@sap.com>
This commit is contained in:
caikn
2026-11-08 21:48:44 +08:00
committed by GitHub
parent 46fef953c8
commit b228cc6a68
6 changed files with 192 additions and 19 deletions
+5 -1
View File
@@ -68,7 +68,11 @@ curl "$MAGPIE_GATEWAY/v1/messages" \
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.
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, non-image multimodal content, and hosted tools are rejected; base64 image blocks are accepted only when the matched catalog version advertises image input. Client-only `metadata` (including `metadata.user_id` session tracking) is accepted and silently removed before both whole-reply and streaming Bedrock dispatch; it is not forwarded upstream. 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.
`context_management` and `anthropic_beta` are opaque native fields. The plugin does not validate their contents; SAP and Bedrock own that. Both reach the Bedrock body unchanged, including unknown edit types, keep policies, extra fields, multiple edits, and future beta strings. When `context_management` is present and the caller sends no `anthropic_beta`, the plugin adds the known default `anthropic_beta:["context-management-2025-06-27"]`. An explicit `anthropic_beta` is forwarded verbatim and overrides that default, including an empty list or null; SAP rejects an invalid format. Without `context_management`, the plugin adds no default beta; an explicit beta still passes through. SAP can reject novel or malformed directives, and its errors surface without retries or silent dropping.
Live-verified through SAP deployments from Lima: Opus 4.8, Opus 4.6, and Sonnet 4.6 accept the literal `{"edits":[{"type":"clear_thinking_20251015","keep":"all"}]}` directive with adaptive thinking for whole replies and streaming. Sonnet 4.6 also accepts enabled thinking and continuation with real signed prior thinking blocks. Without the beta, SAP returns 400 `context_management: Extra inputs are not permitted`. Opus 4.8 also accepts `keep:{"type":"thinking_turns","value":2}` for whole replies and streaming. Unknown edit types and a future beta identifier reached SAP and returned native 400 errors, with one inference attempt per request. Default retention without the directive was not compared; the plugin preserves the requested policy rather than silently dropping it.
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. Each `tool_result.content` may be a string or an array of text/base64-image blocks, with images subject to the same model-capability gate and source validation as user attachments. Other nested content types remain unsupported. Image tool results are covered by mocked transport tests, not a live SAP round-trip. A rejected signature or mismatched result surfaces as an upstream error.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-sap-aicore-auth",
"version": "0.3.1",
"version": "0.3.2",
"description": "SAP AI Core deployments in Magpie with credential-file sign-in, account-scoped discovery and native Responses / Messages transport",
"license": "MIT",
"type": "module",
+10 -7
View File
@@ -17,6 +17,7 @@ export { responseError } from "./transport.js"
const DEPLOYMENT_PATH = /^\/v2\/inference\/deployments\/[A-Za-z0-9_-]+$/
const ANTHROPIC_VERSION = "bedrock-2023-05-31"
const CONTEXT_MANAGEMENT_BETA = "context-management-2025-06-27"
// --- strict native request validation -------------------------------------
@@ -25,7 +26,6 @@ const ANTHROPIC_VERSION = "bedrock-2023-05-31"
// 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.",
@@ -35,11 +35,13 @@ const REJECTED = {
}
// 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.
// recognized; `model`/`stream` are the routing envelope consumed by dispatch,
// and client-only `metadata` is accepted but never forwarded to Bedrock.
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",
"output_config", "anthropic_version", "stream", "metadata",
"context_management", "anthropic_beta",
])
const ROLES = new Set(["user", "assistant"])
const TOOL_CHOICE_TYPES = new Set(["auto", "any", "tool", "none"])
@@ -308,9 +310,9 @@ function targetURL(entry, aiRoot, streaming) {
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.
// Adapt the routing envelope only: drop the canonical routing model, stream
// selector and client-only metadata; strip the validated non-native client tool
// hints (eager_input_streaming, defer_loading); supply the Bedrock version.
// Conversation semantics are preserved verbatim.
function stripToolHints(tools) {
@@ -329,10 +331,11 @@ function stripToolHints(tools) {
function bedrockBody(body) {
const out = {}
for (const key of Object.keys(body)) {
if (key === "model" || key === "stream") continue
if (key === "model" || key === "stream" || key === "metadata") continue
out[key] = body[key]
}
if ("tools" in out) out.tools = stripToolHints(out.tools)
if (Object.hasOwn(out, "context_management") && !Object.hasOwn(out, "anthropic_beta")) out.anthropic_beta = [CONTEXT_MANAGEMENT_BETA]
out.anthropic_version = ANTHROPIC_VERSION
return out
}
@@ -109,12 +109,13 @@ function consumer(response) {
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 () => {
test("a streamed request with session metadata routes to Bedrock and relays text then tool-arg deltas before the terminal", async () => {
const { post, calls } = await fixture(() => streamResponse(STREAM.map(frame)))
const response = await post()
const response = await post({ metadata: { user_id: '{"session_id":"synthetic-session"}' } })
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")
assert.equal("metadata" in JSON.parse(calls.at(-1).init.body), false)
const c = consumer(response)
const events = await c.finish()
@@ -126,6 +127,64 @@ test("a streamed request routes to /invoke-with-response-stream and relays text
assert.equal(events.at(-1).type, "message_stop")
})
test("agent thinking context management reaches streaming Bedrock with its beta and preserves native events", async () => {
const native = STREAM.map(event => event.type === "message_start"
? { ...event, message: { ...event.message, context_management: { applied_edits: [] } } }
: event)
const { post, calls } = await fixture(() => streamResponse(native.map(frame)))
const body = {
thinking: { type: "adaptive" },
context_management: { edits: [{ type: "clear_thinking_20251015", keep: "all" }] },
}
const response = await post(body)
assert.equal(response.status, 200)
assert.equal(calls.at(-1).url, OPUS_URL + "/invoke-with-response-stream")
const upstream = JSON.parse(calls.at(-1).init.body)
assert.deepEqual(upstream.context_management, body.context_management)
assert.deepEqual(upstream.anthropic_beta, ["context-management-2025-06-27"])
assert.deepEqual(upstream.thinking, body.thinking)
assert.deepEqual(await consumer(response).finish(), native)
assert.equal("anthropic_beta" in body, false)
})
test("streaming defaults the known beta for a bare directive, forwards an explicit beta verbatim, and leaks neither when absent", async () => {
const { post, calls } = await fixture(() => streamResponse(STREAM.map(frame)))
const context_management = { edits: [{ type: "clear_thinking_20251015", keep: "all" }] }
const defaulted = await post({ thinking: { type: "adaptive" }, context_management })
assert.equal(defaulted.status, 200)
assert.deepEqual(JSON.parse(calls.at(-1).init.body).anthropic_beta, ["context-management-2025-06-27"])
assert.equal((await consumer(defaulted).finish()).at(-1).type, "message_stop")
const future = { edits: [{ type: "clear_tool_uses_20250919", keep: 3, future_field: true }] }
const explicit = await post({ context_management: future, anthropic_beta: ["future-beta"] })
assert.equal(explicit.status, 200)
const upstream = JSON.parse(calls.at(-1).init.body)
assert.deepEqual(upstream.context_management, future)
assert.deepEqual(upstream.anthropic_beta, ["future-beta"])
assert.equal((await consumer(explicit).finish()).at(-1).type, "message_stop")
const ok = await post({ thinking: { type: "adaptive" } })
assert.equal(ok.status, 200)
const bare = JSON.parse(calls.at(-1).init.body)
assert.equal("context_management" in bare, false)
assert.equal("anthropic_beta" in bare, false, "thinking alone adds no beta")
assert.equal((await consumer(ok).finish()).at(-1).type, "message_stop")
})
test("a novel streamed context_management or anthropic_beta reaches inference, and its native rejection surfaces once with redaction and no retry", async () => {
const upstream = { type: "error", error: { type: "invalid_request_error", message: "bad beta " + CREDS.clientSecret } }
const { post, calls } = await fixture(() => new Response(JSON.stringify(upstream), { status: 400, headers: { "content-type": "application/json" } }))
const mark = calls.length
const response = await post({ context_management: { edits: [{ type: "novel_edit" }] }, anthropic_beta: ["unrecognized"] })
assert.equal(response.status, 400)
assert.equal(calls.length, mark + 1, "the streamed request reached inference exactly once, with no retry")
assert.deepEqual(JSON.parse(calls.at(-1).init.body).anthropic_beta, ["unrecognized"])
const text = await response.text()
assert.equal(text.includes(CREDS.clientSecret), false)
assert.ok(text.includes("[redacted]"))
})
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.
+104 -2
View File
@@ -57,11 +57,10 @@ test("max_tokens is required; zero is accepted; negative and non-integer are rej
})
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"]) {
for (const field of ["top_logprobs", "functions", "tool_Calls", "stream_options"]) {
await assert.rejects(parse(base({ [field]: field === "top_logprobs" ? 1 : [] })), { code: "invalid-request" }, field)
}
})
@@ -160,6 +159,25 @@ test("native thinking controls validate structurally: enabled budget, adaptive/d
await assert.rejects(parse(base({ output_config: { effort: 5 } })), { code: "invalid-request" })
})
test("context_management and anthropic_beta pass through validation unchanged as opaque native fields", async () => {
const shapes = [
{ edits: [{ type: "clear_thinking_20251015", keep: "all" }] },
{ edits: [{ type: "clear_tool_uses_20250919", keep: 5, future_field: true }] },
{ edits: [{ type: "clear_thinking_20251015", keep: "all" }, { type: "clear_tool_uses_20250919", keep: "all" }] },
{ edits: [], trigger: { type: "input_tokens", value: 100000 } },
]
for (const context_management of shapes) {
const body = base({ context_management })
assert.deepEqual(await parse(body), body)
}
for (const anthropic_beta of [["context-management-2025-06-27"], ["some-future-beta"], [], null]) {
const body = base({ context_management: shapes[0], anthropic_beta })
assert.deepEqual(await parse(body), body)
}
const beta = base({ anthropic_beta: ["x"] })
assert.deepEqual(await parse(beta), beta)
})
// --- whole-reply dispatch through the plugin loader ------------------------
async function fixture(inference = () => new Response(JSON.stringify(MESSAGE)), options = {}) {
@@ -219,6 +237,90 @@ test("a whole Claude reply reaches /invoke and returns native Anthropic JSON", a
assert.deepEqual(call.body.messages, [{ role: "user", content: "hi" }])
})
test("session metadata is accepted without changing the Bedrock request or native reply", async () => {
const { post, sent } = await fixture()
const body = base({ max_tokens: 256, system: "be terse", stop_sequences: ["STOP"] })
const baseline = await post("/messages", body)
assert.equal(baseline.status, 200)
assert.deepEqual(await baseline.json(), MESSAGE)
const upstream = sent.at(-1).body
const response = await post("/messages", { ...body, metadata: { user_id: '{"session_id":"synthetic-session"}' } })
assert.equal(response.status, 200)
assert.deepEqual(await response.json(), MESSAGE)
assert.equal("metadata" in sent.at(-1).body, false)
assert.deepEqual(sent.at(-1).body, upstream)
})
test("agent thinking context management reaches Bedrock with its beta and preserves the whole native reply", async () => {
const reply = { ...MESSAGE, context_management: { applied_edits: [] } }
const { post, sent } = await fixture(() => new Response(JSON.stringify(reply)))
const body = base({
max_tokens: 256,
thinking: { type: "adaptive" },
context_management: { edits: [{ type: "clear_thinking_20251015", keep: "all" }] },
messages: [
{ role: "user", content: "first question" },
{ role: "assistant", content: [{ type: "thinking", thinking: "earlier reasoning", signature: "signed-history" }, { type: "text", text: "first answer" }] },
{ role: "user", content: "next question" },
],
})
const response = await post("/messages", body)
assert.equal(response.status, 200)
assert.deepEqual(await response.json(), reply)
assert.equal(sent.at(-1).url, OPUS_URL + "/invoke")
assert.deepEqual(sent.at(-1).body.context_management, body.context_management)
assert.deepEqual(sent.at(-1).body.anthropic_beta, ["context-management-2025-06-27"])
assert.deepEqual(sent.at(-1).body.thinking, body.thinking)
assert.deepEqual(sent.at(-1).body.messages, body.messages)
assert.equal("anthropic_beta" in body, false)
})
test("the known beta defaults for a bare directive, an explicit beta overrides it verbatim, and an absent directive leaks neither on the same loader", async () => {
const { post, sent } = await fixture()
const context_management = { edits: [{ type: "clear_thinking_20251015", keep: "all" }] }
const defaulted = await post("/messages", base({ max_tokens: 64, thinking: { type: "adaptive" }, context_management }))
assert.equal(defaulted.status, 200)
assert.deepEqual(sent.at(-1).body.context_management, context_management)
assert.deepEqual(sent.at(-1).body.anthropic_beta, ["context-management-2025-06-27"])
for (const anthropic_beta of [["context-management-2025-06-27", "future-beta"], [], null]) {
const overridden = await post("/messages", base({ max_tokens: 64, context_management, anthropic_beta }))
assert.equal(overridden.status, 200)
assert.deepEqual(sent.at(-1).body.anthropic_beta, anthropic_beta, JSON.stringify(anthropic_beta))
assert.deepEqual(sent.at(-1).body.context_management, context_management)
}
const future = { edits: [{ type: "clear_tool_uses_20250919", keep: 3, future_field: true }] }
const futured = await post("/messages", base({ max_tokens: 64, context_management: future }))
assert.equal(futured.status, 200)
assert.deepEqual(sent.at(-1).body.context_management, future)
assert.deepEqual(sent.at(-1).body.anthropic_beta, ["context-management-2025-06-27"])
const ok = await post("/messages", base({ max_tokens: 64, thinking: { type: "adaptive" } }))
assert.equal(ok.status, 200)
assert.equal("context_management" in sent.at(-1).body, false)
assert.equal("anthropic_beta" in sent.at(-1).body, false, "thinking alone adds no beta")
})
test("a novel context_management or anthropic_beta the plugin does not model reaches inference, and its native rejection surfaces once with redaction and no retry", async () => {
const upstream = { type: "error", error: { type: "invalid_request_error", message: "context_management: unknown edit " + CREDS.clientSecret } }
const { post, sent } = await fixture(() => new Response(JSON.stringify(upstream), { status: 400 }))
const mark = sent.length
const response = await post("/messages", base({
max_tokens: 64,
context_management: { edits: [{ type: "clear_tool_uses_20250919", keep: "all" }] },
anthropic_beta: ["some-unrecognized-beta"],
}))
assert.equal(response.status, 400)
assert.equal(sent.length, mark + 1, "the request reached inference exactly once, with no retry")
assert.deepEqual(sent.at(-1).body.anthropic_beta, ["some-unrecognized-beta"], "the explicit beta reached upstream verbatim")
const text = await response.text()
assert.equal(text.includes(CREDS.clientSecret), false)
assert.ok(text.includes("[redacted]"))
})
test("image tool-result content reaches Bedrock verbatim with call identity and cache controls intact", async () => {
const { post, sent } = await fixture()
const cache_control = { type: "ephemeral" }
+11 -6
View File
@@ -828,12 +828,14 @@ describe("regression: malformed and edge responses", () => {
const plugin = await SAPAICorePlugin()
const p = writeCredFile(dir, "late-fail-newer.json")
const firstStarted = Promise.withResolvers()
const firstFailure = Promise.withResolvers()
let callCount = 0
const racingFetch = async (url, init) => {
callCount++
const n = callCount
if (n === 1) {
await new Promise(r => setTimeout(r, 50))
if (callCount === 1) {
firstStarted.resolve()
await firstFailure.promise
return makeErrResponse(500, {}, url)
}
return makeOkResponse(TOKEN_RESPONSE, url)
@@ -841,13 +843,16 @@ describe("regression: malformed and edge responses", () => {
const [r1, r2] = await withFetch(racingFetch, async () => {
const p1 = plugin.auth.methods[0].authorize({ credentialFile: p })
await new Promise(r => setTimeout(r, 10))
await firstStarted.promise
const p2 = plugin.auth.methods[0].authorize({ credentialFile: p })
// Release the old failure only after the newer candidate is registered.
firstFailure.resolve()
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")
assert.equal(r1.type, "failed")
assert.equal(r2.type, "success", "newer candidate must succeed despite late first failure")
assert.equal(callCount, 2)
})
})