@magpie-community/opencode-kiro-auth 0.1.32 → 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.
- package/index.mjs +351 -21
- 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"
|
|
@@ -1422,8 +1424,12 @@ const timing = {
|
|
|
1422
1424
|
// account. The answer of the last try is the answer.
|
|
1423
1425
|
async function paced(a, body, signal) {
|
|
1424
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
|
|
1425
1431
|
for (let n = 1; ; n++) {
|
|
1426
|
-
const res = await sendKiro(a,
|
|
1432
|
+
const res = cr ? await sendResponses(a, sent, signal, n) : await sendKiro(a, sent, signal, n, invocation)
|
|
1427
1433
|
if (res.status !== 429 || n >= TRIES) return res
|
|
1428
1434
|
const text = (await res.text()).slice(0, 1 << 20)
|
|
1429
1435
|
const again = () => new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
|
|
@@ -1434,6 +1440,315 @@ async function paced(a, body, signal) {
|
|
|
1434
1440
|
}
|
|
1435
1441
|
}
|
|
1436
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
|
+
|
|
1437
1752
|
// tooLongSaid is whether Kiro's words say the conversation is past the
|
|
1438
1753
|
// model's window: its ValidationException "Input is too long." with reason
|
|
1439
1754
|
// CONTENT_LENGTH_EXCEEDS_THRESHOLD, as an HTTP answer or as an exception
|
|
@@ -1677,9 +1992,35 @@ class ThinkParser {
|
|
|
1677
1992
|
}
|
|
1678
1993
|
}
|
|
1679
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
|
+
|
|
1680
2021
|
// events turns Kiro's reply into events: text, thinking, tool calls (the
|
|
1681
2022
|
// arguments in pieces), then the usage and why it stopped — or an error.
|
|
1682
|
-
async function* events(body, model, budget) {
|
|
2023
|
+
async function* events(body, model, budget, sse = false) {
|
|
1683
2024
|
const think = new ThinkParser()
|
|
1684
2025
|
let tool = ""
|
|
1685
2026
|
let tools = 0
|
|
@@ -1695,21 +2036,13 @@ async function* events(body, model, budget) {
|
|
|
1695
2036
|
let pct = 0
|
|
1696
2037
|
let said = 0
|
|
1697
2038
|
let failed = ""
|
|
1698
|
-
const dec = new TextDecoder()
|
|
1699
2039
|
try {
|
|
1700
|
-
for await (const
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
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
|
|
1704
2043
|
break
|
|
1705
2044
|
}
|
|
1706
|
-
|
|
1707
|
-
try {
|
|
1708
|
-
m = JSON.parse(dec.decode(f.payload))
|
|
1709
|
-
} catch {
|
|
1710
|
-
continue
|
|
1711
|
-
}
|
|
1712
|
-
const kind = f.headers[":event-type"]
|
|
2045
|
+
const { kind, m } = ev
|
|
1713
2046
|
if (kind === "assistantResponseEvent") {
|
|
1714
2047
|
const text = typeof m.content === "string" ? m.content : ""
|
|
1715
2048
|
said += text.length
|
|
@@ -1755,9 +2088,6 @@ async function* events(body, model, budget) {
|
|
|
1755
2088
|
if (m.contextUsagePercentage > 0) pct = m.contextUsagePercentage
|
|
1756
2089
|
} else if (kind === "meteringEvent") {
|
|
1757
2090
|
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
2091
|
}
|
|
1762
2092
|
}
|
|
1763
2093
|
} catch (e) {
|
|
@@ -2178,7 +2508,7 @@ async function generate(creds, auth, req, signal, conversation) {
|
|
|
2178
2508
|
if (hosted?.error) return errorResponse(400, hosted.error)
|
|
2179
2509
|
const first = await ask(creds, auth, req, model, budget, signal, conversation)
|
|
2180
2510
|
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)
|
|
2511
|
+
const it = hosted ? searching(creds, auth, req, model, budget, signal, hosted, first, conversation) : events(first.res.body, model, budget, responses.has(first.res))
|
|
2182
2512
|
return kept(await reply(it, model, req.stream === true, toolNames(req)))
|
|
2183
2513
|
}
|
|
2184
2514
|
|
|
@@ -2272,7 +2602,7 @@ async function* searching(creds, auth, req, model, budget, signal, hosted, first
|
|
|
2272
2602
|
let client = false
|
|
2273
2603
|
let current = null
|
|
2274
2604
|
let stop = null
|
|
2275
|
-
for await (const e of events(res.body, model, budget)) {
|
|
2605
|
+
for await (const e of events(res.body, model, budget, responses.has(res))) {
|
|
2276
2606
|
if (e.kind === "toolStart") {
|
|
2277
2607
|
current = e.name === SEARCH_NAME ? { args: "" } : null
|
|
2278
2608
|
if (current) calls.push(current)
|
|
@@ -2803,4 +3133,4 @@ export async function KiroAuthPlugin({ client } = {}) {
|
|
|
2803
3133
|
}
|
|
2804
3134
|
|
|
2805
3135
|
// 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 }
|
|
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 }
|