@javargasm/pi-kiro 0.2.0

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/dist/core.js ADDED
@@ -0,0 +1,2849 @@
1
+ import { createRequire } from "node:module";
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true,
8
+ configurable: true,
9
+ set: (newValue) => all[name] = () => newValue
10
+ });
11
+ };
12
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
14
+
15
+ // src/debug.ts
16
+ import { appendFileSync, mkdirSync } from "node:fs";
17
+ import { dirname, isAbsolute, resolve } from "node:path";
18
+ function currentLevel() {
19
+ const raw = (globalThis.process?.env?.KIRO_LOG ?? "").toLowerCase();
20
+ if (raw === "error" || raw === "warn" || raw === "info" || raw === "debug")
21
+ return raw;
22
+ return "warn";
23
+ }
24
+ function enabled(level) {
25
+ return LEVEL_ORDER[level] <= LEVEL_ORDER[currentLevel()];
26
+ }
27
+ function currentFilePath() {
28
+ const raw = globalThis.process?.env?.KIRO_LOG_FILE;
29
+ if (!raw)
30
+ return null;
31
+ return isAbsolute(raw) ? raw : resolve(process.cwd(), raw);
32
+ }
33
+ function writeToFile(filePath, line) {
34
+ try {
35
+ const dir = dirname(filePath);
36
+ if (!ensuredDirs.has(dir)) {
37
+ mkdirSync(dir, { recursive: true });
38
+ ensuredDirs.add(dir);
39
+ }
40
+ appendFileSync(filePath, line + `
41
+ `);
42
+ } catch (err) {
43
+ if (!fileFallbackWarned) {
44
+ fileFallbackWarned = true;
45
+ console.error(`[pi-kiro] ERROR failed to write KIRO_LOG_FILE=${filePath}:`, err);
46
+ }
47
+ }
48
+ }
49
+ function emit(level, message, data) {
50
+ if (!enabled(level))
51
+ return;
52
+ const filePath = currentFilePath();
53
+ if (filePath) {
54
+ const record = {
55
+ ts: new Date().toISOString(),
56
+ level,
57
+ msg: message
58
+ };
59
+ if (data !== undefined)
60
+ record.data = data;
61
+ let line;
62
+ try {
63
+ line = JSON.stringify(record);
64
+ } catch {
65
+ line = JSON.stringify({ ...record, data: String(data) });
66
+ }
67
+ writeToFile(filePath, line);
68
+ return;
69
+ }
70
+ const prefix = `[pi-kiro] ${level.toUpperCase()}`;
71
+ const sink = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
72
+ if (data === undefined) {
73
+ sink(`${prefix} ${message}`);
74
+ } else {
75
+ sink(`${prefix} ${message}`, data);
76
+ }
77
+ }
78
+ function previewChunk(s) {
79
+ let out = "";
80
+ const limit = Math.min(s.length, CHUNK_PREVIEW_LIMIT);
81
+ for (let i = 0;i < limit; i++) {
82
+ const c = s.charCodeAt(i);
83
+ if (c === 10)
84
+ out += "\\n";
85
+ else if (c === 13)
86
+ out += "\\r";
87
+ else if (c === 9)
88
+ out += "\\t";
89
+ else if (c < 32 || c === 127)
90
+ out += `\\x${c.toString(16).padStart(2, "0")}`;
91
+ else
92
+ out += s[i];
93
+ }
94
+ if (s.length > CHUNK_PREVIEW_LIMIT)
95
+ out += `…(+${s.length - CHUNK_PREVIEW_LIMIT} chars)`;
96
+ return out;
97
+ }
98
+ var LEVEL_ORDER, ensuredDirs, fileFallbackWarned = false, log, CHUNK_PREVIEW_LIMIT = 2048;
99
+ var init_debug = __esm(() => {
100
+ LEVEL_ORDER = {
101
+ error: 0,
102
+ warn: 1,
103
+ info: 2,
104
+ debug: 3
105
+ };
106
+ ensuredDirs = new Set;
107
+ log = {
108
+ error: (msg, data) => emit("error", msg, data),
109
+ warn: (msg, data) => emit("warn", msg, data),
110
+ info: (msg, data) => emit("info", msg, data),
111
+ debug: (msg, data) => emit("debug", msg, data),
112
+ isDebug: () => enabled("debug")
113
+ };
114
+ });
115
+
116
+ // src/kiro-cli-sync.ts
117
+ var exports_kiro_cli_sync = {};
118
+ __export(exports_kiro_cli_sync, {
119
+ saveKiroCliCredentials: () => saveKiroCliCredentials,
120
+ importFromKiroCli: () => importFromKiroCli,
121
+ getKiroCliCredentialsAllowExpired: () => getKiroCliCredentialsAllowExpired
122
+ });
123
+ import { homedir } from "node:os";
124
+ import { join } from "node:path";
125
+ import { existsSync } from "node:fs";
126
+ function getKiroDbPath() {
127
+ const home = homedir();
128
+ if (process.platform === "win32") {
129
+ return join(process.env.APPDATA || join(home, "AppData", "Roaming"), "kiro", "db", "kiro.db");
130
+ }
131
+ return join(home, ".kiro", "db", "kiro.db");
132
+ }
133
+ function safeJsonParse(value) {
134
+ if (typeof value !== "string")
135
+ return null;
136
+ try {
137
+ return JSON.parse(value);
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+ function findClientCreds(obj) {
143
+ if (!obj || typeof obj !== "object")
144
+ return {};
145
+ if (typeof obj.clientId === "string" && typeof obj.clientSecret === "string") {
146
+ return { clientId: obj.clientId, clientSecret: obj.clientSecret };
147
+ }
148
+ for (const key of Object.keys(obj)) {
149
+ const result = findClientCreds(obj[key]);
150
+ if (result.clientId)
151
+ return result;
152
+ }
153
+ return {};
154
+ }
155
+ function extractRegionFromArn(arn) {
156
+ if (!arn)
157
+ return;
158
+ const parts = arn.split(":");
159
+ if (parts.length < 6 || parts[0] !== "arn")
160
+ return;
161
+ const region = parts[3];
162
+ return region && region.length > 0 ? region : undefined;
163
+ }
164
+ async function importFromKiroCli() {
165
+ const dbPath = getKiroDbPath();
166
+ if (!existsSync(dbPath)) {
167
+ log.debug(`Kiro CLI DB not found at ${dbPath}`);
168
+ return null;
169
+ }
170
+ try {
171
+ let Database;
172
+ try {
173
+ Database = (await import("bun:sqlite")).Database;
174
+ } catch {
175
+ try {
176
+ Database = (await import("better-sqlite3")).default;
177
+ } catch {
178
+ log.debug("No SQLite driver available (need bun:sqlite or better-sqlite3)");
179
+ return null;
180
+ }
181
+ }
182
+ const db = new Database(dbPath, { readonly: true });
183
+ try {
184
+ db.run?.("PRAGMA busy_timeout = 5000") ?? db.exec?.("PRAGMA busy_timeout = 5000");
185
+ } catch {}
186
+ let rows;
187
+ try {
188
+ const stmt = db.prepare("SELECT key, value FROM auth_kv");
189
+ rows = stmt.all();
190
+ } catch {
191
+ log.debug("Failed to read auth_kv table from Kiro DB");
192
+ try {
193
+ db.close();
194
+ } catch {}
195
+ return null;
196
+ }
197
+ let activeProfileArn;
198
+ try {
199
+ const stateStmt = db.prepare("SELECT value FROM state WHERE key = ?");
200
+ const stateRow = stateStmt.get("api.codewhisperer.profile");
201
+ const parsed = safeJsonParse(stateRow?.value);
202
+ const arn = parsed?.arn || parsed?.profileArn || parsed?.profile_arn;
203
+ if (typeof arn === "string" && arn.trim()) {
204
+ activeProfileArn = arn.trim();
205
+ }
206
+ } catch {}
207
+ const deviceRegRow = rows.find((r) => typeof r?.key === "string" && r.key.includes("device-registration"));
208
+ const deviceReg = safeJsonParse(deviceRegRow?.value);
209
+ const regCreds = deviceReg ? findClientCreds(deviceReg) : {};
210
+ for (const row of rows) {
211
+ if (!row.key.includes(":token"))
212
+ continue;
213
+ const data = safeJsonParse(row.value);
214
+ if (!data)
215
+ continue;
216
+ const accessToken = data.accessToken || data.access_token;
217
+ const refreshToken = data.refreshToken || data.refresh_token;
218
+ if (!accessToken && !refreshToken)
219
+ continue;
220
+ const isIdc = row.key.includes("oidc") || row.key.includes("idc");
221
+ const authMethod = isIdc ? "idc" : "desktop";
222
+ const oidcRegion = data.region || "us-east-1";
223
+ let profileArn = data.profile_arn || data.profileArn;
224
+ if (!profileArn && isIdc) {
225
+ profileArn = activeProfileArn;
226
+ }
227
+ const serviceRegion = extractRegionFromArn(profileArn) || oidcRegion;
228
+ const result = {
229
+ accessToken: accessToken || "",
230
+ refreshToken: refreshToken || "",
231
+ region: serviceRegion,
232
+ authMethod,
233
+ profileArn,
234
+ email: data.email || data.emailAddress
235
+ };
236
+ if (isIdc && regCreds.clientId) {
237
+ result.clientId = regCreds.clientId;
238
+ result.clientSecret = regCreds.clientSecret;
239
+ }
240
+ try {
241
+ db.close();
242
+ } catch {}
243
+ log.info(`Imported Kiro CLI credentials (method=${authMethod}, region=${serviceRegion}${result.email ? `, email=${result.email}` : ""})`);
244
+ return result;
245
+ }
246
+ try {
247
+ db.close();
248
+ } catch {}
249
+ log.debug("No valid token entries found in Kiro CLI DB");
250
+ return null;
251
+ } catch (err) {
252
+ log.warn(`Failed to import from Kiro CLI: ${err}`);
253
+ return null;
254
+ }
255
+ }
256
+ async function getKiroCliCredentialsAllowExpired() {
257
+ return importFromKiroCli();
258
+ }
259
+ async function saveKiroCliCredentials(creds) {
260
+ const dbPath = getKiroDbPath();
261
+ if (!existsSync(dbPath)) {
262
+ log.debug(`Kiro CLI DB not found at ${dbPath} — cannot save credentials`);
263
+ return false;
264
+ }
265
+ try {
266
+ let Database;
267
+ try {
268
+ Database = (await import("bun:sqlite")).Database;
269
+ } catch {
270
+ try {
271
+ Database = (await import("better-sqlite3")).default;
272
+ } catch {
273
+ log.debug("No SQLite driver available for credential write-back");
274
+ return false;
275
+ }
276
+ }
277
+ const db = new Database(dbPath);
278
+ try {
279
+ db.run?.("PRAGMA busy_timeout = 5000") ?? db.exec?.("PRAGMA busy_timeout = 5000");
280
+ } catch {}
281
+ let rows;
282
+ try {
283
+ const stmt = db.prepare("SELECT key, value FROM auth_kv");
284
+ rows = stmt.all();
285
+ } catch {
286
+ log.debug("Failed to read auth_kv table for credential write-back");
287
+ try {
288
+ db.close();
289
+ } catch {}
290
+ return false;
291
+ }
292
+ const tokenRow = rows.find((r) => r.key.includes(":token"));
293
+ if (!tokenRow) {
294
+ log.debug("No token entry found in auth_kv — cannot write back");
295
+ try {
296
+ db.close();
297
+ } catch {}
298
+ return false;
299
+ }
300
+ const existing = safeJsonParse(tokenRow.value) ?? {};
301
+ const updated = {
302
+ ...existing,
303
+ accessToken: creds.accessToken,
304
+ access_token: creds.accessToken,
305
+ refreshToken: creds.refreshToken,
306
+ refresh_token: creds.refreshToken
307
+ };
308
+ try {
309
+ const updateStmt = db.prepare("UPDATE auth_kv SET value = ? WHERE key = ?");
310
+ updateStmt.run(JSON.stringify(updated), tokenRow.key);
311
+ } catch (err) {
312
+ log.warn(`Failed to write credentials back to Kiro CLI DB: ${err}`);
313
+ try {
314
+ db.close();
315
+ } catch {}
316
+ return false;
317
+ }
318
+ try {
319
+ db.close();
320
+ } catch {}
321
+ log.info("Wrote refreshed credentials back to Kiro CLI DB");
322
+ return true;
323
+ } catch (err) {
324
+ log.warn(`Failed to save credentials to Kiro CLI: ${err}`);
325
+ return false;
326
+ }
327
+ }
328
+ var init_kiro_cli_sync = __esm(() => {
329
+ init_debug();
330
+ });
331
+
332
+ // src/oauth.ts
333
+ init_debug();
334
+
335
+ // src/stream.ts
336
+ init_debug();
337
+ import { calculateCost, createAssistantMessageEventStream } from "@earendil-works/pi-ai";
338
+
339
+ // src/event-parser.ts
340
+ init_debug();
341
+ function findJsonEnd(text, start) {
342
+ let braceCount = 0;
343
+ let inString = false;
344
+ let escapeNext = false;
345
+ for (let i = start;i < text.length; i++) {
346
+ const char = text[i];
347
+ if (escapeNext) {
348
+ escapeNext = false;
349
+ continue;
350
+ }
351
+ if (char === "\\") {
352
+ escapeNext = true;
353
+ continue;
354
+ }
355
+ if (char === '"') {
356
+ inString = !inString;
357
+ continue;
358
+ }
359
+ if (!inString) {
360
+ if (char === "{")
361
+ braceCount++;
362
+ else if (char === "}") {
363
+ braceCount--;
364
+ if (braceCount === 0)
365
+ return i;
366
+ }
367
+ }
368
+ }
369
+ return -1;
370
+ }
371
+ function parseKiroEvent(parsed) {
372
+ if (parsed.content !== undefined) {
373
+ return { type: "content", data: parsed.content };
374
+ }
375
+ if (parsed.reasoningText !== undefined || parsed.signature !== undefined || parsed.text !== undefined && !parsed.content && !parsed.name && !parsed.message) {
376
+ let text = "";
377
+ let signature;
378
+ if (parsed.reasoningText) {
379
+ const rt = parsed.reasoningText;
380
+ text = (rt.text ?? rt.Text) || "";
381
+ signature = rt.signature ?? rt.Signature;
382
+ } else {
383
+ text = parsed.text || "";
384
+ signature = parsed.signature;
385
+ }
386
+ return {
387
+ type: "reasoning",
388
+ data: { text, signature }
389
+ };
390
+ }
391
+ if (parsed.name && parsed.toolUseId) {
392
+ const rawInput = parsed.input;
393
+ const input = typeof rawInput === "string" ? rawInput : rawInput && typeof rawInput === "object" && Object.keys(rawInput).length > 0 ? JSON.stringify(rawInput) : "";
394
+ return {
395
+ type: "toolUse",
396
+ data: {
397
+ name: parsed.name,
398
+ toolUseId: parsed.toolUseId,
399
+ input,
400
+ stop: parsed.stop
401
+ }
402
+ };
403
+ }
404
+ if (parsed.input !== undefined && !parsed.name) {
405
+ return {
406
+ type: "toolUseInput",
407
+ data: {
408
+ input: typeof parsed.input === "string" ? parsed.input : JSON.stringify(parsed.input)
409
+ }
410
+ };
411
+ }
412
+ if (parsed.stop !== undefined && parsed.contextUsagePercentage === undefined) {
413
+ return { type: "toolUseStop", data: { stop: parsed.stop } };
414
+ }
415
+ if (parsed.contextUsagePercentage !== undefined) {
416
+ return {
417
+ type: "contextUsage",
418
+ data: { contextUsagePercentage: parsed.contextUsagePercentage }
419
+ };
420
+ }
421
+ if (parsed.followupPrompt !== undefined) {
422
+ return { type: "followupPrompt", data: parsed.followupPrompt };
423
+ }
424
+ if (parsed.error !== undefined || parsed.Error !== undefined) {
425
+ const err = parsed.error || parsed.Error || "unknown";
426
+ const message = parsed.message || parsed.Message || parsed.reason;
427
+ return {
428
+ type: "error",
429
+ data: {
430
+ error: typeof err === "string" ? err : JSON.stringify(err),
431
+ message
432
+ }
433
+ };
434
+ }
435
+ if (parsed.usage !== undefined) {
436
+ const u = parsed.usage;
437
+ return {
438
+ type: "usage",
439
+ data: {
440
+ inputTokens: u.inputTokens,
441
+ outputTokens: u.outputTokens
442
+ }
443
+ };
444
+ }
445
+ return null;
446
+ }
447
+ var EVENT_PATTERNS = [
448
+ '{"content":',
449
+ '{"reasoningText":',
450
+ '{"signature":',
451
+ '{"text":',
452
+ '{"name":',
453
+ '{"input":',
454
+ '{"stop":',
455
+ '{"contextUsagePercentage":',
456
+ '{"followupPrompt":',
457
+ '{"usage":',
458
+ '{"toolUseId":',
459
+ '{"unit":',
460
+ '{"error":',
461
+ '{"Error":',
462
+ '{"message":'
463
+ ];
464
+ function findNextEventStart(buffer, from) {
465
+ let earliest = -1;
466
+ for (const pattern of EVENT_PATTERNS) {
467
+ const idx = buffer.indexOf(pattern, from);
468
+ if (idx >= 0 && (earliest < 0 || idx < earliest))
469
+ earliest = idx;
470
+ }
471
+ return earliest;
472
+ }
473
+ function parseKiroEvents(buffer) {
474
+ const events = [];
475
+ let pos = 0;
476
+ while (pos < buffer.length) {
477
+ const jsonStart = findNextEventStart(buffer, pos);
478
+ if (jsonStart < 0) {
479
+ if (log.isDebug()) {
480
+ const gap = buffer.substring(pos);
481
+ const braceIdx = gap.indexOf('{"');
482
+ if (braceIdx >= 0) {
483
+ log.debug("event.unmatchedBrace", {
484
+ from: pos + braceIdx,
485
+ preview: gap.substring(braceIdx, Math.min(braceIdx + 200, gap.length))
486
+ });
487
+ }
488
+ }
489
+ break;
490
+ }
491
+ if (log.isDebug() && jsonStart > pos) {
492
+ const skipped = buffer.substring(pos, jsonStart);
493
+ const braceIdx = skipped.indexOf('{"');
494
+ if (braceIdx >= 0) {
495
+ log.debug("event.skippedBrace", {
496
+ from: pos + braceIdx,
497
+ preview: skipped.substring(braceIdx, Math.min(braceIdx + 200, skipped.length))
498
+ });
499
+ }
500
+ }
501
+ const jsonEnd = findJsonEnd(buffer, jsonStart);
502
+ if (jsonEnd < 0) {
503
+ return { events, remaining: buffer.substring(jsonStart) };
504
+ }
505
+ try {
506
+ const parsed = JSON.parse(buffer.substring(jsonStart, jsonEnd + 1));
507
+ const event = parseKiroEvent(parsed);
508
+ if (event) {
509
+ events.push(event);
510
+ } else if (log.isDebug()) {
511
+ log.debug("event.unknown", { keys: Object.keys(parsed), raw: parsed });
512
+ }
513
+ } catch (err) {
514
+ if (log.isDebug()) {
515
+ log.debug("event.parseFail", {
516
+ err: err instanceof Error ? err.message : String(err),
517
+ snippet: buffer.substring(jsonStart, Math.min(jsonEnd + 1, jsonStart + 200))
518
+ });
519
+ }
520
+ }
521
+ pos = jsonEnd + 1;
522
+ }
523
+ return { events, remaining: "" };
524
+ }
525
+
526
+ // src/health.ts
527
+ var PERMANENT_PATTERNS = [
528
+ "Invalid refresh token",
529
+ "Invalid grant provided",
530
+ "InvalidGrantException",
531
+ "UnauthorizedClientException",
532
+ "AuthorizationPendingException",
533
+ "ExpiredTokenException",
534
+ "client is not registered",
535
+ "The security token is expired",
536
+ "Access denied"
537
+ ];
538
+ function isPermanentError(reason) {
539
+ if (!reason)
540
+ return false;
541
+ return PERMANENT_PATTERNS.some((p) => reason.includes(p));
542
+ }
543
+
544
+ // src/thinking-parser.ts
545
+ init_debug();
546
+ var THINKING_END_TAG = "</thinking>";
547
+ var THINKING_TAG_VARIANTS = [
548
+ { open: "<thinking>", close: "</thinking>" },
549
+ { open: "<think>", close: "</think>" },
550
+ { open: "<reasoning>", close: "</reasoning>" },
551
+ { open: "<thought>", close: "</thought>" }
552
+ ];
553
+ function trailingPrefixLength(text, tag) {
554
+ const max = Math.min(text.length, tag.length - 1);
555
+ for (let len = max;len > 0; len--) {
556
+ if (text.endsWith(tag.slice(0, len)))
557
+ return len;
558
+ }
559
+ return 0;
560
+ }
561
+ function maxTrailingPrefixLength(text, tags) {
562
+ let max = 0;
563
+ for (const tag of tags) {
564
+ max = Math.max(max, trailingPrefixLength(text, tag));
565
+ }
566
+ return max;
567
+ }
568
+
569
+ class ThinkingTagParser {
570
+ output;
571
+ stream;
572
+ textBuffer = "";
573
+ inThinking = false;
574
+ thinkingExtracted = false;
575
+ thinkingBlockIndex = null;
576
+ textBlockIndex = null;
577
+ lastTextBlockIndex = null;
578
+ activeEndTag = THINKING_END_TAG;
579
+ constructor(output, stream) {
580
+ this.output = output;
581
+ this.stream = stream;
582
+ }
583
+ processChunk(chunk) {
584
+ this.textBuffer += chunk;
585
+ if (log.isDebug()) {
586
+ log.debug("thinking.chunk", {
587
+ chunkLen: chunk.length,
588
+ bufferLen: this.textBuffer.length,
589
+ inThinking: this.inThinking,
590
+ thinkingExtracted: this.thinkingExtracted
591
+ });
592
+ }
593
+ while (this.textBuffer.length > 0) {
594
+ const prev = this.textBuffer.length;
595
+ if (!this.inThinking && !this.thinkingExtracted) {
596
+ this.processBeforeThinking();
597
+ if (this.textBuffer.length === 0)
598
+ break;
599
+ }
600
+ if (this.inThinking) {
601
+ this.processInsideThinking();
602
+ if (this.textBuffer.length === 0)
603
+ break;
604
+ }
605
+ if (this.thinkingExtracted) {
606
+ this.processAfterThinking();
607
+ break;
608
+ }
609
+ if (this.textBuffer.length >= prev)
610
+ break;
611
+ }
612
+ }
613
+ finalize() {
614
+ if (log.isDebug()) {
615
+ log.debug("thinking.finalize", {
616
+ bufferLen: this.textBuffer.length,
617
+ inThinking: this.inThinking,
618
+ thinkingExtracted: this.thinkingExtracted,
619
+ textBlockIndex: this.textBlockIndex,
620
+ thinkingBlockIndex: this.thinkingBlockIndex
621
+ });
622
+ }
623
+ if (this.textBuffer.length === 0)
624
+ return;
625
+ if (this.inThinking && this.thinkingBlockIndex !== null) {
626
+ const block = this.output.content[this.thinkingBlockIndex];
627
+ if (block) {
628
+ block.thinking += this.textBuffer;
629
+ this.stream.push({
630
+ type: "thinking_delta",
631
+ contentIndex: this.thinkingBlockIndex,
632
+ delta: this.textBuffer,
633
+ partial: this.output
634
+ });
635
+ this.stream.push({
636
+ type: "thinking_end",
637
+ contentIndex: this.thinkingBlockIndex,
638
+ content: block.thinking,
639
+ partial: this.output
640
+ });
641
+ }
642
+ } else {
643
+ this.emitText(this.textBuffer);
644
+ }
645
+ this.textBuffer = "";
646
+ }
647
+ getTextBlockIndex() {
648
+ return this.textBlockIndex ?? this.lastTextBlockIndex;
649
+ }
650
+ processBeforeThinking() {
651
+ let bestPos = -1;
652
+ let bestVariant = null;
653
+ for (const variant of THINKING_TAG_VARIANTS) {
654
+ const pos = this.textBuffer.indexOf(variant.open);
655
+ if (pos !== -1 && (bestPos === -1 || pos < bestPos)) {
656
+ bestPos = pos;
657
+ bestVariant = variant;
658
+ }
659
+ }
660
+ if (bestPos !== -1 && bestVariant) {
661
+ if (log.isDebug()) {
662
+ log.debug("thinking.open", { tag: bestVariant.open, at: bestPos });
663
+ }
664
+ if (bestPos > 0)
665
+ this.emitText(this.textBuffer.slice(0, bestPos));
666
+ this.textBuffer = this.textBuffer.slice(bestPos + bestVariant.open.length);
667
+ this.activeEndTag = bestVariant.close;
668
+ this.inThinking = true;
669
+ return;
670
+ }
671
+ const trailing = maxTrailingPrefixLength(this.textBuffer, THINKING_TAG_VARIANTS.map((v) => v.open));
672
+ const safeLen = this.textBuffer.length - trailing;
673
+ if (safeLen > 0) {
674
+ this.emitText(this.textBuffer.slice(0, safeLen));
675
+ this.textBuffer = this.textBuffer.slice(safeLen);
676
+ }
677
+ }
678
+ processInsideThinking() {
679
+ const endPos = this.textBuffer.indexOf(this.activeEndTag);
680
+ if (endPos !== -1) {
681
+ if (log.isDebug()) {
682
+ log.debug("thinking.close", { tag: this.activeEndTag, at: endPos });
683
+ }
684
+ if (endPos > 0)
685
+ this.emitThinking(this.textBuffer.slice(0, endPos));
686
+ if (this.thinkingBlockIndex !== null) {
687
+ const block = this.output.content[this.thinkingBlockIndex];
688
+ if (block) {
689
+ this.stream.push({
690
+ type: "thinking_end",
691
+ contentIndex: this.thinkingBlockIndex,
692
+ content: block.thinking,
693
+ partial: this.output
694
+ });
695
+ }
696
+ }
697
+ this.textBuffer = this.textBuffer.slice(endPos + this.activeEndTag.length);
698
+ this.inThinking = false;
699
+ this.thinkingExtracted = true;
700
+ this.lastTextBlockIndex = this.textBlockIndex;
701
+ this.textBlockIndex = null;
702
+ if (this.textBuffer.startsWith(`
703
+
704
+ `))
705
+ this.textBuffer = this.textBuffer.slice(2);
706
+ return;
707
+ }
708
+ const trailing = trailingPrefixLength(this.textBuffer, this.activeEndTag);
709
+ const safeLen = this.textBuffer.length - trailing;
710
+ if (safeLen > 0) {
711
+ this.emitThinking(this.textBuffer.slice(0, safeLen));
712
+ this.textBuffer = this.textBuffer.slice(safeLen);
713
+ }
714
+ }
715
+ processAfterThinking() {
716
+ this.emitText(this.textBuffer);
717
+ this.textBuffer = "";
718
+ }
719
+ emitText(text) {
720
+ if (!text)
721
+ return;
722
+ if (this.textBlockIndex === null) {
723
+ this.textBlockIndex = this.output.content.length;
724
+ this.output.content.push({ type: "text", text: "" });
725
+ this.stream.push({ type: "text_start", contentIndex: this.textBlockIndex, partial: this.output });
726
+ }
727
+ const block = this.output.content[this.textBlockIndex];
728
+ if (!block)
729
+ return;
730
+ block.text += text;
731
+ this.stream.push({
732
+ type: "text_delta",
733
+ contentIndex: this.textBlockIndex,
734
+ delta: text,
735
+ partial: this.output
736
+ });
737
+ }
738
+ emitThinking(thinking) {
739
+ if (!thinking)
740
+ return;
741
+ if (this.thinkingBlockIndex === null) {
742
+ if (this.textBlockIndex !== null) {
743
+ this.thinkingBlockIndex = this.textBlockIndex;
744
+ this.output.content.splice(this.thinkingBlockIndex, 0, { type: "thinking", thinking: "" });
745
+ this.textBlockIndex = this.textBlockIndex + 1;
746
+ } else {
747
+ this.thinkingBlockIndex = this.output.content.length;
748
+ this.output.content.push({ type: "thinking", thinking: "" });
749
+ }
750
+ this.stream.push({
751
+ type: "thinking_start",
752
+ contentIndex: this.thinkingBlockIndex,
753
+ partial: this.output
754
+ });
755
+ }
756
+ const block = this.output.content[this.thinkingBlockIndex];
757
+ if (!block)
758
+ return;
759
+ block.thinking += thinking;
760
+ this.stream.push({
761
+ type: "thinking_delta",
762
+ contentIndex: this.thinkingBlockIndex,
763
+ delta: thinking,
764
+ partial: this.output
765
+ });
766
+ }
767
+ }
768
+
769
+ // src/tokenizer.ts
770
+ function countTokens(text) {
771
+ if (!text)
772
+ return 0;
773
+ return Math.ceil(text.length / 4);
774
+ }
775
+
776
+ // src/transform.ts
777
+ import { createHash } from "node:crypto";
778
+
779
+ // src/kiro-defaults.ts
780
+ var SYSTEM_SEED_INSTRUCTION = `Follow this instruction: # Kiro CLI Default Agent
781
+
782
+ ` + "You are the default Kiro CLI agent, bringing the power of AI-assisted development " + "directly to the user's terminal. You help with coding tasks, system operations, " + `AWS management, and development workflows.
783
+
784
+ ` + `The current model is {{modelId}}.
785
+ `;
786
+ var SYSTEM_SEED_ACK = "I will fully incorporate this information when generating my responses, " + "and explicitly acknowledge relevant parts of the summary when answering questions.";
787
+ function resolveOS() {
788
+ switch (process.platform) {
789
+ case "darwin":
790
+ return "macos";
791
+ case "win32":
792
+ return "windows";
793
+ default:
794
+ return process.platform;
795
+ }
796
+ }
797
+ var COMPACTION_THRESHOLD_PCT = 95;
798
+
799
+ // src/transform.ts
800
+ function normalizeMessages(messages) {
801
+ return messages.filter((msg) => msg.role !== "assistant" || msg.stopReason !== "error" && msg.stopReason !== "aborted");
802
+ }
803
+ var TOOL_RESULT_LIMIT = 250000;
804
+ var MAX_KIRO_IMAGES = 4;
805
+ var MAX_KIRO_IMAGE_BYTES = 3750000;
806
+ function truncate(text, limit) {
807
+ if (text.length <= limit)
808
+ return text;
809
+ const half = Math.floor(limit / 2);
810
+ return `${text.substring(0, half)}
811
+ ... [TRUNCATED] ...
812
+ ${text.substring(text.length - half)}`;
813
+ }
814
+ function extractImages(msg) {
815
+ if (msg.role === "toolResult" || typeof msg.content === "string")
816
+ return [];
817
+ if (!Array.isArray(msg.content))
818
+ return [];
819
+ return msg.content.filter((c) => c.type === "image");
820
+ }
821
+ function getContentText(msg) {
822
+ if (msg.role === "toolResult") {
823
+ return msg.content.map((c) => c.type === "text" ? c.text : "").join("");
824
+ }
825
+ if (typeof msg.content === "string")
826
+ return msg.content;
827
+ if (!Array.isArray(msg.content))
828
+ return "";
829
+ return msg.content.map((c) => {
830
+ if (c.type === "text")
831
+ return c.text;
832
+ if (c.type === "thinking")
833
+ return c.thinking;
834
+ return "";
835
+ }).join("");
836
+ }
837
+ function parseToolArgs(input) {
838
+ if (input && typeof input === "object")
839
+ return input;
840
+ if (typeof input !== "string")
841
+ return {};
842
+ try {
843
+ return JSON.parse(input);
844
+ } catch {
845
+ return {};
846
+ }
847
+ }
848
+ var KIRO_TOOL_USE_ID_RE = /^tooluse_[A-Za-z0-9]+$/;
849
+ function toKiroToolUseId(id) {
850
+ if (KIRO_TOOL_USE_ID_RE.test(id))
851
+ return id;
852
+ const digest = createHash("sha256").update(id).digest("hex").slice(0, 22);
853
+ return `tooluse_${digest}`;
854
+ }
855
+ function convertImagesToKiro(images) {
856
+ let omitted = 0;
857
+ const valid = [];
858
+ for (const img of images) {
859
+ const estimatedBytes = Math.ceil(img.data.length * 3 / 4);
860
+ if (estimatedBytes > MAX_KIRO_IMAGE_BYTES) {
861
+ omitted++;
862
+ continue;
863
+ }
864
+ if (valid.length >= MAX_KIRO_IMAGES) {
865
+ omitted++;
866
+ continue;
867
+ }
868
+ valid.push({
869
+ format: img.mimeType.split("/")[1] || "png",
870
+ source: { bytes: img.data }
871
+ });
872
+ }
873
+ return { images: valid, omitted };
874
+ }
875
+ function buildHistory(messages, _modelId, systemPrompt) {
876
+ const history = [];
877
+ let systemPrepended = false;
878
+ let currentMsgStartIdx = messages.length - 1;
879
+ while (currentMsgStartIdx > 0 && messages[currentMsgStartIdx]?.role === "toolResult") {
880
+ currentMsgStartIdx--;
881
+ }
882
+ const anchor = messages[currentMsgStartIdx];
883
+ if (anchor?.role === "assistant") {
884
+ const hasToolCall = Array.isArray(anchor.content) && anchor.content.some((b) => b.type === "toolCall");
885
+ if (!hasToolCall)
886
+ currentMsgStartIdx++;
887
+ }
888
+ const historyMessages = messages.slice(0, currentMsgStartIdx);
889
+ for (let i = 0;i < historyMessages.length; i++) {
890
+ const msg = historyMessages[i];
891
+ if (!msg)
892
+ continue;
893
+ if (msg.role === "user") {
894
+ let content = typeof msg.content === "string" ? msg.content : getContentText(msg);
895
+ if (systemPrompt && !systemPrepended) {
896
+ content = `${systemPrompt}
897
+
898
+ ${content}`;
899
+ systemPrepended = true;
900
+ }
901
+ const images = extractImages(msg);
902
+ const uim = {
903
+ content,
904
+ origin: "KIRO_CLI",
905
+ ...images.length > 0 ? { images: convertImagesToKiro(images).images } : {}
906
+ };
907
+ const prev2 = history[history.length - 1];
908
+ if (prev2?.userInputMessage) {
909
+ prev2.userInputMessage.content += `
910
+
911
+ ${uim.content}`;
912
+ if (uim.images) {
913
+ prev2.userInputMessage.images = [...prev2.userInputMessage.images ?? [], ...uim.images];
914
+ }
915
+ } else {
916
+ history.push({ userInputMessage: uim });
917
+ }
918
+ continue;
919
+ }
920
+ if (msg.role === "assistant") {
921
+ let armContent = "";
922
+ const armToolUses = [];
923
+ if (Array.isArray(msg.content)) {
924
+ for (const block of msg.content) {
925
+ if (block.type === "text") {
926
+ armContent += block.text;
927
+ } else if (block.type === "thinking") {
928
+ armContent = `<thinking>${block.thinking}</thinking>
929
+
930
+ ${armContent}`;
931
+ } else if (block.type === "toolCall") {
932
+ const tc = block;
933
+ armToolUses.push({
934
+ name: tc.name,
935
+ toolUseId: toKiroToolUseId(tc.id),
936
+ input: parseToolArgs(tc.arguments)
937
+ });
938
+ }
939
+ }
940
+ }
941
+ if (!armContent && armToolUses.length === 0)
942
+ continue;
943
+ history.push({
944
+ assistantResponseMessage: {
945
+ content: armContent,
946
+ ...armToolUses.length > 0 ? { toolUses: armToolUses } : {}
947
+ }
948
+ });
949
+ continue;
950
+ }
951
+ const trMsg = msg;
952
+ const toolResults = [
953
+ {
954
+ content: [{ text: truncate(getContentText(msg), TOOL_RESULT_LIMIT) }],
955
+ status: trMsg.isError ? "error" : "success",
956
+ toolUseId: toKiroToolUseId(trMsg.toolCallId)
957
+ }
958
+ ];
959
+ const trImages = [];
960
+ if (Array.isArray(trMsg.content)) {
961
+ for (const c of trMsg.content)
962
+ if (c.type === "image")
963
+ trImages.push(c);
964
+ }
965
+ let j = i + 1;
966
+ while (j < historyMessages.length && historyMessages[j]?.role === "toolResult") {
967
+ const next = historyMessages[j];
968
+ toolResults.push({
969
+ content: [{ text: truncate(getContentText(next), TOOL_RESULT_LIMIT) }],
970
+ status: next.isError ? "error" : "success",
971
+ toolUseId: toKiroToolUseId(next.toolCallId)
972
+ });
973
+ if (Array.isArray(next.content)) {
974
+ for (const c of next.content)
975
+ if (c.type === "image")
976
+ trImages.push(c);
977
+ }
978
+ j++;
979
+ }
980
+ i = j - 1;
981
+ const prev = history[history.length - 1];
982
+ if (prev?.userInputMessage) {
983
+ prev.userInputMessage.content += `
984
+
985
+ Tool results provided.`;
986
+ if (trImages.length > 0) {
987
+ prev.userInputMessage.images = [
988
+ ...prev.userInputMessage.images ?? [],
989
+ ...convertImagesToKiro(trImages).images
990
+ ];
991
+ }
992
+ if (!prev.userInputMessage.userInputMessageContext) {
993
+ prev.userInputMessage.userInputMessageContext = {};
994
+ }
995
+ prev.userInputMessage.userInputMessageContext.toolResults = [
996
+ ...prev.userInputMessage.userInputMessageContext.toolResults ?? [],
997
+ ...toolResults
998
+ ];
999
+ } else {
1000
+ history.push({
1001
+ userInputMessage: {
1002
+ content: "Tool results provided.",
1003
+ origin: "KIRO_CLI",
1004
+ ...trImages.length > 0 ? { images: convertImagesToKiro(trImages).images } : {},
1005
+ userInputMessageContext: { toolResults }
1006
+ }
1007
+ });
1008
+ }
1009
+ }
1010
+ return { history: collapseAgenticLoops(history), systemPrepended, currentMsgStartIdx };
1011
+ }
1012
+ function collapseAgenticLoops(history) {
1013
+ if (history.length < 4)
1014
+ return history;
1015
+ const result = [];
1016
+ let i = 0;
1017
+ while (i < history.length) {
1018
+ const entry = history[i];
1019
+ if (entry?.assistantResponseMessage?.toolUses && i + 1 < history.length && history[i + 1]?.userInputMessage?.userInputMessageContext?.toolResults) {
1020
+ let j = i;
1021
+ while (j < history.length) {
1022
+ const asst = history[j];
1023
+ if (!asst?.assistantResponseMessage?.toolUses)
1024
+ break;
1025
+ const nextUser = j + 1 < history.length ? history[j + 1] : null;
1026
+ if (!nextUser?.userInputMessage?.userInputMessageContext?.toolResults)
1027
+ break;
1028
+ j += 2;
1029
+ }
1030
+ const pairCount = (j - i) / 2;
1031
+ if (pairCount > 1) {
1032
+ for (let k = i;k < j; k += 2) {
1033
+ const asst = history[k];
1034
+ const user = history[k + 1];
1035
+ if (k === i) {
1036
+ result.push(asst);
1037
+ } else {
1038
+ result.push({
1039
+ assistantResponseMessage: {
1040
+ content: "[tool calling continues]",
1041
+ toolUses: asst.assistantResponseMessage.toolUses
1042
+ }
1043
+ });
1044
+ }
1045
+ result.push(user);
1046
+ }
1047
+ } else {
1048
+ result.push(history[i], history[i + 1]);
1049
+ }
1050
+ i = j;
1051
+ } else {
1052
+ result.push(entry);
1053
+ i++;
1054
+ }
1055
+ }
1056
+ return result;
1057
+ }
1058
+
1059
+ // src/stream.ts
1060
+ var FIRST_TOKEN_TIMEOUT_DEFAULT_MS = 90000;
1061
+ var IDLE_TIMEOUT_MS = 60000;
1062
+ var MAX_RETRIES = 3;
1063
+ var MAX_RETRY_DELAY_MS = 1e4;
1064
+ var CAPACITY_MAX_RETRIES = 3;
1065
+ var CAPACITY_BASE_DELAY_MS = 5000;
1066
+ var CAPACITY_MAX_DELAY_MS = 30000;
1067
+ var TRANSIENT_MAX_RETRIES = 3;
1068
+ var TRANSIENT_BASE_DELAY_MS = 2000;
1069
+ var TRANSIENT_MAX_DELAY_MS = 15000;
1070
+ var CONTEXT_TRUNCATION_MAX_RETRIES = 3;
1071
+ var CONTEXT_TRUNCATION_DROP_RATIO = 0.3;
1072
+ var TOO_BIG_PATTERNS = ["CONTENT_LENGTH_EXCEEDS_THRESHOLD", "Input is too long", "Improperly formed"];
1073
+ var NON_RETRYABLE_BODY_PATTERNS = ["MONTHLY_REQUEST_COUNT"];
1074
+ var CAPACITY_PATTERN = "INSUFFICIENT_MODEL_CAPACITY";
1075
+ function exponentialBackoff(attempt, baseMs, maxMs) {
1076
+ return Math.min(baseMs * 2 ** attempt, maxMs);
1077
+ }
1078
+ function isTooBigError(status, body) {
1079
+ return status === 413 || status === 400 && TOO_BIG_PATTERNS.some((p) => body.includes(p));
1080
+ }
1081
+ function isNonRetryableBodyError(body) {
1082
+ return NON_RETRYABLE_BODY_PATTERNS.some((p) => body.includes(p));
1083
+ }
1084
+ function isCapacityError(body) {
1085
+ return body.includes(CAPACITY_PATTERN);
1086
+ }
1087
+ function isTransientError(status) {
1088
+ return status === 429 || status >= 500;
1089
+ }
1090
+ function firstTokenTimeoutForModel(modelId) {
1091
+ const m = kiroModels.find((x) => x.id === modelId);
1092
+ return m?.firstTokenTimeout ?? FIRST_TOKEN_TIMEOUT_DEFAULT_MS;
1093
+ }
1094
+ var HIDDEN_REASONING_PLACEHOLDER = "Reasoning hidden by provider";
1095
+ var HIDDEN_REASONING_COUNTDOWN_MS = 2000;
1096
+ function emitHiddenReasoningLate(output, stream) {
1097
+ const contentIndex = output.content.length;
1098
+ const block = {
1099
+ type: "thinking",
1100
+ thinking: HIDDEN_REASONING_PLACEHOLDER,
1101
+ redacted: true
1102
+ };
1103
+ output.content.push(block);
1104
+ stream.push({ type: "thinking_start", contentIndex, partial: output });
1105
+ stream.push({
1106
+ type: "thinking_delta",
1107
+ contentIndex,
1108
+ delta: HIDDEN_REASONING_PLACEHOLDER,
1109
+ partial: output
1110
+ });
1111
+ stream.push({
1112
+ type: "thinking_end",
1113
+ contentIndex,
1114
+ content: "",
1115
+ partial: output
1116
+ });
1117
+ }
1118
+ function abortableDelay(ms, signal) {
1119
+ if (signal?.aborted)
1120
+ return Promise.reject(signal.reason);
1121
+ return new Promise((resolve2, reject) => {
1122
+ const timer = setTimeout(resolve2, ms);
1123
+ signal?.addEventListener("abort", () => {
1124
+ clearTimeout(timer);
1125
+ reject(signal.reason);
1126
+ }, { once: true });
1127
+ });
1128
+ }
1129
+ var profileArnCache = new Map;
1130
+ var profileArnSkipResolution = false;
1131
+ async function resolveProfileArn(accessToken, endpoint) {
1132
+ if (profileArnSkipResolution)
1133
+ return;
1134
+ const cached = profileArnCache.get(endpoint);
1135
+ if (cached !== undefined)
1136
+ return cached;
1137
+ try {
1138
+ const ep = new URL(endpoint);
1139
+ ep.hostname = ep.hostname.replace("runtime.", "management.");
1140
+ ep.pathname = "/";
1141
+ ep.search = "";
1142
+ ep.hash = "";
1143
+ const resp = await fetch(ep.toString(), {
1144
+ method: "POST",
1145
+ headers: {
1146
+ "Content-Type": "application/x-amz-json-1.0",
1147
+ Authorization: `Bearer ${accessToken}`,
1148
+ "X-Amz-Target": "AmazonCodeWhispererService.ListAvailableProfiles"
1149
+ },
1150
+ body: "{}"
1151
+ });
1152
+ if (!resp.ok) {
1153
+ log.warn(`profileArn resolution failed: ${resp.status} ${resp.statusText}`);
1154
+ return;
1155
+ }
1156
+ const j = await resp.json();
1157
+ const arn = j.profiles?.find((p) => p.arn)?.arn;
1158
+ if (!arn) {
1159
+ log.warn("profileArn resolution returned no profile ARN");
1160
+ return;
1161
+ }
1162
+ profileArnCache.set(endpoint, arn);
1163
+ return arn;
1164
+ } catch (error) {
1165
+ log.warn(`profileArn resolution threw: ${error instanceof Error ? error.message : String(error)}`);
1166
+ return;
1167
+ }
1168
+ }
1169
+ function uniqueSorted(values) {
1170
+ return [...new Set(values)].sort();
1171
+ }
1172
+ function duplicateValues(values) {
1173
+ const seen = new Set;
1174
+ const dupes = new Set;
1175
+ for (const value of values) {
1176
+ if (seen.has(value))
1177
+ dupes.add(value);
1178
+ else
1179
+ seen.add(value);
1180
+ }
1181
+ return [...dupes].sort();
1182
+ }
1183
+ function objectKeys(value) {
1184
+ if (!value || typeof value !== "object" || Array.isArray(value))
1185
+ return [];
1186
+ return Object.keys(value).sort();
1187
+ }
1188
+ function summarizeToolUse(toolUse) {
1189
+ const input = toolUse.input;
1190
+ return {
1191
+ name: toolUse.name,
1192
+ toolUseId: toolUse.toolUseId,
1193
+ inputType: Array.isArray(input) ? "array" : typeof input,
1194
+ inputKeys: objectKeys(input)
1195
+ };
1196
+ }
1197
+ function summarizeToolResult(toolResult) {
1198
+ return {
1199
+ toolUseId: toolResult.toolUseId,
1200
+ status: toolResult.status,
1201
+ contentCount: toolResult.content.length,
1202
+ textChars: toolResult.content.reduce((sum, part) => sum + part.text.length, 0)
1203
+ };
1204
+ }
1205
+ function summarizeToolSpec(toolSpec) {
1206
+ const spec = toolSpec.toolSpecification;
1207
+ const schema = spec.inputSchema.json;
1208
+ const properties = schema.properties;
1209
+ const required = schema.required;
1210
+ return {
1211
+ name: spec.name,
1212
+ descriptionChars: spec.description.length,
1213
+ schemaKeys: objectKeys(schema),
1214
+ propertyNames: properties && typeof properties === "object" && !Array.isArray(properties) ? Object.keys(properties).sort() : [],
1215
+ requiredCount: Array.isArray(required) ? required.length : 0
1216
+ };
1217
+ }
1218
+ function summarizeHistoryEntry(entry, index) {
1219
+ if (entry.userInputMessage) {
1220
+ const toolResults = entry.userInputMessage.userInputMessageContext?.toolResults ?? [];
1221
+ return {
1222
+ index,
1223
+ role: "user",
1224
+ contentChars: entry.userInputMessage.content.length,
1225
+ imageCount: entry.userInputMessage.images?.length ?? 0,
1226
+ ...toolResults.length > 0 ? { toolResults: toolResults.map(summarizeToolResult) } : {}
1227
+ };
1228
+ }
1229
+ if (entry.assistantResponseMessage) {
1230
+ const toolUses = entry.assistantResponseMessage.toolUses ?? [];
1231
+ return {
1232
+ index,
1233
+ role: "assistant",
1234
+ contentChars: entry.assistantResponseMessage.content.length,
1235
+ ...toolUses.length > 0 ? { toolUses: toolUses.map(summarizeToolUse) } : {}
1236
+ };
1237
+ }
1238
+ return { index, role: "unknown", contentChars: 0 };
1239
+ }
1240
+ function collectToolIntegrity(history, currentToolResults) {
1241
+ const toolUseIds = [];
1242
+ const toolResultIds = currentToolResults.map((toolResult) => toolResult.toolUseId);
1243
+ for (const entry of history) {
1244
+ for (const toolUse of entry.assistantResponseMessage?.toolUses ?? []) {
1245
+ toolUseIds.push(toolUse.toolUseId);
1246
+ }
1247
+ for (const toolResult of entry.userInputMessage?.userInputMessageContext?.toolResults ?? []) {
1248
+ toolResultIds.push(toolResult.toolUseId);
1249
+ }
1250
+ }
1251
+ const useSet = new Set(toolUseIds);
1252
+ const resultSet = new Set(toolResultIds);
1253
+ return {
1254
+ toolUseIds: uniqueSorted(toolUseIds),
1255
+ toolResultIds: uniqueSorted(toolResultIds),
1256
+ duplicateToolUseIds: duplicateValues(toolUseIds),
1257
+ duplicateToolResultIds: duplicateValues(toolResultIds),
1258
+ unmatchedToolResults: uniqueSorted(toolResultIds.filter((id) => !useSet.has(id))),
1259
+ toolUsesWithoutResults: uniqueSorted(toolUseIds.filter((id) => !resultSet.has(id)))
1260
+ };
1261
+ }
1262
+ function summarizeKiroRequest(request, requestBody) {
1263
+ const current = request.conversationState.currentMessage.userInputMessage;
1264
+ const history = request.conversationState.history ?? [];
1265
+ const currentContext = current.userInputMessageContext;
1266
+ const currentToolResults = currentContext?.toolResults ?? [];
1267
+ const currentTools = currentContext?.tools ?? [];
1268
+ const historySummary = history.map(summarizeHistoryEntry);
1269
+ return {
1270
+ conversationId: request.conversationState.conversationId,
1271
+ modelId: current.modelId,
1272
+ requestJsonChars: requestBody.length,
1273
+ historyLen: history.length,
1274
+ roleSequence: historySummary.map((entry) => entry.role),
1275
+ history: historySummary,
1276
+ current: {
1277
+ contentChars: current.content.length,
1278
+ imageCount: current.images?.length ?? 0,
1279
+ toolResultCount: currentToolResults.length,
1280
+ toolSpecCount: currentTools.length,
1281
+ toolSpecNames: currentTools.map((toolSpec) => toolSpec.toolSpecification.name).sort(),
1282
+ toolResults: currentToolResults.map(summarizeToolResult),
1283
+ toolSpecs: currentTools.map(summarizeToolSpec)
1284
+ },
1285
+ toolIntegrity: collectToolIntegrity(history, currentToolResults),
1286
+ additionalModelRequestFieldKeys: objectKeys(request.additionalModelRequestFields),
1287
+ hasProfileArn: !!request.profileArn,
1288
+ agentMode: request.agentMode
1289
+ };
1290
+ }
1291
+ function emitToolCall(state, output, stream) {
1292
+ if (!state.input.trim())
1293
+ state.input = "{}";
1294
+ let args;
1295
+ try {
1296
+ args = JSON.parse(state.input);
1297
+ if (args && typeof args === "object" && "__tool_use_purpose" in args) {
1298
+ delete args.__tool_use_purpose;
1299
+ }
1300
+ } catch (e) {
1301
+ log.warn(`failed to parse tool input for "${state.name}" (${state.toolUseId}): ${e instanceof Error ? e.message : String(e)}`);
1302
+ return false;
1303
+ }
1304
+ const contentIndex = output.content.length;
1305
+ const toolCall = { type: "toolCall", id: state.toolUseId, name: state.name, arguments: args };
1306
+ output.content.push(toolCall);
1307
+ stream.push({ type: "toolcall_start", contentIndex, partial: output });
1308
+ stream.push({ type: "toolcall_delta", contentIndex, delta: state.input, partial: output });
1309
+ stream.push({ type: "toolcall_end", contentIndex, toolCall, partial: output });
1310
+ return true;
1311
+ }
1312
+ function streamKiro(model, context, options) {
1313
+ const stream = createAssistantMessageEventStream();
1314
+ (async () => {
1315
+ const output = {
1316
+ role: "assistant",
1317
+ content: [],
1318
+ api: model.api,
1319
+ provider: model.provider,
1320
+ model: model.id,
1321
+ usage: {
1322
+ input: 0,
1323
+ output: 0,
1324
+ cacheRead: 0,
1325
+ cacheWrite: 0,
1326
+ totalTokens: 0,
1327
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
1328
+ },
1329
+ stopReason: "stop",
1330
+ timestamp: Date.now()
1331
+ };
1332
+ let hiddenShimTimer = null;
1333
+ try {
1334
+ const accessToken = options?.apiKey;
1335
+ if (!accessToken) {
1336
+ throw new Error("Kiro credentials not set. Run /login kiro.");
1337
+ }
1338
+ const endpoint = model.baseUrl || "https://runtime.us-east-1.kiro.dev";
1339
+ const profileArn = await resolveProfileArn(accessToken, endpoint);
1340
+ const kiroModelId = resolveKiroModel(model.id);
1341
+ const thinkingEnabled = !!options?.reasoning || model.reasoning;
1342
+ const reasoningHidden = !!model.reasoningHidden;
1343
+ log.debug("request.init", {
1344
+ endpoint,
1345
+ model: model.id,
1346
+ kiroModelId,
1347
+ contextWindow: model.contextWindow,
1348
+ thinkingEnabled,
1349
+ reasoningHidden,
1350
+ reasoning: options?.reasoning,
1351
+ messageCount: context.messages.length,
1352
+ toolCount: context.tools?.length ?? 0,
1353
+ hasSystemPrompt: !!context.systemPrompt,
1354
+ profileArn,
1355
+ sessionId: options?.sessionId
1356
+ });
1357
+ let systemPrompt = context.systemPrompt ?? "";
1358
+ if (thinkingEnabled && !reasoningHidden) {
1359
+ const budget = options?.reasoning === "xhigh" ? 50000 : options?.reasoning === "high" ? 30000 : options?.reasoning === "medium" ? 20000 : 1e4;
1360
+ systemPrompt = `<thinking_mode>enabled</thinking_mode><max_thinking_length>${budget}</max_thinking_length>${systemPrompt ? `
1361
+ ${systemPrompt}` : ""}`;
1362
+ }
1363
+ const envState = {
1364
+ operatingSystem: resolveOS(),
1365
+ currentWorkingDirectory: process.cwd()
1366
+ };
1367
+ const conversationId = options?.sessionId ?? crypto.randomUUID();
1368
+ let retryCount = 0;
1369
+ while (retryCount <= MAX_RETRIES) {
1370
+ if (options?.signal?.aborted)
1371
+ throw options.signal.reason;
1372
+ const normalized = normalizeMessages(context.messages);
1373
+ const {
1374
+ history,
1375
+ systemPrepended,
1376
+ currentMsgStartIdx
1377
+ } = buildHistory(normalized, kiroModelId, systemPrompt);
1378
+ const seedInstruction = SYSTEM_SEED_INSTRUCTION.replace("{{modelId}}", kiroModelId);
1379
+ const seedPair = [
1380
+ { userInputMessage: { content: seedInstruction, origin: "KIRO_CLI" } },
1381
+ { assistantResponseMessage: { content: SYSTEM_SEED_ACK } }
1382
+ ];
1383
+ history.unshift(...seedPair);
1384
+ const currentMessages = normalized.slice(currentMsgStartIdx);
1385
+ const firstMsg = currentMessages[0];
1386
+ let currentContent = "";
1387
+ const currentToolResults = [];
1388
+ let currentImages;
1389
+ if (firstMsg?.role === "assistant") {
1390
+ const am = firstMsg;
1391
+ let armContent = "";
1392
+ const armToolUses = [];
1393
+ if (Array.isArray(am.content)) {
1394
+ for (const b of am.content) {
1395
+ if (b.type === "text") {
1396
+ armContent += b.text;
1397
+ } else if (b.type === "thinking") {
1398
+ armContent = `<thinking>${b.thinking}</thinking>
1399
+
1400
+ ${armContent}`;
1401
+ } else if (b.type === "toolCall") {
1402
+ const tc = b;
1403
+ armToolUses.push({
1404
+ name: tc.name,
1405
+ toolUseId: toKiroToolUseId(tc.id),
1406
+ input: parseToolArgs(tc.arguments)
1407
+ });
1408
+ }
1409
+ }
1410
+ }
1411
+ if (armContent || armToolUses.length > 0) {
1412
+ const last = history[history.length - 1];
1413
+ if (last && !last.userInputMessage && last.assistantResponseMessage) {
1414
+ last.assistantResponseMessage.content += `
1415
+
1416
+ ${armContent}`;
1417
+ if (armToolUses.length > 0) {
1418
+ last.assistantResponseMessage.toolUses = [
1419
+ ...last.assistantResponseMessage.toolUses ?? [],
1420
+ ...armToolUses
1421
+ ];
1422
+ }
1423
+ } else {
1424
+ history.push({
1425
+ assistantResponseMessage: {
1426
+ content: armContent,
1427
+ ...armToolUses.length > 0 ? { toolUses: armToolUses } : {}
1428
+ }
1429
+ });
1430
+ }
1431
+ }
1432
+ const toolResultImages = [];
1433
+ for (let i = 1;i < currentMessages.length; i++) {
1434
+ const m = currentMessages[i];
1435
+ if (m?.role === "toolResult") {
1436
+ const trm = m;
1437
+ currentToolResults.push({
1438
+ content: [{ text: truncate(getContentText(m), TOOL_RESULT_LIMIT) }],
1439
+ status: trm.isError ? "error" : "success",
1440
+ toolUseId: toKiroToolUseId(trm.toolCallId)
1441
+ });
1442
+ if (Array.isArray(trm.content)) {
1443
+ for (const c of trm.content) {
1444
+ if (c.type === "image")
1445
+ toolResultImages.push(c);
1446
+ }
1447
+ }
1448
+ }
1449
+ }
1450
+ if (toolResultImages.length > 0) {
1451
+ const { images: converted, omitted } = convertImagesToKiro(toolResultImages);
1452
+ if (omitted > 0)
1453
+ log.warn(`${omitted} tool-result image(s) omitted (size/count limit)`);
1454
+ currentImages = currentImages ? [...currentImages, ...converted] : converted;
1455
+ }
1456
+ currentContent = currentToolResults.length > 0 ? "Tool results provided." : "Please proceed with the task.";
1457
+ } else if (firstMsg?.role === "toolResult") {
1458
+ const toolResultImages = [];
1459
+ for (const m of currentMessages) {
1460
+ if (m?.role === "toolResult") {
1461
+ const trm = m;
1462
+ currentToolResults.push({
1463
+ content: [{ text: truncate(getContentText(m), TOOL_RESULT_LIMIT) }],
1464
+ status: trm.isError ? "error" : "success",
1465
+ toolUseId: toKiroToolUseId(trm.toolCallId)
1466
+ });
1467
+ if (Array.isArray(trm.content)) {
1468
+ for (const c of trm.content) {
1469
+ if (c.type === "image")
1470
+ toolResultImages.push(c);
1471
+ }
1472
+ }
1473
+ }
1474
+ }
1475
+ if (toolResultImages.length > 0) {
1476
+ const { images: converted, omitted } = convertImagesToKiro(toolResultImages);
1477
+ if (omitted > 0)
1478
+ log.warn(`${omitted} tool-result image(s) omitted (size/count limit)`);
1479
+ currentImages = currentImages ? [...currentImages, ...converted] : converted;
1480
+ }
1481
+ currentContent = "Tool results provided.";
1482
+ } else if (firstMsg?.role === "user") {
1483
+ currentContent = typeof firstMsg.content === "string" ? firstMsg.content : getContentText(firstMsg);
1484
+ if (systemPrompt && !systemPrepended) {
1485
+ currentContent = `${systemPrompt}
1486
+
1487
+ ${currentContent}`;
1488
+ }
1489
+ }
1490
+ const now = new Date;
1491
+ const tzOffset = -now.getTimezoneOffset();
1492
+ const tzSign = tzOffset >= 0 ? "+" : "-";
1493
+ const tzH = String(Math.floor(Math.abs(tzOffset) / 60)).padStart(2, "0");
1494
+ const tzM = String(Math.abs(tzOffset) % 60).padStart(2, "0");
1495
+ const isoLocal = now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, "0") + "-" + String(now.getDate()).padStart(2, "0") + "T" + String(now.getHours()).padStart(2, "0") + ":" + String(now.getMinutes()).padStart(2, "0") + ":" + String(now.getSeconds()).padStart(2, "0") + "." + String(now.getMilliseconds()).padStart(3, "0") + tzSign + tzH + ":" + tzM;
1496
+ const weekday = now.toLocaleDateString("en-US", { weekday: "long" });
1497
+ currentContent = `--- CONTEXT ENTRY BEGIN ---
1498
+ ` + `Current time: ${weekday}, ${isoLocal}
1499
+ ` + `--- CONTEXT ENTRY END ---
1500
+
1501
+ ` + `--- USER MESSAGE BEGIN ---
1502
+ ` + `${currentContent}
1503
+ ` + `--- USER MESSAGE END ---`;
1504
+ let uimc = {
1505
+ envState
1506
+ };
1507
+ if (currentToolResults.length > 0)
1508
+ uimc.toolResults = currentToolResults;
1509
+ if (context.tools?.length) {
1510
+ const deepCleanSchema = (obj) => {
1511
+ if (Array.isArray(obj)) {
1512
+ return obj.map(deepCleanSchema);
1513
+ } else if (obj !== null && typeof obj === "object") {
1514
+ const cleaned = {};
1515
+ for (const [k, v] of Object.entries(obj)) {
1516
+ if (k === "$schema")
1517
+ continue;
1518
+ if (k === "required" && Array.isArray(v) && v.length === 0)
1519
+ continue;
1520
+ cleaned[k] = deepCleanSchema(v);
1521
+ }
1522
+ return cleaned;
1523
+ }
1524
+ return obj;
1525
+ };
1526
+ uimc.tools = context.tools.map((t) => {
1527
+ const params = deepCleanSchema(t.parameters);
1528
+ if (params.properties) {
1529
+ params.properties.__tool_use_purpose = {
1530
+ type: "string",
1531
+ description: "A brief explanation why you are making this tool use."
1532
+ };
1533
+ }
1534
+ return {
1535
+ toolSpecification: {
1536
+ name: t.name,
1537
+ description: t.description || `Use ${t.name}`,
1538
+ inputSchema: { json: params }
1539
+ }
1540
+ };
1541
+ });
1542
+ }
1543
+ if (firstMsg?.role === "user") {
1544
+ const imgs = extractImages(firstMsg);
1545
+ if (imgs.length > 0) {
1546
+ const { images: converted, omitted } = convertImagesToKiro(imgs);
1547
+ if (omitted > 0)
1548
+ log.warn(`${omitted} user image(s) omitted (size/count limit)`);
1549
+ currentImages = converted;
1550
+ }
1551
+ }
1552
+ const request = {
1553
+ conversationState: {
1554
+ chatTriggerType: "MANUAL",
1555
+ agentTaskType: "vibe",
1556
+ conversationId,
1557
+ currentMessage: {
1558
+ userInputMessage: {
1559
+ content: currentContent,
1560
+ modelId: kiroModelId,
1561
+ origin: "KIRO_CLI",
1562
+ ...currentImages ? { images: currentImages } : {},
1563
+ userInputMessageContext: uimc
1564
+ }
1565
+ },
1566
+ ...history.length > 0 ? { history } : {}
1567
+ },
1568
+ ...profileArn ? { profileArn } : {},
1569
+ agentMode: "vibe"
1570
+ };
1571
+ const EFFORT_MAP = {
1572
+ minimal: "low",
1573
+ low: "medium",
1574
+ medium: "high",
1575
+ high: "xhigh",
1576
+ xhigh: "max"
1577
+ };
1578
+ const staticModel = kiroModels.find((m) => m.id === model.id);
1579
+ const dynamicModel = getCachedDynamicModels()?.find((m) => m.id === model.id);
1580
+ const supportedEfforts = staticModel?.supportedEfforts ?? dynamicModel?.supportedEfforts;
1581
+ const supportsThinkingConfig = staticModel?.supportsThinkingConfig ?? dynamicModel?.supportsThinkingConfig;
1582
+ if (supportedEfforts && supportedEfforts.length > 0 && options?.reasoning && typeof options.reasoning === "string") {
1583
+ const kiroEffort = EFFORT_MAP[options.reasoning];
1584
+ if (kiroEffort && supportedEfforts.includes(kiroEffort)) {
1585
+ request.additionalModelRequestFields = request.additionalModelRequestFields || {};
1586
+ request.additionalModelRequestFields.output_config = { effort: kiroEffort };
1587
+ log.debug("effort.set", { piReasoning: options.reasoning, kiroEffort, model: model.id });
1588
+ }
1589
+ }
1590
+ if (supportsThinkingConfig && thinkingEnabled) {
1591
+ request.additionalModelRequestFields = request.additionalModelRequestFields || {};
1592
+ request.additionalModelRequestFields.thinking = {
1593
+ type: "adaptive",
1594
+ display: "summarized"
1595
+ };
1596
+ log.debug("thinking.set", { type: "adaptive", display: "summarized", model: model.id });
1597
+ }
1598
+ stream.push({ type: "start", partial: output });
1599
+ if (reasoningHidden && thinkingEnabled && hiddenShimTimer === null) {
1600
+ hiddenShimTimer = setTimeout(() => {
1601
+ hiddenShimTimer = null;
1602
+ emitHiddenReasoningLate(output, stream);
1603
+ }, HIDDEN_REASONING_COUNTDOWN_MS);
1604
+ }
1605
+ let response;
1606
+ let capacityRetryCount = 0;
1607
+ let transientRetryCount = 0;
1608
+ let contextTruncationAttempt = 0;
1609
+ while (true) {
1610
+ const mid = crypto.randomUUID().replace(/-/g, "");
1611
+ const ua = `aws-sdk-rust/1.0.0 ua/2.1 os/other lang/rust api/codewhispererstreaming#1.28.3 m/E app/AmazonQ-For-CLI md/appVersion-1.28.3-${mid}`;
1612
+ const requestBody = JSON.stringify(request);
1613
+ const requestShape = log.isDebug() ? summarizeKiroRequest(request, requestBody) : undefined;
1614
+ if (requestShape)
1615
+ log.debug("request.shape", requestShape);
1616
+ log.debug("request.send", {
1617
+ attempt: retryCount,
1618
+ capacityAttempt: capacityRetryCount,
1619
+ historyLen: history.length,
1620
+ currentContentLen: currentContent.length,
1621
+ hasImages: !!currentImages,
1622
+ toolResultCount: currentToolResults.length,
1623
+ requestJsonChars: requestBody.length
1624
+ });
1625
+ response = await fetch(endpoint, {
1626
+ method: "POST",
1627
+ headers: {
1628
+ "Content-Type": "application/x-amz-json-1.0",
1629
+ Accept: "application/json",
1630
+ Authorization: `Bearer ${accessToken}`,
1631
+ "X-Amz-Target": "AmazonCodeWhispererStreamingService.GenerateAssistantResponse",
1632
+ "x-amzn-codewhisperer-optout": "true",
1633
+ "amz-sdk-invocation-id": crypto.randomUUID(),
1634
+ "amz-sdk-request": "attempt=1; max=1",
1635
+ "x-amzn-kiro-agent-mode": "vibe",
1636
+ "x-amz-user-agent": ua,
1637
+ "user-agent": ua
1638
+ },
1639
+ body: requestBody,
1640
+ signal: options?.signal
1641
+ });
1642
+ if (response.ok)
1643
+ break;
1644
+ let errText = "";
1645
+ try {
1646
+ errText = await response.text();
1647
+ } catch {
1648
+ errText = "";
1649
+ }
1650
+ log.debug("response.error", {
1651
+ status: response.status,
1652
+ body: errText,
1653
+ ...requestShape ? { requestShape } : {}
1654
+ });
1655
+ if (isCapacityError(errText) && capacityRetryCount < CAPACITY_MAX_RETRIES) {
1656
+ capacityRetryCount++;
1657
+ const delayMs = exponentialBackoff(capacityRetryCount - 1, CAPACITY_BASE_DELAY_MS, CAPACITY_MAX_DELAY_MS);
1658
+ log.warn(`INSUFFICIENT_MODEL_CAPACITY — retrying in ${delayMs}ms (${capacityRetryCount}/${CAPACITY_MAX_RETRIES})`);
1659
+ await abortableDelay(delayMs, options?.signal);
1660
+ continue;
1661
+ }
1662
+ if (isNonRetryableBodyError(errText) || isCapacityError(errText)) {
1663
+ throw new Error(`Kiro API error: ${errText || response.statusText}`);
1664
+ }
1665
+ if (isTooBigError(response.status, errText)) {
1666
+ if (contextTruncationAttempt < CONTEXT_TRUNCATION_MAX_RETRIES && history.length > 0) {
1667
+ contextTruncationAttempt++;
1668
+ const dropCount = Math.max(1, Math.floor(history.length * CONTEXT_TRUNCATION_DROP_RATIO));
1669
+ const before = history.length;
1670
+ history.splice(0, dropCount);
1671
+ log.warn(`context too large — truncated history from ${before} to ${history.length} entries ` + `(attempt ${contextTruncationAttempt}/${CONTEXT_TRUNCATION_MAX_RETRIES})`);
1672
+ request.conversationState.history = history.length > 0 ? history : undefined;
1673
+ continue;
1674
+ }
1675
+ throw new Error(`Kiro API error: context_length_exceeded (${response.status} ${errText})`);
1676
+ }
1677
+ if (isTransientError(response.status) && transientRetryCount < TRANSIENT_MAX_RETRIES) {
1678
+ transientRetryCount++;
1679
+ const jitter = Math.floor(Math.random() * 1000);
1680
+ const delayMs = exponentialBackoff(transientRetryCount - 1, TRANSIENT_BASE_DELAY_MS, TRANSIENT_MAX_DELAY_MS) + jitter;
1681
+ log.warn(`transient error ${response.status} — retrying in ${delayMs}ms ` + `(${transientRetryCount}/${TRANSIENT_MAX_RETRIES})`);
1682
+ await abortableDelay(delayMs, options?.signal);
1683
+ continue;
1684
+ }
1685
+ if (response.status === 401) {
1686
+ const permanent = isPermanentError(errText);
1687
+ if (permanent) {
1688
+ profileArnCache.delete(endpoint);
1689
+ throw new Error(`Kiro API error: credentials permanently invalid — run /login kiro to re-authenticate. ${errText}`);
1690
+ }
1691
+ }
1692
+ if (response.status === 403) {
1693
+ profileArnCache.delete(endpoint);
1694
+ throw new Error(`Kiro API error: access token rejected (403) — run /login kiro to re-authenticate. ${errText}`);
1695
+ }
1696
+ throw new Error(`Kiro API error: ${response.status} ${response.statusText} ${errText}`);
1697
+ }
1698
+ if (capacityRetryCount > 0) {
1699
+ log.info(`recovered from capacity pressure after ${capacityRetryCount} retries`);
1700
+ }
1701
+ if (transientRetryCount > 0) {
1702
+ log.info(`recovered from transient error after ${transientRetryCount} retries`);
1703
+ }
1704
+ if (contextTruncationAttempt > 0) {
1705
+ log.info(`recovered after ${contextTruncationAttempt} context truncation(s)`);
1706
+ }
1707
+ const reader = response.body?.getReader();
1708
+ if (!reader)
1709
+ throw new Error("No response body");
1710
+ const decoder = new TextDecoder;
1711
+ let buffer = "";
1712
+ let totalContent = "";
1713
+ let lastContentData = "";
1714
+ let usageEvent = null;
1715
+ let receivedContextUsage = false;
1716
+ let chunkSeq = 0;
1717
+ let eventSeq = 0;
1718
+ const thinkingParser = thinkingEnabled ? new ThinkingTagParser(output, stream) : null;
1719
+ let textBlockIndex = null;
1720
+ let emittedToolCalls = 0;
1721
+ let sawAnyToolCalls = false;
1722
+ let currentToolCall = null;
1723
+ const flushToolCall = () => {
1724
+ if (!currentToolCall)
1725
+ return;
1726
+ if (emitToolCall(currentToolCall, output, stream))
1727
+ emittedToolCalls++;
1728
+ currentToolCall = null;
1729
+ };
1730
+ const cancelHiddenShim = () => {
1731
+ if (hiddenShimTimer) {
1732
+ clearTimeout(hiddenShimTimer);
1733
+ hiddenShimTimer = null;
1734
+ }
1735
+ };
1736
+ let idleTimer = null;
1737
+ let idleCancelled = false;
1738
+ const resetIdle = () => {
1739
+ if (idleTimer)
1740
+ clearTimeout(idleTimer);
1741
+ idleTimer = setTimeout(() => {
1742
+ idleCancelled = true;
1743
+ reader.cancel().catch(() => {});
1744
+ }, IDLE_TIMEOUT_MS);
1745
+ };
1746
+ let gotFirstToken = false;
1747
+ let firstTokenTimedOut = false;
1748
+ let streamError = null;
1749
+ const FIRST_TOKEN_SENTINEL = Symbol("firstTokenTimeout");
1750
+ while (true) {
1751
+ let readResult;
1752
+ if (!gotFirstToken) {
1753
+ const readPromise = reader.read();
1754
+ let firstTokenTimer = null;
1755
+ const result = await Promise.race([
1756
+ readPromise,
1757
+ new Promise((resolve2) => {
1758
+ firstTokenTimer = setTimeout(() => resolve2(FIRST_TOKEN_SENTINEL), firstTokenTimeoutForModel(model.id));
1759
+ })
1760
+ ]);
1761
+ if (firstTokenTimer)
1762
+ clearTimeout(firstTokenTimer);
1763
+ if (result === FIRST_TOKEN_SENTINEL) {
1764
+ readPromise.catch(() => {});
1765
+ reader.cancel().catch(() => {});
1766
+ firstTokenTimedOut = true;
1767
+ break;
1768
+ }
1769
+ readResult = result;
1770
+ gotFirstToken = true;
1771
+ resetIdle();
1772
+ } else {
1773
+ readResult = await reader.read();
1774
+ }
1775
+ const { done, value } = readResult;
1776
+ if (done)
1777
+ break;
1778
+ const decoded = decoder.decode(value, { stream: true });
1779
+ buffer += decoded;
1780
+ if (log.isDebug()) {
1781
+ log.debug("stream.chunk", {
1782
+ seq: chunkSeq++,
1783
+ bytes: value?.byteLength ?? 0,
1784
+ decodedLen: decoded.length,
1785
+ preview: previewChunk(decoded)
1786
+ });
1787
+ }
1788
+ const { events, remaining } = parseKiroEvents(buffer);
1789
+ buffer = remaining;
1790
+ if (events.length > 0)
1791
+ resetIdle();
1792
+ if (log.isDebug() && events.length > 0) {
1793
+ for (const ev of events) {
1794
+ log.debug("stream.event", { seq: eventSeq++, event: ev });
1795
+ }
1796
+ }
1797
+ for (const event of events) {
1798
+ switch (event.type) {
1799
+ case "contextUsage": {
1800
+ const pct = event.data.contextUsagePercentage;
1801
+ output.usage.input = pct >= COMPACTION_THRESHOLD_PCT ? model.contextWindow + 1 : Math.round(pct / 100 * model.contextWindow);
1802
+ receivedContextUsage = true;
1803
+ log.debug("contextUsage", { pct, threshold: COMPACTION_THRESHOLD_PCT, willCompact: pct >= COMPACTION_THRESHOLD_PCT });
1804
+ break;
1805
+ }
1806
+ case "reasoning": {
1807
+ cancelHiddenShim();
1808
+ if (output.content.length === 0 || output.content[output.content.length - 1]?.type !== "thinking") {
1809
+ output.content.push({ type: "thinking", thinking: "" });
1810
+ stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
1811
+ }
1812
+ const contentIndex = output.content.length - 1;
1813
+ const tc = output.content[contentIndex];
1814
+ if (event.data.text) {
1815
+ tc.thinking += event.data.text;
1816
+ stream.push({ type: "thinking_delta", contentIndex, delta: event.data.text, partial: output });
1817
+ }
1818
+ if (event.data.signature) {
1819
+ tc.thinkingSignature = event.data.signature;
1820
+ }
1821
+ break;
1822
+ }
1823
+ case "content": {
1824
+ if (event.data === lastContentData)
1825
+ continue;
1826
+ lastContentData = event.data;
1827
+ totalContent += event.data;
1828
+ cancelHiddenShim();
1829
+ if (thinkingParser) {
1830
+ thinkingParser.processChunk(event.data);
1831
+ } else {
1832
+ if (textBlockIndex === null) {
1833
+ textBlockIndex = output.content.length;
1834
+ output.content.push({ type: "text", text: "" });
1835
+ stream.push({ type: "text_start", contentIndex: textBlockIndex, partial: output });
1836
+ }
1837
+ const block = output.content[textBlockIndex];
1838
+ if (block) {
1839
+ block.text += event.data;
1840
+ stream.push({
1841
+ type: "text_delta",
1842
+ contentIndex: textBlockIndex,
1843
+ delta: event.data,
1844
+ partial: output
1845
+ });
1846
+ }
1847
+ }
1848
+ break;
1849
+ }
1850
+ case "toolUse": {
1851
+ const tc = event.data;
1852
+ cancelHiddenShim();
1853
+ sawAnyToolCalls = true;
1854
+ if (!currentToolCall || currentToolCall.toolUseId !== tc.toolUseId) {
1855
+ flushToolCall();
1856
+ currentToolCall = { toolUseId: tc.toolUseId, name: tc.name, input: "" };
1857
+ }
1858
+ currentToolCall.input += tc.input || "";
1859
+ if (tc.input)
1860
+ totalContent += tc.input;
1861
+ if (tc.stop)
1862
+ flushToolCall();
1863
+ break;
1864
+ }
1865
+ case "toolUseInput": {
1866
+ if (currentToolCall)
1867
+ currentToolCall.input += event.data.input || "";
1868
+ if (event.data.input)
1869
+ totalContent += event.data.input;
1870
+ break;
1871
+ }
1872
+ case "toolUseStop": {
1873
+ if (event.data.stop)
1874
+ flushToolCall();
1875
+ break;
1876
+ }
1877
+ case "usage": {
1878
+ usageEvent = event.data;
1879
+ break;
1880
+ }
1881
+ case "error": {
1882
+ streamError = event.data.message ? `${event.data.error}: ${event.data.message}` : event.data.error;
1883
+ reader.cancel().catch(() => {});
1884
+ break;
1885
+ }
1886
+ }
1887
+ if (streamError)
1888
+ break;
1889
+ }
1890
+ }
1891
+ if (idleTimer)
1892
+ clearTimeout(idleTimer);
1893
+ if (firstTokenTimedOut || idleCancelled || streamError) {
1894
+ if (retryCount < MAX_RETRIES) {
1895
+ retryCount++;
1896
+ const delayMs = exponentialBackoff(retryCount - 1, 1000, MAX_RETRY_DELAY_MS);
1897
+ log.warn(`stream ${firstTokenTimedOut ? "first-token timed out" : idleCancelled ? "idle timed out" : `error: ${streamError}`} — retrying (${retryCount}/${MAX_RETRIES})`);
1898
+ cancelHiddenShim();
1899
+ await abortableDelay(delayMs, options?.signal);
1900
+ output.content = [];
1901
+ textBlockIndex = null;
1902
+ continue;
1903
+ }
1904
+ if (streamError)
1905
+ throw new Error(`Kiro API stream error after max retries: ${streamError}`);
1906
+ throw new Error(`Kiro API error: ${firstTokenTimedOut ? "first token" : "idle"} timeout after max retries`);
1907
+ }
1908
+ cancelHiddenShim();
1909
+ if (currentToolCall && emitToolCall(currentToolCall, output, stream))
1910
+ emittedToolCalls++;
1911
+ if (thinkingParser) {
1912
+ thinkingParser.finalize();
1913
+ textBlockIndex = thinkingParser.getTextBlockIndex();
1914
+ }
1915
+ if (textBlockIndex !== null) {
1916
+ const block = output.content[textBlockIndex];
1917
+ if (block) {
1918
+ stream.push({
1919
+ type: "text_end",
1920
+ contentIndex: textBlockIndex,
1921
+ content: block.text,
1922
+ partial: output
1923
+ });
1924
+ }
1925
+ }
1926
+ if (usageEvent?.inputTokens !== undefined)
1927
+ output.usage.input = usageEvent.inputTokens;
1928
+ output.usage.output = usageEvent?.outputTokens ?? countTokens(totalContent);
1929
+ output.usage.totalTokens = output.usage.input + output.usage.output;
1930
+ try {
1931
+ calculateCost(model, output.usage);
1932
+ } catch {
1933
+ output.usage.cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
1934
+ }
1935
+ const textBlock = textBlockIndex !== null ? output.content[textBlockIndex] : undefined;
1936
+ const hasText = !!textBlock && textBlock.text.length > 0;
1937
+ if (!hasText && !sawAnyToolCalls) {
1938
+ if (retryCount < MAX_RETRIES) {
1939
+ retryCount++;
1940
+ const delayMs = exponentialBackoff(retryCount - 1, 1000, MAX_RETRY_DELAY_MS);
1941
+ log.warn(`empty response — retrying (${retryCount}/${MAX_RETRIES})`);
1942
+ cancelHiddenShim();
1943
+ output.content = [];
1944
+ textBlockIndex = null;
1945
+ await abortableDelay(delayMs, options?.signal);
1946
+ continue;
1947
+ }
1948
+ log.warn(`empty response persisted after ${MAX_RETRIES} retries`);
1949
+ cancelHiddenShim();
1950
+ }
1951
+ if (!receivedContextUsage && emittedToolCalls === 0) {
1952
+ output.stopReason = "length";
1953
+ } else {
1954
+ output.stopReason = emittedToolCalls > 0 ? "toolUse" : "stop";
1955
+ }
1956
+ stream.push({
1957
+ type: "done",
1958
+ reason: output.stopReason,
1959
+ message: output
1960
+ });
1961
+ log.debug("response.done", {
1962
+ stopReason: output.stopReason,
1963
+ emittedToolCalls,
1964
+ sawAnyToolCalls,
1965
+ usage: output.usage
1966
+ });
1967
+ stream.end();
1968
+ return;
1969
+ }
1970
+ } catch (error) {
1971
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
1972
+ output.errorMessage = error instanceof Error ? error.message : String(error);
1973
+ log.debug("response.caught", { stopReason: output.stopReason, error: output.errorMessage });
1974
+ if (hiddenShimTimer) {
1975
+ clearTimeout(hiddenShimTimer);
1976
+ hiddenShimTimer = null;
1977
+ }
1978
+ stream.push({ type: "error", reason: output.stopReason, error: output });
1979
+ stream.end();
1980
+ }
1981
+ })().catch(() => {
1982
+ try {
1983
+ stream.end();
1984
+ } catch {}
1985
+ });
1986
+ return stream;
1987
+ }
1988
+
1989
+ // src/models.ts
1990
+ var KIRO_MODEL_IDS = new Set([
1991
+ "claude-opus-4.8",
1992
+ "claude-opus-4.7",
1993
+ "claude-opus-4.6",
1994
+ "claude-opus-4.6-1m",
1995
+ "claude-sonnet-4.6",
1996
+ "claude-sonnet-4.6-1m",
1997
+ "claude-opus-4.5",
1998
+ "claude-sonnet-4.5",
1999
+ "claude-sonnet-4.5-1m",
2000
+ "claude-sonnet-4",
2001
+ "claude-haiku-4.5",
2002
+ "deepseek-3.2",
2003
+ "kimi-k2.5",
2004
+ "minimax-m2.1",
2005
+ "minimax-m2.5",
2006
+ "glm-4.7",
2007
+ "glm-4.7-flash",
2008
+ "qwen3-coder-next",
2009
+ "agi-nova-beta-1m",
2010
+ "qwen3-coder-480b",
2011
+ "auto"
2012
+ ]);
2013
+ function dotToDash(modelId) {
2014
+ return modelId.replace(/(\d)\.(\d)/g, "$1-$2");
2015
+ }
2016
+ function resolveKiroModel(modelId) {
2017
+ const kiroId = modelId.replace(/(\d)-(\d)/g, "$1.$2");
2018
+ if (!KIRO_MODEL_IDS.has(kiroId)) {
2019
+ throw new Error(`Unknown Kiro model ID: ${modelId}`);
2020
+ }
2021
+ return kiroId;
2022
+ }
2023
+ var API_REGION_MAP = {
2024
+ "us-west-1": "us-east-1",
2025
+ "us-west-2": "us-east-1",
2026
+ "us-east-2": "us-east-1",
2027
+ "eu-west-1": "eu-central-1",
2028
+ "eu-west-2": "eu-central-1",
2029
+ "eu-west-3": "eu-central-1",
2030
+ "eu-north-1": "eu-central-1",
2031
+ "eu-south-1": "eu-central-1",
2032
+ "eu-south-2": "eu-central-1",
2033
+ "eu-central-2": "eu-central-1",
2034
+ "ap-northeast-1": "us-east-1",
2035
+ "ap-northeast-2": "us-east-1",
2036
+ "ap-northeast-3": "us-east-1",
2037
+ "ap-southeast-1": "us-east-1",
2038
+ "ap-southeast-2": "us-east-1",
2039
+ "ap-south-1": "us-east-1",
2040
+ "ap-east-1": "us-east-1",
2041
+ "ap-south-2": "us-east-1",
2042
+ "ap-southeast-3": "us-east-1",
2043
+ "ap-southeast-4": "us-east-1"
2044
+ };
2045
+ function resolveApiRegion(ssoRegion) {
2046
+ if (!ssoRegion)
2047
+ return "us-east-1";
2048
+ return API_REGION_MAP[ssoRegion] ?? ssoRegion;
2049
+ }
2050
+ var MODELS_BY_REGION = {
2051
+ "us-east-1": new Set([
2052
+ "claude-opus-4-8",
2053
+ "claude-opus-4-7",
2054
+ "claude-opus-4-6",
2055
+ "claude-opus-4-6-1m",
2056
+ "claude-sonnet-4-6",
2057
+ "claude-sonnet-4-6-1m",
2058
+ "claude-opus-4-5",
2059
+ "claude-sonnet-4-5",
2060
+ "claude-sonnet-4-5-1m",
2061
+ "claude-sonnet-4",
2062
+ "claude-haiku-4-5",
2063
+ "deepseek-3-2",
2064
+ "kimi-k2-5",
2065
+ "minimax-m2-1",
2066
+ "minimax-m2-5",
2067
+ "glm-4-7",
2068
+ "glm-4-7-flash",
2069
+ "qwen3-coder-next",
2070
+ "qwen3-coder-480b",
2071
+ "agi-nova-beta-1m",
2072
+ "auto"
2073
+ ]),
2074
+ "eu-central-1": new Set([
2075
+ "claude-opus-4-8",
2076
+ "claude-opus-4-7",
2077
+ "claude-opus-4-6",
2078
+ "claude-sonnet-4-6",
2079
+ "claude-opus-4-5",
2080
+ "claude-sonnet-4-5",
2081
+ "claude-sonnet-4",
2082
+ "claude-haiku-4-5",
2083
+ "minimax-m2-1",
2084
+ "minimax-m2-5",
2085
+ "qwen3-coder-next",
2086
+ "auto"
2087
+ ])
2088
+ };
2089
+ function filterModelsByRegion(models, apiRegion) {
2090
+ const allowed = MODELS_BY_REGION[apiRegion];
2091
+ if (!allowed) {
2092
+ console.warn(`[pi-kiro] Unknown API region "${apiRegion}" — no models available. Update MODELS_BY_REGION in models.ts.`);
2093
+ return [];
2094
+ }
2095
+ return models.filter((m) => allowed.has(m.id));
2096
+ }
2097
+ var RUNTIME_ENDPOINTS = {
2098
+ "us-east-1": "https://runtime.us-east-1.kiro.dev",
2099
+ "eu-central-1": "https://runtime.eu-central-1.kiro.dev"
2100
+ };
2101
+ function resolveRuntimeUrl(apiRegion) {
2102
+ return RUNTIME_ENDPOINTS[apiRegion] ?? `https://runtime.${apiRegion}.kiro.dev`;
2103
+ }
2104
+ var BASE_URL = resolveRuntimeUrl("us-east-1");
2105
+ var ZERO_COST = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
2106
+ var KIRO_DEFAULTS = {
2107
+ api: "kiro-api",
2108
+ provider: "kiro",
2109
+ baseUrl: BASE_URL,
2110
+ cost: ZERO_COST
2111
+ };
2112
+ var MULTIMODAL = ["text", "image"];
2113
+ var TEXT_ONLY = ["text"];
2114
+ var kiroModels = [
2115
+ {
2116
+ ...KIRO_DEFAULTS,
2117
+ id: "claude-opus-4-8",
2118
+ name: "Claude Opus 4.8",
2119
+ reasoning: true,
2120
+ input: MULTIMODAL,
2121
+ contextWindow: 1e6,
2122
+ maxTokens: 128000,
2123
+ firstTokenTimeout: 180000,
2124
+ supportedEfforts: ["low", "medium", "high", "xhigh", "max"]
2125
+ },
2126
+ {
2127
+ ...KIRO_DEFAULTS,
2128
+ id: "claude-opus-4-7",
2129
+ name: "Claude Opus 4.7",
2130
+ reasoning: true,
2131
+ input: MULTIMODAL,
2132
+ contextWindow: 1e6,
2133
+ maxTokens: 128000,
2134
+ firstTokenTimeout: 180000,
2135
+ supportedEfforts: ["low", "medium", "high", "xhigh", "max"]
2136
+ },
2137
+ {
2138
+ ...KIRO_DEFAULTS,
2139
+ id: "claude-opus-4-6",
2140
+ name: "Claude Opus 4.6",
2141
+ reasoning: true,
2142
+ input: MULTIMODAL,
2143
+ contextWindow: 1e6,
2144
+ maxTokens: 64000,
2145
+ supportedEfforts: ["low", "medium", "high", "max"]
2146
+ },
2147
+ {
2148
+ ...KIRO_DEFAULTS,
2149
+ id: "claude-opus-4-6-1m",
2150
+ name: "Claude Opus 4.6 (1M)",
2151
+ reasoning: true,
2152
+ input: MULTIMODAL,
2153
+ contextWindow: 1e6,
2154
+ maxTokens: 64000,
2155
+ supportedEfforts: ["low", "medium", "high", "max"]
2156
+ },
2157
+ {
2158
+ ...KIRO_DEFAULTS,
2159
+ id: "claude-sonnet-4-6",
2160
+ name: "Claude Sonnet 4.6",
2161
+ reasoning: true,
2162
+ input: MULTIMODAL,
2163
+ contextWindow: 1e6,
2164
+ maxTokens: 64000,
2165
+ supportedEfforts: ["low", "medium", "high", "max"]
2166
+ },
2167
+ {
2168
+ ...KIRO_DEFAULTS,
2169
+ id: "claude-sonnet-4-6-1m",
2170
+ name: "Claude Sonnet 4.6 (1M)",
2171
+ reasoning: true,
2172
+ input: MULTIMODAL,
2173
+ contextWindow: 1e6,
2174
+ maxTokens: 64000,
2175
+ supportedEfforts: ["low", "medium", "high", "max"]
2176
+ },
2177
+ {
2178
+ ...KIRO_DEFAULTS,
2179
+ id: "claude-opus-4-5",
2180
+ name: "Claude Opus 4.5",
2181
+ reasoning: true,
2182
+ input: MULTIMODAL,
2183
+ contextWindow: 200000,
2184
+ maxTokens: 64000
2185
+ },
2186
+ {
2187
+ ...KIRO_DEFAULTS,
2188
+ id: "claude-sonnet-4-5",
2189
+ name: "Claude Sonnet 4.5",
2190
+ reasoning: true,
2191
+ input: MULTIMODAL,
2192
+ contextWindow: 200000,
2193
+ maxTokens: 65536
2194
+ },
2195
+ {
2196
+ ...KIRO_DEFAULTS,
2197
+ id: "claude-sonnet-4-5-1m",
2198
+ name: "Claude Sonnet 4.5 (1M)",
2199
+ reasoning: true,
2200
+ input: MULTIMODAL,
2201
+ contextWindow: 1e6,
2202
+ maxTokens: 65536
2203
+ },
2204
+ {
2205
+ ...KIRO_DEFAULTS,
2206
+ id: "claude-sonnet-4",
2207
+ name: "Claude Sonnet 4",
2208
+ reasoning: true,
2209
+ input: MULTIMODAL,
2210
+ contextWindow: 200000,
2211
+ maxTokens: 65536
2212
+ },
2213
+ {
2214
+ ...KIRO_DEFAULTS,
2215
+ id: "claude-haiku-4-5",
2216
+ name: "Claude Haiku 4.5",
2217
+ reasoning: false,
2218
+ input: MULTIMODAL,
2219
+ contextWindow: 200000,
2220
+ maxTokens: 65536
2221
+ },
2222
+ {
2223
+ ...KIRO_DEFAULTS,
2224
+ id: "deepseek-3-2",
2225
+ name: "DeepSeek 3.2",
2226
+ reasoning: true,
2227
+ input: TEXT_ONLY,
2228
+ contextWindow: 128000,
2229
+ maxTokens: 8192
2230
+ },
2231
+ {
2232
+ ...KIRO_DEFAULTS,
2233
+ id: "kimi-k2-5",
2234
+ name: "Kimi K2.5",
2235
+ reasoning: true,
2236
+ input: TEXT_ONLY,
2237
+ contextWindow: 200000,
2238
+ maxTokens: 8192
2239
+ },
2240
+ {
2241
+ ...KIRO_DEFAULTS,
2242
+ id: "minimax-m2-5",
2243
+ name: "MiniMax M2.5",
2244
+ reasoning: false,
2245
+ input: TEXT_ONLY,
2246
+ contextWindow: 196000,
2247
+ maxTokens: 64000
2248
+ },
2249
+ {
2250
+ ...KIRO_DEFAULTS,
2251
+ id: "minimax-m2-1",
2252
+ name: "MiniMax M2.1",
2253
+ reasoning: false,
2254
+ input: MULTIMODAL,
2255
+ contextWindow: 196000,
2256
+ maxTokens: 64000
2257
+ },
2258
+ {
2259
+ ...KIRO_DEFAULTS,
2260
+ id: "glm-4-7",
2261
+ name: "GLM 4.7",
2262
+ reasoning: true,
2263
+ input: TEXT_ONLY,
2264
+ contextWindow: 128000,
2265
+ maxTokens: 8192
2266
+ },
2267
+ {
2268
+ ...KIRO_DEFAULTS,
2269
+ id: "glm-4-7-flash",
2270
+ name: "GLM 4.7 Flash",
2271
+ reasoning: false,
2272
+ input: TEXT_ONLY,
2273
+ contextWindow: 128000,
2274
+ maxTokens: 8192
2275
+ },
2276
+ {
2277
+ ...KIRO_DEFAULTS,
2278
+ id: "qwen3-coder-next",
2279
+ name: "Qwen3 Coder Next",
2280
+ reasoning: true,
2281
+ input: MULTIMODAL,
2282
+ contextWindow: 256000,
2283
+ maxTokens: 64000
2284
+ },
2285
+ {
2286
+ ...KIRO_DEFAULTS,
2287
+ id: "qwen3-coder-480b",
2288
+ name: "Qwen3 Coder 480B",
2289
+ reasoning: true,
2290
+ input: TEXT_ONLY,
2291
+ contextWindow: 128000,
2292
+ maxTokens: 8192
2293
+ },
2294
+ {
2295
+ ...KIRO_DEFAULTS,
2296
+ id: "agi-nova-beta-1m",
2297
+ name: "AGI Nova Beta (1M)",
2298
+ reasoning: true,
2299
+ input: MULTIMODAL,
2300
+ contextWindow: 1e6,
2301
+ maxTokens: 65536
2302
+ },
2303
+ {
2304
+ ...KIRO_DEFAULTS,
2305
+ id: "auto",
2306
+ name: "Auto",
2307
+ reasoning: true,
2308
+ input: MULTIMODAL,
2309
+ contextWindow: 200000,
2310
+ maxTokens: 65536
2311
+ }
2312
+ ];
2313
+ async function fetchAvailableModels(accessToken, apiRegion) {
2314
+ const runtimeUrl = `https://runtime.${apiRegion}.kiro.dev/`;
2315
+ const profileArn = await resolveProfileArn(accessToken, runtimeUrl);
2316
+ if (!profileArn) {
2317
+ throw new Error("Missing profileArn: cannot fetch available models.");
2318
+ }
2319
+ const url = `https://management.${apiRegion}.kiro.dev/ListAvailableModels?origin=KIRO_CLI&profileArn=${encodeURIComponent(profileArn)}`;
2320
+ const resp = await fetch(url, {
2321
+ method: "GET",
2322
+ headers: {
2323
+ Authorization: `Bearer ${accessToken}`,
2324
+ Accept: "application/json",
2325
+ "User-Agent": "pi-kiro"
2326
+ }
2327
+ });
2328
+ if (!resp.ok) {
2329
+ throw new Error(`ListAvailableModels failed: HTTP ${resp.status}`);
2330
+ }
2331
+ const data = await resp.json();
2332
+ return (data.models ?? []).filter((m) => m.modelId !== "auto");
2333
+ }
2334
+ var REASONING_FAMILIES = new Set([
2335
+ "claude-sonnet",
2336
+ "claude-opus",
2337
+ "deepseek",
2338
+ "kimi",
2339
+ "glm",
2340
+ "qwen",
2341
+ "agi-nova",
2342
+ "minimax"
2343
+ ]);
2344
+ function isReasoningModel(dotId) {
2345
+ for (const family of REASONING_FAMILIES) {
2346
+ if (dotId.startsWith(family))
2347
+ return true;
2348
+ }
2349
+ return false;
2350
+ }
2351
+ function firstTokenTimeout(dotId) {
2352
+ if (dotId.startsWith("claude-opus"))
2353
+ return 180000;
2354
+ return 90000;
2355
+ }
2356
+ function buildModelsFromApi(apiModels) {
2357
+ return apiModels.map((m) => {
2358
+ KIRO_MODEL_IDS.add(m.modelId);
2359
+ const dashId = dotToDash(m.modelId);
2360
+ const supportedTypes = m.supportedInputTypes ?? ["TEXT"];
2361
+ const input = supportedTypes.includes("IMAGE") ? ["text", "image"] : ["text"];
2362
+ const effortEnum = m.additionalModelRequestFieldsSchema?.properties?.output_config?.properties?.effort?.enum;
2363
+ const supportedEfforts = Array.isArray(effortEnum) && effortEnum.length > 0 ? effortEnum : undefined;
2364
+ const supportsThinkingConfig = !!m.additionalModelRequestFieldsSchema?.properties?.thinking;
2365
+ return {
2366
+ id: dashId,
2367
+ name: m.modelName,
2368
+ reasoning: isReasoningModel(m.modelId),
2369
+ input,
2370
+ contextWindow: m.tokenLimits?.maxInputTokens ?? 200000,
2371
+ maxTokens: m.tokenLimits?.maxOutputTokens ?? 8192,
2372
+ firstTokenTimeout: firstTokenTimeout(m.modelId),
2373
+ ...supportedEfforts ? { supportedEfforts } : {},
2374
+ ...supportsThinkingConfig ? { supportsThinkingConfig } : {}
2375
+ };
2376
+ });
2377
+ }
2378
+ var cachedDynamicModels = null;
2379
+ function getCachedDynamicModels() {
2380
+ return cachedDynamicModels;
2381
+ }
2382
+ function setCachedDynamicModels(models) {
2383
+ cachedDynamicModels = models;
2384
+ }
2385
+
2386
+ // src/oauth.ts
2387
+ var BUILDER_ID_START_URL = "https://view.awsapps.com/start";
2388
+ var BUILDER_ID_REGION = "us-east-1";
2389
+ var SSO_SCOPES = [
2390
+ "codewhisperer:completions",
2391
+ "codewhisperer:analysis",
2392
+ "codewhisperer:conversations",
2393
+ "codewhisperer:transformations",
2394
+ "codewhisperer:taskassist"
2395
+ ];
2396
+ var IDC_PROBE_REGIONS = [
2397
+ "us-east-1",
2398
+ "eu-west-1",
2399
+ "eu-central-1",
2400
+ "us-east-2",
2401
+ "eu-west-2",
2402
+ "eu-west-3",
2403
+ "eu-north-1",
2404
+ "ap-southeast-1",
2405
+ "ap-northeast-1",
2406
+ "us-west-2"
2407
+ ];
2408
+ var EXPIRES_BUFFER_MS = 5 * 60 * 1000;
2409
+ function abortableDelay2(ms, signal) {
2410
+ if (signal?.aborted)
2411
+ return Promise.reject(signal.reason ?? new Error("Login cancelled"));
2412
+ return new Promise((resolve2, reject) => {
2413
+ const timer = setTimeout(resolve2, ms);
2414
+ signal?.addEventListener("abort", () => {
2415
+ clearTimeout(timer);
2416
+ reject(signal.reason ?? new Error("Login cancelled"));
2417
+ }, { once: true });
2418
+ });
2419
+ }
2420
+ async function tryRegisterAndAuthorize(startUrl, region) {
2421
+ const oidcEndpoint = `https://oidc.${region}.amazonaws.com`;
2422
+ const regResp = await fetch(`${oidcEndpoint}/client/register`, {
2423
+ method: "POST",
2424
+ headers: { "Content-Type": "application/json", "User-Agent": "pi-kiro" },
2425
+ body: JSON.stringify({
2426
+ clientName: "pi-kiro",
2427
+ clientType: "public",
2428
+ scopes: SSO_SCOPES,
2429
+ grantTypes: ["urn:ietf:params:oauth:grant-type:device_code", "refresh_token"]
2430
+ })
2431
+ });
2432
+ if (!regResp.ok)
2433
+ return null;
2434
+ const { clientId, clientSecret } = await regResp.json();
2435
+ const devResp = await fetch(`${oidcEndpoint}/device_authorization`, {
2436
+ method: "POST",
2437
+ headers: { "Content-Type": "application/json", "User-Agent": "pi-kiro" },
2438
+ body: JSON.stringify({ clientId, clientSecret, startUrl })
2439
+ });
2440
+ if (!devResp.ok)
2441
+ return null;
2442
+ return {
2443
+ clientId,
2444
+ clientSecret,
2445
+ oidcEndpoint,
2446
+ devAuth: await devResp.json()
2447
+ };
2448
+ }
2449
+ async function pollForToken(oidcEndpoint, clientId, clientSecret, devAuth, signal) {
2450
+ const deadline = Date.now() + (devAuth.expiresIn || 600) * 1000;
2451
+ const baseInterval = (devAuth.interval || 5) * 1000;
2452
+ let interval = baseInterval;
2453
+ while (Date.now() < deadline) {
2454
+ if (signal?.aborted)
2455
+ throw new Error("Login cancelled");
2456
+ await abortableDelay2(interval, signal);
2457
+ let resp;
2458
+ try {
2459
+ resp = await fetch(`${oidcEndpoint}/token`, {
2460
+ method: "POST",
2461
+ headers: { "Content-Type": "application/json", "User-Agent": "pi-kiro" },
2462
+ body: JSON.stringify({
2463
+ clientId,
2464
+ clientSecret,
2465
+ deviceCode: devAuth.deviceCode,
2466
+ grantType: "urn:ietf:params:oauth:grant-type:device_code"
2467
+ })
2468
+ });
2469
+ } catch {
2470
+ continue;
2471
+ }
2472
+ if (resp.status >= 500)
2473
+ continue;
2474
+ let data;
2475
+ try {
2476
+ data = await resp.json();
2477
+ } catch {
2478
+ if (!resp.ok) {
2479
+ throw new Error(`Authorization failed: HTTP ${resp.status}`);
2480
+ }
2481
+ continue;
2482
+ }
2483
+ if (!data.error && data.accessToken && data.refreshToken)
2484
+ return data;
2485
+ if (data.error === "authorization_pending")
2486
+ continue;
2487
+ if (data.error === "slow_down") {
2488
+ interval += baseInterval;
2489
+ continue;
2490
+ }
2491
+ if (data.error)
2492
+ throw new Error(`Authorization failed: ${data.error}`);
2493
+ }
2494
+ throw new Error("Authorization timed out");
2495
+ }
2496
+ async function loginKiro(callbacks) {
2497
+ const method = await callbacks.onSelect({
2498
+ message: "Select login method:",
2499
+ options: [
2500
+ { id: "builder-id", label: "AWS Builder ID (personal account)" },
2501
+ { id: "idc", label: "IAM Identity Center (enterprise SSO)" },
2502
+ { id: "sync", label: "Import from Kiro IDE (auto-sync local DB)" },
2503
+ { id: "desktop", label: "Desktop refresh token (manual)" }
2504
+ ]
2505
+ });
2506
+ if (!method)
2507
+ throw new Error("Login cancelled");
2508
+ if (method === "sync") {
2509
+ return loginCliSync(callbacks);
2510
+ }
2511
+ if (method === "desktop") {
2512
+ return loginDesktopManual(callbacks);
2513
+ }
2514
+ if (method === "builder-id") {
2515
+ return runDeviceCodeFlow(callbacks, BUILDER_ID_START_URL, [BUILDER_ID_REGION], "builder-id");
2516
+ }
2517
+ const startUrl = (await callbacks.onPrompt({
2518
+ message: "Paste your IAM Identity Center start URL:",
2519
+ placeholder: "https://mycompany.awsapps.com/start",
2520
+ allowEmpty: false
2521
+ }))?.trim();
2522
+ if (!startUrl || !startUrl.startsWith("http")) {
2523
+ throw new Error(`Invalid start URL "${startUrl ?? ""}" — expected https://…`);
2524
+ }
2525
+ const regionRaw = await callbacks.onPrompt({
2526
+ message: `Identity Center region, or blank to auto-detect (${IDC_PROBE_REGIONS.join(", ")})`,
2527
+ placeholder: "us-east-1",
2528
+ allowEmpty: true
2529
+ });
2530
+ const region = (regionRaw ?? "").trim();
2531
+ const regions = region ? [region] : IDC_PROBE_REGIONS;
2532
+ callbacks.onProgress?.(region ? `Connecting to ${region}…` : "Detecting your Identity Center region…");
2533
+ return runDeviceCodeFlow(callbacks, startUrl, regions, "idc");
2534
+ }
2535
+ async function loginCliSync(callbacks) {
2536
+ callbacks.onProgress?.("Scanning for Kiro IDE credentials (~/.kiro/db)…");
2537
+ const { importFromKiroCli: importFromKiroCli2 } = await Promise.resolve().then(() => (init_kiro_cli_sync(), exports_kiro_cli_sync));
2538
+ const imported = await importFromKiroCli2();
2539
+ if (!imported || !imported.accessToken && !imported.refreshToken) {
2540
+ throw new Error(`No Kiro IDE credentials found.
2541
+ Make sure Kiro IDE is installed and you're logged in, then try again.
2542
+ Alternatively, use 'desktop' to paste a refresh token manually.`);
2543
+ }
2544
+ log.info("Successfully imported credentials from Kiro IDE");
2545
+ callbacks.onProgress?.(`Imported from Kiro IDE (${imported.authMethod}, ${imported.region}${imported.email ? `, ${imported.email}` : ""})`);
2546
+ try {
2547
+ const apiRegion = resolveApiRegion(imported.region);
2548
+ const apiModels = await fetchAvailableModels(imported.accessToken, apiRegion);
2549
+ setCachedDynamicModels(buildModelsFromApi(apiModels));
2550
+ log.info(`Fetched and cached ${apiModels.length} models after CLI sync`);
2551
+ } catch (err) {
2552
+ log.warn(`Failed to fetch models after CLI sync: ${err}`);
2553
+ }
2554
+ const refreshPacked = imported.clientId ? `${imported.refreshToken}|${imported.clientId}|${imported.clientSecret ?? ""}|${imported.authMethod}` : `${imported.refreshToken}|||desktop`;
2555
+ return {
2556
+ refresh: refreshPacked,
2557
+ access: imported.accessToken,
2558
+ expires: Date.now() + 3600000 - EXPIRES_BUFFER_MS,
2559
+ clientId: imported.clientId ?? "",
2560
+ clientSecret: imported.clientSecret ?? "",
2561
+ region: imported.region,
2562
+ authMethod: imported.authMethod
2563
+ };
2564
+ }
2565
+ async function loginDesktopManual(callbacks) {
2566
+ const refreshRaw = await callbacks.onPrompt({
2567
+ message: `Paste your Kiro desktop refresh token
2568
+ ` + "(find it in ~/.kiro/db/kiro.db → auth_kv table):",
2569
+ placeholder: "refresh-token",
2570
+ allowEmpty: true
2571
+ });
2572
+ const refreshToken = (refreshRaw ?? "").trim();
2573
+ if (!refreshToken) {
2574
+ throw new Error("Login cancelled — no refresh token provided");
2575
+ }
2576
+ const regionRaw = await callbacks.onPrompt({
2577
+ message: "Kiro region:",
2578
+ placeholder: "us-east-1",
2579
+ allowEmpty: true
2580
+ });
2581
+ const region = (regionRaw ?? "").trim() || "us-east-1";
2582
+ const refreshCreds = {
2583
+ refresh: `${refreshToken}|||desktop`,
2584
+ access: "",
2585
+ expires: 0,
2586
+ clientId: "",
2587
+ clientSecret: "",
2588
+ region,
2589
+ authMethod: "desktop"
2590
+ };
2591
+ callbacks.onProgress?.("Exchanging refresh token…");
2592
+ return refreshKiroToken(refreshCreds);
2593
+ }
2594
+ async function runDeviceCodeFlow(callbacks, startUrl, regions, authMethod) {
2595
+ let result = null;
2596
+ let detectedRegion = "";
2597
+ for (const region of regions) {
2598
+ result = await tryRegisterAndAuthorize(startUrl, region);
2599
+ if (result) {
2600
+ detectedRegion = region;
2601
+ if (regions.length > 1)
2602
+ callbacks.onProgress?.(`Region: ${region}`);
2603
+ break;
2604
+ }
2605
+ }
2606
+ if (!result || !detectedRegion) {
2607
+ throw new Error(`Could not authorize ${startUrl} in ${regions.join(", ")}. Check your start URL${regions.length === 1 ? " and region" : ""} and try again.`);
2608
+ }
2609
+ callbacks.onAuth({
2610
+ url: result.devAuth.verificationUriComplete,
2611
+ instructions: `Code: ${result.devAuth.userCode}
2612
+ Complete authorization within 10 minutes.`
2613
+ });
2614
+ callbacks.onProgress?.("Waiting for browser authorization (up to 10 minutes)…");
2615
+ const tok = await pollForToken(result.oidcEndpoint, result.clientId, result.clientSecret, result.devAuth, callbacks.signal);
2616
+ if (!tok.accessToken || !tok.refreshToken) {
2617
+ throw new Error("Authorization completed but no tokens returned");
2618
+ }
2619
+ try {
2620
+ const apiRegion = resolveApiRegion(detectedRegion);
2621
+ const apiModels = await fetchAvailableModels(tok.accessToken, apiRegion);
2622
+ setCachedDynamicModels(buildModelsFromApi(apiModels));
2623
+ log.info(`Fetched and cached ${apiModels.length} models after login`);
2624
+ } catch (err) {
2625
+ log.warn(`Failed to fetch models after login, falling back: ${err}`);
2626
+ }
2627
+ return {
2628
+ refresh: `${tok.refreshToken}|${result.clientId}|${result.clientSecret}|${authMethod}`,
2629
+ access: tok.accessToken,
2630
+ expires: Date.now() + (tok.expiresIn ?? 3600) * 1000 - EXPIRES_BUFFER_MS,
2631
+ clientId: result.clientId,
2632
+ clientSecret: result.clientSecret,
2633
+ region: detectedRegion,
2634
+ authMethod
2635
+ };
2636
+ }
2637
+ async function syncBackToKiroCli(result) {
2638
+ try {
2639
+ const { saveKiroCliCredentials: saveKiroCliCredentials2 } = await Promise.resolve().then(() => (init_kiro_cli_sync(), exports_kiro_cli_sync));
2640
+ const synced = await saveKiroCliCredentials2({
2641
+ accessToken: result.access,
2642
+ refreshToken: result.refresh.split("|")[0] ?? "",
2643
+ region: result.region,
2644
+ authMethod: result.authMethod === "builder-id" ? "idc" : result.authMethod
2645
+ });
2646
+ if (synced)
2647
+ log.info("Synced refreshed credentials back to Kiro CLI DB");
2648
+ } catch (err) {
2649
+ log.debug(`Credential sync-back skipped: ${err}`);
2650
+ }
2651
+ }
2652
+ function kiroCredsFromCliImport(imported) {
2653
+ const authMethod = imported.authMethod === "idc" ? "idc" : "desktop";
2654
+ const refreshPacked = imported.clientId ? `${imported.refreshToken}|${imported.clientId}|${imported.clientSecret ?? ""}|${authMethod}` : `${imported.refreshToken}|||desktop`;
2655
+ return {
2656
+ refresh: refreshPacked,
2657
+ access: imported.accessToken,
2658
+ expires: Date.now() + 3600000 - EXPIRES_BUFFER_MS,
2659
+ clientId: imported.clientId ?? "",
2660
+ clientSecret: imported.clientSecret ?? "",
2661
+ region: imported.region,
2662
+ authMethod
2663
+ };
2664
+ }
2665
+ async function refreshTokenInner(credentials) {
2666
+ const parts = credentials.refresh.split("|");
2667
+ const refreshToken = parts[0] ?? "";
2668
+ const clientId = parts[1] ?? credentials.clientId ?? "";
2669
+ const clientSecret = parts[2] ?? credentials.clientSecret ?? "";
2670
+ const region = credentials.region;
2671
+ const authMethod = credentials.authMethod;
2672
+ if (!refreshToken || !region) {
2673
+ throw new Error("Refresh token is missing region — re-login required");
2674
+ }
2675
+ if (authMethod !== "desktop" && (!clientId || !clientSecret)) {
2676
+ throw new Error("Refresh token is missing clientId/clientSecret — re-login required");
2677
+ }
2678
+ if (authMethod === "desktop") {
2679
+ const desktopEndpoint = `https://prod.${region}.auth.desktop.kiro.dev/refreshToken`;
2680
+ const resp2 = await fetch(desktopEndpoint, {
2681
+ method: "POST",
2682
+ headers: { "Content-Type": "application/json", "User-Agent": "pi-kiro" },
2683
+ body: JSON.stringify({ refreshToken })
2684
+ });
2685
+ if (!resp2.ok) {
2686
+ const body = await resp2.text().catch(() => "");
2687
+ throw new Error(`Desktop token refresh failed: ${resp2.status} ${body}`);
2688
+ }
2689
+ const data2 = await resp2.json();
2690
+ try {
2691
+ const apiRegion = resolveApiRegion(region);
2692
+ const apiModels = await fetchAvailableModels(data2.accessToken, apiRegion);
2693
+ setCachedDynamicModels(buildModelsFromApi(apiModels));
2694
+ log.info(`Fetched and cached ${apiModels.length} models after desktop token refresh`);
2695
+ } catch (err) {
2696
+ log.warn(`Failed to fetch models after desktop token refresh: ${err}`);
2697
+ }
2698
+ return {
2699
+ refresh: `${data2.refreshToken}|||desktop`,
2700
+ access: data2.accessToken,
2701
+ expires: Date.now() + (data2.expiresIn ?? 3600) * 1000 - EXPIRES_BUFFER_MS,
2702
+ clientId: "",
2703
+ clientSecret: "",
2704
+ region,
2705
+ authMethod: "desktop"
2706
+ };
2707
+ }
2708
+ const endpoint = `https://oidc.${region}.amazonaws.com/token`;
2709
+ const resp = await fetch(endpoint, {
2710
+ method: "POST",
2711
+ headers: { "Content-Type": "application/json", "User-Agent": "pi-kiro" },
2712
+ body: JSON.stringify({ clientId, clientSecret, refreshToken, grantType: "refresh_token" })
2713
+ });
2714
+ if (!resp.ok) {
2715
+ const body = await resp.text().catch(() => "");
2716
+ throw new Error(`Token refresh failed: ${resp.status} ${body}`);
2717
+ }
2718
+ const data = await resp.json();
2719
+ try {
2720
+ const apiRegion = resolveApiRegion(region);
2721
+ const apiModels = await fetchAvailableModels(data.accessToken, apiRegion);
2722
+ setCachedDynamicModels(buildModelsFromApi(apiModels));
2723
+ log.info(`Fetched and cached ${apiModels.length} models after token refresh`);
2724
+ } catch (err) {
2725
+ log.warn(`Failed to fetch models after token refresh, falling back: ${err}`);
2726
+ }
2727
+ return {
2728
+ refresh: `${data.refreshToken}|${clientId}|${clientSecret}|${authMethod}`,
2729
+ access: data.accessToken,
2730
+ expires: Date.now() + (data.expiresIn ?? 3600) * 1000 - EXPIRES_BUFFER_MS,
2731
+ clientId,
2732
+ clientSecret,
2733
+ region,
2734
+ authMethod
2735
+ };
2736
+ }
2737
+ async function refreshKiroToken(credentials) {
2738
+ const inputMethod = credentials.authMethod;
2739
+ const authMethod = inputMethod === "builder-id" || inputMethod === "idc" || inputMethod === "desktop" ? inputMethod : "idc";
2740
+ if (inputMethod !== undefined && inputMethod !== "builder-id" && inputMethod !== "idc" && inputMethod !== "desktop") {
2741
+ log.warn(`refreshKiroToken: unrecognized authMethod "${String(inputMethod)}" — defaulting to "idc"`);
2742
+ }
2743
+ const baseCreds = {
2744
+ ...credentials,
2745
+ clientId: credentials.clientId ?? credentials.refresh.split("|")[1] ?? "",
2746
+ clientSecret: credentials.clientSecret ?? credentials.refresh.split("|")[2] ?? "",
2747
+ region: credentials.region,
2748
+ authMethod
2749
+ };
2750
+ const errors = [];
2751
+ try {
2752
+ log.debug("refresh.cascade: layer 1 — normal refresh");
2753
+ const result = await refreshTokenInner(baseCreds);
2754
+ syncBackToKiroCli(result);
2755
+ return result;
2756
+ } catch (err) {
2757
+ const msg = err instanceof Error ? err.message : String(err);
2758
+ errors.push(`L1(normal): ${msg}`);
2759
+ log.warn(`refresh.cascade: layer 1 failed — ${msg}`);
2760
+ }
2761
+ let freshImport = null;
2762
+ try {
2763
+ log.debug("refresh.cascade: layer 2 — fresh kiro-cli import");
2764
+ const { importFromKiroCli: importFromKiroCli2 } = await Promise.resolve().then(() => (init_kiro_cli_sync(), exports_kiro_cli_sync));
2765
+ freshImport = await importFromKiroCli2();
2766
+ if (freshImport?.accessToken) {
2767
+ const result = kiroCredsFromCliImport(freshImport);
2768
+ log.info("refresh.cascade: layer 2 succeeded — using fresh kiro-cli credentials");
2769
+ return result;
2770
+ }
2771
+ errors.push("L2(fresh-import): no valid credentials found");
2772
+ log.debug("refresh.cascade: layer 2 — no fresh credentials");
2773
+ } catch (err) {
2774
+ const msg = err instanceof Error ? err.message : String(err);
2775
+ errors.push(`L2(fresh-import): ${msg}`);
2776
+ log.warn(`refresh.cascade: layer 2 failed — ${msg}`);
2777
+ }
2778
+ if (freshImport?.refreshToken) {
2779
+ try {
2780
+ log.debug("refresh.cascade: layer 3 — refresh fresh kiro-cli creds");
2781
+ const freshCreds = kiroCredsFromCliImport(freshImport);
2782
+ const result = await refreshTokenInner(freshCreds);
2783
+ syncBackToKiroCli(result);
2784
+ log.info("refresh.cascade: layer 3 succeeded — refreshed fresh kiro-cli credentials");
2785
+ return result;
2786
+ } catch (err) {
2787
+ const msg = err instanceof Error ? err.message : String(err);
2788
+ errors.push(`L3(refresh-fresh): ${msg}`);
2789
+ log.warn(`refresh.cascade: layer 3 failed — ${msg}`);
2790
+ }
2791
+ }
2792
+ let expiredImport = null;
2793
+ try {
2794
+ log.debug("refresh.cascade: layer 4 — expired kiro-cli import");
2795
+ const { getKiroCliCredentialsAllowExpired: getKiroCliCredentialsAllowExpired2 } = await Promise.resolve().then(() => (init_kiro_cli_sync(), exports_kiro_cli_sync));
2796
+ expiredImport = await getKiroCliCredentialsAllowExpired2();
2797
+ if (expiredImport?.accessToken && expiredImport !== freshImport) {
2798
+ const result = kiroCredsFromCliImport(expiredImport);
2799
+ log.info("refresh.cascade: layer 4 succeeded — using expired kiro-cli credentials");
2800
+ return result;
2801
+ }
2802
+ errors.push("L4(expired-import): no different expired credentials");
2803
+ log.debug("refresh.cascade: layer 4 — no additional expired credentials");
2804
+ } catch (err) {
2805
+ const msg = err instanceof Error ? err.message : String(err);
2806
+ errors.push(`L4(expired-import): ${msg}`);
2807
+ log.warn(`refresh.cascade: layer 4 failed — ${msg}`);
2808
+ }
2809
+ if (expiredImport?.refreshToken) {
2810
+ try {
2811
+ log.debug("refresh.cascade: layer 5 — refresh expired kiro-cli creds");
2812
+ const expiredCreds = kiroCredsFromCliImport(expiredImport);
2813
+ const result = await refreshTokenInner(expiredCreds);
2814
+ syncBackToKiroCli(result);
2815
+ log.info("refresh.cascade: layer 5 succeeded — refreshed expired kiro-cli credentials");
2816
+ return result;
2817
+ } catch (err) {
2818
+ const msg = err instanceof Error ? err.message : String(err);
2819
+ errors.push(`L5(refresh-expired): ${msg}`);
2820
+ log.warn(`refresh.cascade: layer 5 failed — ${msg}`);
2821
+ }
2822
+ }
2823
+ throw new Error(`Kiro token refresh failed — all 5 cascade layers exhausted. ` + `Re-login required.
2824
+ ${errors.join(`
2825
+ `)}`);
2826
+ }
2827
+
2828
+ // src/core.ts
2829
+ init_kiro_cli_sync();
2830
+ export {
2831
+ streamKiro,
2832
+ saveKiroCliCredentials,
2833
+ resolveRuntimeUrl,
2834
+ resolveKiroModel,
2835
+ resolveApiRegion,
2836
+ refreshKiroToken,
2837
+ loginKiro,
2838
+ kiroModels,
2839
+ isPermanentError,
2840
+ importFromKiroCli,
2841
+ getKiroCliCredentialsAllowExpired,
2842
+ filterModelsByRegion,
2843
+ collapseAgenticLoops,
2844
+ MAX_KIRO_IMAGE_BYTES,
2845
+ MAX_KIRO_IMAGES,
2846
+ KIRO_MODEL_IDS,
2847
+ BUILDER_ID_START_URL,
2848
+ BUILDER_ID_REGION
2849
+ };