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

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/README.md +6 -3
  2. package/index.mjs +372 -22
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -237,8 +237,10 @@ own search used instead.
237
237
  The `config` hook declares `auto` (Kiro picks the model). Once signed in,
238
238
  the `provider.models` hook replaces it with the account's own list from
239
239
  `List-Available-Models`, with the default first. Each model carries its
240
- context window, output limit and whether it takes images. Claude models
241
- and Auto have the thinking variants.
240
+ context window, output limit and whether it takes images, and its credit
241
+ multiplier as `rate` (Kiro's `rateMultiplier` when `rateUnit` is `Credit`:
242
+ 1.3 for claude-sonnet-4.5, 0.4 for claude-haiku-4.5), which magpie shows
243
+ beside the model. Claude models and Auto have the thinking variants.
242
244
 
243
245
  ## Usage in magpie
244
246
 
@@ -254,7 +256,8 @@ month's window counts against the overage cap (`overageCap`), which is the
254
256
  month's whole limit; with it off, against the plan's credits.
255
257
 
256
258
  Each request's cost is what Kiro's `meteringEvent`s say, in credits, summed
257
- over the request (a web search's turns included). It goes on as
259
+ over the request (a web search's turns included). Kiro has already applied
260
+ the model's multiplier to it, so it isn't multiplied again. It goes on as
258
261
  `usage.credit` in the last `message_delta`, or in the message's `usage`, for
259
262
  magpie's ledger (yetone/magpie#4328). Kiro gives no token counts, so the
260
263
  input is reckoned from how full the context is, and the cache is unknown
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"
@@ -780,6 +782,8 @@ function configModel(m) {
780
782
  ? { reasoning: true, variants: Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) }
781
783
  : {}),
782
784
  tool_call: true,
785
+ // magpie's own: the credit multiplier Kiro lists for the model
786
+ ...(m.rate ? { rate: m.rate } : {}),
783
787
  }
784
788
  }
785
789
 
@@ -805,6 +809,8 @@ function runtimeModel(m) {
805
809
  interleaved: false,
806
810
  },
807
811
  release_date: "",
812
+ // magpie's own: the credit multiplier Kiro lists for the model
813
+ ...(m.rate ? { rate: m.rate } : {}),
808
814
  variants: thinks(m.id) ? Object.fromEntries(Object.entries(BUDGETS).map(([k, b]) => [k, { thinking: { type: "enabled", budgetTokens: b } }])) : {},
809
815
  }
810
816
  }
@@ -829,6 +835,21 @@ async function keyModels(a) {
829
835
  return out
830
836
  }
831
837
 
838
+ // rateOf is the credits a model's request costs as a multiple, as Kiro's
839
+ // list says it (rateMultiplier with rateUnit "Credit": on 11-09 a Free
840
+ // account's list had auto 1, claude-sonnet-4.5 1.3, claude-haiku-4.5 0.4,
841
+ // glm-5 0.5, deepseek-3.2 and minimax-m2.5 0.25, minimax-m2.1 0.15 and
842
+ // qwen3-coder-next 0.05, which kiro-cli 2.x reads as its rate_multiplier).
843
+ // Nothing is the rate when Kiro gives none, or gives it in another unit.
844
+ // It is only shown: what a request cost is the meteringEvent's credits,
845
+ // which Kiro has already multiplied (the same prompt metered 0.00535 on
846
+ // claude-haiku-4.5 and 0.01739 on claude-sonnet-4.5, 0.4 to 1.3).
847
+ function rateOf(m) {
848
+ const n = m?.rateMultiplier
849
+ if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) return undefined
850
+ return String(m.rateUnit ?? "").toLowerCase() === "credit" ? n : undefined
851
+ }
852
+
832
853
  // listModels is List-Available-Models, the default first.
833
854
  async function listModels(a) {
834
855
  const out = a.tokenType === "API_KEY" ? await keyModels(a) : await managementCall(a.region, a, "List-Available-Models", { origin: "KIRO_CLI", profileArn: a.profile })
@@ -837,8 +858,9 @@ async function listModels(a) {
837
858
  if (!m?.modelId) continue
838
859
  let name = m.modelName
839
860
  if (!name || name === m.modelId) name = m.modelId === "auto" ? "Auto" : m.modelId
861
+ const rate = rateOf(m)
840
862
  const model = { id: m.modelId, name, context: m.tokenLimits?.maxInputTokens ?? 0, output: m.tokenLimits?.maxOutputTokens ?? 0,
841
- images: (m.supportedInputTypes ?? []).some((t) => String(t).toUpperCase() === "IMAGE") }
863
+ images: (m.supportedInputTypes ?? []).some((t) => String(t).toUpperCase() === "IMAGE"), ...(rate ? { rate } : {}) }
842
864
  if (m.modelId === out?.defaultModel?.modelId) list.unshift(model)
843
865
  else list.push(model)
844
866
  }
