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

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 (3) hide show
  1. package/index.mjs +81 -13
  2. package/opencode2.mjs +0 -1
  3. package/package.json +1 -1
package/index.mjs CHANGED
@@ -1338,8 +1338,8 @@ function sessionOf(input, init) {
1338
1338
  // is the AWS SDK for JavaScript's: the SDK's user agent, m/N for the
1339
1339
  // endpoint the IDE names itself, then the IDE's own "KiroIDE <version>
1340
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.
1341
+ // "-". Its retry budget is 3 tries, said in amz-sdk-request and
1342
+ // x-amzn-kiro-attempt, which count up on each (see paced).
1343
1343
  const IDE_VERSION = "1.4.121"
1344
1344
  const IDE_KAS = "0.66.89"
1345
1345
  const IDE_NODE = "24.22.1"
@@ -1350,11 +1350,11 @@ const IDE_SDK_UA = `aws-sdk-js/1.0.0 ua/2.1 os/${sdkPart(platform())}#${sdkPart(
1350
1350
  // sdkHeaders are the AWS SDK's headers on a call to Kiro's runtime, as the
1351
1351
  // Kiro IDE's client sends them: who is calling, and as which client. The
1352
1352
  // IDE names a Builder ID or Identity Center token's kind (SSO_OIDC) too.
1353
- function sdkHeaders(a) {
1353
+ function sdkHeaders(a, attempt = 1, invocation = randomUUID()) {
1354
1354
  const h = {
1355
1355
  ...authHeaders(a),
1356
- "amz-sdk-invocation-id": randomUUID(),
1357
- "amz-sdk-request": "attempt=1; max=3",
1356
+ "amz-sdk-invocation-id": invocation,
1357
+ "amz-sdk-request": `attempt=${attempt}; max=${TRIES}`,
1358
1358
  "x-amz-user-agent": `aws-sdk-js/1.0.0 ${IDE_APP}`,
1359
1359
  "User-Agent": IDE_SDK_UA,
1360
1360
  "x-amzn-kiro-client-attribution": "kiro-ide",
@@ -1363,16 +1363,77 @@ function sdkHeaders(a) {
1363
1363
  return h
1364
1364
  }
1365
1365
 
1366
- function sendKiro(a, body, signal) {
1366
+ function sendKiro(a, body, signal, attempt = 1, invocation) {
1367
1367
  return fetch(runtime(a.region) + "/generateAssistantResponse", {
1368
1368
  method: "POST",
1369
- headers: { ...sdkHeaders(a), "x-amzn-kiro-attempt": "1;max=3", "x-amzn-codewhisperer-optout": "true", "x-amzn-kiro-agent-mode": "vibe",
1370
- "Content-Type": "application/json", Accept: "application/vnd.amazon.eventstream" },
1369
+ headers: { ...sdkHeaders(a, attempt, invocation), "x-amzn-kiro-attempt": `${attempt};max=${TRIES}`, "x-amzn-codewhisperer-optout": "true",
1370
+ "x-amzn-kiro-agent-mode": "vibe", "Content-Type": "application/json", Accept: "application/vnd.amazon.eventstream" },
1371
1371
  body,
1372
1372
  signal,
1373
1373
  })
1374
1374
  }
1375
1375
 
1376
+ // TRIES is the Kiro IDE's tries of one chat call (its QClientRetryStrategy,
1377
+ // agent 1.1.787, QAf), the first included.
1378
+ const TRIES = 3
1379
+ // PACE is the IDE's pause before the nth try after a throttle (its
1380
+ // throttling backoff: 1s doubling, 20% either way, at most 20s), unless
1381
+ // Kiro said how long (retryAfterMilliseconds and the like).
1382
+ const PACE = { base: 1000, jitter: 0.2, max: 20_000 }
1383
+ const paceOf = (n) => Math.min(PACE.max, PACE.base * 2 ** (n - 1)) * (1 - PACE.jitter + Math.random() * 2 * PACE.jitter)
1384
+ // THROTTLES are the reasons the IDE takes a 429 for a throttle it waits
1385
+ // out and tries again (its C1p and ServiceThrottleError): a throttle
1386
+ // Kiro gives no reason for is one too. A daily, monthly or usage limit
1387
+ // is not (usedUpSaid), nor is INSUFFICIENT_MODEL_CAPACITY.
1388
+ const THROTTLES = new Set(["USER_REQUEST_RATE_EXCEEDED", "CREDIT_CONSUMPTION_RATE_EXCEEDED", "SERVICE_REQUEST_RATE_EXCEEDED"])
1389
+ function throttleSaid(text) {
1390
+ let e = {}
1391
+ try {
1392
+ e = JSON.parse(text) ?? {}
1393
+ } catch {}
1394
+ if (e.reason) return THROTTLES.has(e.reason)
1395
+ return !usedUpSaid(text) && !/INSUFFICIENT_MODEL_CAPACITY/.test(text) && /too many requests|throttl/i.test(text)
1396
+ }
1397
+
1398
+ // timing is how the plugin waits; tests make it instant.
1399
+ const timing = {
1400
+ sleep: (ms, signal) =>
1401
+ new Promise((resolve, reject) => {
1402
+ if (signal?.aborted) return reject(aborted())
1403
+ const t = setTimeout(() => {
1404
+ signal?.removeEventListener("abort", stop)
1405
+ resolve()
1406
+ }, ms)
1407
+ const stop = () => {
1408
+ clearTimeout(t)
1409
+ reject(aborted())
1410
+ }
1411
+ signal?.addEventListener("abort", stop, { once: true })
1412
+ }),
1413
+ }
1414
+
1415
+ // paced is sendKiro as the Kiro IDE sends a chat call: a 429 throttle is
1416
+ // waited out and tried again, up to TRIES in all, each try said in
1417
+ // amz-sdk-request and x-amzn-kiro-attempt under one invocation id. The
1418
+ // IDE answers its own USER_REQUEST_RATE_EXCEEDED so ("Retrying in N
1419
+ // seconds"), which is why a burst it rides out reached magpie's agent
1420
+ // as a 429 (onemezao on Discord). A wait Kiro says is longer than PACE.max
1421
+ // isn't held here: the 429 goes back with it, for magpie to rest the
1422
+ // account. The answer of the last try is the answer.
1423
+ async function paced(a, body, signal) {
1424
+ const invocation = randomUUID()
1425
+ for (let n = 1; ; n++) {
1426
+ const res = await sendKiro(a, body, signal, n, invocation)
1427
+ if (res.status !== 429 || n >= TRIES) return res
1428
+ const text = (await res.text()).slice(0, 1 << 20)
1429
+ const again = () => new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
1430
+ if (!throttleSaid(text)) return again()
1431
+ const said = saidWait(res.headers, text)
1432
+ if (said > PACE.max) return again()
1433
+ await timing.sleep(said ?? paceOf(n), signal)
1434
+ }
1435
+ }
1436
+
1376
1437
  // tooLongSaid is whether Kiro's words say the conversation is past the
1377
1438
  // model's window: its ValidationException "Input is too long." with reason
1378
1439
  // CONTENT_LENGTH_EXCEEDS_THRESHOLD, as an HTTP answer or as an exception
@@ -1447,6 +1508,14 @@ const requestID = (headers) => headers.get("x-amzn-requestid") || headers.get("x
1447
1508
  // seconds or as a date. Unsaid, magpie keeps to its own pauses, but for
1448
1509
  // an account's request rate (USER_RATE_WAIT).
1449
1510
  function waitOf(headers, body) {
1511
+ let w = saidWait(headers, body)
1512
+ if (w === undefined && String(body ?? "").includes(USER_RATE)) w = USER_RATE_WAIT
1513
+ return w
1514
+ }
1515
+
1516
+ // saidWait is the wait Kiro itself said, if any (waitOf, but none of
1517
+ // magpie's own).
1518
+ function saidWait(headers, body) {
1450
1519
  const ms = (v) => {
1451
1520
  const n = v == null || v === "" ? NaN : Number(v)
1452
1521
  return Number.isFinite(n) && n > 0 ? n : undefined
@@ -1461,7 +1530,6 @@ function waitOf(headers, body) {
1461
1530
  const secs = ms(ra)
1462
1531
  w = secs !== undefined ? secs * 1000 : ms(Date.parse(ra) - Date.now())
1463
1532
  }
1464
- if (w === undefined && String(body ?? "").includes(USER_RATE)) w = USER_RATE_WAIT
1465
1533
  return w
1466
1534
  }
1467
1535
 
@@ -2125,7 +2193,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2125
2193
  }
2126
2194
  let res
2127
2195
  try {
2128
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2196
+ res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2129
2197
  } catch (e) {
2130
2198
  if (e?.name === "AbortError") throw e
2131
2199
  return { status: 502, message: e.message }
@@ -2138,7 +2206,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2138
2206
  return { status: 502, message: e.message }
2139
2207
  }
2140
2208
  try {
2141
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2209
+ res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2142
2210
  } catch (e) {
2143
2211
  if (e?.name === "AbortError") throw e
2144
2212
  return { status: 502, message: e.message }
@@ -2163,7 +2231,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2163
2231
  if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
2164
2232
  a = next
2165
2233
  try {
2166
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2234
+ res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2167
2235
  } catch (e) {
2168
2236
  if (e?.name === "AbortError") throw e
2169
2237
  return { status: 502, message: e.message }
@@ -2735,4 +2803,4 @@ export async function KiroAuthPlugin({ client } = {}) {
2735
2803
  }
2736
2804
 
2737
2805
  // for tests
2738
- export const _internal = { generate, waitOf, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames }
2806
+ export const _internal = { generate, waitOf, timing, TRIES, refresh, usageOf, buildKiro, kiroBody, IMAGE_LIMIT, events, reply, failure, toolID, toolName, toolNames, thinking, nativeFields, listModels, contextFirst, configModel, runtimeModel, readCLI, readIDE, regionOf, planName, frames }
package/opencode2.mjs CHANGED
@@ -85,7 +85,6 @@ export function fieldsOf(prompts) {
85
85
  if (p.placeholder) f.placeholder = String(p.placeholder)
86
86
  if (p.type === "select" && Array.isArray(p.options))
87
87
  f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
88
- // a prompt shown only when another answer says so can't be required
89
88
  // a prompt shown only when another answer says so can't be required, and
90
89
  // neither can one whose own validate() accepts an empty answer (the
91
90
  // browser sign-in's optional API key)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-kiro-auth",
3
- "version": "0.1.31",
3
+ "version": "0.1.32",
4
4
  "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",