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

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 +430 -32
  2. package/opencode2.mjs +0 -1
  3. package/package.json +1 -1
package/index.mjs CHANGED
@@ -15,7 +15,9 @@
15
15
  // Messages, and the fetch here sends each request whole to Kiro's own API
16
16
  // (runtime.<region>.kiro.dev/generateAssistantResponse, the one kiro-cli
17
17
  // talks to) as a conversation, and turns the AWS event stream it answers
18
- // with back into Messages' events.
18
+ // with back into Messages' events. An account Kiro has put on its
19
+ // CreateResponse experiment is asked as the Kiro IDE asks it then
20
+ // (/v1/responses, answered with server-sent events; see createResponse).
19
21
  import { createServer } from "node:http"
20
22
  import { createHash, randomBytes, randomUUID } from "node:crypto"
21
23
  import { execFile } from "node:child_process"
@@ -1338,8 +1340,8 @@ function sessionOf(input, init) {
1338
1340
  // is the AWS SDK for JavaScript's: the SDK's user agent, m/N for the
1339
1341
  // endpoint the IDE names itself, then the IDE's own "KiroIDE <version>
1340
1342
  // <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
+ // "-". Its retry budget is 3 tries, said in amz-sdk-request and
1344
+ // x-amzn-kiro-attempt, which count up on each (see paced).
1343
1345
  const IDE_VERSION = "1.4.121"
1344
1346
  const IDE_KAS = "0.66.89"
1345
1347
  const IDE_NODE = "24.22.1"
@@ -1350,11 +1352,11 @@ const IDE_SDK_UA = `aws-sdk-js/1.0.0 ua/2.1 os/${sdkPart(platform())}#${sdkPart(
1350
1352
  // sdkHeaders are the AWS SDK's headers on a call to Kiro's runtime, as the
1351
1353
  // Kiro IDE's client sends them: who is calling, and as which client. The
1352
1354
  // IDE names a Builder ID or Identity Center token's kind (SSO_OIDC) too.
1353
- function sdkHeaders(a) {
1355
+ function sdkHeaders(a, attempt = 1, invocation = randomUUID()) {
1354
1356
  const h = {
1355
1357
  ...authHeaders(a),
1356
- "amz-sdk-invocation-id": randomUUID(),
1357
- "amz-sdk-request": "attempt=1; max=3",
1358
+ "amz-sdk-invocation-id": invocation,
1359
+ "amz-sdk-request": `attempt=${attempt}; max=${TRIES}`,
1358
1360
  "x-amz-user-agent": `aws-sdk-js/1.0.0 ${IDE_APP}`,
1359
1361
  "User-Agent": IDE_SDK_UA,
1360
1362
  "x-amzn-kiro-client-attribution": "kiro-ide",
@@ -1363,16 +1365,390 @@ function sdkHeaders(a) {
1363
1365
  return h
1364
1366
  }
1365
1367
 
1366
- function sendKiro(a, body, signal) {
1368
+ function sendKiro(a, body, signal, attempt = 1, invocation) {
1367
1369
  return fetch(runtime(a.region) + "/generateAssistantResponse", {
1368
1370
  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" },
1371
+ headers: { ...sdkHeaders(a, attempt, invocation), "x-amzn-kiro-attempt": `${attempt};max=${TRIES}`, "x-amzn-codewhisperer-optout": "true",
1372
+ "x-amzn-kiro-agent-mode": "vibe", "Content-Type": "application/json", Accept: "application/vnd.amazon.eventstream" },
1371
1373
  body,
1372
1374
  signal,
1373
1375
  })
1374
1376
  }
1375
1377
 
1378
+ // TRIES is the Kiro IDE's tries of one chat call (its QClientRetryStrategy,
1379
+ // agent 1.1.787, QAf), the first included.
1380
+ const TRIES = 3
1381
+ // PACE is the IDE's pause before the nth try after a throttle (its
1382
+ // throttling backoff: 1s doubling, 20% either way, at most 20s), unless
1383
+ // Kiro said how long (retryAfterMilliseconds and the like).
1384
+ const PACE = { base: 1000, jitter: 0.2, max: 20_000 }
1385
+ const paceOf = (n) => Math.min(PACE.max, PACE.base * 2 ** (n - 1)) * (1 - PACE.jitter + Math.random() * 2 * PACE.jitter)
1386
+ // THROTTLES are the reasons the IDE takes a 429 for a throttle it waits
1387
+ // out and tries again (its C1p and ServiceThrottleError): a throttle
1388
+ // Kiro gives no reason for is one too. A daily, monthly or usage limit
1389
+ // is not (usedUpSaid), nor is INSUFFICIENT_MODEL_CAPACITY.
1390
+ const THROTTLES = new Set(["USER_REQUEST_RATE_EXCEEDED", "CREDIT_CONSUMPTION_RATE_EXCEEDED", "SERVICE_REQUEST_RATE_EXCEEDED"])
1391
+ function throttleSaid(text) {
1392
+ let e = {}
1393
+ try {
1394
+ e = JSON.parse(text) ?? {}
1395
+ } catch {}
1396
+ if (e.reason) return THROTTLES.has(e.reason)
1397
+ return !usedUpSaid(text) && !/INSUFFICIENT_MODEL_CAPACITY/.test(text) && /too many requests|throttl/i.test(text)
1398
+ }
1399
+
1400
+ // timing is how the plugin waits; tests make it instant.
1401
+ const timing = {
1402
+ sleep: (ms, signal) =>
1403
+ new Promise((resolve, reject) => {
1404
+ if (signal?.aborted) return reject(aborted())
1405
+ const t = setTimeout(() => {
1406
+ signal?.removeEventListener("abort", stop)
1407
+ resolve()
1408
+ }, ms)
1409
+ const stop = () => {
1410
+ clearTimeout(t)
1411
+ reject(aborted())
1412
+ }
1413
+ signal?.addEventListener("abort", stop, { once: true })
1414
+ }),
1415
+ }
1416
+
1417
+ // paced is sendKiro as the Kiro IDE sends a chat call: a 429 throttle is
1418
+ // waited out and tried again, up to TRIES in all, each try said in
1419
+ // amz-sdk-request and x-amzn-kiro-attempt under one invocation id. The
1420
+ // IDE answers its own USER_REQUEST_RATE_EXCEEDED so ("Retrying in N
1421
+ // seconds"), which is why a burst it rides out reached magpie's agent
1422
+ // as a 429 (onemezao on Discord). A wait Kiro says is longer than PACE.max
1423
+ // isn't held here: the 429 goes back with it, for magpie to rest the
1424
+ // account. The answer of the last try is the answer.
1425
+ async function paced(a, body, signal) {
1426
+ const invocation = randomUUID()
1427
+ // the IDE's own choice of API for the account (createResponseFor): its
1428
+ // CreateResponse arm is asked at /v1/responses, the rest as ever
1429
+ const cr = await createResponseFor(a, signal)
1430
+ const sent = cr ? JSON.stringify(responsesBody(JSON.parse(body))) : body
1431
+ for (let n = 1; ; n++) {
1432
+ const res = cr ? await sendResponses(a, sent, signal, n) : await sendKiro(a, sent, signal, n, invocation)
1433
+ if (res.status !== 429 || n >= TRIES) return res
1434
+ const text = (await res.text()).slice(0, 1 << 20)
1435
+ const again = () => new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
1436
+ if (!throttleSaid(text)) return again()
1437
+ const said = saidWait(res.headers, text)
1438
+ if (said > PACE.max) return again()
1439
+ await timing.sleep(said ?? paceOf(n), signal)
1440
+ }
1441
+ }
1442
+
1443
+ // ---- CreateResponse: the Kiro IDE's other chat API ------------------------------------
1444
+ //
1445
+ // Kiro IDE 1.4.121 (agent 1.1.787) asks Kiro one of two ways, by an A/B
1446
+ // experiment the account is in: generateAssistantResponse (sendKiro), or,
1447
+ // in the create_response_api arm, CreateResponse: POST /v1/responses on
1448
+ // the same runtime, an OpenAI Responses-like body built from the same
1449
+ // conversation (its buildCreateResponseRequest), answered with server-sent
1450
+ // events (its parseCreateResponseSse). chensihan0709-ui (plugins#848) had a
1451
+ // Builder ID student account answered 429 USER_REQUEST_RATE_EXCEEDED on
1452
+ // generateAssistantResponse through the plugin while the IDE, 11s later
1453
+ // on the same account, was answered on CreateResponse ("api=CreateResponse
1454
+ // armSource=experiment callPath=main"), and the IDE's own session-title
1455
+ // call, which stayed on generateAssistantResponse, got the 429 too.
1456
+
1457
+ // FEATURE_SALT is what the IDE hashes a feature's name with to find it in
1458
+ // Kiro's feature configuration (its deriveWireKey: sha256 hex of salt +
1459
+ // name); CREATE_RESPONSE is the experiment's, and "create_response" the
1460
+ // value of its arm (selectModelApi). A chat call is the IDE's "main" call
1461
+ // path, which takes CreateResponse on the experiment alone.
1462
+ const FEATURE_SALT = "kiro-feature-config-key-salt-3e9b1d7a"
1463
+ const featureKey = (name) => createHash("sha256").update(FEATURE_SALT + name).digest("hex")
1464
+ const CREATE_RESPONSE = featureKey("create_response_api")
1465
+ // the IDE's ExperimentConfigService: a configuration is kept 15 minutes
1466
+ // for one sign-in (token and profile), asked for again after a minute
1467
+ // when it couldn't be read, and read within 5s or not at all, which
1468
+ // leaves the call on generateAssistantResponse (the default)
1469
+ const FEATURES = { ttl: 15 * 60_000, retry: 60_000, timeout: 5000 }
1470
+ const features = new Map() // account → { token, profile, until, config, pending }
1471
+
1472
+ // createResponseFor is whether the account is asked as the IDE's
1473
+ // CreateResponse arm.
1474
+ async function createResponseFor(a, signal) {
1475
+ const config = await featuresOf(a, signal)
1476
+ return config[CREATE_RESPONSE] === "create_response"
1477
+ }
1478
+
1479
+ async function featuresOf(a, signal) {
1480
+ const who = a.key || a.profile || a.token
1481
+ let f = features.get(who)
1482
+ if (!f || f.token !== a.token || f.profile !== a.profile) {
1483
+ f = { token: a.token, profile: a.profile, until: 0, config: {} }
1484
+ features.set(who, f)
1485
+ }
1486
+ if (Date.now() < f.until) return f.config
1487
+ f.pending ??= readFeatures(a, signal)
1488
+ .then((config) => {
1489
+ f.config = config
1490
+ f.until = Date.now() + FEATURES.ttl
1491
+ })
1492
+ .catch(() => {
1493
+ // what was read before is kept, as the IDE keeps its last good one
1494
+ f.until = Date.now() + FEATURES.retry
1495
+ })
1496
+ .finally(() => (f.pending = undefined))
1497
+ await f.pending
1498
+ return f.config
1499
+ }
1500
+
1501
+ // readFeatures is Kiro's GetFeatureConfiguration as the IDE calls it: GET
1502
+ // /featureConfiguration on the runtime with the origin and the IDE's
1503
+ // version as the query, the profile as x-amzn-kiro-profile-arn, through
1504
+ // the same SDK client (one try), answered {configuration: {...}}.
1505
+ async function readFeatures(a, signal) {
1506
+ const q = new URLSearchParams({ origin: "AI_EDITOR", version: IDE_VERSION })
1507
+ const headers = { ...sdkHeaders(a, 1), "amz-sdk-request": "attempt=1; max=1", Accept: "application/json" }
1508
+ if (a.profile) headers["x-amzn-kiro-profile-arn"] = a.profile
1509
+ const timeout = AbortSignal.timeout(FEATURES.timeout)
1510
+ const res = await fetch(`${runtime(a.region)}/featureConfiguration?${q}`, {
1511
+ headers,
1512
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
1513
+ })
1514
+ if (!res.ok) {
1515
+ await res.body?.cancel()
1516
+ throw new Error(`featureConfiguration ${res.status}`)
1517
+ }
1518
+ const c = (await res.json())?.configuration
1519
+ return c && typeof c === "object" && !Array.isArray(c) ? c : {}
1520
+ }
1521
+
1522
+ // responses are the Responses (Response objects) answered with
1523
+ // server-sent events: CreateResponse's, read by crMessages
1524
+ const responses = new WeakSet()
1525
+
1526
+ // sendResponses is CreateResponse as the IDE sends it (its
1527
+ // sendCreateResponseRaw): its own few headers, the plain user agent (its
1528
+ // userAgent.forHttp(), no AWS SDK's), the profile as x-amzn-kiro-profile,
1529
+ // and the try as x-amzn-kiro-attempt. A refusal is said back in
1530
+ // generateAssistantResponse's words (crRefusal), so it is read, retried
1531
+ // and reported as one of its.
1532
+ async function sendResponses(a, body, signal, attempt = 1) {
1533
+ const headers = {
1534
+ "Content-Type": "application/json",
1535
+ Authorization: `Bearer ${a.token}`,
1536
+ "x-amzn-kiro-origin": "AI_EDITOR",
1537
+ "x-amzn-codewhisperer-optout": "true",
1538
+ "User-Agent": IDE_APP,
1539
+ "x-amzn-kiro-attempt": `${attempt};max=${TRIES}`,
1540
+ }
1541
+ if (a.profile) headers["x-amzn-kiro-profile"] = a.profile
1542
+ const kind = a.tokenType || (a.idc ? "SSO_OIDC" : "")
1543
+ if (kind) headers.TokenType = kind
1544
+ const res = await fetch(runtime(a.region) + "/v1/responses", { method: "POST", headers, body, signal })
1545
+ if (!res.ok) {
1546
+ const text = (await res.text()).slice(0, 1 << 20)
1547
+ return new Response(crRefusal(res.status, text), { status: res.status, statusText: res.statusText, headers: res.headers })
1548
+ }
1549
+ responses.add(res)
1550
+ return res
1551
+ }
1552
+
1553
+ // CR_REASONS are the IDE's CreateResponse codes it says in
1554
+ // generateAssistantResponse's reasons (its normalizeReason).
1555
+ const CR_REASONS = { context_length_exceeded: "CONTENT_LENGTH_EXCEEDS_THRESHOLD", model_not_found: "INVALID_MODEL_ID",
1556
+ invalid_function_parameters: "TOOL_SCHEMA_INVALID", invalid_json: "REQUEST_BODY_INVALID_JSON",
1557
+ "kiro:model_requires_user_opt_in": "MODEL_REQUIRES_USER_OPT_IN", server_is_overloaded: "MODEL_TEMPORARILY_UNAVAILABLE",
1558
+ rate_limit_exceeded: "USER_REQUEST_RATE_EXCEEDED" }
1559
+ function crReason(status, code) {
1560
+ if (status === 413) return "CONTENT_LENGTH_EXCEEDS_THRESHOLD"
1561
+ if (typeof code !== "string" || !code) return undefined
1562
+ return CR_REASONS[code] ?? (code.startsWith("kiro:") ? code.slice(5).toUpperCase() : code)
1563
+ }
1564
+
1565
+ // crRefusal is CreateResponse's refusal ({error: {message, type, code}},
1566
+ // or Kiro's {message, reason}) as generateAssistantResponse says one:
1567
+ // {message, reason, retryAfterMilliseconds}.
1568
+ function crRefusal(status, text) {
1569
+ let o = {}
1570
+ try {
1571
+ o = JSON.parse(text) ?? {}
1572
+ } catch {}
1573
+ if (typeof o !== "object") o = {}
1574
+ const e = o.error && typeof o.error === "object" ? o.error : {}
1575
+ const message = e.message ?? o.message ?? o.Message ?? (String(text).trim() || `CreateResponse HTTP ${status}`)
1576
+ const reason = crReason(status, e.code ?? o.reason)
1577
+ const out = { message, ...(reason ? { reason } : {}) }
1578
+ if (Number.isFinite(o.retryAfterMilliseconds) && o.retryAfterMilliseconds >= 0) out.retryAfterMilliseconds = o.retryAfterMilliseconds
1579
+ return JSON.stringify(out)
1580
+ }
1581
+
1582
+ // responsesBody is a generateAssistantResponse body (kiroRequest's) as
1583
+ // the IDE's CreateResponse body: the conversation as input items, the
1584
+ // current message's tools as functions, and what went in the state as
1585
+ // metadata. The instructions stay at the head of the first message, as
1586
+ // the IDE sends them without its system_field_injection feature.
1587
+ function responsesBody(g) {
1588
+ const s = g.conversationState
1589
+ const current = s.currentMessage?.userInputMessage ?? {}
1590
+ const input = []
1591
+ for (const e of [...(s.history ?? []), s.currentMessage]) if (e) input.push(...responsesInput(e))
1592
+ const tools = []
1593
+ for (const t of current.userInputMessageContext?.tools ?? []) {
1594
+ const spec = t.toolSpecification
1595
+ if (spec?.name) tools.push({ type: "function", name: spec.name, description: spec.description, parameters: spec.inputSchema?.json })
1596
+ }
1597
+ const metadata = { "kiro:agent_mode": "vibe" }
1598
+ if (s.conversationId !== undefined) metadata["kiro:conversation_id"] = s.conversationId
1599
+ const out = { model: current.modelId, input, ...(tools.length ? { tools } : {}), stream: true, origin: current.origin ?? "AI_EDITOR" }
1600
+ if (g.profileArn !== undefined) out.profileArn = g.profileArn
1601
+ out.metadata = metadata
1602
+ // its buildReasoningField: the thinking type, the effort and how it is shown
1603
+ const f = g.additionalModelRequestFields
1604
+ if (f && typeof f === "object") {
1605
+ const str = (v) => (typeof v === "string" && v ? v : undefined)
1606
+ const type = str(f.thinking?.type)
1607
+ const effort = str(f.output_config?.effort) ?? str(f.reasoning?.effort)
1608
+ const summary = str(f.thinking?.display)
1609
+ if (type || effort || summary)
1610
+ out.reasoning = { ...(type ? { type } : {}), ...(effort ? { effort } : {}), ...(summary ? { summary } : {}) }
1611
+ }
1612
+ return out
1613
+ }
1614
+
1615
+ // responsesInput is one entry of the conversation as the IDE's input
1616
+ // items (its toResponsesInputMessages): tool results, then what the user
1617
+ // said (with images, a list of parts); the reply's text, then its calls.
1618
+ function responsesInput(e) {
1619
+ const out = []
1620
+ const u = e.userInputMessage
1621
+ if (u) {
1622
+ for (const r of u.userInputMessageContext?.toolResults ?? [])
1623
+ out.push({ type: "function_call_output", call_id: r.toolUseId, output: (r.content ?? []).map((p) => p.text ?? "").join("\n") })
1624
+ const images = (u.images ?? []).filter((i) => i.source?.bytes)
1625
+ .map((i) => ({ type: "input_image", image_url: `data:image/${String(i.format).toLowerCase()};base64,${i.source.bytes}` }))
1626
+ const text = typeof u.content === "string" ? u.content : ""
1627
+ if (images.length) out.push({ role: "user", content: [...(text ? [{ type: "input_text", text }] : []), ...images] })
1628
+ else if (text) out.push({ role: "user", content: text })
1629
+ }
1630
+ const m = e.assistantResponseMessage
1631
+ if (m) {
1632
+ if (typeof m.content === "string" && m.content) out.push({ role: "assistant", content: m.content })
1633
+ for (const c of m.toolUses ?? [])
1634
+ out.push({ type: "function_call", call_id: c.toolUseId, name: c.name, arguments: typeof c.input === "string" ? c.input : JSON.stringify(c.input ?? {}) })
1635
+ }
1636
+ return out
1637
+ }
1638
+
1639
+ // CR_STOPS are the IDE's stop reasons for an incomplete response.
1640
+ const CR_STOPS = { max_output_tokens: "MAX_TOKENS", content_filter: "CONTENT_FILTERED",
1641
+ compaction_required_for_model_handoff: "COMPACTION_REQUIRED_FOR_MODEL_HANDOFF" }
1642
+ // CR_TYPES are the error types the IDE takes for one when a stream's
1643
+ // error has a code alone
1644
+ const CR_TYPES = new Set(["invalid_request", "not_found", "too_many_requests", "insufficient_quota", "server_error", "model_error"])
1645
+
1646
+ // crFailed is what a CreateResponse stream's error says, in the words of
1647
+ // generateAssistantResponse's (exception).
1648
+ function crFailed(err) {
1649
+ let type = err?.type
1650
+ let code = err?.code
1651
+ if (!type && code && CR_TYPES.has(code)) [type, code] = [code, undefined]
1652
+ const t = String(type ?? "").toLowerCase()
1653
+ const throttled = t === "too_many_requests" || code === "rate_limit_exceeded"
1654
+ const reason = crReason(code === "context_length_exceeded" ? 413 : 0, code)
1655
+ let msg = err?.message || `CreateResponse stream failed (${type ?? code ?? "unknown"})`
1656
+ if (reason) msg += ` (${reason})`
1657
+ if (reason === USER_RATE) return userRate(msg)
1658
+ if (throttled) return "rate limited: " + msg
1659
+ return type ? `${type}: ${msg}` : msg
1660
+ }
1661
+
1662
+ // crMessages reads CreateResponse's server-sent events as the events of
1663
+ // generateAssistantResponse's stream ({kind, m}, or {failed}), as the IDE
1664
+ // reads them (its parseCreateResponseSse).
1665
+ async function* crMessages(body) {
1666
+ const open = new Set() // calls started and not stopped
1667
+ const argued = new Set() // calls whose arguments came in pieces
1668
+ let call
1669
+ let refused = false // the refusal came in pieces, said already
1670
+ const line = function* (l) {
1671
+ if (!l.startsWith("data:")) return
1672
+ const d = l.slice(5).trim()
1673
+ if (!d || d === "[DONE]") return
1674
+ let w
1675
+ try {
1676
+ w = JSON.parse(d)
1677
+ } catch {
1678
+ return
1679
+ }
1680
+ const type = w?.type ?? ""
1681
+ if (type === "response.output_text.delta" && typeof w.delta === "string") yield { kind: "assistantResponseEvent", m: { content: w.delta } }
1682
+ else if ((type === "response.reasoning_text.delta" || type === "response.reasoning.delta") && typeof w.delta === "string")
1683
+ yield { kind: "reasoningContentEvent", m: { text: w.delta } }
1684
+ else if (type === "response.output_item.done" && w.item?.type === "reasoning") {
1685
+ let env
1686
+ try {
1687
+ env = JSON.parse(w.item.encrypted_content)
1688
+ } catch {}
1689
+ const sig = env?.reasoningText?.signature
1690
+ if (typeof sig === "string" && sig) yield { kind: "reasoningContentEvent", m: { signature: sig } }
1691
+ } else if (type === "response.refusal.delta" && typeof w.delta === "string") {
1692
+ // a refusal is said as the reply's text
1693
+ refused = true
1694
+ yield { kind: "assistantResponseEvent", m: { content: w.delta } }
1695
+ } else if (type === "response.refusal.done" && typeof w.refusal === "string") {
1696
+ if (!refused) yield { kind: "assistantResponseEvent", m: { content: w.refusal } }
1697
+ }
1698
+ else if (type === "response.output_item.added" && w.item?.type === "function_call") {
1699
+ call = w.item.call_id ?? w.item.id ?? ""
1700
+ open.add(call)
1701
+ yield { kind: "toolUseEvent", m: { toolUseId: call, name: w.item.name, input: w.item.arguments ?? "" } }
1702
+ } else if (type === "response.function_call_arguments.delta" && typeof w.delta === "string") {
1703
+ if (call) argued.add(call)
1704
+ yield { kind: "toolUseEvent", m: { toolUseId: call, input: w.delta } }
1705
+ } else if (type === "response.function_call_arguments.done") {
1706
+ if (call && open.has(call)) {
1707
+ open.delete(call)
1708
+ argued.delete(call)
1709
+ call = undefined
1710
+ }
1711
+ } else if (type === "response.output_item.done" && w.item?.type === "function_call") {
1712
+ const id = w.item.call_id ?? w.item.id ?? ""
1713
+ if (!open.has(id)) return
1714
+ open.delete(id)
1715
+ if (!argued.delete(id)) yield { kind: "toolUseEvent", m: { toolUseId: id, input: w.item.arguments ?? "" } }
1716
+ } else if (type === "response.completed" || type === "response.incomplete") {
1717
+ const r = w.response ?? {}
1718
+ const incomplete = type === "response.incomplete" || r.status === "incomplete"
1719
+ const stopReason = (incomplete && CR_STOPS[r.incomplete_details?.reason]) || "END_TURN"
1720
+ yield { kind: "metadataEvent", m: { stopReason } }
1721
+ const pct = r.usage?.["kiro:context_usage_percentage"]
1722
+ if (typeof pct === "number" && Number.isFinite(pct)) yield { kind: "contextUsageEvent", m: { contextUsagePercentage: pct } }
1723
+ const credits = r.usage?.["kiro:credits"]
1724
+ if (typeof credits?.value === "number" && Number.isFinite(credits.value))
1725
+ yield { kind: "meteringEvent", m: { usage: credits.value, ...(credits.unit !== undefined ? { unit: credits.unit } : {}) } }
1726
+ } else if (type === "error" || type === "response.failed") yield { failed: crFailed(type === "error" ? w.error : w.response?.error) }
1727
+ }
1728
+ const dec = new TextDecoder()
1729
+ let buf = ""
1730
+ const reader = body.getReader()
1731
+ try {
1732
+ for (;;) {
1733
+ const { value, done } = await reader.read()
1734
+ buf += done ? dec.decode() : dec.decode(value, { stream: true })
1735
+ const lines = buf.split("\n")
1736
+ buf = done ? "" : lines.pop() ?? ""
1737
+ if (buf.length > CR_LINE) throw new Error("a server-sent event over 4 MiB")
1738
+ for (const l of lines)
1739
+ for (const ev of line(l.replace(/\r$/, ""))) {
1740
+ yield ev
1741
+ if (ev.failed) return
1742
+ }
1743
+ if (done) return
1744
+ }
1745
+ } finally {
1746
+ reader.releaseLock?.()
1747
+ }
1748
+ }
1749
+ // CR_LINE is the longest line the IDE reads of the stream
1750
+ const CR_LINE = 4 << 20
1751
+
1376
1752
  // tooLongSaid is whether Kiro's words say the conversation is past the
1377
1753
  // model's window: its ValidationException "Input is too long." with reason
1378
1754
  // CONTENT_LENGTH_EXCEEDS_THRESHOLD, as an HTTP answer or as an exception
@@ -1447,6 +1823,14 @@ const requestID = (headers) => headers.get("x-amzn-requestid") || headers.get("x
1447
1823
  // seconds or as a date. Unsaid, magpie keeps to its own pauses, but for
1448
1824
  // an account's request rate (USER_RATE_WAIT).
1449
1825
  function waitOf(headers, body) {
1826
+ let w = saidWait(headers, body)
1827
+ if (w === undefined && String(body ?? "").includes(USER_RATE)) w = USER_RATE_WAIT
1828
+ return w
1829
+ }
1830
+
1831
+ // saidWait is the wait Kiro itself said, if any (waitOf, but none of
1832
+ // magpie's own).
1833
+ function saidWait(headers, body) {
1450
1834
  const ms = (v) => {
1451
1835
  const n = v == null || v === "" ? NaN : Number(v)
1452
1836
  return Number.isFinite(n) && n > 0 ? n : undefined
@@ -1461,7 +1845,6 @@ function waitOf(headers, body) {
1461
1845
  const secs = ms(ra)
1462
1846
  w = secs !== undefined ? secs * 1000 : ms(Date.parse(ra) - Date.now())
1463
1847
  }
1464
- if (w === undefined && String(body ?? "").includes(USER_RATE)) w = USER_RATE_WAIT
1465
1848
  return w
1466
1849
  }
1467
1850
 
@@ -1609,9 +1992,35 @@ class ThinkParser {
1609
1992
  }
1610
1993
  }
1611
1994
 
1995
+ // garMessages reads generateAssistantResponse's event stream: each event's
1996
+ // kind and what it says ({kind, m}), or what an error in it says ({failed}).
1997
+ const STREAM_ERRORS = ["error", "throttlingError", "validationError", "serviceUnavailableError", "internalServerException"]
1998
+ async function* garMessages(body) {
1999
+ const dec = new TextDecoder()
2000
+ for await (const f of frames(body)) {
2001
+ const type = f.headers[":message-type"]
2002
+ if (type === "exception" || type === "error") {
2003
+ yield { failed: exception(f.headers[":exception-type"] || f.headers[":error-code"], f.payload) }
2004
+ return
2005
+ }
2006
+ let m
2007
+ try {
2008
+ m = JSON.parse(dec.decode(f.payload))
2009
+ } catch {
2010
+ continue
2011
+ }
2012
+ const kind = f.headers[":event-type"]
2013
+ if (STREAM_ERRORS.includes(kind)) {
2014
+ yield { failed: exception(kind, f.payload) }
2015
+ return
2016
+ }
2017
+ yield { kind, m }
2018
+ }
2019
+ }
2020
+
1612
2021
  // events turns Kiro's reply into events: text, thinking, tool calls (the
1613
2022
  // arguments in pieces), then the usage and why it stopped — or an error.
1614
- async function* events(body, model, budget) {
2023
+ async function* events(body, model, budget, sse = false) {
1615
2024
  const think = new ThinkParser()
1616
2025
  let tool = ""
1617
2026
  let tools = 0
@@ -1627,21 +2036,13 @@ async function* events(body, model, budget) {
1627
2036
  let pct = 0
1628
2037
  let said = 0
1629
2038
  let failed = ""
1630
- const dec = new TextDecoder()
1631
2039
  try {
1632
- for await (const f of frames(body)) {
1633
- const type = f.headers[":message-type"]
1634
- if (type === "exception" || type === "error") {
1635
- failed = exception(f.headers[":exception-type"] || f.headers[":error-code"], f.payload)
2040
+ for await (const ev of (sse ? crMessages : garMessages)(body)) {
2041
+ if (ev.failed) {
2042
+ failed = ev.failed
1636
2043
  break
1637
2044
  }
1638
- let m
1639
- try {
1640
- m = JSON.parse(dec.decode(f.payload))
1641
- } catch {
1642
- continue
1643
- }
1644
- const kind = f.headers[":event-type"]
2045
+ const { kind, m } = ev
1645
2046
  if (kind === "assistantResponseEvent") {
1646
2047
  const text = typeof m.content === "string" ? m.content : ""
1647
2048
  said += text.length
@@ -1687,9 +2088,6 @@ async function* events(body, model, budget) {
1687
2088
  if (m.contextUsagePercentage > 0) pct = m.contextUsagePercentage
1688
2089
  } else if (kind === "meteringEvent") {
1689
2090
  if (Number.isFinite(m.usage) && m.usage >= 0 && (!m.unit || /^credit/i.test(m.unit))) usage.credits = (usage.credits ?? 0) + m.usage
1690
- } else if (["error", "throttlingError", "validationError", "serviceUnavailableError", "internalServerException"].includes(kind)) {
1691
- failed = exception(kind, f.payload)
1692
- break
1693
2091
  }
1694
2092
  }
1695
2093
  } catch (e) {
@@ -2110,7 +2508,7 @@ async function generate(creds, auth, req, signal, conversation) {
2110
2508
  if (hosted?.error) return errorResponse(400, hosted.error)
2111
2509
  const first = await ask(creds, auth, req, model, budget, signal, conversation)
2112
2510
  if (!first.res) return errorResponse(first.status, first.message, first.wait)
2113
- const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget)
2511
+ const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget, responses.has(first.res))
2114
2512
  return kept(await reply(it, model, req.stream === true, toolNames(req)))
2115
2513
  }
2116
2514
 
@@ -2125,7 +2523,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2125
2523
  }
2126
2524
  let res
2127
2525
  try {
2128
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2526
+ res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2129
2527
  } catch (e) {
2130
2528
  if (e?.name === "AbortError") throw e
2131
2529
  return { status: 502, message: e.message }
@@ -2138,7 +2536,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2138
2536
  return { status: 502, message: e.message }
2139
2537
  }
2140
2538
  try {
2141
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2539
+ res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2142
2540
  } catch (e) {
2143
2541
  if (e?.name === "AbortError") throw e
2144
2542
  return { status: 502, message: e.message }
@@ -2163,7 +2561,7 @@ async function ask(creds, auth, req, model, budget, signal, conversation) {
2163
2561
  if (tried.has(next.region)) return { status: 429, message: regionsUsedUp(next) + f.message, wait: f.wait }
2164
2562
  a = next
2165
2563
  try {
2166
- res = await sendKiro(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2564
+ res = await paced(a, await kiroBody(req, model, a.profile, budget, conversation), signal)
2167
2565
  } catch (e) {
2168
2566
  if (e?.name === "AbortError") throw e
2169
2567
  return { status: 502, message: e.message }
@@ -2204,7 +2602,7 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
2204
2602
  let client = false
2205
2603
  let current = null
2206
2604
  let stop = null
2207
- for await (const e of events(res.body, model, budget)) {
2605
+ for await (const e of events(res.body, model, budget, responses.has(res))) {
2208
2606
  if (e.kind === "toolStart") {
2209
2607
  current = e.name === SEARCH_NAME ? { args: "" } : null
2210
2608
  if (current) calls.push(current)
@@ -2735,4 +3133,4 @@ export async function KiroAuthPlugin({ client } = {}) {
2735
3133
  }
2736
3134
 
2737
3135
  // 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 }
3136
+ 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, 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.33",
4
4
  "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",