@@ -1422,8 +1444,12 @@ const timing = {
1422
1444
  // account. The answer of the last try is the answer.
1423
1445
  async function paced(a, body, signal) {
1424
1446
  const invocation = randomUUID()
1447
+ // the IDE's own choice of API for the account (createResponseFor): its
1448
+ // CreateResponse arm is asked at /v1/responses, the rest as ever
1449
+ const cr = await createResponseFor(a, signal)
1450
+ const sent = cr ? JSON.stringify(responsesBody(JSON.parse(body))) : body
1425
1451
  for (let n = 1; ; n++) {
1426
- const res = await sendKiro(a, body, signal, n, invocation)
1452
+ const res = cr ? await sendResponses(a, sent, signal, n) : await sendKiro(a, sent, signal, n, invocation)
1427
1453
  if (res.status !== 429 || n >= TRIES) return res
1428
1454
  const text = (await res.text()).slice(0, 1 << 20)
1429
1455
  const again = () => new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
@@ -1434,6 +1460,315 @@ async function paced(a, body, signal) {
1434
1460
  }
1435
1461
  }
1436
1462
 
1463
+ // ---- CreateResponse: the Kiro IDE's other chat API ------------------------------------
1464
+ //
1465
+ // Kiro IDE 1.4.121 (agent 1.1.787) asks Kiro one of two ways, by an A/B
1466
+ // experiment the account is in: generateAssistantResponse (sendKiro), or,
1467
+ // in the create_response_api arm, CreateResponse: POST /v1/responses on
1468
+ // the same runtime, an OpenAI Responses-like body built from the same
1469
+ // conversation (its buildCreateResponseRequest), answered with server-sent
1470
+ // events (its parseCreateResponseSse). chensihan0709-ui (plugins#848) had a
1471
+ // Builder ID student account answered 429 USER_REQUEST_RATE_EXCEEDED on
1472
+ // generateAssistantResponse through the plugin while the IDE, 11s later
1473
+ // on the same account, was answered on CreateResponse ("api=CreateResponse
1474
+ // armSource=experiment callPath=main"), and the IDE's own session-title
1475
+ // call, which stayed on generateAssistantResponse, got the 429 too.
1476
+
1477
+ // FEATURE_SALT is what the IDE hashes a feature's name with to find it in
1478
+ // Kiro's feature configuration (its deriveWireKey: sha256 hex of salt +
1479
+ // name); CREATE_RESPONSE is the experiment's, and "create_response" the
1480
+ // value of its arm (selectModelApi). A chat call is the IDE's "main" call
1481
+ // path, which takes CreateResponse on the experiment alone.
1482
+ const FEATURE_SALT = "kiro-feature-config-key-salt-3e9b1d7a"
1483
+ const featureKey = (name) => createHash("sha256").update(FEATURE_SALT + name).digest("hex")
1484
+ const CREATE_RESPONSE = featureKey("create_response_api")
1485
+ // the IDE's ExperimentConfigService: a configuration is kept 15 minutes
1486
+ // for one sign-in (token and profile), asked for again after a minute
1487
+ // when it couldn't be read, and read within 5s or not at all, which
1488
+ // leaves the call on generateAssistantResponse (the default)
1489
+ const FEATURES = { ttl: 15 * 60_000, retry: 60_000, timeout: 5000 }
1490
+ const features = new Map() // account → { token, profile, until, config, pending }
1491
+
1492
+ // createResponseFor is whether the account is asked as the IDE's
1493
+ // CreateResponse arm.
1494
+ async function createResponseFor(a, signal) {
1495
+ const config = await featuresOf(a, signal)
1496
+ return config[CREATE_RESPONSE] === "create_response"
1497
+ }
1498
+
1499
+ async function featuresOf(a, signal) {
1500
+ const who = a.key || a.profile || a.token
1501
+ let f = features.get(who)
1502
+ if (!f || f.token !== a.token || f.profile !== a.profile) {
1503
+ f = { token: a.token, profile: a.profile, until: 0, config: {} }
1504
+ features.set(who, f)
1505
+ }
1506
+ if (Date.now() < f.until) return f.config
1507
+ f.pending ??= readFeatures(a, signal)
1508
+ .then((config) => {
1509
+ f.config = config
1510
+ f.until = Date.now() + FEATURES.ttl
1511
+ })
1512
+ .catch(() => {
1513
+ // what was read before is kept, as the IDE keeps its last good one
1514
+ f.until = Date.now() + FEATURES.retry
1515
+ })
1516
+ .finally(() => (f.pending = undefined))
1517
+ await f.pending
1518
+ return f.config
1519
+ }
1520
+
1521
+ // readFeatures is Kiro's GetFeatureConfiguration as the IDE calls it: GET
1522
+ // /featureConfiguration on the runtime with the origin and the IDE's
1523
+ // version as the query, the profile as x-amzn-kiro-profile-arn, through
1524
+ // the same SDK client (one try), answered {configuration: {...}}.
1525
+ async function readFeatures(a, signal) {
1526
+ const q = new URLSearchParams({ origin: "AI_EDITOR", version: IDE_VERSION })
1527
+ const headers = { ...sdkHeaders(a, 1), "amz-sdk-request": "attempt=1; max=1", Accept: "application/json" }
1528
+ if (a.profile) headers["x-amzn-kiro-profile-arn"] = a.profile
1529
+ const timeout = AbortSignal.timeout(FEATURES.timeout)
1530
+ const res = await fetch(`${runtime(a.region)}/featureConfiguration?${q}`, {
1531
+ headers,
1532
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
1533
+ })
1534
+ if (!res.ok) {
1535
+ await res.body?.cancel()
1536
+ throw new Error(`featureConfiguration ${res.status}`)
1537
+ }
1538
+ const c = (await res.json())?.configuration
1539
+ return c && typeof c === "object" && !Array.isArray(c) ? c : {}
1540
+ }
1541
+
1542
+ // responses are the Responses (Response objects) answered with
1543
+ // server-sent events: CreateResponse's, read by crMessages
1544
+ const responses = new WeakSet()
1545
+
1546
+ // sendResponses is CreateResponse as the IDE sends it (its
1547
+ // sendCreateResponseRaw): its own few headers, the plain user agent (its
1548
+ // userAgent.forHttp(), no AWS SDK's), the profile as x-amzn-kiro-profile,
1549
+ // and the try as x-amzn-kiro-attempt. A refusal is said back in
1550
+ // generateAssistantResponse's words (crRefusal), so it is read, retried
1551
+ // and reported as one of its.
1552
+ async function sendResponses(a, body, signal, attempt = 1) {
1553
+ const headers = {
1554
+ "Content-Type": "application/json",
1555
+ Authorization: `Bearer ${a.token}`,
1556
+ "x-amzn-kiro-origin": "AI_EDITOR",
1557
+ "x-amzn-codewhisperer-optout": "true",
1558
+ "User-Agent": IDE_APP,
1559
+ "x-amzn-kiro-attempt": `${attempt};max=${TRIES}`,
1560
+ }
1561
+ if (a.profile) headers["x-amzn-kiro-profile"] = a.profile
1562
+ const kind = a.tokenType || (a.idc ? "SSO_OIDC" : "")
1563
+ if (kind) headers.TokenType = kind
1564
+ const res = await fetch(runtime(a.region) + "/v1/responses", { method: "POST", headers, body, signal })
1565
+ if (!res.ok) {
1566
+ const text = (await res.text()).slice(0, 1 << 20)
1567
+ return new Response(crRefusal(res.status, text), { status: res.status, statusText: res.statusText, headers: res.headers })
1568
+ }
1569
+ responses.add(res)
1570
+ return res
1571
+ }
1572
+
1573
+ // CR_REASONS are the IDE's CreateResponse codes it says in
1574
+ // generateAssistantResponse's reasons (its normalizeReason).
1575
+ const CR_REASONS = { context_length_exceeded: "CONTENT_LENGTH_EXCEEDS_THRESHOLD", model_not_found: "INVALID_MODEL_ID",
1576
+ invalid_function_parameters: "TOOL_SCHEMA_INVALID", invalid_json: "REQUEST_BODY_INVALID_JSON",
1577
+ "kiro:model_requires_user_opt_in": "MODEL_REQUIRES_USER_OPT_IN", server_is_overloaded: "MODEL_TEMPORARILY_UNAVAILABLE",
1578
+ rate_limit_exceeded: "USER_REQUEST_RATE_EXCEEDED" }
1579
+ function crReason(status, code) {
1580
+ if (status === 413) return "CONTENT_LENGTH_EXCEEDS_THRESHOLD"
1581
+ if (typeof code !== "string" || !code) return undefined
1582
+ return CR_REASONS[code] ?? (code.startsWith("kiro:") ? code.slice(5).toUpperCase() : code)
1583
+ }
1584
+
1585
+ // crRefusal is CreateResponse's refusal ({error: {message, type, code}},
1586
+ // or Kiro's {message, reason}) as generateAssistantResponse says one:
1587
+ // {message, reason, retryAfterMilliseconds}.
1588
+ function crRefusal(status, text) {
1589
+ let o = {}
1590
+ try {
1591
+ o = JSON.parse(text) ?? {}
1592
+ } catch {}
1593
+ if (typeof o !== "object") o = {}
1594
+ const e = o.error && typeof o.error === "object" ? o.error : {}
1595
+ const message = e.message ?? o.message ?? o.Message ?? (String(text).trim() || `CreateResponse HTTP ${status}`)
1596
+ const reason = crReason(status, e.code ?? o.reason)
1597
+ const out = { message, ...(reason ? { reason } : {}) }
1598
+ if (Number.isFinite(o.retryAfterMilliseconds) && o.retryAfterMilliseconds >= 0) out.retryAfterMilliseconds = o.retryAfterMilliseconds
1599
+ return JSON.stringify(out)
1600
+ }
1601
+
1602
+ // responsesBody is a generateAssistantResponse body (kiroRequest's) as
1603
+ // the IDE's CreateResponse body: the conversation as input items, the
1604
+ // current message's tools as functions, and what went in the state as
1605
+ // metadata. The instructions stay at the head of the first message, as
1606
+ // the IDE sends them without its system_field_injection feature.
1607
+ function responsesBody(g) {
1608
+ const s = g.conversationState
1609
+ const current = s.currentMessage?.userInputMessage ?? {}
1610
+ const input = []
1611
+ for (const e of [...(s.history ?? []), s.currentMessage]) if (e) input.push(...responsesInput(e))
1612
+ const tools = []
1613
+ for (const t of current.userInputMessageContext?.tools ?? []) {
1614
+ const spec = t.toolSpecification
1615
+ if (spec?.name) tools.push({ type: "function", name: spec.name, description: spec.description, parameters: spec.inputSchema?.json })
1616
+ }
1617
+ const metadata = { "kiro:agent_mode": "vibe" }
1618
+ if (s.conversationId !== undefined) metadata["kiro:conversation_id"] = s.conversationId
1619
+ const out = { model: current.modelId, input, ...(tools.length ? { tools } : {}), stream: true, origin: current.origin ?? "AI_EDITOR" }
1620
+ if (g.profileArn !== undefined) out.profileArn = g.profileArn
1621
+ out.metadata = metadata
1622
+ // its buildReasoningField: the thinking type, the effort and how it is shown
1623
+ const f = g.additionalModelRequestFields
1624
+ if (f && typeof f === "object") {
1625
+ const str = (v) => (typeof v === "string" && v ? v : undefined)
1626
+ const type = str(f.thinking?.type)
1627
+ const effort = str(f.output_config?.effort) ?? str(f.reasoning?.effort)
1628
+ const summary = str(f.thinking?.display)
1629
+ if (type || effort || summary)
1630
+ out.reasoning = { ...(type ? { type } : {}), ...(effort ? { effort } : {}), ...(summary ? { summary } : {}) }
1631
+ }
1632
+ return out
1633
+ }
1634
+
1635
+ // responsesInput is one entry of the conversation as the IDE's input
1636
+ // items (its toResponsesInputMessages): tool results, then what the user
1637
+ // said (with images, a list of parts); the reply's text, then its calls.
1638
+ function responsesInput(e) {
1639
+ const out = []
1640
+ const u = e.userInputMessage
1641
+ if (u) {
1642
+ for (const r of u.userInputMessageContext?.toolResults ?? [])
1643
+ out.push({ type: "function_call_output", call_id: r.toolUseId, output: (r.content ?? []).map((p) => p.text ?? "").join("\n") })
1644
+ const images = (u.images ?? []).filter((i) => i.source?.bytes)
1645
+ .map((i) => ({ type: "input_image", image_url: `data:image/${String(i.format).toLowerCase()};base64,${i.source.bytes}` }))
1646
+ const text = typeof u.content === "string" ? u.content : ""
1647
+ if (images.length) out.push({ role: "user", content: [...(text ? [{ type: "input_text", text }] : []), ...images] })
1648
+ else if (text) out.push({ role: "user", content: text })
1649
+ }
1650
+ const m = e.assistantResponseMessage
1651
+ if (m) {
1652
+ if (typeof m.content === "string" && m.content) out.push({ role: "assistant", content: m.content })
1653
+ for (const c of m.toolUses ?? [])
1654
+ out.push({ type: "function_call", call_id: c.toolUseId, name: c.name, arguments: typeof c.input === "string" ? c.input : JSON.stringify(c.input ?? {}) })
1655
+ }
1656
+ return out
1657
+ }
1658
+
1659
+ // CR_STOPS are the IDE's stop reasons for an incomplete response.
1660
+ const CR_STOPS = { max_output_tokens: "MAX_TOKENS", content_filter: "CONTENT_FILTERED",
1661
+ compaction_required_for_model_handoff: "COMPACTION_REQUIRED_FOR_MODEL_HANDOFF" }
1662
+ // CR_TYPES are the error types the IDE takes for one when a stream's
1663
+ // error has a code alone
1664
+ const CR_TYPES = new Set(["invalid_request", "not_found", "too_many_requests", "insufficient_quota", "server_error", "model_error"])
1665
+
1666
+ // crFailed is what a CreateResponse stream's error says, in the words of
1667
+ // generateAssistantResponse's (exception).
1668
+ function crFailed(err) {
1669
+ let type = err?.type
1670
+ let code = err?.code
1671
+ if (!type && code && CR_TYPES.has(code)) [type, code] = [code, undefined]
1672
+ const t = String(type ?? "").toLowerCase()
1673
+ const throttled = t === "too_many_requests" || code === "rate_limit_exceeded"
1674
+ const reason = crReason(code === "context_length_exceeded" ? 413 : 0, code)
1675
+ let msg = err?.message || `CreateResponse stream failed (${type ?? code ?? "unknown"})`
1676
+ if (reason) msg += ` (${reason})`
1677
+ if (reason === USER_RATE) return userRate(msg)
1678
+ if (throttled) return "rate limited: " + msg
1679
+ return type ? `${type}: ${msg}` : msg
1680
+ }
1681
+
1682
+ // crMessages reads CreateResponse's server-sent events as the events of
1683
+ // generateAssistantResponse's stream ({kind, m}, or {failed}), as the IDE
1684
+ // reads them (its parseCreateResponseSse).
1685
+ async function* crMessages(body) {
1686
+ const open = new Set() // calls started and not stopped
1687
+ const argued = new Set() // calls whose arguments came in pieces
1688
+ let call
1689
+ let refused = false // the refusal came in pieces, said already
1690
+ const line = function* (l) {
1691
+ if (!l.startsWith("data:")) return
1692
+ const d = l.slice(5).trim()
1693
+ if (!d || d === "[DONE]") return
1694
+ let w
1695
+ try {
1696
+ w = JSON.parse(d)
1697
+ } catch {
1698
+ return
1699
+ }
1700
+ const type = w?.type ?? ""
1701
+ if (type === "response.output_text.delta" && typeof w.delta === "string") yield { kind: "assistantResponseEvent", m: { content: w.delta } }
1702
+ else if ((type === "response.reasoning_text.delta" || type === "response.reasoning.delta") && typeof w.delta === "string")
1703
+ yield { kind: "reasoningContentEvent", m: { text: w.delta } }
1704
+ else if (type === "response.output_item.done" && w.item?.type === "reasoning") {
1705
+ let env
1706
+ try {
1707
+ env = JSON.parse(w.item.encrypted_content)
1708
+ } catch {}
1709
+ const sig = env?.reasoningText?.signature
1710
+ if (typeof sig === "string" && sig) yield { kind: "reasoningContentEvent", m: { signature: sig } }
1711
+ } else if (type === "response.refusal.delta" && typeof w.delta === "string") {
1712
+ // a refusal is said as the reply's text
1713
+ refused = true
1714
+ yield { kind: "assistantResponseEvent", m: { content: w.delta } }
1715
+ } else if (type === "response.refusal.done" && typeof w.refusal === "string") {
1716
+ if (!refused) yield { kind: "assistantResponseEvent", m: { content: w.refusal } }
1717
+ }
1718
+ else if (type === "response.output_item.added" && w.item?.type === "function_call") {
1719
+ call = w.item.call_id ?? w.item.id ?? ""
1720
+ open.add(call)
1721
+ yield { kind: "toolUseEvent", m: { toolUseId: call, name: w.item.name, input: w.item.arguments ?? "" } }
1722
+ } else if (type === "response.function_call_arguments.delta" && typeof w.delta === "string") {
1723
+ if (call) argued.add(call)
1724
+ yield { kind: "toolUseEvent", m: { toolUseId: call, input: w.delta } }
1725
+ } else if (type === "response.function_call_arguments.done") {
1726
+ if (call && open.has(call)) {
1727
+ open.delete(call)
1728
+ argued.delete(call)
1729
+ call = undefined
1730
+ }
1731
+ } else if (type === "response.output_item.done" && w.item?.type === "function_call") {
1732
+ const id = w.item.call_id ?? w.item.id ?? ""
1733
+ if (!open.has(id)) return
1734
+ open.delete(id)
1735
+ if (!argued.delete(id)) yield { kind: "toolUseEvent", m: { toolUseId: id, input: w.item.arguments ?? "" } }
1736
+ } else if (type === "response.completed" || type === "response.incomplete") {
1737
+ const r = w.response ?? {}
1738
+ const incomplete = type === "response.incomplete" || r.status === "incomplete"
1739
+ const stopReason = (incomplete && CR_STOPS[r.incomplete_details?.reason]) || "END_TURN"
1740
+ yield { kind: "metadataEvent", m: { stopReason } }
1741
+ const pct = r.usage?.["kiro:context_usage_percentage"]
1742
+ if (typeof pct === "number" && Number.isFinite(pct)) yield { kind: "contextUsageEvent", m: { contextUsagePercentage: pct } }
1743
+ const credits = r.usage?.["kiro:credits"]
1744
+ if (typeof credits?.value === "number" && Number.isFinite(credits.value))
1745
+ yield { kind: "meteringEvent", m: { usage: credits.value, ...(credits.unit !== undefined ? { unit: credits.unit } : {}) } }
1746
+ } else if (type === "error" || type === "response.failed") yield { failed: crFailed(type === "error" ? w.error : w.response?.error) }
1747
+ }
1748
+ const dec = new TextDecoder()
1749
+ let buf = ""
1750
+ const reader = body.getReader()
1751
+ try {
1752
+ for (;;) {
1753
+ const { value, done } = await reader.read()
1754
+ buf += done ? dec.decode() : dec.decode(value, { stream: true })
1755
+ const lines = buf.split("\n")
1756
+ buf = done ? "" : lines.pop() ?? ""
1757
+ if (buf.length > CR_LINE) throw new Error("a server-sent event over 4 MiB")
1758
+ for (const l of lines)
1759
+ for (const ev of line(l.replace(/\r$/, ""))) {
1760
+ yield ev
1761
+ if (ev.failed) return
1762
+ }
1763
+ if (done) return
1764
+ }
1765
+ } finally {
1766
+ reader.releaseLock?.()
1767
+ }
1768
+ }
1769
+ // CR_LINE is the longest line the IDE reads of the stream
1770
+ const CR_LINE = 4 << 20
1771
+
1437
1772
  // tooLongSaid is whether Kiro's words say the conversation is past the
1438
1773
  // model's window: its ValidationException "Input is too long." with reason
1439
1774
  // CONTENT_LENGTH_EXCEEDS_THRESHOLD, as an HTTP answer or as an exception
@@ -1677,9 +2012,35 @@ class ThinkParser {
1677
2012
  }
1678
2013
  }
1679
2014
 
2015
+ // garMessages reads generateAssistantResponse's event stream: each event's
2016
+ // kind and what it says ({kind, m}), or what an error in it says ({failed}).
2017
+ const STREAM_ERRORS = ["error", "throttlingError", "validationError", "serviceUnavailableError", "internalServerException"]
2018
+ async function* garMessages(body) {
2019
+ const dec = new TextDecoder()
2020
+ for await (const f of frames(body)) {
2021
+ const type = f.headers[":message-type"]
2022
+ if (type === "exception" || type === "error") {
2023
+ yield { failed: exception(f.headers[":exception-type"] || f.headers[":error-code"], f.payload) }
2024
+ return
2025
+ }
2026
+ let m
2027
+ try {
2028
+ m = JSON.parse(dec.decode(f.payload))
2029
+ } catch {
2030
+ continue
2031
+ }
2032
+ const kind = f.headers[":event-type"]
2033
+ if (STREAM_ERRORS.includes(kind)) {
2034
+ yield { failed: exception(kind, f.payload) }
2035
+ return
2036
+ }
2037
+ yield { kind, m }
2038
+ }
2039
+ }
2040
+
1680
2041
  // events turns Kiro's reply into events: text, thinking, tool calls (the
1681
2042
  // arguments in pieces), then the usage and why it stopped — or an error.
1682
- async function* events(body, model, budget) {
2043
+ async function* events(body, model, budget, sse = false) {
1683
2044
  const think = new ThinkParser()
1684
2045
  let tool = ""
1685
2046
  let tools = 0
@@ -1695,21 +2056,13 @@ async function* events(body, model, budget) {
1695
2056
  let pct = 0
1696
2057
  let said = 0
1697
2058
  let failed = ""
1698
- const dec = new TextDecoder()
1699
2059
  try {
1700
- for await (const f of frames(body)) {
1701
- const type = f.headers[":message-type"]
1702
- if (type === "exception" || type === "error") {
1703
- failed = exception(f.headers[":exception-type"] || f.headers[":error-code"], f.payload)
2060
+ for await (const ev of (sse ? crMessages : garMessages)(body)) {
2061
+ if (ev.failed) {
2062
+ failed = ev.failed
1704
2063
  break
1705
2064
  }
1706
- let m
1707
- try {
1708
- m = JSON.parse(dec.decode(f.payload))
1709
- } catch {
1710
- continue
1711
- }
1712
- const kind = f.headers[":event-type"]
2065
+ const { kind, m } = ev
1713
2066
  if (kind === "assistantResponseEvent") {
1714
2067
  const text = typeof m.content === "string" ? m.content : ""
1715
2068
  said += text.length
@@ -1755,9 +2108,6 @@ async function* events(body, model, budget) {
1755
2108
  if (m.contextUsagePercentage > 0) pct = m.contextUsagePercentage
1756
2109
  } else if (kind === "meteringEvent") {
1757
2110
  if (Number.isFinite(m.usage) && m.usage >= 0 && (!m.unit || /^credit/i.test(m.unit))) usage.credits = (usage.credits ?? 0) + m.usage
1758
- } else if (["error", "throttlingError", "validationError", "serviceUnavailableError", "internalServerException"].includes(kind)) {
1759
- failed = exception(kind, f.payload)
1760
- break
1761
2111
  }
1762
2112
  }
1763
2113
  } catch (e) {
@@ -2178,7 +2528,7 @@ async function generate(creds, auth, req, signal, conversation) {
2178
2528
  if (hosted?.error) return errorResponse(400, hosted.error)
2179
2529
  const first = await ask(creds, auth, req, model, budget, signal, conversation)
2180
2530
  if (!first.res) return errorResponse(first.status, first.message, first.wait)
2181
- const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget)
2531
+ const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget, responses.has(first.res))
2182
2532
  return kept(await reply(it, model, req.stream === true, toolNames(req)))
2183
2533
  }
2184
2534
 
@@ -2272,7 +2622,7 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
2272
2622
  let client = false
2273
2623
  let current = null
2274
2624
  let stop = null
2275
- for await (const e of events(res.body, model, budget)) {
2625
+ for await (const e of events(res.body, model, budget, responses.has(res))) {
2276
2626
  if (e.kind === "toolStart") {
2277
2627
  current = e.name === SEARCH_NAME ? { args: "" } : null
2278
2628
  if (current) calls.push(current)
@@ -2803,4 +3153,4 @@ export async function KiroAuthPlugin({ client } = {}) {
2803
3153
  }
2804
3154
 
2805
3155
  // for tests
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 }
3156
+ 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 }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-kiro-auth",
3
- "version": "0.1.32",
3
+ "version": "0.1.34",
4
4
  "description": "Kiro subscriptions (Free, Pro, Pro+, Power) in OpenCode and magpie",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",