diff --git a/packages/kiro/ide-identity.test.mjs b/packages/kiro/ide-identity.test.mjs new file mode 100644 index 0000000..7f6753d --- /dev/null +++ b/packages/kiro/ide-identity.test.mjs @@ -0,0 +1,112 @@ +// onemezao (Discord): a Builder ID account on Kiro Pro for students was +// answered 429 USER_REQUEST_RATE_EXCEEDED on claude-haiku-5.5 through the +// plugin, and by kiro-cli too, while the Kiro IDE went on working on the +// same account. The plugin called as kiro-cli; it now calls as the Kiro IDE +// 1.4.121 does, with the values read from the IDE's own extension.js: the +// AWS SDK for JavaScript's user agent with the IDE's "KiroIDE-- +// -KAS/ acp-client/kiro-ide" (one machine id per +// install, never a random one per request), origin AI_EDITOR, its +// x-amzn-kiro-* headers, and one conversationId for a whole session. +import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let plugin +beforeAll(async () => { + // Bun reads HOME once, at start: run as HOME=$(mktemp -d) bun test, so + // no real sign-in is ever read or written + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + ;({ KiroAuthPlugin: plugin } = await import("./index.mjs")) +}) +const offline = async () => { throw new Error("no network in tests") } +const real = globalThis.fetch +globalThis.fetch = offline +afterAll(() => (globalThis.fetch = real)) +afterEach(() => (globalThis.fetch = offline)) + +const BUILDER_ID = "arn:aws:codewhisperer:us-east-1:638616132270:profile/AAAACCCCXXXX" +const later = () => Date.now() + 60 * 60_000 +// the reporter's sign-in: Builder ID, made here +const AUTH = { type: "oauth", access: "t", refresh: "r", expires: later(), method: "idc", loginProvider: "BuilderId", region: "us-east-1", + profileArn: BUILDER_ID, clientId: "c", clientSecret: "s", accountId: "student@example.edu" } + +// kiro records each chat call's headers and body, and answers it 500 so +// the request ends there +function kiro() { + const chats = [] + globalThis.fetch = async (input, init = {}) => { + const url = new URL(String(input)) + if (url.pathname === "/generateAssistantResponse") { + chats.push({ headers: Object.fromEntries(Object.entries(init.headers).map(([k, v]) => [k.toLowerCase(), v])), body: JSON.parse(init.body) }) + return new Response(JSON.stringify({ message: "stop here" }), { status: 500 }) + } + throw new Error("unexpected " + url) + } + return chats +} + +const ask = async (headers, content = "hi") => { + const h = await plugin({ client: { auth: { set: async () => {} } } }) + const l = await h.auth.loader(async () => AUTH) + return l.fetch("https://kiro.invalid/v1/messages", { method: "POST", headers, + body: JSON.stringify({ model: "claude-haiku-5.5", messages: [{ role: "user", content }] }) }) +} + +const APP = /^KiroIDE-1\.4\.121-[0-9a-f]{64}-KAS\/0\.66\.89 acp-client\/kiro-ide$/ + +test("a chat call names itself as the Kiro IDE does, the same on every call", async () => { + const chats = kiro() + await ask({ "X-Magpie-Conversation": "s1" }) + await ask({ "X-Magpie-Conversation": "s2" }) + const [a, b] = chats.map((c) => c.headers) + const ua = a["user-agent"] + expect(ua).toMatch(/^aws-sdk-js\/1\.0\.0 ua\/2\.1 os\/[\w.-]+#[\w.#-]+ lang\/js md\/nodejs#24\.22\.1 api\/kiroruntime#1\.0\.0 m\/N /) + expect(ua.slice(ua.indexOf("KiroIDE-"))).toMatch(APP) + expect(a["x-amz-user-agent"].replace(/^aws-sdk-js\/1\.0\.0 /, "")).toMatch(APP) + expect(ua).not.toContain("aws-sdk-rust") + expect(ua).not.toContain("AmazonQ-For-CLI") + // one install, one machine id: no random suffix per request + expect(b["user-agent"]).toBe(ua) + expect(b["x-amz-user-agent"]).toBe(a["x-amz-user-agent"]) + expect(a["x-amzn-kiro-client-attribution"]).toBe("kiro-ide") + expect(a["x-amzn-kiro-agent-mode"]).toBe("vibe") + expect(a["x-amzn-kiro-attempt"]).toBe("1;max=3") + expect(a["amz-sdk-request"]).toBe("attempt=1; max=3") + // the IDE says a Builder ID token's kind + expect(a.tokentype).toBe("SSO_OIDC") + expect(a.authorization).toBe("Bearer t") +}) + +test("a chat call's messages come from the IDE (AI_EDITOR), and the agent mode is a header, not a field", async () => { + const chats = kiro() + await ask({ "X-Magpie-Conversation": "s1" }) + const { body } = chats[0] + expect(body.conversationState.currentMessage.userInputMessage.origin).toBe("AI_EDITOR") + expect(body.conversationState.currentMessage.userInputMessage.modelId).toBe("claude-haiku-5.5") + expect(body.profileArn).toBe(BUILDER_ID) + expect("agentMode" in body).toBe(false) +}) + +test("one session keeps one conversationId; another session, or none, has its own", async () => { + const chats = kiro() + await ask({ "X-Magpie-Conversation": "session-A" }, "first") + await ask(new Headers({ "x-magpie-conversation": "session-A" }), "second") + await ask({ "X-Magpie-Conversation": "session-B" }) + await ask({}) + await ask({}) + const ids = chats.map((c) => c.body.conversationState.conversationId) + for (const id of ids) expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + expect(ids[1]).toBe(ids[0]) + expect(ids[2]).not.toBe(ids[0]) + // a call that names no session is a conversation of its own each time + expect(new Set(ids.slice(2)).size).toBe(3) + // the session's own name never goes to Kiro + for (const c of chats) expect(JSON.stringify(c)).not.toContain("session-A") +}) + +test("magpie's session header names the session when no conversation is said", async () => { + const chats = kiro() + await ask({ "X-Magpie-Session": "named" }) + await ask({ "X-Magpie-Session": "named" }) + expect(chats[1].body.conversationState.conversationId).toBe(chats[0].body.conversationState.conversationId) +}) diff --git a/packages/kiro/index.mjs b/packages/kiro/index.mjs index 3bd2522..a973c40 100644 --- a/packages/kiro/index.mjs +++ b/packages/kiro/index.mjs @@ -21,7 +21,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto" import { execFile } from "node:child_process" import { existsSync, statSync } from "node:fs" import { readFile, rename, writeFile } from "node:fs/promises" -import { homedir, hostname } from "node:os" +import { homedir, hostname, platform, release } from "node:os" import { delimiter, join } from "node:path" const ID = "kiro" @@ -40,7 +40,10 @@ const CALLBACK_PORTS = [3128, 4649, 6588, 8008, 9091, 49153, 50153, 51153, 52153 const SCOPES = ["codewhisperer:completions", "codewhisperer:analysis", "codewhisperer:conversations", "codewhisperer:transformations", "codewhisperer:taskassist"] // how the IDE names itself to Kiro's auth service, and when refreshing -const IDE_UA = "KiroIDE-1.1.70-" + createHash("sha256").update("magpie:" + hostname()).digest("hex") +// MACHINE_ID stands where the IDE puts its machine id (node-machine-id's +// sha256): one per install, the same on every call. +const MACHINE_ID = createHash("sha256").update("magpie:" + hostname()).digest("hex") +const IDE_UA = "KiroIDE-1.1.70-" + MACHINE_ID const DESKTOP_UA = "Kiro-Desktop/0.2.13 (darwin; arm64)" const SIGN_IN_TIMEOUT = 10 * 60 * 1000 // A Builder ID sign-in has no profile of its own, and Kiro won't list one @@ -704,7 +707,7 @@ function account(client) { // kiro-cli names no profile in an API key's calls, even one GetProfile // found; the profile only says the key's region const profile = c.method === "apikey" ? "" : c.profile - const a = { token: c.access, tokenType: tokenType(c), profile, region: regionOf(c.profile, c.region) } + const a = { token: c.access, tokenType: tokenType(c), idc: c.method === "idc", profile, region: regionOf(c.profile, c.region) } if (!twoRegions(c) || st.builderID || !c.profiles) return a // the first enabled region with credits left, in CREDIT_REGIONS' order const now = Date.now() @@ -1067,14 +1070,14 @@ function inputSchema(s) { // buildKiro is the body of a generateAssistantResponse call, as it is // before its images are fitted (kiroBody). -function buildKiro(req, model, profile, budget) { - return JSON.stringify(kiroRequest(req, model, profile, budget)) +function buildKiro(req, model, profile, budget, conversation) { + return JSON.stringify(kiroRequest(req, model, profile, budget, conversation)) } // kiroBody is the body sent: buildKiro's, with every image it keeps under // Kiro's size limit. -async function kiroBody(req, model, profile, budget) { - return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget))) +async function kiroBody(req, model, profile, budget, conversation) { + return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget, conversation))) } // UNDERSTOOD is the reply Kiro IDE puts in its history where a turn has @@ -1105,7 +1108,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) { +function kiroRequest(req, model, profile, budget, conversation) { 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) @@ -1113,7 +1116,7 @@ function kiroRequest(req, model, profile, budget) { const mark = (msg, parts) => { if (parts.some((p) => p?.cache_control)) marked.add(msg) } - const user = () => ({ content: "", modelId: model, origin: "KIRO_CLI" }) + const user = () => ({ content: "", modelId: model, origin: "AI_EDITOR" }) const resultsOnly = new WeakSet() // the messages made to carry a reply's web search results for (const m of contextFirst(req.messages ?? [])) { const parts = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content ?? [] @@ -1294,31 +1297,76 @@ function kiroRequest(req, model, profile, budget) { } for (const drop of points.slice(0, Math.max(0, points.length - 4))) drop() - const state = { chatTriggerType: "MANUAL", agentTaskType: "vibe", conversationId: randomUUID(), currentMessage: { userInputMessage: current } } + const state = { chatTriggerType: "MANUAL", agentTaskType: "vibe", conversationId: conversationID(conversation), currentMessage: { userInputMessage: current } } if (entries.length > 1) state.history = entries.slice(0, -1) - const out = { conversationState: state, agentMode: "vibe" } + // the agent mode goes as a header (x-amzn-kiro-agent-mode), as the IDE's + // client binds it, not in the body + const out = { conversationState: state } if (profile) out.profileArn = profile if (native) out.additionalModelRequestFields = native return out } -// sdkHeaders are the AWS SDK's headers on a call to Kiro's runtime, as -// kiro-cli's client sends them: who is calling, and as which client. +// conversationID is the conversationId of a chat call. The IDE keeps one +// for a whole conversation; the plugin keeps one for the caller's session +// (magpie's X-Magpie-Conversation), the same id on each turn of it, and a +// new one when it can't tell the session. +function conversationID(key) { + if (!key) return randomUUID() + const h = createHash("sha256").update("kiro-conversation:" + key).digest("hex") + return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${"89ab"[parseInt(h[16], 16) & 3]}${h.slice(17, 20)}-${h.slice(20, 32)}` +} + +// the headers that name the caller's session, the first one sent +const SESSION_HEADERS = ["x-magpie-conversation", "x-magpie-session", "x-opencode-session"] +function sessionOf(input, init) { + const sets = [init?.headers, input instanceof Request ? input.headers : undefined] + for (const name of SESSION_HEADERS) + for (const h of sets) { + if (!h) continue + const v = h instanceof Headers ? h.get(name) + : Array.isArray(h) ? h.find(([k]) => k.toLowerCase() === name)?.[1] + : Object.entries(h).find(([k]) => k.toLowerCase() === name)?.[1] + if (v) return String(v) + } + return "" +} + +// What Kiro IDE 1.4.121 (its agent, KAS 0.66.89, on Electron 44's Node +// 24.22.1) sends on a chat call, read from the IDE's own extension.js. Its +// KiroRuntime client (@amzn/kiro-runtime-service-typescript-client 1.0.0) +// is the AWS SDK for JavaScript's: the SDK's user agent, m/N for the +// endpoint the IDE names itself, then the IDE's own "KiroIDE +// " with KAS/ and acp-client/kiro-ide, spaces made +// "-". Its retry budget is 3 tries at a conversation's start, said in +// amz-sdk-request and x-amzn-kiro-attempt; the plugin tries once. +const IDE_VERSION = "1.4.121" +const IDE_KAS = "0.66.89" +const IDE_NODE = "24.22.1" +const IDE_APP = `KiroIDE-${IDE_VERSION}-${MACHINE_ID}-KAS/${IDE_KAS} acp-client/kiro-ide` +const sdkPart = (s) => String(s).replace(/[^!$%&'*+\-.^_`|~\w#]/g, "-") +const IDE_SDK_UA = `aws-sdk-js/1.0.0 ua/2.1 os/${sdkPart(platform())}#${sdkPart(release())} lang/js md/nodejs#${IDE_NODE} api/kiroruntime#1.0.0 m/N ${IDE_APP}` + +// sdkHeaders are the AWS SDK's headers on a call to Kiro's runtime, as the +// Kiro IDE's client sends them: who is calling, and as which client. The +// IDE names a Builder ID or Identity Center token's kind (SSO_OIDC) too. function sdkHeaders(a) { - const ua = `aws-sdk-rust/1.0.0 ua/2.1 os/other lang/rust api/codewhispererstreaming#1.28.3 m/E app/AmazonQ-For-CLI md/appVersion-1.28.3-${randomUUID().replaceAll("-", "")}` - return { + const h = { ...authHeaders(a), "amz-sdk-invocation-id": randomUUID(), - "amz-sdk-request": "attempt=1; max=1", - "x-amz-user-agent": ua, - "User-Agent": ua, + "amz-sdk-request": "attempt=1; max=3", + "x-amz-user-agent": `aws-sdk-js/1.0.0 ${IDE_APP}`, + "User-Agent": IDE_SDK_UA, + "x-amzn-kiro-client-attribution": "kiro-ide", } + if (!a.tokenType && a.idc) h.tokentype = "SSO_OIDC" + return h } function sendKiro(a, body, signal) { return fetch(runtime(a.region) + "/generateAssistantResponse", { method: "POST", - headers: { ...sdkHeaders(a), "x-amzn-codewhisperer-optout": "true", "x-amzn-kiro-agent-mode": "vibe", + headers: { ...sdkHeaders(a), "x-amzn-kiro-attempt": "1;max=3", "x-amzn-codewhisperer-optout": "true", "x-amzn-kiro-agent-mode": "vibe", "Content-Type": "application/json", Accept: "application/vnd.amazon.eventstream" }, body, signal, @@ -2052,20 +2100,20 @@ function searchAnswer(text, hosted) { // refreshed, when Kiro turns the token down (403). As the built-in: no // credentials is a 401, a failed refresh after the 403 a 502; none marks // the account. -async function generate(creds, auth, req, signal) { +async function generate(creds, auth, req, signal, conversation) { const model = String(req.model ?? "auto") const budget = thinking(req, model) const hosted = hostedSearch(req) if (hosted?.error) return errorResponse(400, hosted.error) - const first = await ask(creds, auth, req, model, budget, signal) + 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) : events(first.res.body, model, budget) + const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget) return kept(await reply(it, model, req.stream === true, toolNames(req))) } // ask sends one turn to Kiro: { res, a }, a 200, or the { status, message } // of a failure. -async function ask(creds, auth, req, model, budget, signal) { +async function ask(creds, auth, req, model, budget, signal, conversation) { let a try { a = await creds(auth) @@ -2074,7 +2122,7 @@ async function ask(creds, auth, req, model, budget, signal) { } let res try { - res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal) + res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal) } catch (e) { if (e?.name === "AbortError") throw e return { status: 502, message: e.message } @@ -2087,7 +2135,7 @@ async function ask(creds, auth, req, model, budget, signal) { return { status: 502, message: e.message } } try { - res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal) + res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal) } catch (e) { if (e?.name === "AbortError") throw e return { status: 502, message: e.message } @@ -2112,7 +2160,7 @@ async function ask(creds, auth, req, model, budget, signal) { if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait } a = next try { - res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal) + res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal) } catch (e) { if (e?.name === "AbortError") throw e return { status: 502, message: e.message } @@ -2142,7 +2190,7 @@ const aborted = () => Object.assign(new Error("the request was cancelled"), { na // caller's (passed on as ever, the searches of its turn with it), or has // taken hosted.uses + 2 turns (pause_turn, which the caller may send back // to go on). Searches past hosted.uses are max_uses_exceeded. -async function* searching(creds, auth, req, model, budget, signal, hosted, first) { +async function* searching(creds, auth, req, model, budget, signal, hosted, first, conversation) { let { res, a } = first const messages = [...(req.messages ?? [])] const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reported: false, searches: 0 } @@ -2254,7 +2302,7 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first return } messages.push({ role: "assistant", content: said }) - const next = await ask(creds, auth, { ...req, messages }, model, budget, signal) + const next = await ask(creds, auth, { ...req, messages }, model, budget, signal, conversation) if (!next.res) { yield { kind: "error", status: next.status, text: `Kiro, after its web search: ${next.message} (${next.status})` } return @@ -2598,7 +2646,7 @@ export async function KiroAuthPlugin({ client } = {}) { } catch { return errorResponse(400, "a request that isn't JSON") } - return generate(creds, (await getAuth()) ?? auth, req, init.signal) + return generate(creds, (await getAuth()) ?? auth, req, init.signal, sessionOf(input, init)) }, } },