@magpie-community/opencode-kiro-auth 0.1.30 → 0.1.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.mjs +81 -30
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -21,7 +21,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto"
21
21
  import { execFile } from "node:child_process"
22
22
  import { existsSync, statSync } from "node:fs"
23
23
  import { readFile, rename, writeFile } from "node:fs/promises"
24
- import { homedir, hostname } from "node:os"
24
+ import { homedir, hostname, platform, release } from "node:os"
25
25
  import { delimiter, join } from "node:path"
26
26
 
27
27
  const ID = "kiro"
@@ -40,7 +40,10 @@ const CALLBACK_PORTS = [3128, 4649, 6588, 8008, 9091, 49153, 50153, 51153, 52153
40
40
  const SCOPES = ["codewhisperer:completions", "codewhisperer:analysis", "codewhisperer:conversations",
41
41
  "codewhisperer:transformations", "codewhisperer:taskassist"]
42
42
  // how the IDE names itself to Kiro's auth service, and when refreshing
43
- const IDE_UA = "KiroIDE-1.1.70-" + createHash("sha256").update("magpie:" + hostname()).digest("hex")
43
+ // MACHINE_ID stands where the IDE puts its machine id (node-machine-id's
44
+ // sha256): one per install, the same on every call.
45
+ const MACHINE_ID = createHash("sha256").update("magpie:" + hostname()).digest("hex")
46
+ const IDE_UA = "KiroIDE-1.1.70-" + MACHINE_ID
44
47
  const DESKTOP_UA = "Kiro-Desktop/0.2.13 (darwin; arm64)"
45
48
  const SIGN_IN_TIMEOUT = 10 * 60 * 1000
46
49
  // A Builder ID sign-in has no profile of its own, and Kiro won't list one
@@ -704,7 +707,7 @@ function account(client) {
704
707
  // kiro-cli names no profile in an API key's calls, even one GetProfile
705
708
  // found; the profile only says the key's region
706
709
  const profile = c.method === "apikey" ? "" : c.profile
707
- const a = { token: c.access, tokenType: tokenType(c), profile, region: regionOf(c.profile, c.region) }
710
+ const a = { token: c.access, tokenType: tokenType(c), idc: c.method === "idc", profile, region: regionOf(c.profile, c.region) }
708
711
  if (!twoRegions(c) || st.builderID || !c.profiles) return a
709
712
  // the first enabled region with credits left, in CREDIT_REGIONS' order
710
713
  const now = Date.now()
@@ -1067,14 +1070,14 @@ function inputSchema(s) {
1067
1070
 
1068
1071
  // buildKiro is the body of a generateAssistantResponse call, as it is
1069
1072
  // before its images are fitted (kiroBody).
1070
- function buildKiro(req, model, profile, budget) {
1071
- return JSON.stringify(kiroRequest(req, model, profile, budget))
1073
+ function buildKiro(req, model, profile, budget, conversation) {
1074
+ return JSON.stringify(kiroRequest(req, model, profile, budget, conversation))
1072
1075
  }
1073
1076
 
1074
1077
  // kiroBody is the body sent: buildKiro's, with every image it keeps under
1075
1078
  // Kiro's size limit.
1076
- async function kiroBody(req, model, profile, budget) {
1077
- return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget)))
1079
+ async function kiroBody(req, model, profile, budget, conversation) {
1080
+ return JSON.stringify(await fitImages(kiroRequest(req, model, profile, budget, conversation)))
1078
1081
  }
1079
1082
 
1080
1083
  // UNDERSTOOD is the reply Kiro IDE puts in its history where a turn has
@@ -1105,7 +1108,7 @@ function contextFirst(messages) {
1105
1108
  return [...messages.slice(0, start), ...context.map((m) => ({ ...m, role: "user" })), { role: "assistant", content: UNDERSTOOD }, ...turn]
1106
1109
  }
1107
1110
 
1108
- function kiroRequest(req, model, profile, budget) {
1111
+ function kiroRequest(req, model, profile, budget, conversation) {
1109
1112
  const entries = []
1110
1113
  // the messages the caller marked for its prompt cache (cache_control),
1111
1114
  // 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) {
1113
1116
  const mark = (msg, parts) => {
1114
1117
  if (parts.some((p) => p?.cache_control)) marked.add(msg)
1115
1118
  }
1116
- const user = () => ({ content: "", modelId: model, origin: "KIRO_CLI" })
1119
+ const user = () => ({ content: "", modelId: model, origin: "AI_EDITOR" })
1117
1120
  const resultsOnly = new WeakSet() // the messages made to carry a reply's web search results
1118
1121
  for (const m of contextFirst(req.messages ?? [])) {
1119
1122
  const parts = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content ?? []
@@ -1294,31 +1297,76 @@ function kiroRequest(req, model, profile, budget) {
1294
1297
  }
1295
1298
  for (const drop of points.slice(0, Math.max(0, points.length - 4))) drop()
1296
1299
 
1297
- const state = { chatTriggerType: "MANUAL", agentTaskType: "vibe", conversationId: randomUUID(), currentMessage: { userInputMessage: current } }
1300
+ const state = { chatTriggerType: "MANUAL", agentTaskType: "vibe", conversationId: conversationID(conversation), currentMessage: { userInputMessage: current } }
1298
1301
  if (entries.length > 1) state.history = entries.slice(0, -1)
1299
- const out = { conversationState: state, agentMode: "vibe" }
1302
+ // the agent mode goes as a header (x-amzn-kiro-agent-mode), as the IDE's
1303
+ // client binds it, not in the body
1304
+ const out = { conversationState: state }
1300
1305
  if (profile) out.profileArn = profile
1301
1306
  if (native) out.additionalModelRequestFields = native
1302
1307
  return out
1303
1308
  }
1304
1309
 
1305
- // sdkHeaders are the AWS SDK's headers on a call to Kiro's runtime, as
1306
- // kiro-cli's client sends them: who is calling, and as which client.
1310
+ // conversationID is the conversationId of a chat call. The IDE keeps one
1311
+ // for a whole conversation; the plugin keeps one for the caller's session
1312
+ // (magpie's X-Magpie-Conversation), the same id on each turn of it, and a
1313
+ // new one when it can't tell the session.
1314
+ function conversationID(key) {
1315
+ if (!key) return randomUUID()
1316
+ const h = createHash("sha256").update("kiro-conversation:" + key).digest("hex")
1317
+ 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)}`
1318
+ }
1319
+
1320
+ // the headers that name the caller's session, the first one sent
1321
+ const SESSION_HEADERS = ["x-magpie-conversation", "x-magpie-session", "x-opencode-session"]
1322
+ function sessionOf(input, init) {
1323
+ const sets = [init?.headers, input instanceof Request ? input.headers : undefined]
1324
+ for (const name of SESSION_HEADERS)
1325
+ for (const h of sets) {
1326
+ if (!h) continue
1327
+ const v = h instanceof Headers ? h.get(name)
1328
+ : Array.isArray(h) ? h.find(([k]) => k.toLowerCase() === name)?.[1]
1329
+ : Object.entries(h).find(([k]) => k.toLowerCase() === name)?.[1]
1330
+ if (v) return String(v)
1331
+ }
1332
+ return ""
1333
+ }
1334
+
1335
+ // What Kiro IDE 1.4.121 (its agent, KAS 0.66.89, on Electron 44's Node
1336
+ // 24.22.1) sends on a chat call, read from the IDE's own extension.js. Its
1337
+ // KiroRuntime client (@amzn/kiro-runtime-service-typescript-client 1.0.0)
1338
+ // is the AWS SDK for JavaScript's: the SDK's user agent, m/N for the
1339
+ // endpoint the IDE names itself, then the IDE's own "KiroIDE <version>
1340
+ // <machine id>" with KAS/<version> and acp-client/kiro-ide, spaces made
1341
+ // "-". Its retry budget is 3 tries at a conversation's start, said in
1342
+ // amz-sdk-request and x-amzn-kiro-attempt; the plugin tries once.
1343
+ const IDE_VERSION = "1.4.121"
1344
+ const IDE_KAS = "0.66.89"
1345
+ const IDE_NODE = "24.22.1"
1346
+ const IDE_APP = `KiroIDE-${IDE_VERSION}-${MACHINE_ID}-KAS/${IDE_KAS} acp-client/kiro-ide`
1347
+ const sdkPart = (s) => String(s).replace(/[^!$%&'*+\-.^_`|~\w#]/g, "-")
1348
+ 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}`
1349
+
1350
+ // sdkHeaders are the AWS SDK's headers on a call to Kiro's runtime, as the
1351
+ // Kiro IDE's client sends them: who is calling, and as which client. The
1352
+ // IDE names a Builder ID or Identity Center token's kind (SSO_OIDC) too.
1307
1353
  function sdkHeaders(a) {
1308
- 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("-", "")}`
1309
- return {
1354
+ const h = {
1310
1355
  ...authHeaders(a),
1311
1356
  "amz-sdk-invocation-id": randomUUID(),
1312
- "amz-sdk-request": "attempt=1; max=1",
1313
- "x-amz-user-agent": ua,
1314
- "User-Agent": ua,
1357
+ "amz-sdk-request": "attempt=1; max=3",
1358
+ "x-amz-user-agent": `aws-sdk-js/1.0.0 ${IDE_APP}`,
1359
+ "User-Agent": IDE_SDK_UA,
1360
+ "x-amzn-kiro-client-attribution": "kiro-ide",
1315
1361
  }
1362
+ if (!a.tokenType && a.idc) h.tokentype = "SSO_OIDC"
1363
+ return h
1316
1364
  }
1317
1365
 
1318
1366
  function sendKiro(a, body, signal) {
1319
1367
  return fetch(runtime(a.region) + "/generateAssistantResponse", {
1320
1368
  method: "POST",
1321
- headers: { ...sdkHeaders(a), "x-amzn-codewhisperer-optout": "true", "x-amzn-kiro-agent-mode": "vibe",
1369
+ headers: { ...sdkHeaders(a), "x-amzn-kiro-attempt": "1;max=3", "x-amzn-codewhisperer-optout": "true", "x-amzn-kiro-agent-mode": "vibe",
1322
1370
  "Content-Type": "application/json", Accept: "application/vnd.amazon.eventstream" },
1323
1371
  body,
1324
1372
  signal,
@@ -1600,10 +1648,13 @@ async function* events(body, model, budget) {
1600
1648
  if (budget) yield* think.feed(text)
1601
1649
  else if (text) yield { kind: "text", text }
1602
1650
  } else if (kind === "reasoningContentEvent") {
1651
+ // one event may carry the reasoning and its signature together (auto,
1652
+ // called as the IDE): the signature goes on the block it ends
1603
1653
  if (m.text) {
1604
1654
  said += m.text.length
1605
1655
  yield { kind: "think", text: m.text }
1606
- } else if (m.signature) yield { kind: "sig", text: m.signature }
1656
+ }
1657
+ if (m.signature) yield { kind: "sig", text: m.signature }
1607
1658
  } else if (kind === "toolUseEvent") {
1608
1659
  if (m.toolUseId && m.toolUseId !== tool) {
1609
1660
  yield* think.end() // the text before a call is all said
@@ -2052,20 +2103,20 @@ function searchAnswer(text, hosted) {
2052
2103
  // refreshed, when Kiro turns the token down (403). As the built-in: no
2053
2104
  // credentials is a 401, a failed refresh after the 403 a 502; none marks
2054
2105
  // the account.
2055
- async function generate(creds, auth, req, signal) {
2106
+ async function generate(creds, auth, req, signal, conversation) {
2056
2107
  const model = String(req.model ?? "auto")
2057
2108
  const budget = thinking(req, model)
2058
2109
  const hosted = hostedSearch(req)
2059
2110
  if (hosted?.error) return errorResponse(400, hosted.error)
2060
- const first = await ask(creds, auth, req, model, budget, signal)
2111
+ const first = await ask(creds, auth, req, model, budget, signal, conversation)
2061
2112
  if (!first.res) return errorResponse(first.status, first.message, first.wait)
2062
- const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first) : events(first.res.body, model, budget)
2113
+ const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget)
2063
2114
  return kept(await reply(it, model, req.stream === true, toolNames(req)))
2064
2115
  }
2065
2116
 
2066
2117
  // ask sends one turn to Kiro: { res, a }, a 200, or the { status, message }
2067
2118
  // of a failure.
2068
- async function ask(creds, auth, req, model, budget, signal) {
2119
+ async function ask(creds, auth, req, model, budget, signal, conversation) {
2069
2120
  let a
2070
2121
  try {
2071
2122
  a = await creds(auth)
@@ -2074,7 +2125,7 @@ async function ask(creds, auth, req, model, budget, signal) {
2074
2125
  }
2075
2126
  let res
2076
2127
  try {
2077
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal)
2128
+ res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2078
2129
  } catch (e) {
2079
2130
  if (e?.name === "AbortError") throw e
2080
2131
  return { status: 502, message: e.message }
@@ -2087,7 +2138,7 @@ async function ask(creds, auth, req, model, budget, signal) {
2087
2138
  return { status: 502, message: e.message }
2088
2139
  }
2089
2140
  try {
2090
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal)
2141
+ res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2091
2142
  } catch (e) {
2092
2143
  if (e?.name === "AbortError") throw e
2093
2144
  return { status: 502, message: e.message }
@@ -2112,7 +2163,7 @@ async function ask(creds, auth, req, model, budget, signal) {
2112
2163
  if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
2113
2164
  a = next
2114
2165
  try {
2115
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget), signal)
2166
+ res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2116
2167
  } catch (e) {
2117
2168
  if (e?.name === "AbortError") throw e
2118
2169
  return { status: 502, message: e.message }
@@ -2142,7 +2193,7 @@ const aborted = () => Object.assign(new Error("the request was cancelled"), { na
2142
2193
  // caller's (passed on as ever, the searches of its turn with it), or has
2143
2194
  // taken hosted.uses + 2 turns (pause_turn, which the caller may send back
2144
2195
  // to go on). Searches past hosted.uses are max_uses_exceeded.
2145
- async function* searching(creds, auth, req, model, budget, signal, hosted, first) {
2196
+ async function* searching(creds, auth, req, model, budget, signal, hosted, first, conversation) {
2146
2197
  let { res, a } = first
2147
2198
  const messages = [...(req.messages ?? [])]
2148
2199
  const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reported: false, searches: 0 }
@@ -2254,7 +2305,7 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
2254
2305
  return
2255
2306
  }
2256
2307
  messages.push({ role: "assistant", content: said })
2257
- const next = await ask(creds, auth, { ...req, messages }, model, budget, signal)
2308
+ const next = await ask(creds, auth, { ...req, messages }, model, budget, signal, conversation)
2258
2309
  if (!next.res) {
2259
2310
  yield { kind: "error", status: next.status, text: `Kiro, after its web search: ${next.message} (${next.status})` }
2260
2311
  return
@@ -2598,7 +2649,7 @@ export async function KiroAuthPlugin({ client } = {}) {
2598
2649
  } catch {
2599
2650
  return errorResponse(400, "a request that isn't JSON")
2600
2651
  }
2601
- return generate(creds, (await getAuth()) ?? auth, req, init.signal)
2652
+ return generate(creds, (await getAuth()) ?? auth, req, init.signal, sessionOf(input, init))
2602
2653
  },
2603
2654
  }
2604
2655
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-kiro-auth",
3
- "version": "0.1.30",
3
+ "version": "0.1.31",
4
4
  "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",