diff --git a/packages/kiro/README.md b/packages/kiro/README.md index 1987ab2..b64bf92 100644 --- a/packages/kiro/README.md +++ b/packages/kiro/README.md @@ -108,6 +108,10 @@ request: profile ARN names. - It turns the request into a Kiro conversation: - The system prompt goes at the head of the first message. + - System messages that end the conversation (Claude Code's environment + context) are sent as a turn before the question, answered by Kiro IDE's + "Understood.", so the question is the message answered (#538). After + tool results they stay with them. - Tool calls and results are paired: an unanswered call gets an error result, and a result longer than 250,000 characters is cut. - Tool ids Kiro wouldn't take are rewritten. A tool name over 64 @@ -136,6 +140,11 @@ request: the prompt, with a budget: low 10k, medium 20k, high 30k, xhigh and max 50k (as magpie's built-in Kiro: #120). The `` block of the reply comes back as thinking. + A model whose Kiro catalog lists effort levels with adaptive thinking + (`additionalModelRequestFieldsSchema`) is sent the level instead, as Kiro + IDE sends it: `additionalModelRequestFields` with `thinking.type: + "adaptive"` and `output_config.effort` (or `reasoning.effort`), and no + budget. So xhigh and max stay apart there (#538). - Anthropic's hosted web search is answered with Kiro's own web search (see [Web search](#web-search)). - Kiro's failures keep their meaning: diff --git a/packages/kiro/effort.test.mjs b/packages/kiro/effort.test.mjs index 3dc6924..ceea5bd 100644 --- a/packages/kiro/effort.test.mjs +++ b/packages/kiro/effort.test.mjs @@ -1,4 +1,4 @@ -import { test, expect } from "bun:test" +import { test, expect, afterEach } from "bun:test" import { _internal } from "./index.mjs" // Claude Code's levels are low, medium, high, xhigh and max: a thinking @@ -13,3 +13,83 @@ test("a thinking model offers xhigh as its own level", () => { // a model that doesn't think offers none expect(_internal.configModel({ id: "deepseek-3.2", name: "DeepSeek" }).variants).toBeUndefined() }) + +// #538 (zengxiaosong): Claude Code sends adaptive thinking with its level +// in output_config.effort, and xhigh and max both became one 50000 +// . A model whose Kiro list says it takes the effort +// as a field (additionalModelRequestFieldsSchema, read as Kiro IDE reads +// it) is sent each level there instead, and no budget; any other model is +// sent the budget as before. +const OPUS_SCHEMA = { + type: "object", + properties: { + thinking: { type: "object", properties: { type: { type: "string", enum: ["adaptive", "disabled"] } } }, + output_config: { type: "object", properties: { effort: { type: "string", enum: ["low", "medium", "high", "xhigh", "max"] } } }, + }, +} +const listed = (models) => { + const was = globalThis.fetch + globalThis.fetch = async (input) => { + if (new URL(String(input)).pathname !== "/List-Available-Models") throw new Error("no network in tests") + return Response.json({ defaultModel: { modelId: "auto" }, models }) + } + return _internal.listModels({ region: "us-east-1", token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:1:profile/P" }) + .finally(() => (globalThis.fetch = was)) +} +const model = (modelId, schema) => ({ modelId, modelName: modelId, tokenLimits: { maxInputTokens: 1000000, maxOutputTokens: 128000 }, + additionalModelRequestFieldsSchema: schema }) +afterEach(() => listed([model("claude-opus-5.5", null), model("claude-sonnet-4.5", null)])) + +// the reporter's repro, as written in #538 +const repro = (model, effort) => { + const req = { + model, system: "SESSION_INSTRUCTIONS", + thinking: { type: "adaptive" }, output_config: { effort }, + messages: [ + { role: "user", content: "USER_QUESTION" }, + { role: "system", content: "ENV_CONTEXT", output_config: { effort } }, + ], + } + return JSON.parse(_internal.buildKiro(req, model, "", _internal.thinking(req, model))) +} +const said = (body) => [...(body.conversationState.history ?? []).map((e) => e.userInputMessage?.content ?? e.assistantResponseMessage?.content), + body.conversationState.currentMessage.userInputMessage.content].join("\n") + +test("a model Kiro lists with effort fields is sent xhigh and max as two levels, with no budget", async () => { + await listed([model("claude-opus-5.5", OPUS_SCHEMA), model("claude-sonnet-4.5", null)]) + const bodies = {} + for (const effort of ["xhigh", "max"]) { + const body = repro("claude-opus-5.5", effort) + expect(body.additionalModelRequestFields).toEqual({ thinking: { type: "adaptive" }, output_config: { effort } }) + expect(said(body)).not.toContain("max_thinking_length") + expect(said(body)).not.toContain("thinking_mode") + delete body.conversationState.conversationId + bodies[effort] = JSON.stringify(body) + } + expect(bodies.xhigh).not.toBe(bodies.max) + // a level the model doesn't list keeps the budget + const req = { thinking: { type: "adaptive" }, output_config: { effort: "ultra" }, messages: [{ role: "user", content: "q" }] } + const odd = JSON.parse(_internal.buildKiro(req, "claude-opus-5.5", "", _internal.thinking(req, "claude-opus-5.5"))) + expect(odd.additionalModelRequestFields).toBeUndefined() + expect(said(odd)).toContain("20000") + // thinking not asked for: no fields + const off = { output_config: { effort: "low" }, messages: [{ role: "user", content: "q" }] } + expect(JSON.parse(_internal.buildKiro(off, "claude-opus-5.5", "", _internal.thinking(off, "claude-opus-5.5"))).additionalModelRequestFields).toBeUndefined() +}) + +test("a model Kiro lists without effort fields keeps its budget", async () => { + // the list a Free account got on 2026-10-31: the field there, null + await listed([model("claude-opus-5.5", OPUS_SCHEMA), model("claude-sonnet-4.5", null)]) + for (const effort of ["xhigh", "max"]) { + const body = repro("claude-sonnet-4.5", effort) + expect(body.additionalModelRequestFields).toBeUndefined() + expect(said(body)).toContain("enabled50000") + } + // a schema with effort levels but no adaptive thinking isn't taken as one + const noAdaptive = { properties: { output_config: OPUS_SCHEMA.properties.output_config } } + await listed([model("claude-opus-5.5", noAdaptive)]) + expect(repro("claude-opus-5.5", "max").additionalModelRequestFields).toBeUndefined() + // reasoning.effort, the schema's other place for it, as the IDE reads it + await listed([model("claude-opus-5.5", { properties: { thinking: OPUS_SCHEMA.properties.thinking, reasoning: OPUS_SCHEMA.properties.output_config } })]) + expect(repro("claude-opus-5.5", "max").additionalModelRequestFields).toEqual({ thinking: { type: "adaptive" }, reasoning: { effort: "max" } }) +}) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 25090ca..f495855 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -574,6 +574,24 @@ function account(client) { // ---- models ---------------------------------------------------------------------- const windows = new Map() // a model's context, as Kiro last listed it +const natives = new Map() // a model's effort levels sent as fields, as Kiro last listed them (nativeOf) + +// nativeOf is what a model's additionalModelRequestFieldsSchema in Kiro's +// list offers, read as Kiro IDE reads it: the effort levels in the enum of +// output_config's (or reasoning's) effort, and whether thinking.type may be +// "adaptive". A model offering both is sent the caller's effort in +// additionalModelRequestFields, as the IDE sends it; any other keeps the +// budget (#538). +function nativeOf(s) { + if (!s || typeof s !== "object" || Array.isArray(s)) return undefined + const types = s.properties?.thinking?.properties?.type?.enum + if (!Array.isArray(types) || !types.includes("adaptive")) return undefined + for (const path of ["output_config", "reasoning"]) { + const levels = s.properties?.[path]?.properties?.effort?.enum + if (Array.isArray(levels) && levels.length) return { path, levels } + } + return undefined +} const thinks = (id) => /claude/i.test(id) || id === "auto" // the levels a thinking model offers, as the built-in thinks them (xhigh as @@ -653,6 +671,7 @@ async function listModels(a) { } if (!list.length) throw new Error("Kiro listed no models") for (const m of list) windows.set(m.id, m.context) + for (const m of out?.models ?? []) if (m?.modelId) natives.set(m.modelId, nativeOf(m.additionalModelRequestFieldsSchema)) return list } @@ -834,6 +853,17 @@ function thinking(req, model) { return 20000 } +// nativeFields is the additionalModelRequestFields a thinking request is +// sent with when Kiro's list says the model takes its effort as a field: +// adaptive thinking at the caller's level, so xhigh and max reach the model +// as two levels rather than one 50000 budget (#538). undefined otherwise. +function nativeFields(req, model) { + const n = natives.get(model) + const effort = req.output_config?.effort + if (!n || typeof effort !== "string" || !n.levels.includes(effort) || !thinking(req, model)) return undefined + return { thinking: { type: "adaptive" }, [n.path]: { effort } } +} + // formatText is the structured output a request asks for, said in words: // Anthropic's output_config.format (or the AI SDK's output_format) with a // JSON schema, "" when it asks for none. A JSON object with no schema @@ -872,6 +902,34 @@ async function kiroBody(req, model, profile, budget) { return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget))) } +// UNDERSTOOD is the reply Kiro IDE puts in its history where a turn has +// none of its own, before the message being answered +const UNDERSTOOD = "Understood." + +// contextFirst is a conversation that ends in system messages (Claude +// Code's environment context, sent after the user's question) with that +// context said first: a turn of its own, answered by Kiro IDE's +// placeholder, before the question, which stays the message being +// answered rather than the head of "question, then context" (#538). The +// instructions' own field isn't used: Kiro refuses it ("systemPrompt field +// is not enabled for this user"). A question carrying tool results, or +// following tool calls, keeps the context in it as before, so no call is +// parted from its result. +function contextFirst(messages) { + let end = messages.length + while (end > 0 && messages[end - 1]?.role === "system") end-- + if (end === messages.length) return messages + let start = end + while (start > 0 && messages[start - 1]?.role === "user") start-- + const parts = (m) => (typeof m?.content === "string" ? [{ type: "text", text: m.content }] : Array.isArray(m?.content) ? m.content : []) + const context = messages.slice(end) + if (start === end || !context.some((m) => parts(m).some((p) => p?.type !== "text" || p.text))) return messages + const turn = messages.slice(start, end) + if (turn.some((m) => parts(m).some((p) => p?.type === "tool_result"))) return messages + if (parts(messages[start - 1]).some((p) => p?.type === "tool_use" || p?.type === "server_tool_use" || p?.type === "web_search_tool_result")) return messages + return [...messages.slice(0, start), ...context.map((m) => ({ ...m, role: "user" })), { role: "assistant", content: UNDERSTOOD }, ...turn] +} + function kiroRequest(req, model, profile, budget) { const entries = [] // the messages the caller marked for its prompt cache (cache_control), @@ -882,7 +940,7 @@ function kiroRequest(req, model, profile, budget) { } const user = () => ({ content: "", modelId: model, origin: "KIRO_CLI" }) const resultsOnly = new WeakSet() // the messages made to carry a reply's web search results - for (const m of req.messages ?? []) { + for (const m of contextFirst(req.messages ?? [])) { const parts = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content ?? [] const texts = [] if (m.role === "assistant") { @@ -1013,7 +1071,9 @@ function kiroRequest(req, model, profile, budget) { // end of the instructions, as magpie's built-in tells it (inSystem) const format = formatText(req) if (format) system = system ? system + "\n\n" + format : format - if (budget) system = `enabled${budget}` + (system ? "\n" + system : "") + // a level Kiro takes as a field is sent as one, not also as a budget + const native = budget ? nativeFields(req, model) : undefined + if (budget && !native) system = `enabled${budget}` + (system ? "\n" + system : "") if (system) entries[0].userInputMessage.content = system + "\n\n" + entries[0].userInputMessage.content if (Array.isArray(req.system)) mark(entries[0].userInputMessage, req.system) @@ -1063,6 +1123,7 @@ function kiroRequest(req, model, profile, budget) { if (entries.length > 1) state.history = entries.slice(0, -1) const out = { conversationState: state, agentMode: "vibe" } if (profile) out.profileArn = profile + if (native) out.additionalModelRequestFields = native return out } @@ -2309,4 +2370,4 @@ export async function KiroAuthPlugin({ client } = {}) { } // for tests -export const _internal = { generate, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames } +export const _internal = { generate, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames } diff --git a/packages/kiro/package.json b/packages/kiro/package.json index 2ccdc82..793ec83 100644 --- a/packages/kiro/package.json +++ b/packages/kiro/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-kiro-auth", - "version": "0.1.21", + "version": "0.1.22", "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/kiro/system-context.test.mjs b/packages/kiro/system-context.test.mjs new file mode 100644 index 0000000..7d53211 --- /dev/null +++ b/packages/kiro/system-context.test.mjs @@ -0,0 +1,77 @@ +// #538 (zengxiaosong): in a Claude Code project session the plugin is sent +// [user, system], the system message being Claude Code's environment +// context, and both were joined into the message Kiro answers: the +// question, then the context. The context is now a turn of its own before +// the question, answered by Kiro IDE's placeholder ("Understood."), and the +// question is the message answered. Tool calls and their results are never +// parted for it. +import { test, expect } from "bun:test" +import { _internal } from "./index.mjs" + +const MODEL = "claude-opus-5.5" +const build = (req) => JSON.parse(_internal.buildKiro(req, MODEL, "", _internal.thinking(req, MODEL))) +const turns = (body) => + [...(body.conversationState.history ?? []), { userInputMessage: body.conversationState.currentMessage.userInputMessage }].map((e) => + e.userInputMessage ? ["user", e.userInputMessage.content] : ["assistant", e.assistantResponseMessage.content]) + +test("the reporter's [user, system] keeps the question as the message answered", () => { + for (const effort of ["xhigh", "max"]) { + // the repro in #538, as written + const req = { + model: MODEL, system: "SESSION_INSTRUCTIONS", + thinking: { type: "adaptive" }, output_config: { effort }, + messages: [ + { role: "user", content: "USER_QUESTION" }, + { role: "system", content: "ENV_CONTEXT", output_config: { effort } }, + ], + } + expect(turns(build(req))).toEqual([ + ["user", "enabled50000\nSESSION_INSTRUCTIONS\n\nENV_CONTEXT"], + ["assistant", "Understood."], + ["user", "USER_QUESTION"], + ]) + } +}) + +test("context after a later question goes before that question only", () => { + const req = { + system: "S", + messages: [ + { role: "user", content: "first" }, + { role: "assistant", content: "answer" }, + { role: "user", content: [{ type: "text", text: "second" }] }, + { role: "system", content: [{ type: "text", text: "ENV_CONTEXT" }] }, + ], + } + expect(turns(build(req))).toEqual([ + ["user", "S\n\nfirst"], + ["assistant", "answer"], + ["user", "ENV_CONTEXT"], + ["assistant", "Understood."], + ["user", "second"], + ]) + // a conversation not ending in a system message is as it was + const plain = { messages: req.messages.slice(0, 3) } + expect(_internal.contextFirst(plain.messages)).toBe(plain.messages) +}) + +test("context after tool results stays with them, every call answered as before", () => { + const messages = [ + { role: "user", content: "list files" }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "Bash", input: { command: "ls" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "a.txt" }] }, + { role: "system", content: "ENV_CONTEXT" }, + ] + expect(_internal.contextFirst(messages)).toBe(messages) + const body = build({ messages }) + const cur = body.conversationState.currentMessage.userInputMessage + expect(cur.userInputMessageContext.toolResults).toEqual([{ toolUseId: "toolu_1", status: "success", content: [{ text: "a.txt" }] }]) + expect(cur.content).toBe("ENV_CONTEXT") + expect(body.conversationState.history.at(-1).assistantResponseMessage.toolUses).toEqual([{ name: "Bash", toolUseId: "toolu_1", input: { command: "ls" } }]) + // a question right after calls (their results not sent) isn't moved either + const unanswered = [...messages.slice(0, 2), { role: "user", content: "go on" }, { role: "system", content: "ENV_CONTEXT" }] + expect(_internal.contextFirst(unanswered)).toBe(unanswered) + // nor is an empty context + const empty = [{ role: "user", content: "q" }, { role: "system", content: "" }] + expect(_internal.contextFirst(empty)).toBe(empty) +})