diff --git a/packages/sap-aicore/docs/api-reference.md b/packages/sap-aicore/docs/api-reference.md index 4050df1..df64664 100644 --- a/packages/sap-aicore/docs/api-reference.md +++ b/packages/sap-aicore/docs/api-reference.md @@ -31,7 +31,7 @@ Reasoning accepts `effort:low`, `medium`, or `high`, optionally with `summary:au ## 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. +Tools use native Responses function definitions with `name`, `parameters`, and supported `strict:true`. The agent executes tools; the plugin does not. A `function_call_output` requires a non-empty string `call_id`; its `output` may be a string or an array of `input_text` / `input_image` parts. Image parts use the same model-capability gate and URL/detail validation as user attachments. Image tool results are covered by mocked transport tests, not a live SAP round-trip. 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`: @@ -70,7 +70,7 @@ Supported fields: `model`, `messages`, string or text-block `system`, required n 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. +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. 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. diff --git a/packages/sap-aicore/package.json b/packages/sap-aicore/package.json index f21ffba..4f7123c 100644 --- a/packages/sap-aicore/package.json +++ b/packages/sap-aicore/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-sap-aicore-auth", - "version": "0.3.0", + "version": "0.3.1", "description": "SAP AI Core deployments in Magpie with credential-file sign-in, account-scoped discovery and native Responses / Messages transport", "license": "MIT", "type": "module", diff --git a/packages/sap-aicore/src/messages.js b/packages/sap-aicore/src/messages.js index a95e1c9..6291696 100644 --- a/packages/sap-aicore/src/messages.js +++ b/packages/sap-aicore/src/messages.js @@ -104,8 +104,11 @@ function validateContentBlock(block, allowImage) { 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) + if (!Array.isArray(content)) throw invalid("A tool_result \"content\" must be a string or an array of text/image blocks.") + for (const part of content) { + if (part?.type === "image") validateContentBlock(part, allowImage) + else validateTextBlock(part) + } } validateCacheControl(block.cache_control) return diff --git a/packages/sap-aicore/src/responses.js b/packages/sap-aicore/src/responses.js index 6586136..02f2ba4 100644 --- a/packages/sap-aicore/src/responses.js +++ b/packages/sap-aicore/src/responses.js @@ -18,6 +18,7 @@ const ALLOWED = new Set([ // --- strict stateless parameter validation -------------------------------- const MESSAGE_PART = new Set(["input_text", "output_text"]) +const FUNCTION_OUTPUT_PART = new Set(["input_text"]) /** * Validate message content: a string or an array of parts. Text parts are @@ -25,8 +26,9 @@ const MESSAGE_PART = new Set(["input_text", "output_text"]) * model advertises image input. Other multimodal parts are rejected. * @param {unknown} content * @param {boolean} allowImage + * @param {Set} [textTypes] */ -function validateMessageContent(content, allowImage) { +function validateMessageContent(content, allowImage, textTypes = MESSAGE_PART) { 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) { @@ -36,7 +38,7 @@ function validateMessageContent(content, allowImage) { validateInputImage(part) continue } - if (!MESSAGE_PART.has(part.type) || typeof part.text !== "string") throw invalid("Only text message content is supported.") + if (!textTypes.has(part.type) || typeof part.text !== "string") throw invalid("Only text message content is supported.") } } @@ -74,7 +76,9 @@ function validateInputItem(item, allowImage) { 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.") + if (typeof item.call_id !== "string" || !item.call_id) throw invalid("A function result requires a non-empty string call_id.") + // Pi returns input_text/input_image arrays for image-producing tools. + validateMessageContent(item.output, allowImage, FUNCTION_OUTPUT_PART) return } if (type === "reasoning") { diff --git a/packages/sap-aicore/test/messages.test.js b/packages/sap-aicore/test/messages.test.js index 0f112e9..3fb7411 100644 --- a/packages/sap-aicore/test/messages.test.js +++ b/packages/sap-aicore/test/messages.test.js @@ -91,6 +91,29 @@ test("an image-capable model still rejects non-base64 sources and malformed imag for (const block of bad) await assert.rejects(parseWith(withImage(block), IMAGE_CAPABLE), { code: "invalid-request" }, JSON.stringify(block)) }) +test("tool results accept text and images without allowing other nested content", async () => { + const bodyFor = content => base({ messages: [{ role: "user", content: [{ type: "tool_result", tool_use_id: "tool_image", content }] }] }) + for (const content of ["", "tool text", [], [{ type: "text", text: "tool text" }]]) { + assert.deepEqual(await parse(bodyFor(content)), bodyFor(content)) + } + for (const content of [[imageBlock], [{ type: "text", text: "Read image file [image/png]" }, imageBlock]]) { + await assert.rejects(parseWith(bodyFor(content)), { code: "invalid-request" }) + await assert.rejects(parseWith(bodyFor(content), { capabilities: { image: false } }), { code: "invalid-request" }) + assert.deepEqual(await parseWith(bodyFor(content), IMAGE_CAPABLE), bodyFor(content)) + } + const badContents = [ + undefined, null, 7, {}, [null], [{ type: "text" }], + [{ type: "image", source: { type: "url", url: "https://example.invalid/i.png" } }], + [{ type: "image", source: { type: "base64", media_type: "image/png" } }], + [{ ...imageBlock, extra: true }], + [{ type: "tool_use", id: "nested", name: "read", input: {} }], + [{ type: "tool_result", tool_use_id: "nested", content: "ok" }], + [{ type: "thinking", thinking: "x", signature: "sig" }], + [{ type: "document", source: {} }], + ] + for (const content of badContents) await assert.rejects(parseWith(bodyFor(content), IMAGE_CAPABLE), { code: "invalid-request" }) +}) + 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" } }))) @@ -196,6 +219,22 @@ test("a whole Claude reply reaches /invoke and returns native Anthropic JSON", a assert.deepEqual(call.body.messages, [{ role: "user", content: "hi" }]) }) +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" } + const toolUse = { type: "tool_use", id: "tool_image", name: "read", input: { path: "image.png" } } + for (const content of [[imageBlock], [{ type: "text", text: "Read image file [image/png]", cache_control }, { ...imageBlock, cache_control }]]) { + const messages = [ + { role: "user", content: "Read image.png" }, + { role: "assistant", content: [toolUse] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: toolUse.id, content, is_error: false, cache_control }] }, + ] + const response = await post("/messages", base({ messages })) + assert.equal(response.status, 200) + assert.deepEqual(sent.at(-1).body.messages, messages) + } +}) + test("pi's non-native tool hints are stripped from the Bedrock invoke body", async () => { const { post, sent } = await fixture() const tools = [ diff --git a/packages/sap-aicore/test/responses.test.js b/packages/sap-aicore/test/responses.test.js index 8a3d96f..1b6e5e0 100644 --- a/packages/sap-aicore/test/responses.test.js +++ b/packages/sap-aicore/test/responses.test.js @@ -34,7 +34,7 @@ const COMPLETED = { error: null, incomplete_details: null, } -async function fixture(inference = () => new Response(JSON.stringify(COMPLETED))) { +async function fixture(inference = () => new Response(JSON.stringify(COMPLETED)), { image = false } = {}) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-responses-")) cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true })) const credentialFile = path.join(dir, "credentials.json") @@ -52,7 +52,7 @@ async function fixture(inference = () => new Response(JSON.stringify(COMPLETED)) return json({ resources: url.searchParams.get("$skip") === "0" ? [{ id: "deployment-a", status: "RUNNING", deploymentUrl: state.deployment, configurationId: "configuration-a", details: { resources: { backendDetails: { model: { name: MODEL, version: state.activeVersion } } } } }] : [] }) } if (url.pathname === "/v2/lm/configurations/configuration-a") return json({ id: "configuration-a", scenarioId: "foundation-models", executableId: "azure-openai", parameterBindings: [{ key: "modelName", value: MODEL }, { key: "modelVersion", value: VERSION }] }) - if (url.pathname === "/v2/lm/scenarios/foundation-models/models") return json({ resources: [{ model: MODEL, executableId: "azure-openai", allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }], versions: [{ name: VERSION }] }] }) + if (url.pathname === "/v2/lm/scenarios/foundation-models/models") return json({ resources: [{ model: MODEL, executableId: "azure-openai", allowedScenarios: [{ scenarioId: "foundation-models", executableId: "azure-openai" }], versions: [{ name: VERSION, inputTypes: image ? ["text", "image"] : ["text"] }] }] }) sent.push({ url: url.href, init, body: JSON.parse(init.body) }) return inference(input, init) } @@ -340,6 +340,45 @@ test("unsupported stateful, multimodal and unverified parameters never reach SAP assert.equal(sent.length, 0) }) +test("function results accept strings and input_text arrays without image capability", () => { + for (const output of ["", "tool text", [], [{ type: "input_text", text: "tool text" }]]) { + const body = { model: MODEL, input: [{ type: "function_call_output", call_id: "call_image", output }] } + assert.deepEqual(validateResponsesRequest(body).input, body.input) + } +}) + +test("image function results are forwarded verbatim only for image-capable models", async () => { + const { request, sent } = await fixture(undefined, { image: true }) + const image = { type: "input_image", image_url: "data:image/png;base64,iVBORw0KGgo=", detail: "auto" } + for (const output of [[image], [{ type: "input_text", text: "Read image file [image/png]" }, image]]) { + const body = { model: MODEL, input: [USER, CALL, { type: "function_call_output", call_id: CALL.call_id, output }] } + assert.throws(() => validateResponsesRequest(body), { code: "invalid-request" }) + assert.throws(() => validateResponsesRequest(body, { capabilities: { image: false } }), { code: "invalid-request" }) + const response = await request(body) + assert.equal(response.status, 200) + assert.deepEqual(sent.at(-1).body.input, body.input) + } +}) + +test("function result arrays still reject malformed images, unsupported parts and invalid call ids", () => { + const entry = { capabilities: { image: true } } + const badOutputs = [ + undefined, null, 7, {}, [null], + [{ type: "input_text" }], [{ type: "output_text", text: "wrong direction" }], + [{ type: "input_file", file_id: "file_a" }], + [{ type: "input_image" }], + [{ type: "input_image", image_url: "ftp://example.invalid/image.png" }], + [{ type: "input_image", image_url: "data:image/png;base64,x", detail: "high", extra: true }], + [{ type: "input_image", image_url: "data:image/png;base64,x", detail: "invalid" }], + ] + for (const output of badOutputs) { + assert.throws(() => validateResponsesRequest({ model: MODEL, input: [{ type: "function_call_output", call_id: "call_image", output }] }, entry), { code: "invalid-request" }) + } + for (const call_id of [undefined, null, "", 7]) { + assert.throws(() => validateResponsesRequest({ model: MODEL, input: [{ type: "function_call_output", call_id, output: [{ type: "input_text", text: "ok" }] }] }, entry), { code: "invalid-request" }) + } +}) + test("an input_image part is accepted only for an image-capable model", () => { const imagePart = { type: "input_image", image_url: "data:image/png;base64,iVBORw0KGgo=" } const body = { model: MODEL, input: [{ role: "user", content: [{ type: "input_text", text: "what is this?" }, imagePart] }] }