kiro: preserve scoped reasoning across tool continuations (#1156)

Kiro keeps reasoning signatures across tool continuations, sealed as
kiro:<scope>:<payload> where scope hashes the account, region and model, so
a signature is replayed only to the account and model that made it. A 400
from Kiro is returned as is (no strip-and-retry). Effort levels come from a
per-account model list read at request time, shared by concurrent requests
and kept 10 minutes; a failed read is swallowed and the request still goes
out. kiro 0.1.39.

Reviewed at d60a5d001bd7f7b62574798885714d446eb48e9c (mica, temp HOME):
bun test in packages/kiro 203 pass; bun scripts/check.mjs kiro ok. The two
probes from the last review (a failed model list made the request a 502;
an unlisted model was re-listed on every request) failed at 6af97c7 and
pass at this head.
Not tried: a real Kiro account.

Co-authored-by: asp345 <10955734+asp345@users.noreply.github.com>
This commit is contained in:
Chanyeong Lim
2026-11-15 01:25:15 +08:00
committed by GitHub
co-authored by asp345
parent f917240e24
commit a82a2e3558
10 changed files with 675 additions and 72 deletions
+3 -14
View File
@@ -132,6 +132,7 @@ request:
that can't be read or brought under is replaced by a short note, so the
conversation goes on (#428). Smaller images are sent as they are.
- Tools the history used but the request doesn't offer are declared.
- Signed reasoning is replayed as `reasoningContent.reasoningText` with its original text and signature, or as a reasoning input item's `encrypted_content` on CreateResponse. The client's signature carries the native envelope and its account, region and model scope. Raw signatures and envelopes from another scope are omitted. Kiro's signature errors are returned to the client.
- A tool's input schema says `type: "object"` at its root, as Kiro
wants: one that says no type (or object-or-null) is sent saying so, and
an empty one as an object with no properties. Kiro answers 400
@@ -142,19 +143,7 @@ request:
events (streamed) or one message. The reply includes text, thinking,
tool calls and usage. When Kiro reports only how full the context is,
input tokens are estimated from that.
- Thinking (Claude models and Auto) is asked for the way kiro-cli asks, in
the prompt, with a budget: low 10k, medium 20k, high 30k, xhigh and max
50k (as magpie's built-in Kiro: #120). The
`<thinking>` 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).
Thinking is asked for only when the request's `thinking` is `enabled` or
`adaptive`. An effort with no `thinking`, or with it `disabled` (Claude
Code's title requests, or a turn with thinking off), is sent with no
thinking at any level.
- Claude models and Auto use prompt thinking budgets of low 10k, medium 20k, high 30k, and xhigh/max 50k when their catalog has no native adaptive settings. Models whose catalog advertises adaptive thinking receive `additionalModelRequestFields.thinking.type: "adaptive"` and the selected effort under `output_config.effort` or `reasoning.effort`. Claude thinking requires `thinking.type` to be `enabled` or `adaptive`. GPT and Grok models that advertise `reasoning.effort` receive that field directly, with the levels from their catalog. GPT thinking disabled maps to `none` when the model offers it. Cold request-time catalog lookups are optional and shared by account and region for ten minutes, including failures and missing models. A failed lookup does not block chat. Request-time native settings are cached separately for each account and region, and a failed refresh retains that account's last successful settings.
- Anthropic's hosted web search is answered with Kiro's own web search
(see [Web search](#web-search)).
- Kiro's failures keep their meaning:
@@ -246,7 +235,7 @@ the `provider.models` hook replaces it with the account's own list from
context window, output limit and whether it takes images, and its credit
multiplier as `rate` (Kiro's `rateMultiplier` when `rateUnit` is `Credit`:
1.3 for claude-sonnet-4.5, 0.4 for claude-haiku-4.5), which magpie shows
beside the model. Claude models and Auto have the thinking variants.
beside the model. Claude models and Auto have thinking budget variants. Models with native `reasoning.effort` have the effort levels from their catalog.
## Usage in magpie
+177
View File
@@ -0,0 +1,177 @@
import { test, expect } from "bun:test"
const model = "glm-5"
const request = { model, output_config: { effort: "high" }, messages: [{ role: "user", content: "hi" }] }
const account = { accountId: "account-a", uid: "enterprise" }
const credentials = { token: "t", tokenType: "SSO_OIDC", idc: true, profile: "arn:aws:codewhisperer:us-east-1:1:profile/P", region: "us-east-1" }
function answer() {
const header = Buffer.concat(Object.entries({ ":message-type": "event", ":event-type": "assistantResponseEvent" }).map(([key, value]) =>
Buffer.concat([Buffer.from([Buffer.byteLength(key)]), Buffer.from(key), Buffer.from([7, 0, Buffer.byteLength(value)]), Buffer.from(value)])))
const payload = Buffer.from(JSON.stringify({ content: "OK" }))
const frame = Buffer.alloc(16 + header.length + payload.length)
frame.writeUInt32BE(frame.length, 0)
frame.writeUInt32BE(header.length, 4)
header.copy(frame, 12)
payload.copy(frame, 12 + header.length)
return new Response(frame)
}
async function setup(name, catalogResponse) {
const { _internal } = await import(`./index.mjs?catalog-${name}`)
const originalFetch = globalThis.fetch
const reads = [], calls = [], statuses = []
globalThis.fetch = async (input, init) => {
const url = new URL(String(input))
if (url.pathname === "/List-Available-Models") {
reads.push(url)
return catalogResponse(url, init)
}
if (url.pathname === "/featureConfiguration") return Response.json({})
if (url.pathname !== "/generateAssistantResponse") throw new Error("unexpected " + url.pathname)
calls.push(JSON.parse(init.body))
const status = statuses.shift()
return status ? new Response("expired", { status }) : answer()
}
return { reads, calls, statuses, generate: _internal.generate, restore: () => { globalThis.fetch = originalFetch } }
}
for (const kind of ["http-error", "empty"]) {
test(`an optional catalog ${kind} still sends the chat request`, async () => {
const s = await setup(kind, () => kind === "http-error" ? Response.json({ message: "Internal Server Error" }, { status: 500 }) : Response.json({ models: [] }))
try {
const res = await s.generate(async () => credentials, account, { ...request, model: "deepseek-3.2" }, undefined, "session")
expect(res.status).toBe(200)
expect((await res.json()).content).toEqual([{ type: "text", text: "OK" }])
expect(s.reads).toHaveLength(1)
expect(s.calls).toHaveLength(1)
expect(s.calls[0].additionalModelRequestFields).toBeUndefined()
} finally {
s.restore()
}
})
}
test("an unlisted model shares one catalog lookup across consecutive requests", async () => {
const s = await setup("absent", () => Response.json({ models: [{ modelId: "claude-sonnet-4.5" }] }))
try {
for (let i = 0; i < 3; i++) {
const res = await s.generate(async () => credentials, account, request, undefined, "session")
expect(res.status).toBe(200)
await res.text()
}
expect(s.reads).toHaveLength(1)
expect(s.calls).toHaveLength(3)
} finally {
s.restore()
}
})
test("concurrent requests share one optional catalog lookup", async () => {
let release, started
const pending = new Promise(resolve => { release = resolve })
const reading = new Promise(resolve => { started = resolve })
const s = await setup("concurrent", () => { started(); return pending })
try {
const requests = Array.from({ length: 3 }, () => s.generate(async () => credentials, account, request, undefined, "session"))
await reading
expect(s.calls).toHaveLength(0)
release(Response.json({ models: [{ modelId: "claude-sonnet-4.5" }] }))
for (const res of await Promise.all(requests)) {
expect(res.status).toBe(200)
await res.text()
}
expect(s.reads).toHaveLength(1)
expect(s.calls).toHaveLength(3)
} finally {
s.restore()
}
})
test("failed catalog lookups expire and are separate for each account and region", async () => {
const originalNow = Date.now
let now = Date.now()
Date.now = () => now
const s = await setup("scope", () => Response.json({ message: "Internal Server Error" }, { status: 500 }))
const call = async (owner, a) => {
const res = await s.generate(async () => a, owner, request, undefined, "session")
expect(res.status).toBe(200)
await res.text()
}
try {
await call(account, credentials)
await call(account, { ...credentials, token: "refreshed" })
expect(s.reads).toHaveLength(1)
await call({ ...account, accountId: "account-b" }, credentials)
await call(account, { ...credentials, region: "eu-central-1", profile: "arn:aws:codewhisperer:eu-central-1:1:profile/P" })
expect(s.reads).toHaveLength(3)
now += 10 * 60 * 1000 + 1
await call(account, credentials)
expect(s.reads).toHaveLength(4)
} finally {
Date.now = originalNow
s.restore()
}
})
const nativeModel = () => ({ modelId: "gpt-5.6-luna", additionalModelRequestFieldsSchema: { properties: { reasoning: { properties: { effort: { enum: ["low", "high"] } } } } } })
test("native fields use the selected account's regional catalog", async () => {
const s = await setup("native-scope", (url, init) => Response.json({ models: [
init.headers.Authorization === "Bearer t" && url.hostname.includes("us-east-1") ? nativeModel() : { modelId: "gpt-5.6-luna" },
] }))
const call = async (owner, a) => {
const res = await s.generate(async () => a, owner, { ...request, model: "gpt-5.6-luna" }, undefined, "session")
expect(res.status).toBe(200)
await res.text()
}
try {
await call(account, credentials)
await call({ ...account, accountId: "account-b" }, { ...credentials, token: "other" })
await call(account, { ...credentials, region: "eu-central-1", profile: "arn:aws:codewhisperer:eu-central-1:1:profile/P" })
await call(account, credentials)
expect(s.reads).toHaveLength(3)
expect(s.calls.map(body => body.additionalModelRequestFields)).toEqual([
{ reasoning: { effort: "high" } }, undefined, undefined, { reasoning: { effort: "high" } },
])
} finally {
s.restore()
}
})
test("a failed catalog refresh retains the account's last successful native fields", async () => {
const originalNow = Date.now
let now = Date.now(), reads = 0
Date.now = () => now
const s = await setup("last-good", () => ++reads === 1 ? Response.json({ models: [nativeModel()] }) : new Response("unavailable", { status: 500 }))
const call = async () => {
const res = await s.generate(async () => credentials, account, { ...request, model: "gpt-5.6-luna" }, undefined, "session")
expect(res.status).toBe(200)
await res.text()
}
try {
await call()
now += 10 * 60 * 1000 + 1
await call()
await call()
expect(s.reads).toHaveLength(2)
expect(s.calls.map(body => body.additionalModelRequestFields)).toEqual(Array.from({ length: 3 }, () => ({ reasoning: { effort: "high" } })))
} finally {
Date.now = originalNow
s.restore()
}
})
test("a token refresh keeps the failed catalog lookup cached", async () => {
const s = await setup("refresh", () => Response.json({ message: "Internal Server Error" }, { status: 500 }))
s.statuses.push(403)
try {
const res = await s.generate(async (_, stale) => ({ ...credentials, token: stale ? "refreshed" : "t" }), account, request, undefined, "session")
expect(res.status).toBe(200)
expect((await res.json()).content).toEqual([{ type: "text", text: "OK" }])
expect(s.reads).toHaveLength(1)
expect(s.calls).toHaveLength(2)
} finally {
s.restore()
}
})
+3 -1
View File
@@ -207,7 +207,9 @@ test("reasoning and its signature come back as a thinking block; an incomplete r
],
})
const out = await (await generate(creds, {}, req())).json()
expect(out.content).toEqual([{ type: "thinking", thinking: "hmm", signature: "SIG" }, { type: "text", text: "cut" }])
expect(out.content[0]).toMatchObject({ type: "thinking", thinking: "hmm" })
expect(_internal.unsealReasoning(out.content[0].signature, _internal.reasoningScope({}, await creds(), req().model))).toEqual({ reasoningText: { text: "hmm", signature: "SIG" } })
expect(out.content[1]).toEqual({ type: "text", text: "cut" })
expect(out.stop_reason).toBe("max_tokens")
})
+17
View File
@@ -129,3 +129,20 @@ test("each level with thinking on is the field Kiro lists, or its budget", async
expect(said(body)).toContain(`<thinking_mode>enabled</thinking_mode><max_thinking_length>${b}</max_thinking_length>`)
}
})
test("GPT and Grok expose and send their catalog's native reasoning levels", async () => {
for (const id of ["gpt-5.6-luna", "gpt-5.6-sol", "grok-4.7"]) {
const levels = id.startsWith("gpt-") ? ["none", "low", "medium", "high", "xhigh", "max"] : ["low", "medium", "high", "xhigh"]
await listed([model(id, { type: "object", properties: { reasoning: { type: "object", properties: { effort: { type: "string", enum: levels, default: "high" } } } }, additionalProperties: false })])
for (const m of [_internal.configModel({ id }), _internal.runtimeModel({ id })]) expect(Object.keys(m.variants)).toEqual(levels)
for (const effort of levels) {
const body = repro(id, effort)
expect(body.additionalModelRequestFields).toEqual({ reasoning: { effort } })
expect(_internal.responsesBody(body).reasoning).toEqual({ effort })
}
if (id.startsWith("gpt-")) {
const req = { thinking: { type: "disabled" }, output_config: { effort: "high" }, messages: [{ role: "user", content: "q" }] }
expect(JSON.parse(_internal.buildKiro(req, id, "", 0)).additionalModelRequestFields).toEqual({ reasoning: { effort: "none" } })
}
}
})
+94
View File
@@ -0,0 +1,94 @@
import { readFileSync, writeFileSync, mkdirSync, appendFileSync } from 'node:fs'
import { randomUUID, createHash } from 'node:crypto'
import { hostname, platform, release } from 'node:os'
import { _internal as k } from '../index.mjs'
const [authFile, accountKey, outputDir, count = '20'] = process.argv.slice(2)
if (!authFile || !accountKey || !outputDir) throw Error('Usage: node experiments/reasoning.mjs AUTH_JSON ACCOUNT_KEY OUTPUT_DIR [PAIRS]')
mkdirSync(outputDir, { recursive: true, mode: 0o700 })
const model = process.env.KIRO_MODEL ?? 'claude-opus-5.5'
const machine = createHash('sha256').update('magpie:' + hostname()).digest('hex')
const app = `KiroIDE-1.4.121-${machine}-KAS/0.66.89 acp-client/kiro-ide`
function account() {
const a = JSON.parse(readFileSync(authFile, 'utf8'))[accountKey]
if (!a?.access || a.expires < Date.now() + 30000) throw Error('Access token missing or near expiry')
return a
}
const initialAccount = account()
await k.listModels({ token: initialAccount.access, tokenType: initialAccount.method === 'idc' ? 'SSO_OIDC' : '', idc: initialAccount.method === 'idc', profile: initialAccount.profileArn, region: initialAccount.region })
function graph(seed) {
let state = seed >>> 0
const next = n => { state = (Math.imul(state, 1664525) + 1013904223) >>> 0; return state % n }
const edges = []
const n = 16
for (let i = 0; i < n - 1; i++) for (let j = i + 1; j < Math.min(n, i + 5); j++) edges.push([i, j, 1 + next(29)])
const distance = Array(n).fill(Infinity), paths = Array(n)
distance[0] = 0; paths[0] = [0]
for (let i = 0; i < n; i++) for (const [from, to, cost] of edges) if (from === i && distance[from] + cost < distance[to]) { distance[to] = distance[from] + cost; paths[to] = [...paths[from], to] }
return { edges, answer: { path: paths[n - 1], cost: distance[n - 1] } }
}
const tools = [{ name: 'confirm', description: 'Ask for approval to disclose the computed solution. No arguments.', input_schema: { type: 'object', properties: {}, additionalProperties: false } }]
async function call(body, label) {
const a = account()
const headers = { Authorization: `Bearer ${a.access}`, 'Content-Type': 'application/json', Accept: 'text/event-stream', tokentype: a.method === 'idc' ? 'SSO_OIDC' : 'SOCIAL', 'x-amzn-kiro-agent-mode': 'vibe', 'x-amzn-kiro-client-attribution': 'kiro-ide', 'User-Agent': `aws-sdk-js/1.0.0 ua/2.1 os/${platform()}#${release()} lang/js md/nodejs#24.22.1 api/kiroruntime#1.0.0 m/N ${app}`, 'x-amz-user-agent': `aws-sdk-js/1.0.0 ${app}` }
const start = performance.now()
const res = await fetch(`https://runtime.${a.region}.kiro.dev/v1/responses`, { method: 'POST', headers, body: JSON.stringify(body), signal: AbortSignal.timeout(150000) })
const headersMs = performance.now() - start
if (!res.ok) return { label, status: res.status, headersMs, error: await res.text() }
let buf = '', firstEventMs, firstThinkingMs, firstTextMs, output = [], text = '', usage
const reader = res.body.getReader(), dec = new TextDecoder()
for (;;) {
const { value, done } = await reader.read()
buf += done ? dec.decode() : dec.decode(value, { stream: true })
const lines = buf.split('\n'); buf = done ? '' : lines.pop()
for (const line of lines) {
if (!line.startsWith('data:')) continue
let e
try { e = JSON.parse(line.slice(5)) } catch { continue }
const ms = performance.now() - start
if (e.type?.endsWith('.delta')) firstEventMs ??= ms
if (e.type === 'response.reasoning_text.delta' || e.type === 'response.reasoning.delta') firstThinkingMs ??= ms
if (e.type === 'response.output_text.delta') { firstTextMs ??= ms; text += e.delta }
if (e.type === 'response.output_item.done') output.push(e.item)
if (e.type === 'response.completed' || e.type === 'response.incomplete') usage = e.response?.usage
if (e.type === 'response.failed' || e.type === 'error') throw Error(JSON.stringify(e.error ?? e.response?.error))
}
if (done) break
}
const reasoning = body.input.filter(it => it.type === 'reasoning')
return { label, endpoint: '/v1/responses', status: res.status, headersMs, firstEventMs, firstThinkingMs, firstTextMs, totalMs: performance.now() - start, reasoningItems: reasoning.length, reasoningBytes: reasoning.reduce((n, it) => n + (it.encrypted_content?.length ?? 0), 0), inputHashWithoutReasoning: createHash('sha256').update(JSON.stringify({ ...body, input: body.input.filter(it => it.type !== 'reasoning') })).digest('hex'), credits: usage?.['kiro:credits']?.value, usage, text, output }
}
function record(row) {
const { output, ...summary } = row
appendFileSync(`${outputDir}/results.jsonl`, JSON.stringify({ model, ...summary }) + '\n', { mode: 0o600 })
console.log(JSON.stringify({ model, ...summary }))
}
for (let pair = 0; pair < Number(count); pair++) {
const seed = 104729 + pair
const { edges, answer } = graph(seed)
const a = account()
const session = randomUUID()
const prompt = `Find the minimum cost directed path from vertex 0 to vertex 15. Vertices are 0..15. Edges (from,to,cost): ${JSON.stringify(edges)}. Finish solving before calling confirm with {}. Emit no ordinary text before the call, and put no solution in its arguments. After approval return only JSON {"path":[vertices],"cost":number}. Trial ${seed}.`
const request = { model, thinking: { type: 'adaptive' }, output_config: { effort: 'high' }, tools, messages: [{ role: 'user', content: prompt }] }
const gar = JSON.parse(k.buildKiro(request, model, a.profileArn, 30000, session))
const body = k.responsesBody(gar)
const initial = await call(body, `${pair}-initial`)
record({ ...initial, pair, stage: 'initial', seed, answer })
writeFileSync(`${outputDir}/${pair}-initial.json`, JSON.stringify({ body, ...initial }), { mode: 0o600 })
if (initial.status !== 200) throw Error('Initial request failed')
const reasoning = initial.output.filter(it => it.type === 'reasoning' && it.encrypted_content)
const calls = initial.output.filter(it => it.type === 'function_call')
if (!reasoning.length || calls.length !== 1 || calls[0].name !== 'confirm' || initial.text.trim() || Object.keys(JSON.parse(calls[0].arguments || '{}')).length) throw Error('Initial response does not meet the experiment protocol')
const items = initial.output.filter(it => ['reasoning', 'function_call', 'message'].includes(it.type)).map(({ id, status, ...it }) => it)
const continuation = { ...body, input: [...body.input, ...items, { type: 'function_call_output', call_id: calls[0].call_id, output: 'approved' }] }
const order = pair % 2 ? ['drop', 'replay'] : ['replay', 'drop']
for (const mode of order) {
const input = mode === 'replay' ? continuation.input : continuation.input.filter(it => it.type !== 'reasoning')
const row = await call({ ...continuation, input }, `${pair}-${mode}`)
let got
try { got = JSON.parse(row.text) } catch {}
const cost = got?.path?.slice(1).reduce((sum, to, i) => sum + (edges.find(([from, end]) => from === got.path[i] && end === to)?.[2] ?? Infinity), 0)
record({ ...row, pair, stage: 'continuation', mode, order: order.indexOf(mode), seed, answer, correct: got?.cost === answer.cost && cost === answer.cost && got?.path?.[0] === 0 && got?.path?.at(-1) === 15 })
if (row.status !== 200) throw Error('Continuation failed')
}
}
+51
View File
@@ -0,0 +1,51 @@
import json
import random
import statistics
import sys
from pathlib import Path
def interval(values):
rng = random.Random(104729)
medians = sorted(statistics.median(rng.choices(values, k=len(values))) for _ in range(10000))
return [medians[249], medians[9749]]
summaries = []
for filename in sys.argv[1:]:
rows = [json.loads(line) for line in Path(filename).read_text().splitlines()]
continuations = [row for row in rows if row["stage"] == "continuation"]
pairs = {}
for row in continuations:
pairs.setdefault(row["pair"], {})[row["mode"]] = row
assert all(set(pair) == {"replay", "drop"} for pair in pairs.values())
assert all(pair["replay"]["inputHashWithoutReasoning"] == pair["drop"]["inputHashWithoutReasoning"] for pair in pairs.values())
result = {"model": rows[0]["model"], "pairs": len(pairs), "modes": {}}
for mode in ["replay", "drop"]:
selected = [row for row in continuations if row["mode"] == mode]
result["modes"][mode] = {
"first_event_median_ms": statistics.median(row["firstEventMs"] for row in selected),
"first_text_median_ms": statistics.median(row["firstTextMs"] for row in selected),
"completion_median_ms": statistics.median(row["totalMs"] for row in selected),
"mean_credits": statistics.mean(row["credits"] for row in selected),
"correct": sum(row["correct"] for row in selected),
}
differences = [pair["replay"]["firstTextMs"] - pair["drop"]["firstTextMs"] for pair in pairs.values()]
result["paired_first_text_difference_ms"] = statistics.median(differences)
result["paired_first_text_bootstrap_95_interval_ms"] = interval(differences)
result["replay_faster_pairs"] = sum(value < 0 for value in differences)
result["replay_lower_credit_pairs"] = sum(pair["replay"]["credits"] < pair["drop"]["credits"] for pair in pairs.values())
summaries.append(result)
print(json.dumps({
"endpoint": "/v1/responses",
"region": "us-east-1",
"effort": "high",
"account": "one fixed saved account",
"design": "same native first response per pair; replay/drop alternate order; only reasoning items differ",
"task": "minimum cost directed path on a 16-vertex, 54-edge DAG, followed by an empty confirm tool call and approved result",
"seeds": "104729 + pair index",
"timing": "measured from continuation fetch start; first text is the first response.output_text.delta; total is stream completion",
"ground_truth": "computed independently with DAG shortest-path dynamic programming",
"results": summaries,
}, indent=2))
+127 -47
View File
@@ -861,20 +861,18 @@ function account(client, magpie) {
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)
const catalogLookups = new Map()
const CATALOG_TTL = 10 * 60 * 1000
// 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
// <max_thinking_length> budget (#538).
// Effort must match ListAvailableModels' schema (#538): adaptive models
// require thinking.type, while GPT and Grok advertise reasoning.effort alone.
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
const adaptive = Array.isArray(types) && types.includes("adaptive")
for (const path of ["output_config", "reasoning"]) {
const levels = s.properties?.[path]?.properties?.effort?.enum
if (Array.isArray(levels) && levels.length) return { path, levels }
if (Array.isArray(levels) && levels.length && (adaptive || path === "reasoning")) return { path, levels, adaptive }
}
return undefined
}
@@ -884,14 +882,19 @@ const thinks = (id) => /claude/i.test(id) || id === "auto"
// long as max: #120)
const BUDGETS = { low: 10000, medium: 20000, high: 30000, xhigh: 50000, max: 50000 }
function modelVariants(m) {
const native = natives.get(m.id)
if (native && !native.adaptive) return Object.fromEntries(native.levels.map((effort) => [effort, { effort }]))
return thinks(m.id) ? Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) : {}
}
function configModel(m) {
const variants = modelVariants(m)
return {
name: m.name,
limit: { context: m.context ?? 0, output: m.output ?? 0 },
...(m.images ? { attachment: true, modalities: { input: ["text", "image"], output: ["text"] } } : {}),
...(thinks(m.id)
? { reasoning: true, variants: Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) }
: {}),
...(Object.keys(variants).length ? { reasoning: true, variants } : {}),
tool_call: true,
// magpie's own: the credit multiplier Kiro lists for the model
...(m.rate ? { rate: m.rate } : {}),
@@ -899,6 +902,7 @@ function configModel(m) {
}
function runtimeModel(m) {
const variants = modelVariants(m)
const input = { text: true, image: !!m.images, audio: false, video: false, pdf: false }
return {
id: m.id,
@@ -912,7 +916,7 @@ function runtimeModel(m) {
limit: { context: m.context ?? 0, output: m.output ?? 0 },
capabilities: {
temperature: true,
reasoning: thinks(m.id),
reasoning: Object.keys(variants).length > 0,
attachment: !!m.images,
toolcall: true,
input,
@@ -922,7 +926,7 @@ function runtimeModel(m) {
release_date: "",
// magpie's own: the credit multiplier Kiro lists for the model
...(m.rate ? { rate: m.rate } : {}),
variants: thinks(m.id) ? Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) : {},
variants,
}
}
@@ -971,16 +975,33 @@ async function listModels(a) {
if (!name || name === m.modelId) name = m.modelId === "auto" ? "Auto" : m.modelId
const rate = rateOf(m)
const model = { id: m.modelId, name, context: m.tokenLimits?.maxInputTokens ?? 0, output: m.tokenLimits?.maxOutputTokens ?? 0,
images: (m.supportedInputTypes ?? []).some((t) => String(t).toUpperCase() === "IMAGE"), ...(rate ? { rate } : {}) }
images: (m.supportedInputTypes ?? []).some((t) => String(t).toUpperCase() === "IMAGE"), native: nativeOf(m.additionalModelRequestFieldsSchema), ...(rate ? { rate } : {}) }
if (m.modelId === out?.defaultModel?.modelId) list.unshift(model)
else list.push(model)
}
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))
for (const m of list) {
windows.set(m.id, m.context)
natives.set(m.id, m.native)
}
return list
}
// Request-time catalog reads are optional metadata.
async function loadModelCatalog(a, auth) {
const key = JSON.stringify([regionKey(auth), auth?.key, a.profile, a.region])
let lookup = catalogLookups.get(key)
if (!lookup || lookup.until <= Date.now()) {
lookup = { until: Date.now() + CATALOG_TTL, models: lookup?.models ?? new Map() }
lookup.pending = listModels(a).then(models => {
lookup.models = new Map(models.map(m => [m.id, m.native]))
}).catch(() => {})
catalogLookups.set(key, lookup)
}
await lookup.pending
return lookup.models
}
// ---- the request: Messages → a Kiro conversation ---------------------------------------
const PROCEED = "Please proceed with the task." // Kiro takes no empty message
@@ -1164,15 +1185,15 @@ 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 } }
// Adaptive models accept effort only with thinking enabled (#538).
// Native reasoning-only models use reasoning.effort without thinking.type.
function nativeFields(req, model, catalog) {
const n = catalog ? catalog.get(model) : natives.get(model)
if (!n) return undefined
const effort = !n.adaptive && req.thinking?.type === "disabled" ? "none" : req.output_config?.effort
if (typeof effort !== "string" || !n.levels.includes(effort)) return undefined
if (n.adaptive && !thinking(req, model)) return undefined
return { ...(n.adaptive ? { thinking: { type: "adaptive" } } : {}), [n.path]: { effort } }
}
// formatText is the structured output a request asks for, said in words:
@@ -1201,16 +1222,39 @@ function inputSchema(s) {
return s
}
// buildKiro is the body of a generateAssistantResponse call, as it is
// before its images are fitted (kiroBody).
function buildKiro(req, model, profile, budget, conversation) {
return JSON.stringify(kiroRequest(req, model, profile, budget, conversation))
function sealReasoning(value, scope) {
return `kiro:${scope}:${Buffer.from(JSON.stringify(value)).toString("base64url")}`
}
function unsealReasoning(value, scope) {
const prefix = `kiro:${scope}:`
if (!scope || typeof value !== "string" || !value.startsWith(prefix)) return undefined
let content
try {
content = JSON.parse(Buffer.from(value.slice(prefix.length), "base64url").toString())
} catch {
return undefined
}
if (typeof content?.reasoningText?.text === "string" && typeof content.reasoningText.signature === "string" && content.reasoningText.signature) return content
if (typeof content?.redactedContent === "string" && content.redactedContent) return content
return undefined
}
function reasoningScope(auth, a, model) {
const identity = auth?.source ? a.token : auth?.key ?? auth?.accountId ?? a.token
return createHash("sha256").update(JSON.stringify([identity, auth?.uid ?? uidOf(auth?.loginProvider), a.profile, a.region, model])).digest("hex").slice(0, 32)
}
// GenerateAssistantResponse is also the intermediate shape for CreateResponse.
// Images are fitted by kiroBody.
function buildKiro(req, model, profile, budget, conversation, scope, catalog) {
return JSON.stringify(kiroRequest(req, model, profile, budget, conversation, scope, catalog))
}
// kiroBody is the body sent: buildKiro's, with every image it keeps under
// Kiro's size limit.
async function kiroBody(req, model, profile, budget, conversation) {
return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget, conversation)))
async function kiroBody(req, model, profile, budget, conversation, scope, catalog) {
return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget, conversation, scope, catalog)))
}
// UNDERSTOOD is the reply Kiro IDE puts in its history where a turn has
@@ -1241,7 +1285,7 @@ function contextFirst(messages) {
return [...messages.slice(0, start), ...context.map((m) => ({ ...m, role: "user" })), { role: "assistant", content: UNDERSTOOD }, ...turn]
}
function kiroRequest(req, model, profile, budget, conversation) {
function kiroRequest(req, model, profile, budget, conversation, scope, catalog) {
const entries = []
// the messages the caller marked for its prompt cache (cache_control),
// which go to Kiro as a cachePoint on the message they end up in (#110)
@@ -1262,18 +1306,22 @@ function kiroRequest(req, model, profile, budget, conversation) {
let last = null
const flush = () => {
a.content = texts.splice(0).join("\n\n")
if (!a.content && !a.toolUses.length) return // what only thought
if (!a.content && !a.toolUses.length && !a.reasoningContent) return
const prev = entries.at(-1)?.assistantResponseMessage
if (prev) {
prev.content = joinNonEmpty(prev.content, a.content)
prev.toolUses.push(...a.toolUses)
if (a.reasoningContent) prev.reasoningContent = a.reasoningContent
} else entries.push({ assistantResponseMessage: a })
last = prev ?? a
a = { content: "", toolUses: [] }
}
for (const p of parts) {
if (p?.type === "text" && p.text) texts.push(p.text)
else if (p?.type === "tool_use") {
else if (p?.type === "thinking" || p?.type === "redacted_thinking") {
const reasoning = unsealReasoning(p.signature ?? p.data, scope)
if (reasoning) a.reasoningContent = reasoning
} else if (p?.type === "tool_use") {
const input = p.input && typeof p.input === "object" && !Array.isArray(p.input) ? p.input : {}
a.toolUses.push({ name: toolName(p.name), toolUseId: toolID(p.id), input })
} else if (p?.type === "server_tool_use" && p.name === SEARCH_NAME) {
@@ -1383,7 +1431,7 @@ function kiroRequest(req, model, profile, budget, conversation) {
const format = formatText(req)
if (format) system = system ? system + "\n\n" + format : format
// a level Kiro takes as a field is sent as one, not also as a budget
const native = budget ? nativeFields(req, model) : undefined
const native = nativeFields(req, model, catalog)
if (budget && !native) system = `<thinking_mode>enabled</thinking_mode><max_thinking_length>${budget}</max_thinking_length>` + (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)
@@ -1760,6 +1808,7 @@ function responsesInput(e) {
}
const m = e.assistantResponseMessage
if (m) {
if (m.reasoningContent) out.push({ type: "reasoning", encrypted_content: JSON.stringify(m.reasoningContent) })
if (typeof m.content === "string" && m.content) out.push({ role: "assistant", content: m.content })
for (const c of m.toolUses ?? [])
out.push({ type: "function_call", call_id: c.toolUseId, name: c.name, arguments: typeof c.input === "string" ? c.input : JSON.stringify(c.input ?? {}) })
@@ -1818,7 +1867,8 @@ async function* crMessages(body) {
env = JSON.parse(w.item.encrypted_content)
} catch {}
const sig = env?.reasoningText?.signature
if (typeof sig === "string" && sig) yield { kind: "reasoningContentEvent", m: { signature: sig } }
if (typeof sig === "string" && sig) yield { kind: "reasoningContentEvent", m: { signature: sig, encrypted: env } }
if (typeof env?.redactedContent === "string" && env.redactedContent) yield { kind: "reasoningContentEvent", m: { redactedContent: env.redactedContent } }
} else if (type === "response.refusal.delta" && typeof w.delta === "string") {
// a refusal is said as the reply's text
refused = true
@@ -2151,8 +2201,9 @@ async function* garMessages(body) {
// events turns Kiro's reply into events: text, thinking, tool calls (the
// arguments in pieces), then the usage and why it stopped — or an error.
async function* events(body, model, budget, sse = false) {
async function* events(body, model, budget, sse = false, scope) {
const think = new ThinkParser()
let reasoningText = ""
let tool = ""
let tools = 0
let stop = ""
@@ -2183,10 +2234,16 @@ async function* events(body, model, budget, sse = false) {
// one event may carry the reasoning and its signature together (auto,
// called as the IDE): the signature goes on the block it ends
if (m.text) {
reasoningText += m.text
said += m.text.length
yield { kind: "think", text: m.text }
}
if (m.signature) yield { kind: "sig", text: m.signature }
if (m.signature) {
const content = m.encrypted ?? { reasoningText: { text: reasoningText, signature: m.signature } }
yield { kind: "sig", text: sealReasoning(content, scope) }
reasoningText = ""
}
if (m.redactedContent) yield { kind: "redacted", text: sealReasoning({ redactedContent: m.redactedContent }, scope) }
} else if (kind === "toolUseEvent") {
if (m.toolUseId && m.toolUseId !== tool) {
yield* think.end() // the text before a call is all said
@@ -2313,7 +2370,10 @@ async function reply(it, model, stream, names = new Map()) {
if (last?.type === "thinking") last.thinking += e.text
else add({ type: "thinking", thinking: e.text, signature: "" })
} else if (e.kind === "sig") {
if (last?.type === "thinking") last.signature += e.text
if (last?.type !== "thinking") add({ type: "thinking", thinking: "", signature: "" })
last.signature += e.text
} else if (e.kind === "redacted") {
add({ type: "redacted_thinking", data: e.text })
} else if (e.kind === "serverTool") add({ type: "server_tool_use", id: e.id, name: e.name, input: e.input })
else if (e.kind === "searched") add({ type: "web_search_tool_result", tool_use_id: e.id, content: e.content })
else if (e.kind === "toolStart") add({ type: "tool_use", id: e.id, name: names.get(e.name) ?? e.name, input: "" })
@@ -2377,7 +2437,12 @@ async function reply(it, model, stream, names = new Map()) {
ctl.enqueue(sse("content_block_delta", { index, delta: { type: "thinking_delta", thinking: e.text } }))
break
case "sig":
if (open === "thinking") ctl.enqueue(sse("content_block_delta", { index, delta: { type: "signature_delta", signature: e.text } }))
if (open !== "thinking") begin("thinking", { type: "thinking", thinking: "", signature: "" })
ctl.enqueue(sse("content_block_delta", { index, delta: { type: "signature_delta", signature: e.text } }))
break
case "redacted":
begin("redacted", { type: "redacted_thinking", data: e.text })
close()
break
case "toolStart":
begin("tool", { type: "tool_use", id: e.id, name: names.get(e.name) ?? e.name, input: {} })
@@ -2639,7 +2704,7 @@ async function generate(creds, auth, req, signal, conversation) {
if (hosted?.error) return errorResponse(400, hosted.error)
const first = await ask(creds, auth, req, model, budget, signal, conversation)
if (!first.res) return errorResponse(first.status, first.message, first.wait)
const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget, responses.has(first.res))
const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget, responses.has(first.res), first.a.scope)
return kept(await reply(it, model, req.stream === true, toolNames(req)))
}
@@ -2653,9 +2718,14 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
return { status: 401, message: e.message }
}
if (a.pinned) return { status: 429, message: pinnedUnavailable(a) }
const send = async () => {
const catalog = thinks(model) ? undefined : await loadModelCatalog(a, auth)
a.scope = reasoningScope(auth, a, model)
return paced(a, await kiroBody(req, model, a.profile, budget, conversation, a.scope, catalog), signal)
}
let res
try {
res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
res = await send()
} catch (e) {
if (e?.name === "AbortError") throw e
return { status: 502, message: e.message }
@@ -2668,7 +2738,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
return { status: 502, message: e.message }
}
try {
res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
res = await send()
} catch (e) {
if (e?.name === "AbortError") throw e
return { status: 502, message: e.message }
@@ -2694,7 +2764,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
a = next
try {
res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
res = await send()
} catch (e) {
if (e?.name === "AbortError") throw e
return { status: 502, message: e.message }
@@ -2745,7 +2815,7 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
let client = false
let current = null
let stop = null
for await (const e of events(res.body, model, budget, responses.has(res))) {
for await (const e of events(res.body, model, budget, responses.has(res), a.scope)) {
if (e.kind === "toolStart") {
current = e.name === SEARCH_NAME ? { args: "" } : null
if (current) calls.push(current)
@@ -2767,7 +2837,14 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
const b = said.at(-1)
if (b?.type === "text") b.text += e.text
else said.push({ type: "text", text: e.text })
}
} else if (e.kind === "think") {
const b = said.at(-1)
if (b?.type === "thinking") b.thinking += e.text
else said.push({ type: "thinking", thinking: e.text, signature: "" })
} else if (e.kind === "sig") {
if (said.at(-1)?.type !== "thinking") said.push({ type: "thinking", thinking: "", signature: "" })
said.at(-1).signature += e.text
} else if (e.kind === "redacted") said.push({ type: "redacted_thinking", data: e.text })
if (e.kind === "error") {
// in a turn after a search, a status, not a finished answer
// (reply): one past the window says so, as failedBefore does
@@ -3190,6 +3267,9 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
} catch {
return errorResponse(400, "a request that isn't JSON")
}
// magpie's header carries the user's selected effort and takes precedence over the body.
const effort = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined)).get("x-magpie-effort")
if (effort) req.output_config = { ...req.output_config, effort }
return generate(creds, (await getAuth()) ?? auth, req, init.signal, sessionOf(input, init))
},
}
@@ -3292,4 +3372,4 @@ export async function KiroAuthPlugin({ client, magpie } = {}) {
}
// for tests
export const _internal = { generate, responsesBody, crMessages, crRefusal, features, FEATURES, featureKey, waitOf, timing, TRIES, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, rateOf, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames }
export const _internal = { generate, responsesBody, crMessages, crRefusal, features, FEATURES, featureKey, waitOf, timing, TRIES, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, rateOf, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames, sealReasoning, unsealReasoning, reasoningScope }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-kiro-auth",
"version": "0.1.38",
"version": "0.1.39",
"description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
"type": "module",
"main": "./opencode.mjs",
+195
View File
@@ -0,0 +1,195 @@
import { test, expect } from "bun:test"
import { _internal } from "./index.mjs"
const { buildKiro, events, reply, generate, features, sealReasoning, unsealReasoning } = _internal
const scope = "account-region-model"
const native = { reasoningText: { text: "The path costs 35.", signature: "CAQSbmF0aXZlLXNpZ25hdHVyZQ==" } }
const creds = async () => ({ token: "t", tokenType: "SSO_OIDC", idc: true, profile: "arn:aws:codewhisperer:us-east-1:1:profile/P", region: "us-east-1" })
const auth = { accountId: "account", uid: "enterprise" }
const model = "claude-opus-5.5"
const req = { model, messages: [{ role: "user", content: "Compute the path, then ask for confirmation." }] }
function frame(type, payload) {
const enc = new TextEncoder()
const hs = Object.entries({ ":message-type": "event", ":event-type": type }).map(([k, v]) => {
const name = enc.encode(k), value = enc.encode(v)
const h = new Uint8Array(4 + name.length + value.length)
h[0] = name.length
h.set(name, 1)
h[1 + name.length] = 7
new DataView(h.buffer).setUint16(2 + name.length, value.length)
h.set(value, 4 + name.length)
return h
})
const hlen = hs.reduce((n, h) => n + h.length, 0)
const body = enc.encode(JSON.stringify(payload))
const out = new Uint8Array(16 + hlen + body.length)
new DataView(out.buffer).setUint32(0, out.length)
new DataView(out.buffer).setUint32(4, hlen)
let at = 12
for (const h of hs) { out.set(h, at); at += h.length }
out.set(body, at)
return out
}
const stream = (...frames) => new ReadableStream({ start(c) { for (const f of frames) c.enqueue(f); c.close() } })
const gar = () => new Response(stream(
frame("reasoningContentEvent", native.reasoningText),
frame("toolUseEvent", { toolUseId: "call1", name: "confirm", input: "{}" }),
frame("metadataEvent", { stopReason: "TOOL_USE" }),
))
const sse = (...events) => new Response(events.map(e => `data: ${JSON.stringify(e)}\n\n`).join(""))
const cr = () => sse(
{ type: "response.reasoning_text.delta", delta: native.reasoningText.text },
{ type: "response.output_item.done", item: { type: "reasoning", encrypted_content: JSON.stringify(native) } },
{ type: "response.output_item.added", item: { type: "function_call", call_id: "call1", name: "confirm", arguments: "{}" } },
{ type: "response.output_item.done", item: { type: "function_call", call_id: "call1", name: "confirm", arguments: "{}" } },
{ type: "response.completed", response: { status: "completed", usage: {} } },
)
async function content(res, streamed) {
if (!streamed) return (await res.json()).content
const out = []
for (const line of (await res.text()).split("\n")) {
if (!line.startsWith("data:")) continue
const e = JSON.parse(line.slice(5))
if (e.type === "content_block_start") out[e.index] = { ...e.content_block }
if (e.type === "content_block_delta") {
const b = out[e.index], d = e.delta
if (d.type === "thinking_delta") b.thinking += d.thinking
if (d.type === "signature_delta") b.signature += d.signature
}
}
return out
}
for (const api of ["gar", "responses"]) for (const streamed of [false, true]) {
test(`${api}, stream=${streamed}: signed thinking survives a tool continuation`, async () => {
const realFetch = globalThis.fetch
const bodies = []
features.clear()
globalThis.fetch = async (input, init) => {
const path = new URL(String(input)).pathname
if (path === "/featureConfiguration") return Response.json(api === "responses" ? { configuration: { [_internal.featureKey("create_response_api")]: "create_response" } } : {})
bodies.push(JSON.parse(init.body))
return api === "responses" ? cr() : gar()
}
try {
const blocks = await content(await generate(creds, auth, { ...req, stream: streamed }, undefined, "session"), streamed)
const thought = blocks.find(b => b.type === "thinking")
expect(thought.thinking).toBe(native.reasoningText.text)
expect(thought.signature.startsWith("kiro:")).toBe(true)
const messages = [...req.messages, { role: "assistant", content: blocks }, { role: "user", content: [{ type: "tool_result", tool_use_id: "call1", content: "approved" }] }]
await (await generate(creds, auth, { ...req, messages }, undefined, "session")).text()
expect(bodies).toHaveLength(2)
const sent = api === "responses"
? JSON.parse(bodies[1].input.find(it => it.type === "reasoning").encrypted_content)
: bodies[1].conversationState.history[1].assistantResponseMessage.reasoningContent
expect(sent).toEqual(native)
} finally {
globalThis.fetch = realFetch
}
})
}
test("a foreign Anthropic signature makes one request without reasoning", async () => {
const realFetch = globalThis.fetch
const bodies = []
features.clear()
globalThis.fetch = async (input, init) => {
if (new URL(String(input)).pathname === "/featureConfiguration") return Response.json({})
bodies.push(JSON.parse(init.body))
return gar()
}
try {
const messages = [...req.messages, { role: "assistant", content: [{ type: "thinking", thinking: "foreign", signature: "EqQBCgIYAhIM1gbcDa9GJwZA2b==" }, { type: "text", text: "ready" }] }, { role: "user", content: "continue" }]
await (await generate(creds, auth, { ...req, messages }, undefined, "session")).text()
expect(bodies).toHaveLength(1)
expect(bodies[0].conversationState.history[1].assistantResponseMessage).toEqual({ content: "ready" })
} finally {
globalThis.fetch = realFetch
}
})
test("reasoning is bound to the account, region and model scope", () => {
const signature = sealReasoning(native, scope)
expect(unsealReasoning(signature, scope)).toEqual(native)
const b = JSON.parse(buildKiro({ messages: [
...req.messages,
{ role: "assistant", content: [{ type: "thinking", thinking: native.reasoningText.text, signature }, { type: "text", text: "ready" }] },
{ role: "user", content: "continue" },
] }, model, "", 0, "session", "another-account-region-model"))
expect(b.conversationState.history[1].assistantResponseMessage).toEqual({ content: "ready" })
})
test("a separate assistant message keeps its signed reasoning when merged with its call", () => {
const signature = sealReasoning(native, scope)
const b = JSON.parse(buildKiro({ messages: [
...req.messages,
{ role: "assistant", content: [{ type: "tool_use", id: "call1", name: "confirm", input: {} }] },
{ role: "assistant", content: [{ type: "thinking", thinking: native.reasoningText.text, signature }] },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "call1", content: "approved" }] },
] }, model, "", 0, "session", scope))
expect(b.conversationState.history[1].assistantResponseMessage.reasoningContent).toEqual(native)
expect(b.conversationState.history[1].assistantResponseMessage.toolUses).toHaveLength(1)
})
test("a signature-only event after a tool call retains its block, whole and streamed", async () => {
for (const streamed of [false, true]) {
const body = stream(frame("toolUseEvent", { toolUseId: "call1", name: "confirm", input: "{}" }), frame("reasoningContentEvent", { signature: native.reasoningText.signature }), frame("metadataEvent", { stopReason: "TOOL_USE" }))
const blocks = await content(await reply(events(body, model, 0, false, scope), model, streamed), streamed)
const thought = blocks.find(b => b.type === "thinking")
expect(unsealReasoning(thought.signature, scope)).toEqual({ reasoningText: { text: "", signature: native.reasoningText.signature } })
}
})
test("redacted state survives streamed and whole replies", async () => {
for (const streamed of [false, true]) {
const body = stream(frame("reasoningContentEvent", { redactedContent: "UkVEQUNURUQ=" }), frame("metadataEvent", { stopReason: "END_TURN" }))
const blocks = await content(await reply(events(body, model, 0, false, scope), model, streamed), streamed)
expect(unsealReasoning(blocks[0].data, scope)).toEqual({ redactedContent: "UkVEQUNURUQ=" })
}
})
test("the first native-model request loads its schema and applies magpie's effort header", async () => {
const { KiroAuthPlugin } = await import("./index.mjs?native-effort-loader")
const realFetch = globalThis.fetch
const bodies = [], paths = []
globalThis.fetch = async (input, init) => {
const path = new URL(String(input)).pathname
paths.push(path)
if (path === "/List-Available-Models") return Response.json({ models: [{ modelId: "gpt-5.6-luna", additionalModelRequestFieldsSchema: { properties: { reasoning: { properties: { effort: { enum: ["none", "low", "medium", "high", "xhigh", "max"] } } } } } }] })
if (path === "/featureConfiguration") return Response.json({})
bodies.push(JSON.parse(init.body))
return gar()
}
try {
const plugin = await KiroAuthPlugin()
const loader = await plugin.auth.loader(async () => ({ type: "oauth", access: "t", expires: Date.now() + 3600000, accountId: "account", uid: "google", loginProvider: "Google", profileArn: "arn:aws:codewhisperer:us-east-1:1:profile/P", region: "us-east-1" }))
const res = await loader.fetch("https://kiro.test/v1/messages", { method: "POST", headers: { "x-magpie-effort": "low" }, body: JSON.stringify({ model: "gpt-5.6-luna", output_config: { effort: "max" }, messages: req.messages }) })
await res.text()
expect(paths).toContain("/List-Available-Models")
expect(bodies).toHaveLength(1)
expect(bodies[0].additionalModelRequestFields).toEqual({ reasoning: { effort: "low" } })
} finally {
globalThis.fetch = realFetch
}
})
test("Kiro's captured HTTP 400 signature refusal reaches the client", async () => {
const realFetch = globalThis.fetch
const bodies = []
features.clear()
globalThis.fetch = async (input, init) => {
if (new URL(String(input)).pathname === "/featureConfiguration") return Response.json({})
bodies.push(JSON.parse(init.body))
return Response.json({ message: "messages.1.content.0: Invalid `signature` in `thinking` block", reason: "THINKING_SIGNATURE_INVALID" }, { status: 400 })
}
try {
const res = await generate(creds, auth, req, undefined, "session")
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain("THINKING_SIGNATURE_INVALID")
expect(bodies).toHaveLength(1)
} finally {
globalThis.fetch = realFetch
}
})
+7 -9
View File
@@ -1,11 +1,7 @@
// Called as the Kiro IDE (AI_EDITOR), Kiro's auto ends a reply with one
// reasoningContentEvent carrying text and its signature together. These are
// the payloads of a real reply (2026-11-07, auto, "Reply with the single word
// OK."); the signature was dropped and the block sent with an empty one.
import { test, expect } from "bun:test"
import { _internal } from "./index.mjs"
const { events, reply } = _internal
const { events, reply, sealReasoning } = _internal
function frame(headers, payload) {
const enc = new TextEncoder()
@@ -47,6 +43,8 @@ const stream = (...fs) =>
const ev = (type, payload) => frame({ ":message-type": "event", ":event-type": type }, payload)
const SIG = ".KTR~~eyJlbmNyeXB0aW9uUmVnaW9uIjpudWxsLCJtaW50ZWRBdE1zIjoxNzk0MDU1MjcyODg0LCJtb2RlbEhhc2giOiJ5RUxWOXhiY2Z3dlUiLCJzbG90cyI6W10sInYiOjF9"
const SCOPE = "account-region-model"
const signed = () => sealReasoning({ reasoningText: { text: "...", signature: SIG } }, SCOPE)
const body = () => stream(
ev("assistantResponseEvent", { content: "OK", modelId: "auto" }),
ev("reasoningContentEvent", { signature: SIG, text: "..." }),
@@ -54,14 +52,14 @@ const body = () => stream(
)
test("reasoning sent with its signature in one event keeps the signature", async () => {
const res = await reply(events(body(), "auto", 0), "auto", false)
const res = await reply(events(body(), "auto", 0, false, SCOPE), "auto", false)
const j = await res.json()
expect(j.content).toEqual([{ type: "text", text: "OK" }, { type: "thinking", thinking: "...", signature: SIG }])
expect(j.content).toEqual([{ type: "text", text: "OK" }, { type: "thinking", thinking: "...", signature: signed() }])
})
test("streamed, the signature follows the reasoning in its block", async () => {
const res = await reply(events(body(), "auto", 0), "auto", true)
const res = await reply(events(body(), "auto", 0, false, SCOPE), "auto", true)
const out = await res.text()
expect(out).toContain(JSON.stringify({ type: "thinking_delta", thinking: "..." }))
expect(out).toContain(JSON.stringify({ type: "signature_delta", signature: SIG }))
expect(out).toContain(JSON.stringify({ type: "signature_delta", signature: signed() }))
})