ns-omp-provider-kiro 0.3.9 → 0.4.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/index.js +1705 -1032
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -238,11 +238,18 @@ function resolveApiRegion(ssoRegion) {
|
|
|
238
238
|
return "us-east-1";
|
|
239
239
|
return API_REGION_MAP[ssoRegion] ?? ssoRegion;
|
|
240
240
|
}
|
|
241
|
+
function endpointOverride(name, region) {
|
|
242
|
+
const value = process.env[name]?.trim();
|
|
243
|
+
if (!value)
|
|
244
|
+
return void 0;
|
|
245
|
+
const url = value.replaceAll("{region}", region);
|
|
246
|
+
return url.endsWith("/") ? url : `${url}/`;
|
|
247
|
+
}
|
|
241
248
|
function getKiroEndpoints(region) {
|
|
242
249
|
return {
|
|
243
250
|
region,
|
|
244
|
-
management: `https://management.${region}.kiro.dev/`,
|
|
245
|
-
runtime: `https://runtime.${region}.kiro.dev/`
|
|
251
|
+
management: endpointOverride(KIRO_MANAGEMENT_ENDPOINT_ENV, region) ?? `https://management.${region}.kiro.dev/`,
|
|
252
|
+
runtime: endpointOverride(KIRO_RUNTIME_ENDPOINT_ENV, region) ?? `https://runtime.${region}.kiro.dev/`
|
|
246
253
|
};
|
|
247
254
|
}
|
|
248
255
|
function getKiroRegionFromProfileArn(profileArn) {
|
|
@@ -262,7 +269,7 @@ function getKiroRegionFromEndpoint(endpoint) {
|
|
|
262
269
|
return void 0;
|
|
263
270
|
}
|
|
264
271
|
}
|
|
265
|
-
var API_REGION_MAP;
|
|
272
|
+
var API_REGION_MAP, KIRO_RUNTIME_ENDPOINT_ENV, KIRO_MANAGEMENT_ENDPOINT_ENV;
|
|
266
273
|
var init_endpoints = __esm({
|
|
267
274
|
"../kiro-core/dist/endpoints.js"() {
|
|
268
275
|
"use strict";
|
|
@@ -284,6 +291,441 @@ var init_endpoints = __esm({
|
|
|
284
291
|
"eu-south-2": "eu-central-1",
|
|
285
292
|
"eu-central-2": "eu-central-1"
|
|
286
293
|
};
|
|
294
|
+
KIRO_RUNTIME_ENDPOINT_ENV = "KIRO_RUNTIME_ENDPOINT";
|
|
295
|
+
KIRO_MANAGEMENT_ENDPOINT_ENV = "KIRO_MANAGEMENT_ENDPOINT";
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// ../bridge-core/dist/sidecar/binary.js
|
|
300
|
+
import { createRequire } from "node:module";
|
|
301
|
+
function findPackagedSidecarBinary() {
|
|
302
|
+
let bin;
|
|
303
|
+
try {
|
|
304
|
+
bin = localRequire(SIDECAR_BIN_PACKAGE);
|
|
305
|
+
} catch {
|
|
306
|
+
return { error: `${SIDECAR_BIN_PACKAGE} is not installed` };
|
|
307
|
+
}
|
|
308
|
+
try {
|
|
309
|
+
return { path: bin.binaryPath() };
|
|
310
|
+
} catch (error2) {
|
|
311
|
+
return { error: error2 instanceof Error ? error2.message : String(error2) };
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function resolveSidecarBinary(explicit, env = process.env, options = {}) {
|
|
315
|
+
const fromEnv = env[NS_BRIDGE_BIN_ENV]?.trim();
|
|
316
|
+
if (fromEnv)
|
|
317
|
+
return fromEnv;
|
|
318
|
+
if (explicit?.trim())
|
|
319
|
+
return explicit.trim();
|
|
320
|
+
const packaged = (options.packaged ?? findPackagedSidecarBinary)();
|
|
321
|
+
if ("path" in packaged)
|
|
322
|
+
return packaged.path;
|
|
323
|
+
return DEFAULT_SIDECAR_COMMAND;
|
|
324
|
+
}
|
|
325
|
+
var NS_BRIDGE_BIN_ENV, DEFAULT_SIDECAR_COMMAND, SIDECAR_BIN_PACKAGE, localRequire;
|
|
326
|
+
var init_binary = __esm({
|
|
327
|
+
"../bridge-core/dist/sidecar/binary.js"() {
|
|
328
|
+
"use strict";
|
|
329
|
+
NS_BRIDGE_BIN_ENV = "NS_BRIDGE_BIN";
|
|
330
|
+
DEFAULT_SIDECAR_COMMAND = "ns-bridge";
|
|
331
|
+
SIDECAR_BIN_PACKAGE = "ns-bridge-bin";
|
|
332
|
+
localRequire = createRequire(import.meta.url);
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
// ../bridge-core/dist/sidecar/errors.js
|
|
337
|
+
var SidecarError;
|
|
338
|
+
var init_errors = __esm({
|
|
339
|
+
"../bridge-core/dist/sidecar/errors.js"() {
|
|
340
|
+
"use strict";
|
|
341
|
+
SidecarError = class _SidecarError extends Error {
|
|
342
|
+
name = "SidecarError";
|
|
343
|
+
kind;
|
|
344
|
+
vendor;
|
|
345
|
+
status;
|
|
346
|
+
retryAfterMs;
|
|
347
|
+
reasonCode;
|
|
348
|
+
vendorError;
|
|
349
|
+
providerAttempts;
|
|
350
|
+
exitCode;
|
|
351
|
+
exitSignal;
|
|
352
|
+
stderr;
|
|
353
|
+
constructor(kind, message, details = {}) {
|
|
354
|
+
super(message, details.cause === void 0 ? void 0 : { cause: details.cause });
|
|
355
|
+
this.kind = kind;
|
|
356
|
+
this.vendor = details.vendor;
|
|
357
|
+
this.status = details.status;
|
|
358
|
+
this.retryAfterMs = details.retryAfterMs;
|
|
359
|
+
this.reasonCode = details.reasonCode;
|
|
360
|
+
this.vendorError = details.vendorError;
|
|
361
|
+
this.providerAttempts = details.providerAttempts;
|
|
362
|
+
this.exitCode = details.exitCode;
|
|
363
|
+
this.exitSignal = details.exitSignal;
|
|
364
|
+
this.stderr = details.stderr;
|
|
365
|
+
}
|
|
366
|
+
/** Rebuild the error a binary reported on its terminal line. */
|
|
367
|
+
static fromPayload(payload, details = {}) {
|
|
368
|
+
const kind = typeof payload.kind === "string" ? payload.kind : "internal";
|
|
369
|
+
const message = typeof payload.message === "string" && payload.message ? payload.message : `sidecar ${kind} error`;
|
|
370
|
+
return new _SidecarError(kind, message, {
|
|
371
|
+
...details,
|
|
372
|
+
vendor: payload.vendor ?? details.vendor,
|
|
373
|
+
status: payload.status,
|
|
374
|
+
retryAfterMs: payload.retryAfterMs,
|
|
375
|
+
reasonCode: payload.reasonCode,
|
|
376
|
+
vendorError: payload.vendorError,
|
|
377
|
+
providerAttempts: payload.providerAttempts
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
// ../bridge-core/dist/sidecar/stream.js
|
|
385
|
+
import { spawn } from "node:child_process";
|
|
386
|
+
async function* sidecarStream(vendor, request, options = {}) {
|
|
387
|
+
let sawDone = false;
|
|
388
|
+
for await (const message of sidecarLines(vendor, ["stream", "--vendor", vendor], request, options, "done")) {
|
|
389
|
+
if (!EVENT_TYPES.has(message.type))
|
|
390
|
+
continue;
|
|
391
|
+
if (sawDone)
|
|
392
|
+
continue;
|
|
393
|
+
if (message.type === "done")
|
|
394
|
+
sawDone = true;
|
|
395
|
+
yield message;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
async function sidecarCall(vendor, op, request, options = {}) {
|
|
399
|
+
let result;
|
|
400
|
+
for await (const message of sidecarLines(vendor, ["call", "--vendor", vendor, "--op", op], request, options, "result")) {
|
|
401
|
+
if (message.type === "result")
|
|
402
|
+
result = message.result;
|
|
403
|
+
}
|
|
404
|
+
return result;
|
|
405
|
+
}
|
|
406
|
+
async function* sidecarLines(vendor, args, request, options, terminal) {
|
|
407
|
+
const { signal } = options;
|
|
408
|
+
signal?.throwIfAborted();
|
|
409
|
+
const env = options.env ?? process.env;
|
|
410
|
+
const binary = resolveSidecarBinary(options.binary, env);
|
|
411
|
+
const graceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
|
|
412
|
+
let child;
|
|
413
|
+
try {
|
|
414
|
+
child = spawn(binary, args, { env, stdio: "pipe", windowsHide: true });
|
|
415
|
+
} catch (cause) {
|
|
416
|
+
throw unavailable(binary, vendor, cause);
|
|
417
|
+
}
|
|
418
|
+
const lines = [];
|
|
419
|
+
let partial = "";
|
|
420
|
+
let stderr = "";
|
|
421
|
+
let spawnError;
|
|
422
|
+
let exited = false;
|
|
423
|
+
let closed = false;
|
|
424
|
+
let exitCode = null;
|
|
425
|
+
let exitSignal = null;
|
|
426
|
+
let aborted = false;
|
|
427
|
+
let wake;
|
|
428
|
+
const notify = () => {
|
|
429
|
+
const resolve = wake;
|
|
430
|
+
wake = void 0;
|
|
431
|
+
resolve?.();
|
|
432
|
+
};
|
|
433
|
+
child.stdout.setEncoding("utf8");
|
|
434
|
+
child.stdout.on("data", (chunk) => {
|
|
435
|
+
const parts = (partial + chunk).split("\n");
|
|
436
|
+
partial = parts.pop() ?? "";
|
|
437
|
+
for (const part of parts)
|
|
438
|
+
if (part.trim())
|
|
439
|
+
lines.push(part);
|
|
440
|
+
notify();
|
|
441
|
+
});
|
|
442
|
+
child.stderr.setEncoding("utf8");
|
|
443
|
+
const stderrSink = options.stderr === void 0 ? process.stderr : options.stderr;
|
|
444
|
+
child.stderr.on("data", (chunk) => {
|
|
445
|
+
if (stderrSink)
|
|
446
|
+
stderrSink.write(chunk);
|
|
447
|
+
stderr = (stderr + chunk).slice(-STDERR_TAIL_BYTES);
|
|
448
|
+
});
|
|
449
|
+
child.stdin.on("error", () => {
|
|
450
|
+
});
|
|
451
|
+
child.on("error", (error2) => {
|
|
452
|
+
spawnError = error2;
|
|
453
|
+
notify();
|
|
454
|
+
});
|
|
455
|
+
child.on("exit", (code, sig) => {
|
|
456
|
+
exited = true;
|
|
457
|
+
exitCode = code;
|
|
458
|
+
exitSignal = sig;
|
|
459
|
+
});
|
|
460
|
+
child.on("close", (code, sig) => {
|
|
461
|
+
exited = true;
|
|
462
|
+
closed = true;
|
|
463
|
+
exitCode ??= code;
|
|
464
|
+
exitSignal ??= sig;
|
|
465
|
+
if (partial.trim())
|
|
466
|
+
lines.push(partial);
|
|
467
|
+
partial = "";
|
|
468
|
+
notify();
|
|
469
|
+
});
|
|
470
|
+
const timers = [];
|
|
471
|
+
const cancel = () => {
|
|
472
|
+
if (!child.stdin.destroyed)
|
|
473
|
+
child.stdin.end();
|
|
474
|
+
if (exited)
|
|
475
|
+
return;
|
|
476
|
+
const escalate = (delay, sig) => {
|
|
477
|
+
const timer = setTimeout(() => {
|
|
478
|
+
if (!exited)
|
|
479
|
+
child.kill(sig);
|
|
480
|
+
}, delay);
|
|
481
|
+
timer.unref();
|
|
482
|
+
timers.push(timer);
|
|
483
|
+
};
|
|
484
|
+
escalate(graceMs, "SIGTERM");
|
|
485
|
+
escalate(graceMs * 2, "SIGKILL");
|
|
486
|
+
};
|
|
487
|
+
const onAbort = () => {
|
|
488
|
+
aborted = true;
|
|
489
|
+
cancel();
|
|
490
|
+
notify();
|
|
491
|
+
};
|
|
492
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
493
|
+
child.stdin.write(`${JSON.stringify({ protocol: SIDECAR_PROTOCOL_VERSION, request })}
|
|
494
|
+
`);
|
|
495
|
+
const details = () => ({ vendor, exitCode, exitSignal, stderr: stderr.trim() || void 0 });
|
|
496
|
+
let sawTerminal = false;
|
|
497
|
+
let finished = false;
|
|
498
|
+
try {
|
|
499
|
+
while (true) {
|
|
500
|
+
if (aborted)
|
|
501
|
+
throw abortReason(signal);
|
|
502
|
+
if (spawnError !== void 0)
|
|
503
|
+
throw unavailable(binary, vendor, spawnError);
|
|
504
|
+
const line = lines.shift();
|
|
505
|
+
if (line !== void 0) {
|
|
506
|
+
const message = parseLine(line, details);
|
|
507
|
+
if (message.type === "error") {
|
|
508
|
+
throw SidecarError.fromPayload(message.error ?? { kind: "protocol", message: "ns-bridge wrote an error line without a payload" }, details());
|
|
509
|
+
}
|
|
510
|
+
if (message.type === terminal)
|
|
511
|
+
sawTerminal = true;
|
|
512
|
+
yield message;
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
if (closed)
|
|
516
|
+
break;
|
|
517
|
+
await new Promise((resolve) => {
|
|
518
|
+
wake = resolve;
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
if (exitCode !== 0) {
|
|
522
|
+
const how = exitSignal ? `was killed by ${exitSignal}` : `exited with code ${exitCode}`;
|
|
523
|
+
throw new SidecarError("crashed", `ns-bridge (${vendor}) ${how} without reporting an error`, details());
|
|
524
|
+
}
|
|
525
|
+
if (!sawTerminal) {
|
|
526
|
+
throw new SidecarError("protocol", `ns-bridge (${vendor}) exited without a ${terminal} ${terminal === "done" ? "event" : "line"}`, details());
|
|
527
|
+
}
|
|
528
|
+
finished = true;
|
|
529
|
+
} finally {
|
|
530
|
+
signal?.removeEventListener("abort", onAbort);
|
|
531
|
+
if (finished) {
|
|
532
|
+
for (const timer of timers)
|
|
533
|
+
clearTimeout(timer);
|
|
534
|
+
} else {
|
|
535
|
+
cancel();
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
function parseLine(line, details) {
|
|
540
|
+
let value;
|
|
541
|
+
try {
|
|
542
|
+
value = JSON.parse(line);
|
|
543
|
+
} catch (cause) {
|
|
544
|
+
throw new SidecarError("protocol", `ns-bridge wrote a line that is not JSON: ${line.slice(0, 200)}`, {
|
|
545
|
+
...details(),
|
|
546
|
+
cause
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
if (!value || typeof value !== "object" || typeof value.type !== "string") {
|
|
550
|
+
throw new SidecarError("protocol", `ns-bridge wrote a line without a type: ${line.slice(0, 200)}`, details());
|
|
551
|
+
}
|
|
552
|
+
return value;
|
|
553
|
+
}
|
|
554
|
+
function unavailable(binary, vendor, cause) {
|
|
555
|
+
const code = cause?.code;
|
|
556
|
+
const reason = code === "ENOENT" ? "not found" : code === "EACCES" ? "not executable" : String(cause);
|
|
557
|
+
const packaged = binary === DEFAULT_SIDECAR_COMMAND ? findPackagedSidecarBinary() : void 0;
|
|
558
|
+
const why = packaged && "error" in packaged ? ` ${packaged.error}.` : "";
|
|
559
|
+
return new SidecarError("unavailable", `Cannot start the ns-bridge binary "${binary}" (${reason}).${why} Install ns-bridge-bin or point NS_BRIDGE_BIN at a binary.`, { vendor, cause });
|
|
560
|
+
}
|
|
561
|
+
function abortReason(signal) {
|
|
562
|
+
const reason = signal?.reason;
|
|
563
|
+
if (reason instanceof Error)
|
|
564
|
+
return reason;
|
|
565
|
+
return new DOMException(typeof reason === "string" ? reason : "This operation was aborted", "AbortError");
|
|
566
|
+
}
|
|
567
|
+
var SIDECAR_PROTOCOL_VERSION, DEFAULT_KILL_GRACE_MS, STDERR_TAIL_BYTES, EVENT_TYPES;
|
|
568
|
+
var init_stream = __esm({
|
|
569
|
+
"../bridge-core/dist/sidecar/stream.js"() {
|
|
570
|
+
"use strict";
|
|
571
|
+
init_binary();
|
|
572
|
+
init_errors();
|
|
573
|
+
SIDECAR_PROTOCOL_VERSION = 1;
|
|
574
|
+
DEFAULT_KILL_GRACE_MS = 2e3;
|
|
575
|
+
STDERR_TAIL_BYTES = 8 * 1024;
|
|
576
|
+
EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
577
|
+
"start",
|
|
578
|
+
"text_start",
|
|
579
|
+
"text_delta",
|
|
580
|
+
"text_end",
|
|
581
|
+
"thinking_start",
|
|
582
|
+
"thinking_delta",
|
|
583
|
+
"thinking_end",
|
|
584
|
+
"tool_call_start",
|
|
585
|
+
"tool_call_delta",
|
|
586
|
+
"tool_call_end",
|
|
587
|
+
"reset",
|
|
588
|
+
"usage",
|
|
589
|
+
"done"
|
|
590
|
+
]);
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
|
|
594
|
+
// ../bridge-core/dist/sidecar/engine.js
|
|
595
|
+
import { existsSync, statSync } from "node:fs";
|
|
596
|
+
import { delimiter, isAbsolute, join as join2 } from "node:path";
|
|
597
|
+
function parseSetting(value) {
|
|
598
|
+
switch (value?.trim().toLowerCase()) {
|
|
599
|
+
case "go":
|
|
600
|
+
case "sidecar":
|
|
601
|
+
case "native":
|
|
602
|
+
return "go";
|
|
603
|
+
case "ts":
|
|
604
|
+
case "typescript":
|
|
605
|
+
case "js":
|
|
606
|
+
case "node":
|
|
607
|
+
case "in-process":
|
|
608
|
+
return "ts";
|
|
609
|
+
case "auto":
|
|
610
|
+
return "auto";
|
|
611
|
+
default:
|
|
612
|
+
return void 0;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
function bridgeEngineSetting(vendor, env = process.env) {
|
|
616
|
+
const perVendor = vendor ? parseSetting(env[`${NS_BRIDGE_ENGINE_ENV}_${vendor.toUpperCase()}`]) : void 0;
|
|
617
|
+
return perVendor ?? parseSetting(env[NS_BRIDGE_ENGINE_ENV]) ?? DEFAULT_BRIDGE_ENGINE;
|
|
618
|
+
}
|
|
619
|
+
function isFile(path) {
|
|
620
|
+
try {
|
|
621
|
+
return statSync(path).isFile();
|
|
622
|
+
} catch {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
function onPath(command, env) {
|
|
627
|
+
if (isAbsolute(command))
|
|
628
|
+
return isFile(command);
|
|
629
|
+
const extensions = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
|
|
630
|
+
for (const dir of (env.PATH ?? "").split(delimiter)) {
|
|
631
|
+
if (!dir)
|
|
632
|
+
continue;
|
|
633
|
+
for (const ext of extensions)
|
|
634
|
+
if (isFile(join2(dir, command + ext.toLowerCase())) || isFile(join2(dir, command + ext)))
|
|
635
|
+
return true;
|
|
636
|
+
}
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
function sidecarBinaryAvailable(env = process.env) {
|
|
640
|
+
const fromEnv = env[NS_BRIDGE_BIN_ENV]?.trim();
|
|
641
|
+
if (fromEnv)
|
|
642
|
+
return existsSync(fromEnv) || onPath(fromEnv, env);
|
|
643
|
+
if ("path" in findPackagedSidecarBinary())
|
|
644
|
+
return true;
|
|
645
|
+
return onPath(DEFAULT_SIDECAR_COMMAND, env);
|
|
646
|
+
}
|
|
647
|
+
function selectBridgeEngine(vendor, env = process.env) {
|
|
648
|
+
const setting = bridgeEngineSetting(vendor, env);
|
|
649
|
+
if (setting !== "auto")
|
|
650
|
+
return setting;
|
|
651
|
+
return sidecarBinaryAvailable(env) ? "go" : "ts";
|
|
652
|
+
}
|
|
653
|
+
function isAutoFallback(error2) {
|
|
654
|
+
return error2.kind === "unavailable" || error2.kind === "unsupported" || error2.kind === "crashed" && error2.exitCode === 2;
|
|
655
|
+
}
|
|
656
|
+
async function* engineStream(options) {
|
|
657
|
+
const env = options.env ?? process.env;
|
|
658
|
+
const engine = options.engine ?? selectBridgeEngine(options.vendor, env);
|
|
659
|
+
if (engine === "ts") {
|
|
660
|
+
yield* options.inProcess();
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
let delivered = false;
|
|
664
|
+
try {
|
|
665
|
+
const raw = sidecarStream(options.vendor, options.request(), {
|
|
666
|
+
...options.sidecar,
|
|
667
|
+
...options.signal ? { signal: options.signal } : {},
|
|
668
|
+
env
|
|
669
|
+
});
|
|
670
|
+
for await (const event of options.transform ? options.transform(raw) : raw) {
|
|
671
|
+
delivered = true;
|
|
672
|
+
yield event;
|
|
673
|
+
}
|
|
674
|
+
} catch (error2) {
|
|
675
|
+
if (error2 instanceof SidecarError && isAutoFallback(error2) && !delivered && options.engine === void 0 && bridgeEngineSetting(options.vendor, env) === "auto") {
|
|
676
|
+
if (!warnedFallback) {
|
|
677
|
+
warnedFallback = true;
|
|
678
|
+
console.warn(`[ns-bridge] ${error2.message} Falling back to the in-process TypeScript core.`);
|
|
679
|
+
}
|
|
680
|
+
yield* options.inProcess();
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
throw error2 instanceof SidecarError && options.mapError ? options.mapError(error2) : error2;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
async function engineCall(options) {
|
|
687
|
+
const env = options.env ?? process.env;
|
|
688
|
+
const engine = options.engine ?? selectBridgeEngine(options.vendor, env);
|
|
689
|
+
if (engine === "ts")
|
|
690
|
+
return options.inProcess();
|
|
691
|
+
try {
|
|
692
|
+
return await sidecarCall(options.vendor, options.op, options.request(), {
|
|
693
|
+
...options.sidecar,
|
|
694
|
+
...options.signal ? { signal: options.signal } : {},
|
|
695
|
+
env
|
|
696
|
+
});
|
|
697
|
+
} catch (error2) {
|
|
698
|
+
if (error2 instanceof SidecarError && isAutoFallback(error2) && options.engine === void 0 && bridgeEngineSetting(options.vendor, env) === "auto") {
|
|
699
|
+
if (!warnedFallback) {
|
|
700
|
+
warnedFallback = true;
|
|
701
|
+
console.warn(`[ns-bridge] ${error2.message} Falling back to the in-process TypeScript core.`);
|
|
702
|
+
}
|
|
703
|
+
return options.inProcess();
|
|
704
|
+
}
|
|
705
|
+
throw error2 instanceof SidecarError && options.mapError ? options.mapError(error2) : error2;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
var NS_BRIDGE_ENGINE_ENV, DEFAULT_BRIDGE_ENGINE, warnedFallback;
|
|
709
|
+
var init_engine = __esm({
|
|
710
|
+
"../bridge-core/dist/sidecar/engine.js"() {
|
|
711
|
+
"use strict";
|
|
712
|
+
init_binary();
|
|
713
|
+
init_errors();
|
|
714
|
+
init_stream();
|
|
715
|
+
NS_BRIDGE_ENGINE_ENV = "NS_BRIDGE_ENGINE";
|
|
716
|
+
DEFAULT_BRIDGE_ENGINE = "auto";
|
|
717
|
+
warnedFallback = false;
|
|
718
|
+
}
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
// ../bridge-core/dist/sidecar/index.js
|
|
722
|
+
var init_sidecar = __esm({
|
|
723
|
+
"../bridge-core/dist/sidecar/index.js"() {
|
|
724
|
+
"use strict";
|
|
725
|
+
init_binary();
|
|
726
|
+
init_engine();
|
|
727
|
+
init_errors();
|
|
728
|
+
init_stream();
|
|
287
729
|
}
|
|
288
730
|
});
|
|
289
731
|
|
|
@@ -302,16 +744,16 @@ __export(kiro_cli_exports, {
|
|
|
302
744
|
tryKiroCliToken: () => tryKiroCliToken
|
|
303
745
|
});
|
|
304
746
|
import { execFileSync, execSync } from "node:child_process";
|
|
305
|
-
import { existsSync } from "node:fs";
|
|
306
|
-
import { createRequire } from "node:module";
|
|
747
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
748
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
307
749
|
import { homedir as homedir2, platform } from "node:os";
|
|
308
|
-
import { join as
|
|
750
|
+
import { join as join3 } from "node:path";
|
|
309
751
|
function getKiroCliDbPath() {
|
|
310
752
|
const p = platform();
|
|
311
|
-
const localAppData = process.env.LOCALAPPDATA ||
|
|
312
|
-
const roamingAppData = process.env.APPDATA ||
|
|
313
|
-
const candidates = p === "win32" ? [
|
|
314
|
-
return candidates.find((candidate) =>
|
|
753
|
+
const localAppData = process.env.LOCALAPPDATA || join3(homedir2(), "AppData", "Local");
|
|
754
|
+
const roamingAppData = process.env.APPDATA || join3(homedir2(), "AppData", "Roaming");
|
|
755
|
+
const candidates = p === "win32" ? [join3(localAppData, "Kiro-Cli", "data.sqlite3"), join3(roamingAppData, "kiro-cli", "data.sqlite3")] : p === "darwin" ? [join3(homedir2(), "Library", "Application Support", "kiro-cli", "data.sqlite3")] : [join3(homedir2(), ".local", "share", "kiro-cli", "data.sqlite3")];
|
|
756
|
+
return candidates.find((candidate) => existsSync2(candidate));
|
|
315
757
|
}
|
|
316
758
|
function getKiroCliExternalIdpCredentials() {
|
|
317
759
|
const dbPath = getKiroCliDbPath();
|
|
@@ -591,7 +1033,7 @@ var init_kiro_cli = __esm({
|
|
|
591
1033
|
"../kiro-core/dist/kiro-cli.js"() {
|
|
592
1034
|
"use strict";
|
|
593
1035
|
init_debug();
|
|
594
|
-
require2 =
|
|
1036
|
+
require2 = createRequire2(import.meta.url);
|
|
595
1037
|
EXTERNAL_IDP_TOKEN_KEY = "kirocli:external-idp:token";
|
|
596
1038
|
TOKEN_KEY_BY_AUTH_METHOD = {
|
|
597
1039
|
idc: ["kirocli:odic:token", "codewhisperer:odic:token"],
|
|
@@ -603,12 +1045,12 @@ var init_kiro_cli = __esm({
|
|
|
603
1045
|
});
|
|
604
1046
|
|
|
605
1047
|
// ../kiro-core/dist/kiro-ide.js
|
|
606
|
-
import { existsSync as
|
|
1048
|
+
import { existsSync as existsSync3, readFileSync } from "node:fs";
|
|
607
1049
|
import { homedir as homedir3 } from "node:os";
|
|
608
|
-
import { join as
|
|
1050
|
+
import { join as join4 } from "node:path";
|
|
609
1051
|
function readKiroIdeToken(allowExpired) {
|
|
610
1052
|
try {
|
|
611
|
-
if (!
|
|
1053
|
+
if (!existsSync3(KIRO_IDE_TOKEN_PATH))
|
|
612
1054
|
return void 0;
|
|
613
1055
|
const tokenData = JSON.parse(readFileSync(KIRO_IDE_TOKEN_PATH, "utf-8"));
|
|
614
1056
|
if (!tokenData.accessToken || !tokenData.refreshToken)
|
|
@@ -620,8 +1062,8 @@ function readKiroIdeToken(allowExpired) {
|
|
|
620
1062
|
let clientId = "";
|
|
621
1063
|
let clientSecret = "";
|
|
622
1064
|
if (tokenData.clientIdHash) {
|
|
623
|
-
const regPath =
|
|
624
|
-
if (
|
|
1065
|
+
const regPath = join4(SSO_CACHE_DIR, `${tokenData.clientIdHash}.json`);
|
|
1066
|
+
if (existsSync3(regPath)) {
|
|
625
1067
|
try {
|
|
626
1068
|
const reg = JSON.parse(readFileSync(regPath, "utf-8"));
|
|
627
1069
|
clientId = reg.clientId ?? "";
|
|
@@ -655,8 +1097,8 @@ var SSO_CACHE_DIR, KIRO_IDE_TOKEN_PATH;
|
|
|
655
1097
|
var init_kiro_ide = __esm({
|
|
656
1098
|
"../kiro-core/dist/kiro-ide.js"() {
|
|
657
1099
|
"use strict";
|
|
658
|
-
SSO_CACHE_DIR =
|
|
659
|
-
KIRO_IDE_TOKEN_PATH =
|
|
1100
|
+
SSO_CACHE_DIR = join4(homedir3(), ".aws", "sso", "cache");
|
|
1101
|
+
KIRO_IDE_TOKEN_PATH = join4(SSO_CACHE_DIR, "kiro-auth-token.json");
|
|
660
1102
|
}
|
|
661
1103
|
});
|
|
662
1104
|
|
|
@@ -794,6 +1236,13 @@ async function refreshKiroTokenInternal(credentials) {
|
|
|
794
1236
|
}
|
|
795
1237
|
}
|
|
796
1238
|
async function refreshKiroTokenDirect(credentials) {
|
|
1239
|
+
const { runKiroOp: runKiroOp2 } = await Promise.resolve().then(() => (init_engine_ops(), engine_ops_exports));
|
|
1240
|
+
return runKiroOp2("refreshToken", () => ({ credentials }), () => refreshKiroTokenDirectInProcess(credentials));
|
|
1241
|
+
}
|
|
1242
|
+
function endpointFromEnv(name, fallback, region) {
|
|
1243
|
+
return (process.env[name]?.trim() || fallback).replaceAll("{region}", region);
|
|
1244
|
+
}
|
|
1245
|
+
async function refreshKiroTokenDirectInProcess(credentials) {
|
|
797
1246
|
const parts = credentials.refresh.split("|");
|
|
798
1247
|
const refreshToken = parts[0] ?? "";
|
|
799
1248
|
const authMethod = parts[parts.length - 1] ?? "idc";
|
|
@@ -801,7 +1250,7 @@ async function refreshKiroTokenDirect(credentials) {
|
|
|
801
1250
|
if (authMethod === "apikey")
|
|
802
1251
|
return credentials;
|
|
803
1252
|
if (authMethod === "desktop") {
|
|
804
|
-
const url =
|
|
1253
|
+
const url = endpointFromEnv(KIRO_DESKTOP_REFRESH_ENDPOINT_ENV, KIRO_DESKTOP_REFRESH_URL, region);
|
|
805
1254
|
const response2 = await fetch(url, {
|
|
806
1255
|
method: "POST",
|
|
807
1256
|
headers: { "Content-Type": "application/json", "User-Agent": KIRO_DESKTOP_USER_AGENT },
|
|
@@ -861,7 +1310,7 @@ async function refreshKiroTokenDirect(credentials) {
|
|
|
861
1310
|
}
|
|
862
1311
|
const clientId = parts[1] ?? "";
|
|
863
1312
|
const clientSecret = parts[2] ?? "";
|
|
864
|
-
const ssoEndpoint =
|
|
1313
|
+
const ssoEndpoint = endpointFromEnv(KIRO_OIDC_ENDPOINT_ENV, "https://oidc.{region}.amazonaws.com", region);
|
|
865
1314
|
const response = await fetch(`${ssoEndpoint}/token`, {
|
|
866
1315
|
method: "POST",
|
|
867
1316
|
headers: { "Content-Type": "application/json", ...kiroUserAgent("ssooidc", "E") },
|
|
@@ -909,7 +1358,7 @@ async function resolveKiroCredentials() {
|
|
|
909
1358
|
throw lastFailure;
|
|
910
1359
|
return void 0;
|
|
911
1360
|
}
|
|
912
|
-
var KIRO_DESKTOP_REFRESH_URL, EXPIRES_BUFFER_MS, KIRO_DESKTOP_USER_AGENT, AUTH_SOURCE_ENV;
|
|
1361
|
+
var KIRO_DESKTOP_REFRESH_URL, EXPIRES_BUFFER_MS, KIRO_DESKTOP_USER_AGENT, AUTH_SOURCE_ENV, KIRO_DESKTOP_REFRESH_ENDPOINT_ENV, KIRO_OIDC_ENDPOINT_ENV;
|
|
913
1362
|
var init_oauth = __esm({
|
|
914
1363
|
"../kiro-core/dist/oauth.js"() {
|
|
915
1364
|
"use strict";
|
|
@@ -920,6 +1369,8 @@ var init_oauth = __esm({
|
|
|
920
1369
|
EXPIRES_BUFFER_MS = 5 * 60 * 1e3;
|
|
921
1370
|
KIRO_DESKTOP_USER_AGENT = "Kiro-Desktop/0.2.13 (darwin; arm64)";
|
|
922
1371
|
AUTH_SOURCE_ENV = "KIRO_AUTH_SOURCE";
|
|
1372
|
+
KIRO_DESKTOP_REFRESH_ENDPOINT_ENV = "KIRO_DESKTOP_REFRESH_ENDPOINT";
|
|
1373
|
+
KIRO_OIDC_ENDPOINT_ENV = "KIRO_OIDC_ENDPOINT";
|
|
923
1374
|
}
|
|
924
1375
|
});
|
|
925
1376
|
|
|
@@ -1035,6 +1486,32 @@ async function parseManagementResponse(response, operation, region) {
|
|
|
1035
1486
|
throw new Error(`Kiro management ${operation} returned invalid JSON in ${region}`, { cause: error2 });
|
|
1036
1487
|
}
|
|
1037
1488
|
}
|
|
1489
|
+
function snapshotKiroProfileArnCache() {
|
|
1490
|
+
return Object.fromEntries(profileArnCache);
|
|
1491
|
+
}
|
|
1492
|
+
function snapshotKiroProfileRegionCache() {
|
|
1493
|
+
return Object.fromEntries(profileRegionCache);
|
|
1494
|
+
}
|
|
1495
|
+
function applyKiroProfileRegionChanges(regions) {
|
|
1496
|
+
if (!regions)
|
|
1497
|
+
return;
|
|
1498
|
+
for (const [key, region] of Object.entries(regions))
|
|
1499
|
+
if (typeof region === "string" && region)
|
|
1500
|
+
profileRegionCache.set(key, region);
|
|
1501
|
+
}
|
|
1502
|
+
function applyKiroProfileArnCacheChanges(changes) {
|
|
1503
|
+
if (!changes)
|
|
1504
|
+
return;
|
|
1505
|
+
for (const [key, arn] of Object.entries(changes)) {
|
|
1506
|
+
if (typeof arn === "string" && arn) {
|
|
1507
|
+
profileArnCache.set(key, arn);
|
|
1508
|
+
} else {
|
|
1509
|
+
profileArnCache.delete(key);
|
|
1510
|
+
profileRegionCache.delete(key);
|
|
1511
|
+
pendingProfileRequests.delete(key);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1038
1515
|
function invalidateKiroProfileArn(auth) {
|
|
1039
1516
|
const key = profileCacheKey(auth);
|
|
1040
1517
|
profileArnCache.delete(key);
|
|
@@ -1188,12 +1665,13 @@ __export(models_exports, {
|
|
|
1188
1665
|
mapKiroCatalogModels: () => mapKiroCatalogModels,
|
|
1189
1666
|
resolveApiRegion: () => resolveApiRegion,
|
|
1190
1667
|
resolveKiroModel: () => resolveKiroModel,
|
|
1191
|
-
updateKiroModelsCache: () => updateKiroModelsCache
|
|
1668
|
+
updateKiroModelsCache: () => updateKiroModelsCache,
|
|
1669
|
+
updateKiroModelsCacheInProcess: () => updateKiroModelsCacheInProcess
|
|
1192
1670
|
});
|
|
1193
1671
|
import { randomUUID } from "node:crypto";
|
|
1194
|
-
import { existsSync as
|
|
1672
|
+
import { existsSync as existsSync4, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
1195
1673
|
import { homedir as homedir4 } from "node:os";
|
|
1196
|
-
import { join as
|
|
1674
|
+
import { join as join5 } from "node:path";
|
|
1197
1675
|
function isRecord2(value) {
|
|
1198
1676
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1199
1677
|
}
|
|
@@ -1245,7 +1723,7 @@ function parseManagementCache(raw) {
|
|
|
1245
1723
|
};
|
|
1246
1724
|
}
|
|
1247
1725
|
function readManagementCache() {
|
|
1248
|
-
if (!
|
|
1726
|
+
if (!existsSync4(KIRO_MANAGEMENT_CACHE_PATH))
|
|
1249
1727
|
return void 0;
|
|
1250
1728
|
try {
|
|
1251
1729
|
return parseManagementCache(readFileSync2(KIRO_MANAGEMENT_CACHE_PATH, "utf-8"));
|
|
@@ -1380,6 +1858,25 @@ function isCacheStale(region) {
|
|
|
1380
1858
|
return !entry || Date.now() - entry.fetchedAt > CACHE_MAX_AGE_MS;
|
|
1381
1859
|
}
|
|
1382
1860
|
async function updateKiroModelsCache(accessToken, region, profileArn) {
|
|
1861
|
+
const { runKiroOp: runKiroOp2 } = await Promise.resolve().then(() => (init_engine_ops(), engine_ops_exports));
|
|
1862
|
+
await runKiroOp2("refreshModels", () => ({
|
|
1863
|
+
accessToken,
|
|
1864
|
+
region,
|
|
1865
|
+
...profileArn ? { profileArn } : {},
|
|
1866
|
+
known: kiroModels.map((model) => ({
|
|
1867
|
+
id: model.id,
|
|
1868
|
+
name: model.name,
|
|
1869
|
+
input: model.input,
|
|
1870
|
+
...model.firstTokenTimeout ? { firstTokenTimeout: model.firstTokenTimeout } : {}
|
|
1871
|
+
})),
|
|
1872
|
+
cachePath: KIRO_MANAGEMENT_CACHE_PATH
|
|
1873
|
+
}), async () => {
|
|
1874
|
+
await updateKiroModelsCacheInProcess(accessToken, region, profileArn);
|
|
1875
|
+
return {};
|
|
1876
|
+
});
|
|
1877
|
+
refreshKnownModelIds(readManagementCache());
|
|
1878
|
+
}
|
|
1879
|
+
async function updateKiroModelsCacheInProcess(accessToken, region, profileArn) {
|
|
1383
1880
|
const response = await fetchKiroModelCatalog({ accessToken, region }, profileArn);
|
|
1384
1881
|
const models = mapKiroCatalogModels(response.models, region, getKiroCliModelRates());
|
|
1385
1882
|
const cache = readManagementCache() ?? {
|
|
@@ -1420,7 +1917,7 @@ var init_models = __esm({
|
|
|
1420
1917
|
init_endpoints();
|
|
1421
1918
|
KIRO_MANAGEMENT_CACHE_VERSION = 1;
|
|
1422
1919
|
KIRO_MANAGEMENT_CACHE_SOURCE = "ns-kiro-provider-management";
|
|
1423
|
-
KIRO_MANAGEMENT_CACHE_PATH =
|
|
1920
|
+
KIRO_MANAGEMENT_CACHE_PATH = join5(homedir4(), ".ns-kiro-provider-models-cache.json");
|
|
1424
1921
|
CACHE_MAX_AGE_MS = 36e5;
|
|
1425
1922
|
DEFAULT_CONTEXT_WINDOW = 2e5;
|
|
1426
1923
|
DEFAULT_MAX_TOKENS = 8192;
|
|
@@ -1642,85 +2139,305 @@ var init_models = __esm({
|
|
|
1642
2139
|
}
|
|
1643
2140
|
});
|
|
1644
2141
|
|
|
1645
|
-
//
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
var tmp;
|
|
1685
|
-
var lens = getLens(b64);
|
|
1686
|
-
var validLen = lens[0];
|
|
1687
|
-
var placeHoldersLen = lens[1];
|
|
1688
|
-
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
|
|
1689
|
-
var curByte = 0;
|
|
1690
|
-
var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
|
|
1691
|
-
var i2;
|
|
1692
|
-
for (i2 = 0; i2 < len2; i2 += 4) {
|
|
1693
|
-
tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
|
|
1694
|
-
arr[curByte++] = tmp >> 16 & 255;
|
|
1695
|
-
arr[curByte++] = tmp >> 8 & 255;
|
|
1696
|
-
arr[curByte++] = tmp & 255;
|
|
1697
|
-
}
|
|
1698
|
-
if (placeHoldersLen === 2) {
|
|
1699
|
-
tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
|
|
1700
|
-
arr[curByte++] = tmp & 255;
|
|
1701
|
-
}
|
|
1702
|
-
if (placeHoldersLen === 1) {
|
|
1703
|
-
tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
|
|
1704
|
-
arr[curByte++] = tmp >> 8 & 255;
|
|
1705
|
-
arr[curByte++] = tmp & 255;
|
|
1706
|
-
}
|
|
1707
|
-
return arr;
|
|
1708
|
-
}
|
|
1709
|
-
function tripletToBase64(num2) {
|
|
1710
|
-
return lookup[num2 >> 18 & 63] + lookup[num2 >> 12 & 63] + lookup[num2 >> 6 & 63] + lookup[num2 & 63];
|
|
1711
|
-
}
|
|
1712
|
-
function encodeChunk(uint8, start, end) {
|
|
1713
|
-
var tmp;
|
|
1714
|
-
var output = [];
|
|
1715
|
-
for (var i2 = start; i2 < end; i2 += 3) {
|
|
1716
|
-
tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
|
|
1717
|
-
output.push(tripletToBase64(tmp));
|
|
2142
|
+
// ../kiro-core/dist/retry.js
|
|
2143
|
+
function firstTokenTimeoutForModel(modelId) {
|
|
2144
|
+
if (retryConfig.firstTokenTimeoutMs !== FIRST_TOKEN_TIMEOUT) {
|
|
2145
|
+
return retryConfig.firstTokenTimeoutMs;
|
|
2146
|
+
}
|
|
2147
|
+
const model = kiroModels.find((m) => m.id === modelId);
|
|
2148
|
+
return model?.firstTokenTimeout ?? FIRST_TOKEN_TIMEOUT;
|
|
2149
|
+
}
|
|
2150
|
+
function exponentialBackoff(attempt, baseMs, maxMs) {
|
|
2151
|
+
return Math.min(baseMs * 2 ** attempt, maxMs);
|
|
2152
|
+
}
|
|
2153
|
+
function extractKiroReason(errorText) {
|
|
2154
|
+
if (!errorText)
|
|
2155
|
+
return void 0;
|
|
2156
|
+
try {
|
|
2157
|
+
const parsed = JSON.parse(errorText);
|
|
2158
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
2159
|
+
return void 0;
|
|
2160
|
+
const reason = parsed.reason;
|
|
2161
|
+
return typeof reason === "string" && reason.length > 0 ? reason : void 0;
|
|
2162
|
+
} catch {
|
|
2163
|
+
return void 0;
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
function parseRetryAfterMs(headers, nowMs = Date.now()) {
|
|
2167
|
+
const get = headers?.get?.bind(headers);
|
|
2168
|
+
if (!get)
|
|
2169
|
+
return void 0;
|
|
2170
|
+
const milliseconds = nonNegativeNumber(get("retry-after-ms"));
|
|
2171
|
+
if (milliseconds !== void 0)
|
|
2172
|
+
return Math.round(milliseconds);
|
|
2173
|
+
const retryAfter = get("retry-after");
|
|
2174
|
+
if (retryAfter !== null && retryAfter.trim() !== "") {
|
|
2175
|
+
const seconds = Number(retryAfter);
|
|
2176
|
+
if (Number.isFinite(seconds)) {
|
|
2177
|
+
if (seconds >= 0) {
|
|
2178
|
+
const delayMs = seconds * 1e3;
|
|
2179
|
+
if (Number.isFinite(delayMs))
|
|
2180
|
+
return Math.round(delayMs);
|
|
1718
2181
|
}
|
|
1719
|
-
|
|
2182
|
+
} else {
|
|
2183
|
+
const dateMs = Date.parse(retryAfter);
|
|
2184
|
+
if (!Number.isNaN(dateMs))
|
|
2185
|
+
return Math.max(0, dateMs - nowMs);
|
|
1720
2186
|
}
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
2187
|
+
}
|
|
2188
|
+
const resetAfterSeconds = nonNegativeNumber(get("x-ratelimit-reset-after"));
|
|
2189
|
+
if (resetAfterSeconds !== void 0) {
|
|
2190
|
+
const delayMs = resetAfterSeconds * 1e3;
|
|
2191
|
+
if (Number.isFinite(delayMs))
|
|
2192
|
+
return Math.round(delayMs);
|
|
2193
|
+
}
|
|
2194
|
+
return void 0;
|
|
2195
|
+
}
|
|
2196
|
+
function resolveRequestRateRetryDelay(headers, nowMs = Date.now()) {
|
|
2197
|
+
const advertisedDelayMs = parseRetryAfterMs(headers, nowMs);
|
|
2198
|
+
const requestedDelayMs = advertisedDelayMs ?? REQUEST_RATE_FALLBACK_DELAY_MS;
|
|
2199
|
+
return {
|
|
2200
|
+
delayMs: Math.min(requestedDelayMs, MAX_RETRY_DELAY),
|
|
2201
|
+
...advertisedDelayMs !== void 0 ? { advertisedDelayMs } : {},
|
|
2202
|
+
capped: requestedDelayMs > MAX_RETRY_DELAY
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
function nonNegativeNumber(value) {
|
|
2206
|
+
if (value === null || value.trim() === "")
|
|
2207
|
+
return void 0;
|
|
2208
|
+
const parsed = Number(value);
|
|
2209
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
|
|
2210
|
+
}
|
|
2211
|
+
function isTooBigError(status, errorText) {
|
|
2212
|
+
return status === 413 || status === 400 && TOO_BIG_PATTERNS.some((p) => errorText.includes(p));
|
|
2213
|
+
}
|
|
2214
|
+
function isNonRetryableBodyError(errorText) {
|
|
2215
|
+
return NON_RETRYABLE_BODY_PATTERNS.some((p) => errorText.includes(p));
|
|
2216
|
+
}
|
|
2217
|
+
function isCapacityError(errorText) {
|
|
2218
|
+
return errorText.includes(CAPACITY_PATTERN);
|
|
2219
|
+
}
|
|
2220
|
+
var FIRST_TOKEN_TIMEOUT, REQUEST_HEADER_TIMEOUT, retryConfig, MAX_RETRY_DELAY, REQUEST_RATE_FALLBACK_DELAY_MS, KIRO_REASON_CODES, TOO_BIG_PATTERNS, NON_RETRYABLE_BODY_PATTERNS, CAPACITY_PATTERN, CAPACITY_MAX_RETRIES, CAPACITY_BASE_DELAY_MS, capacityRetryConfig;
|
|
2221
|
+
var init_retry = __esm({
|
|
2222
|
+
"../kiro-core/dist/retry.js"() {
|
|
2223
|
+
"use strict";
|
|
2224
|
+
init_models();
|
|
2225
|
+
FIRST_TOKEN_TIMEOUT = 9e4;
|
|
2226
|
+
REQUEST_HEADER_TIMEOUT = 9e4;
|
|
2227
|
+
retryConfig = {
|
|
2228
|
+
firstTokenTimeoutMs: FIRST_TOKEN_TIMEOUT,
|
|
2229
|
+
requestHeaderTimeoutMs: REQUEST_HEADER_TIMEOUT
|
|
2230
|
+
};
|
|
2231
|
+
MAX_RETRY_DELAY = 1e4;
|
|
2232
|
+
REQUEST_RATE_FALLBACK_DELAY_MS = 1e4;
|
|
2233
|
+
KIRO_REASON_CODES = Object.freeze({
|
|
2234
|
+
/** Request body exceeded the service's size threshold. */
|
|
2235
|
+
CONTENT_LENGTH_EXCEEDS_THRESHOLD: "CONTENT_LENGTH_EXCEEDS_THRESHOLD",
|
|
2236
|
+
/** Prose-only size rejection; the service sends no reason code for this one. */
|
|
2237
|
+
INPUT_TOO_LONG: "Input is too long",
|
|
2238
|
+
/** Monthly request quota exhausted — hard limit, not transient. */
|
|
2239
|
+
MONTHLY_REQUEST_COUNT: "MONTHLY_REQUEST_COUNT",
|
|
2240
|
+
/** Model capacity temporarily unavailable — transient, worth retrying. */
|
|
2241
|
+
INSUFFICIENT_MODEL_CAPACITY: "INSUFFICIENT_MODEL_CAPACITY",
|
|
2242
|
+
/** Short-window request throttle — retry only within the provider budget. */
|
|
2243
|
+
USER_REQUEST_RATE_EXCEEDED: "USER_REQUEST_RATE_EXCEEDED",
|
|
2244
|
+
/**
|
|
2245
|
+
* Generic request-validation rejection, returned for a malformed body of any
|
|
2246
|
+
* size (empty `content`, history referencing tools absent from the catalog).
|
|
2247
|
+
* Not a size signal: classifying it as "too big" makes the caller compact a
|
|
2248
|
+
* history that was never the problem, a loop it can never satisfy.
|
|
2249
|
+
*/
|
|
2250
|
+
REQUEST_BODY_INVALID: "REQUEST_BODY_INVALID"
|
|
2251
|
+
});
|
|
2252
|
+
TOO_BIG_PATTERNS = Object.freeze([
|
|
2253
|
+
KIRO_REASON_CODES.CONTENT_LENGTH_EXCEEDS_THRESHOLD,
|
|
2254
|
+
KIRO_REASON_CODES.INPUT_TOO_LONG
|
|
2255
|
+
]);
|
|
2256
|
+
NON_RETRYABLE_BODY_PATTERNS = Object.freeze([KIRO_REASON_CODES.MONTHLY_REQUEST_COUNT]);
|
|
2257
|
+
CAPACITY_PATTERN = KIRO_REASON_CODES.INSUFFICIENT_MODEL_CAPACITY;
|
|
2258
|
+
CAPACITY_MAX_RETRIES = 3;
|
|
2259
|
+
CAPACITY_BASE_DELAY_MS = 5e3;
|
|
2260
|
+
capacityRetryConfig = {
|
|
2261
|
+
maxRetries: CAPACITY_MAX_RETRIES,
|
|
2262
|
+
baseDelayMs: CAPACITY_BASE_DELAY_MS
|
|
2263
|
+
};
|
|
2264
|
+
}
|
|
2265
|
+
});
|
|
2266
|
+
|
|
2267
|
+
// ../kiro-core/dist/errors.js
|
|
2268
|
+
function extractKiroReasonCode(errorText) {
|
|
2269
|
+
if (!errorText)
|
|
2270
|
+
return void 0;
|
|
2271
|
+
const trimmed = errorText.trim();
|
|
2272
|
+
if (trimmed.startsWith("{")) {
|
|
2273
|
+
try {
|
|
2274
|
+
const parsed = JSON.parse(trimmed);
|
|
2275
|
+
const reason = parsed.reason ?? parsed.reasonCode;
|
|
2276
|
+
if (typeof reason === "string" && reason.length > 0)
|
|
2277
|
+
return reason;
|
|
2278
|
+
} catch {
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
return REASON_CODE_MARKERS.find((code) => errorText.includes(code));
|
|
2282
|
+
}
|
|
2283
|
+
var REASON_CODE_MARKERS, KiroApiError;
|
|
2284
|
+
var init_errors2 = __esm({
|
|
2285
|
+
"../kiro-core/dist/errors.js"() {
|
|
2286
|
+
"use strict";
|
|
2287
|
+
init_retry();
|
|
2288
|
+
init_retry();
|
|
2289
|
+
REASON_CODE_MARKERS = [
|
|
2290
|
+
KIRO_REASON_CODES.CONTENT_LENGTH_EXCEEDS_THRESHOLD,
|
|
2291
|
+
KIRO_REASON_CODES.MONTHLY_REQUEST_COUNT,
|
|
2292
|
+
KIRO_REASON_CODES.INSUFFICIENT_MODEL_CAPACITY,
|
|
2293
|
+
KIRO_REASON_CODES.REQUEST_BODY_INVALID
|
|
2294
|
+
];
|
|
2295
|
+
KiroApiError = class extends Error {
|
|
2296
|
+
status;
|
|
2297
|
+
reasonCode;
|
|
2298
|
+
retryAfterMs;
|
|
2299
|
+
providerAttempts;
|
|
2300
|
+
constructor(message, status, reasonCode, retryAfterMs, providerAttempts) {
|
|
2301
|
+
super(message);
|
|
2302
|
+
this.status = status;
|
|
2303
|
+
this.reasonCode = reasonCode;
|
|
2304
|
+
this.retryAfterMs = retryAfterMs;
|
|
2305
|
+
this.providerAttempts = providerAttempts;
|
|
2306
|
+
this.name = "KiroApiError";
|
|
2307
|
+
}
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
});
|
|
2311
|
+
|
|
2312
|
+
// ../kiro-core/dist/engine-ops.js
|
|
2313
|
+
var engine_ops_exports = {};
|
|
2314
|
+
__export(engine_ops_exports, {
|
|
2315
|
+
kiroErrorFromSidecar: () => kiroErrorFromSidecar,
|
|
2316
|
+
runKiroOp: () => runKiroOp
|
|
2317
|
+
});
|
|
2318
|
+
function kiroErrorFromSidecar(error2) {
|
|
2319
|
+
switch (error2.vendorError) {
|
|
2320
|
+
case "KiroApiError":
|
|
2321
|
+
return new KiroApiError(error2.message, error2.status ?? 0, error2.reasonCode, error2.retryAfterMs, error2.providerAttempts);
|
|
2322
|
+
case "KiroManagementHttpError":
|
|
2323
|
+
return new KiroManagementHttpError(error2.message, error2.status ?? 0);
|
|
2324
|
+
case "Error":
|
|
2325
|
+
return new Error(error2.message);
|
|
2326
|
+
default:
|
|
2327
|
+
return error2;
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
async function runKiroOp(op, request, inProcess) {
|
|
2331
|
+
let ranInProcess = false;
|
|
2332
|
+
const result = await engineCall({
|
|
2333
|
+
vendor: "kiro",
|
|
2334
|
+
op,
|
|
2335
|
+
request: () => ({
|
|
2336
|
+
...request(),
|
|
2337
|
+
profileArnCache: snapshotKiroProfileArnCache(),
|
|
2338
|
+
profileRegions: snapshotKiroProfileRegionCache()
|
|
2339
|
+
}),
|
|
2340
|
+
inProcess: async () => {
|
|
2341
|
+
ranInProcess = true;
|
|
2342
|
+
return await inProcess();
|
|
2343
|
+
},
|
|
2344
|
+
mapError: kiroErrorFromSidecar
|
|
2345
|
+
});
|
|
2346
|
+
if (ranInProcess || !result || typeof result !== "object")
|
|
2347
|
+
return result;
|
|
2348
|
+
const { kiroProfileArns, kiroProfileRegions, ...rest } = result;
|
|
2349
|
+
applyKiroProfileArnCacheChanges(kiroProfileArns);
|
|
2350
|
+
applyKiroProfileRegionChanges(kiroProfileRegions);
|
|
2351
|
+
return rest;
|
|
2352
|
+
}
|
|
2353
|
+
var init_engine_ops = __esm({
|
|
2354
|
+
"../kiro-core/dist/engine-ops.js"() {
|
|
2355
|
+
"use strict";
|
|
2356
|
+
init_sidecar();
|
|
2357
|
+
init_errors2();
|
|
2358
|
+
init_management();
|
|
2359
|
+
}
|
|
2360
|
+
});
|
|
2361
|
+
|
|
2362
|
+
// ../../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js
|
|
2363
|
+
var require_base64_js = __commonJS({
|
|
2364
|
+
"../../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js"(exports) {
|
|
2365
|
+
"use strict";
|
|
2366
|
+
exports.byteLength = byteLength;
|
|
2367
|
+
exports.toByteArray = toByteArray;
|
|
2368
|
+
exports.fromByteArray = fromByteArray;
|
|
2369
|
+
var lookup = [];
|
|
2370
|
+
var revLookup = [];
|
|
2371
|
+
var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
|
|
2372
|
+
var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
2373
|
+
for (i = 0, len = code.length; i < len; ++i) {
|
|
2374
|
+
lookup[i] = code[i];
|
|
2375
|
+
revLookup[code.charCodeAt(i)] = i;
|
|
2376
|
+
}
|
|
2377
|
+
var i;
|
|
2378
|
+
var len;
|
|
2379
|
+
revLookup["-".charCodeAt(0)] = 62;
|
|
2380
|
+
revLookup["_".charCodeAt(0)] = 63;
|
|
2381
|
+
function getLens(b64) {
|
|
2382
|
+
var len2 = b64.length;
|
|
2383
|
+
if (len2 % 4 > 0) {
|
|
2384
|
+
throw new Error("Invalid string. Length must be a multiple of 4");
|
|
2385
|
+
}
|
|
2386
|
+
var validLen = b64.indexOf("=");
|
|
2387
|
+
if (validLen === -1) validLen = len2;
|
|
2388
|
+
var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
|
|
2389
|
+
return [validLen, placeHoldersLen];
|
|
2390
|
+
}
|
|
2391
|
+
function byteLength(b64) {
|
|
2392
|
+
var lens = getLens(b64);
|
|
2393
|
+
var validLen = lens[0];
|
|
2394
|
+
var placeHoldersLen = lens[1];
|
|
2395
|
+
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
|
|
2396
|
+
}
|
|
2397
|
+
function _byteLength(b64, validLen, placeHoldersLen) {
|
|
2398
|
+
return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
|
|
2399
|
+
}
|
|
2400
|
+
function toByteArray(b64) {
|
|
2401
|
+
var tmp;
|
|
2402
|
+
var lens = getLens(b64);
|
|
2403
|
+
var validLen = lens[0];
|
|
2404
|
+
var placeHoldersLen = lens[1];
|
|
2405
|
+
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
|
|
2406
|
+
var curByte = 0;
|
|
2407
|
+
var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
|
|
2408
|
+
var i2;
|
|
2409
|
+
for (i2 = 0; i2 < len2; i2 += 4) {
|
|
2410
|
+
tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
|
|
2411
|
+
arr[curByte++] = tmp >> 16 & 255;
|
|
2412
|
+
arr[curByte++] = tmp >> 8 & 255;
|
|
2413
|
+
arr[curByte++] = tmp & 255;
|
|
2414
|
+
}
|
|
2415
|
+
if (placeHoldersLen === 2) {
|
|
2416
|
+
tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
|
|
2417
|
+
arr[curByte++] = tmp & 255;
|
|
2418
|
+
}
|
|
2419
|
+
if (placeHoldersLen === 1) {
|
|
2420
|
+
tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
|
|
2421
|
+
arr[curByte++] = tmp >> 8 & 255;
|
|
2422
|
+
arr[curByte++] = tmp & 255;
|
|
2423
|
+
}
|
|
2424
|
+
return arr;
|
|
2425
|
+
}
|
|
2426
|
+
function tripletToBase64(num2) {
|
|
2427
|
+
return lookup[num2 >> 18 & 63] + lookup[num2 >> 12 & 63] + lookup[num2 >> 6 & 63] + lookup[num2 & 63];
|
|
2428
|
+
}
|
|
2429
|
+
function encodeChunk(uint8, start, end) {
|
|
2430
|
+
var tmp;
|
|
2431
|
+
var output = [];
|
|
2432
|
+
for (var i2 = start; i2 < end; i2 += 3) {
|
|
2433
|
+
tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
|
|
2434
|
+
output.push(tripletToBase64(tmp));
|
|
2435
|
+
}
|
|
2436
|
+
return output.join("");
|
|
2437
|
+
}
|
|
2438
|
+
function fromByteArray(uint8) {
|
|
2439
|
+
var tmp;
|
|
2440
|
+
var len2 = uint8.length;
|
|
1724
2441
|
var extraBytes = len2 % 3;
|
|
1725
2442
|
var parts = [];
|
|
1726
2443
|
var maxChunkLength = 16383;
|
|
@@ -1958,365 +2675,139 @@ init_debug();
|
|
|
1958
2675
|
init_effort();
|
|
1959
2676
|
init_endpoints();
|
|
1960
2677
|
|
|
1961
|
-
// ../kiro-core/dist/
|
|
2678
|
+
// ../kiro-core/dist/engine.js
|
|
2679
|
+
init_sidecar();
|
|
2680
|
+
init_debug();
|
|
2681
|
+
init_endpoints();
|
|
2682
|
+
init_engine_ops();
|
|
2683
|
+
init_management();
|
|
1962
2684
|
init_models();
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
var
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
if (
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
} catch {
|
|
1991
|
-
return void 0;
|
|
2685
|
+
init_retry();
|
|
2686
|
+
|
|
2687
|
+
// ../kiro-core/dist/stream.js
|
|
2688
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
2689
|
+
init_debug();
|
|
2690
|
+
init_effort();
|
|
2691
|
+
init_endpoints();
|
|
2692
|
+
init_errors2();
|
|
2693
|
+
init_kiro_cli();
|
|
2694
|
+
init_management();
|
|
2695
|
+
init_models();
|
|
2696
|
+
init_oauth();
|
|
2697
|
+
|
|
2698
|
+
// ../kiro-core/dist/request-builder.js
|
|
2699
|
+
init_debug();
|
|
2700
|
+
|
|
2701
|
+
// ../kiro-core/dist/history.js
|
|
2702
|
+
var HISTORY_LIMIT = 85e4;
|
|
2703
|
+
var HISTORY_LIMIT_CONTEXT_WINDOW = 2e5;
|
|
2704
|
+
var HISTORY_IMAGE_BASE64_LIMIT = 512 * 1024;
|
|
2705
|
+
function stripHistoryImages(history, keepNewestBounded = true) {
|
|
2706
|
+
let newestImageIndex = -1;
|
|
2707
|
+
for (let index = history.length - 1; index >= 0; index--) {
|
|
2708
|
+
if ((history[index]?.userInputMessage?.images?.length ?? 0) > 0) {
|
|
2709
|
+
newestImageIndex = index;
|
|
2710
|
+
break;
|
|
2711
|
+
}
|
|
1992
2712
|
}
|
|
2713
|
+
const newestImages = newestImageIndex >= 0 ? history[newestImageIndex]?.userInputMessage?.images : void 0;
|
|
2714
|
+
const keepNewest = keepNewestBounded && newestImages !== void 0 && newestImages.reduce((size, image) => size + image.source.bytes.length, 0) <= HISTORY_IMAGE_BASE64_LIMIT;
|
|
2715
|
+
return history.map((entry, index) => {
|
|
2716
|
+
if (!entry.userInputMessage?.images || index === newestImageIndex && keepNewest)
|
|
2717
|
+
return entry;
|
|
2718
|
+
const { images: _images, ...rest } = entry.userInputMessage;
|
|
2719
|
+
return { ...entry, userInputMessage: { ...rest } };
|
|
2720
|
+
});
|
|
1993
2721
|
}
|
|
1994
|
-
function
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
if (
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2722
|
+
function sanitizeHistory(history) {
|
|
2723
|
+
while (history.length > 0 && (!history[0]?.userInputMessage || history[0].userInputMessage.userInputMessageContext?.toolResults))
|
|
2724
|
+
history = history.slice(1);
|
|
2725
|
+
const result = [];
|
|
2726
|
+
for (let i = 0; i < history.length; i++) {
|
|
2727
|
+
const m = history[i];
|
|
2728
|
+
if (!m)
|
|
2729
|
+
continue;
|
|
2730
|
+
if (m.assistantResponseMessage && !m.assistantResponseMessage.toolUses && !m.assistantResponseMessage.content)
|
|
2731
|
+
continue;
|
|
2732
|
+
if (m.assistantResponseMessage?.toolUses) {
|
|
2733
|
+
const next = history[i + 1];
|
|
2734
|
+
if (next?.userInputMessage?.userInputMessageContext?.toolResults)
|
|
2735
|
+
result.push(m);
|
|
2736
|
+
} else if (m.userInputMessage?.userInputMessageContext?.toolResults) {
|
|
2737
|
+
const prev = result[result.length - 1];
|
|
2738
|
+
if (prev?.assistantResponseMessage?.toolUses)
|
|
2739
|
+
result.push(m);
|
|
2010
2740
|
} else {
|
|
2011
|
-
|
|
2012
|
-
if (!Number.isNaN(dateMs))
|
|
2013
|
-
return Math.max(0, dateMs - nowMs);
|
|
2741
|
+
result.push(m);
|
|
2014
2742
|
}
|
|
2015
2743
|
}
|
|
2016
|
-
|
|
2017
|
-
if (resetAfterSeconds !== void 0) {
|
|
2018
|
-
const delayMs = resetAfterSeconds * 1e3;
|
|
2019
|
-
if (Number.isFinite(delayMs))
|
|
2020
|
-
return Math.round(delayMs);
|
|
2021
|
-
}
|
|
2022
|
-
return void 0;
|
|
2023
|
-
}
|
|
2024
|
-
function resolveRequestRateRetryDelay(headers, nowMs = Date.now()) {
|
|
2025
|
-
const advertisedDelayMs = parseRetryAfterMs(headers, nowMs);
|
|
2026
|
-
const requestedDelayMs = advertisedDelayMs ?? REQUEST_RATE_FALLBACK_DELAY_MS;
|
|
2027
|
-
return {
|
|
2028
|
-
delayMs: Math.min(requestedDelayMs, MAX_RETRY_DELAY),
|
|
2029
|
-
...advertisedDelayMs !== void 0 ? { advertisedDelayMs } : {},
|
|
2030
|
-
capped: requestedDelayMs > MAX_RETRY_DELAY
|
|
2031
|
-
};
|
|
2032
|
-
}
|
|
2033
|
-
function nonNegativeNumber(value) {
|
|
2034
|
-
if (value === null || value.trim() === "")
|
|
2035
|
-
return void 0;
|
|
2036
|
-
const parsed = Number(value);
|
|
2037
|
-
return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
|
|
2038
|
-
}
|
|
2039
|
-
var KIRO_REASON_CODES = Object.freeze({
|
|
2040
|
-
/** Request body exceeded the service's size threshold. */
|
|
2041
|
-
CONTENT_LENGTH_EXCEEDS_THRESHOLD: "CONTENT_LENGTH_EXCEEDS_THRESHOLD",
|
|
2042
|
-
/** Prose-only size rejection; the service sends no reason code for this one. */
|
|
2043
|
-
INPUT_TOO_LONG: "Input is too long",
|
|
2044
|
-
/** Monthly request quota exhausted — hard limit, not transient. */
|
|
2045
|
-
MONTHLY_REQUEST_COUNT: "MONTHLY_REQUEST_COUNT",
|
|
2046
|
-
/** Model capacity temporarily unavailable — transient, worth retrying. */
|
|
2047
|
-
INSUFFICIENT_MODEL_CAPACITY: "INSUFFICIENT_MODEL_CAPACITY",
|
|
2048
|
-
/** Short-window request throttle — retry only within the provider budget. */
|
|
2049
|
-
USER_REQUEST_RATE_EXCEEDED: "USER_REQUEST_RATE_EXCEEDED",
|
|
2050
|
-
/**
|
|
2051
|
-
* Generic request-validation rejection, returned for a malformed body of any
|
|
2052
|
-
* size (empty `content`, history referencing tools absent from the catalog).
|
|
2053
|
-
* Not a size signal: classifying it as "too big" makes the caller compact a
|
|
2054
|
-
* history that was never the problem, a loop it can never satisfy.
|
|
2055
|
-
*/
|
|
2056
|
-
REQUEST_BODY_INVALID: "REQUEST_BODY_INVALID"
|
|
2057
|
-
});
|
|
2058
|
-
var TOO_BIG_PATTERNS = Object.freeze([
|
|
2059
|
-
KIRO_REASON_CODES.CONTENT_LENGTH_EXCEEDS_THRESHOLD,
|
|
2060
|
-
KIRO_REASON_CODES.INPUT_TOO_LONG
|
|
2061
|
-
]);
|
|
2062
|
-
var NON_RETRYABLE_BODY_PATTERNS = Object.freeze([KIRO_REASON_CODES.MONTHLY_REQUEST_COUNT]);
|
|
2063
|
-
var CAPACITY_PATTERN = KIRO_REASON_CODES.INSUFFICIENT_MODEL_CAPACITY;
|
|
2064
|
-
var CAPACITY_MAX_RETRIES = 3;
|
|
2065
|
-
var CAPACITY_BASE_DELAY_MS = 5e3;
|
|
2066
|
-
var capacityRetryConfig = {
|
|
2067
|
-
maxRetries: CAPACITY_MAX_RETRIES,
|
|
2068
|
-
baseDelayMs: CAPACITY_BASE_DELAY_MS
|
|
2069
|
-
};
|
|
2070
|
-
function isTooBigError(status, errorText) {
|
|
2071
|
-
return status === 413 || status === 400 && TOO_BIG_PATTERNS.some((p) => errorText.includes(p));
|
|
2072
|
-
}
|
|
2073
|
-
function isNonRetryableBodyError(errorText) {
|
|
2074
|
-
return NON_RETRYABLE_BODY_PATTERNS.some((p) => errorText.includes(p));
|
|
2075
|
-
}
|
|
2076
|
-
function isCapacityError(errorText) {
|
|
2077
|
-
return errorText.includes(CAPACITY_PATTERN);
|
|
2744
|
+
return result;
|
|
2078
2745
|
}
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
KIRO_REASON_CODES.REQUEST_BODY_INVALID
|
|
2086
|
-
];
|
|
2087
|
-
var KiroApiError = class extends Error {
|
|
2088
|
-
status;
|
|
2089
|
-
reasonCode;
|
|
2090
|
-
retryAfterMs;
|
|
2091
|
-
providerAttempts;
|
|
2092
|
-
constructor(message, status, reasonCode, retryAfterMs, providerAttempts) {
|
|
2093
|
-
super(message);
|
|
2094
|
-
this.status = status;
|
|
2095
|
-
this.reasonCode = reasonCode;
|
|
2096
|
-
this.retryAfterMs = retryAfterMs;
|
|
2097
|
-
this.providerAttempts = providerAttempts;
|
|
2098
|
-
this.name = "KiroApiError";
|
|
2099
|
-
}
|
|
2100
|
-
};
|
|
2101
|
-
function extractKiroReasonCode(errorText) {
|
|
2102
|
-
if (!errorText)
|
|
2103
|
-
return void 0;
|
|
2104
|
-
const trimmed = errorText.trim();
|
|
2105
|
-
if (trimmed.startsWith("{")) {
|
|
2106
|
-
try {
|
|
2107
|
-
const parsed = JSON.parse(trimmed);
|
|
2108
|
-
const reason = parsed.reason ?? parsed.reasonCode;
|
|
2109
|
-
if (typeof reason === "string" && reason.length > 0)
|
|
2110
|
-
return reason;
|
|
2111
|
-
} catch {
|
|
2746
|
+
function injectSyntheticToolCalls(history) {
|
|
2747
|
+
const validIds = /* @__PURE__ */ new Set();
|
|
2748
|
+
for (const entry of history) {
|
|
2749
|
+
for (const tu of entry.assistantResponseMessage?.toolUses ?? []) {
|
|
2750
|
+
if (tu.toolUseId)
|
|
2751
|
+
validIds.add(tu.toolUseId);
|
|
2112
2752
|
}
|
|
2113
2753
|
}
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
"throttlingError",
|
|
2129
|
-
"toolResultEvent",
|
|
2130
|
-
"toolUseEvent",
|
|
2131
|
-
"validationError"
|
|
2132
|
-
];
|
|
2133
|
-
var KIRO_EVENT_KEY_SET = new Set(KIRO_EVENT_KEYS);
|
|
2134
|
-
var KIRO_ERROR_MEMBERS = {
|
|
2135
|
-
error: { kind: "internalServer", exception: "InternalServerException" },
|
|
2136
|
-
throttlingError: { kind: "throttling", exception: "ThrottlingException" },
|
|
2137
|
-
validationError: { kind: "validation", exception: "ValidationException" },
|
|
2138
|
-
serviceUnavailableError: { kind: "serviceUnavailable", exception: "ServiceUnavailableException" }
|
|
2139
|
-
};
|
|
2140
|
-
var KIRO_ERROR_TOKENS = {
|
|
2141
|
-
...KIRO_ERROR_MEMBERS,
|
|
2142
|
-
InternalServerException: KIRO_ERROR_MEMBERS.error,
|
|
2143
|
-
ThrottlingException: KIRO_ERROR_MEMBERS.throttlingError,
|
|
2144
|
-
ValidationException: KIRO_ERROR_MEMBERS.validationError,
|
|
2145
|
-
ServiceUnavailableException: KIRO_ERROR_MEMBERS.serviceUnavailableError
|
|
2146
|
-
};
|
|
2147
|
-
function lookupKiroErrorMember(key) {
|
|
2148
|
-
return Object.hasOwn(KIRO_ERROR_TOKENS, key) ? KIRO_ERROR_TOKENS[key] : void 0;
|
|
2149
|
-
}
|
|
2150
|
-
var num = (v) => typeof v === "number" ? v : void 0;
|
|
2151
|
-
var str = (v) => typeof v === "string" ? v : void 0;
|
|
2152
|
-
function tokenCount(value) {
|
|
2153
|
-
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
2154
|
-
}
|
|
2155
|
-
function firstTokenCount(source, keys) {
|
|
2156
|
-
for (const key of keys) {
|
|
2157
|
-
const count = tokenCount(source[key]);
|
|
2158
|
-
if (count !== void 0)
|
|
2159
|
-
return count;
|
|
2160
|
-
}
|
|
2161
|
-
return void 0;
|
|
2162
|
-
}
|
|
2163
|
-
var CACHE_READ_KEYS = ["cacheReadInputTokens", "cache_read_input_tokens", "cacheReadTokens"];
|
|
2164
|
-
var CACHE_WRITE_KEYS = [
|
|
2165
|
-
"cacheWriteInputTokens",
|
|
2166
|
-
"cache_creation_input_tokens",
|
|
2167
|
-
"cacheCreationInputTokens",
|
|
2168
|
-
"cacheWriteTokens"
|
|
2169
|
-
];
|
|
2170
|
-
function toolInput(raw) {
|
|
2171
|
-
if (typeof raw === "string")
|
|
2172
|
-
return raw;
|
|
2173
|
-
if (raw && typeof raw === "object" && Object.keys(raw).length > 0) {
|
|
2174
|
-
return JSON.stringify(raw);
|
|
2175
|
-
}
|
|
2176
|
-
return "";
|
|
2177
|
-
}
|
|
2178
|
-
function parseToolUse(parsed) {
|
|
2179
|
-
if (parsed.name && parsed.toolUseId) {
|
|
2180
|
-
return {
|
|
2181
|
-
type: "toolUse",
|
|
2182
|
-
data: {
|
|
2183
|
-
name: parsed.name,
|
|
2184
|
-
toolUseId: parsed.toolUseId,
|
|
2185
|
-
input: toolInput(parsed.input),
|
|
2186
|
-
stop: parsed.stop
|
|
2754
|
+
const result = [];
|
|
2755
|
+
for (const entry of history) {
|
|
2756
|
+
const toolResults = entry.userInputMessage?.userInputMessageContext?.toolResults;
|
|
2757
|
+
if (toolResults) {
|
|
2758
|
+
const orphaned = toolResults.filter((tr) => !validIds.has(tr.toolUseId));
|
|
2759
|
+
if (orphaned.length > 0) {
|
|
2760
|
+
result.push({
|
|
2761
|
+
assistantResponseMessage: {
|
|
2762
|
+
content: "Tool calls were made.",
|
|
2763
|
+
toolUses: orphaned.map((tr) => ({ name: "unknown_tool", toolUseId: tr.toolUseId, input: {} }))
|
|
2764
|
+
}
|
|
2765
|
+
});
|
|
2766
|
+
for (const tr of orphaned)
|
|
2767
|
+
validIds.add(tr.toolUseId);
|
|
2187
2768
|
}
|
|
2188
|
-
}
|
|
2189
|
-
|
|
2190
|
-
if (parsed.input !== void 0) {
|
|
2191
|
-
return { type: "toolUseInput", data: { input: toolInput(parsed.input) } };
|
|
2769
|
+
}
|
|
2770
|
+
result.push(entry);
|
|
2192
2771
|
}
|
|
2193
|
-
|
|
2194
|
-
return { type: "toolUseStop", data: { stop: parsed.stop } };
|
|
2195
|
-
return null;
|
|
2772
|
+
return result;
|
|
2196
2773
|
}
|
|
2197
|
-
function
|
|
2198
|
-
|
|
2199
|
-
const data = {
|
|
2200
|
-
inputTokens: tokenCount(tu.uncachedInputTokens) ?? tokenCount(tu.inputTokens),
|
|
2201
|
-
outputTokens: tokenCount(tu.outputTokens),
|
|
2202
|
-
totalTokens: tokenCount(tu.totalTokens),
|
|
2203
|
-
cacheReadInputTokens: firstTokenCount(tu, CACHE_READ_KEYS),
|
|
2204
|
-
cacheWriteInputTokens: firstTokenCount(tu, CACHE_WRITE_KEYS),
|
|
2205
|
-
contextUsagePercentage: num(tu.contextUsagePercentage),
|
|
2206
|
-
normalizedTokenUsage: num(tu.normalizedTokenUsage),
|
|
2207
|
-
rawStopReason: str(parsed.stopReason),
|
|
2208
|
-
stopDetails: parsed.stopDetails && typeof parsed.stopDetails === "object" ? parsed.stopDetails : void 0
|
|
2209
|
-
};
|
|
2210
|
-
for (const k of Object.keys(data)) {
|
|
2211
|
-
if (data[k] === void 0)
|
|
2212
|
-
delete data[k];
|
|
2213
|
-
}
|
|
2214
|
-
return Object.keys(data).length > 0 ? { type: "usage", data } : null;
|
|
2774
|
+
function prepareHistory(history, keepNewestBoundedImage = true) {
|
|
2775
|
+
return injectSyntheticToolCalls(sanitizeHistory(stripHistoryImages(history, keepNewestBoundedImage)));
|
|
2215
2776
|
}
|
|
2216
|
-
function
|
|
2217
|
-
const
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
if (typeof message === "string")
|
|
2222
|
-
data.message = message;
|
|
2223
|
-
const reason = str(parsed.reason);
|
|
2224
|
-
if (reason !== void 0)
|
|
2225
|
-
data.reason = reason;
|
|
2226
|
-
const retryAfterMilliseconds = num(parsed.retryAfterMilliseconds);
|
|
2227
|
-
if (retryAfterMilliseconds !== void 0)
|
|
2228
|
-
data.retryAfterMilliseconds = retryAfterMilliseconds;
|
|
2229
|
-
return { type: "error", data };
|
|
2777
|
+
function assertHistoryWithinLimit(history, limit) {
|
|
2778
|
+
const size = JSON.stringify(history).length;
|
|
2779
|
+
if (size > limit) {
|
|
2780
|
+
throw new Error(`Kiro API error: context_length_exceeded (local history ${size} chars / ${history.length} entries exceeds ${limit}-char limit)`);
|
|
2781
|
+
}
|
|
2230
2782
|
}
|
|
2231
|
-
function
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
case "reasoningContentEvent": {
|
|
2238
|
-
const text = str(parsed.text);
|
|
2239
|
-
if (text !== void 0)
|
|
2240
|
-
return { type: "thinkingText", data: text };
|
|
2241
|
-
const signature = str(parsed.signature);
|
|
2242
|
-
if (signature !== void 0)
|
|
2243
|
-
return { type: "thinkingSignature", data: signature };
|
|
2244
|
-
return { type: "ignored", data: { key } };
|
|
2245
|
-
}
|
|
2246
|
-
case "toolUseEvent":
|
|
2247
|
-
return parseToolUse(parsed);
|
|
2248
|
-
case "contextUsageEvent": {
|
|
2249
|
-
const pct = num(parsed.contextUsagePercentage);
|
|
2250
|
-
return pct !== void 0 ? { type: "contextUsage", data: { contextUsagePercentage: pct } } : null;
|
|
2251
|
-
}
|
|
2252
|
-
case "metadataEvent":
|
|
2253
|
-
return parseMetadata(parsed);
|
|
2254
|
-
case "meteringEvent":
|
|
2255
|
-
return {
|
|
2256
|
-
type: "metering",
|
|
2257
|
-
data: { credits: tokenCount(parsed.usage), unit: str(parsed.unit), unitPlural: str(parsed.unitPlural) }
|
|
2258
|
-
};
|
|
2259
|
-
// Reachable when a member that models an exception is delivered as an
|
|
2260
|
-
// ordinary event frame. The real wire uses exception framing, handled by
|
|
2261
|
-
// parseKiroExceptionFrame, but both routes must agree.
|
|
2262
|
-
case "error":
|
|
2263
|
-
case "throttlingError":
|
|
2264
|
-
case "validationError":
|
|
2265
|
-
case "serviceUnavailableError": {
|
|
2266
|
-
const member = lookupKiroErrorMember(key);
|
|
2267
|
-
return parseError(parsed, member.kind, member.exception);
|
|
2268
|
-
}
|
|
2269
|
-
// Known members with no consumer yet: explicitly ignored, not unparseable.
|
|
2270
|
-
case "codeReferenceEvent":
|
|
2271
|
-
case "documentCitationEvent":
|
|
2272
|
-
case "toolResultEvent":
|
|
2273
|
-
return { type: "ignored", data: { key } };
|
|
2274
|
-
default: {
|
|
2275
|
-
const member = lookupKiroErrorMember(key);
|
|
2276
|
-
if (member)
|
|
2277
|
-
return parseError(parsed, member.kind, member.exception);
|
|
2278
|
-
return parseKiroEventByShape(parsed);
|
|
2783
|
+
function extractToolNamesFromHistory(history) {
|
|
2784
|
+
const names = /* @__PURE__ */ new Set();
|
|
2785
|
+
for (const entry of history) {
|
|
2786
|
+
for (const tu of entry.assistantResponseMessage?.toolUses ?? []) {
|
|
2787
|
+
if (tu.name)
|
|
2788
|
+
names.add(tu.name);
|
|
2279
2789
|
}
|
|
2280
2790
|
}
|
|
2791
|
+
return names;
|
|
2281
2792
|
}
|
|
2282
|
-
function
|
|
2283
|
-
const
|
|
2284
|
-
if (
|
|
2285
|
-
return
|
|
2286
|
-
const
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
}
|
|
2301
|
-
if (parsed.stop !== void 0 && parsed.contextUsagePercentage === void 0)
|
|
2302
|
-
return { type: "toolUseStop", data: { stop: parsed.stop } };
|
|
2303
|
-
if (parsed.contextUsagePercentage !== void 0)
|
|
2304
|
-
return { type: "contextUsage", data: { contextUsagePercentage: parsed.contextUsagePercentage } };
|
|
2305
|
-
if (parsed.followupPrompt !== void 0)
|
|
2306
|
-
return { type: "followupPrompt", data: parsed.followupPrompt };
|
|
2307
|
-
if (parsed.tokenUsage !== void 0 || parsed.stopReason !== void 0 || parsed.stopDetails !== void 0) {
|
|
2308
|
-
return parseMetadata(parsed);
|
|
2309
|
-
}
|
|
2310
|
-
if (parsed.error !== void 0 || parsed.Error !== void 0) {
|
|
2311
|
-
return parseError(parsed, "unknown", "unknown");
|
|
2312
|
-
}
|
|
2313
|
-
if (typeof parsed.usage === "number") {
|
|
2314
|
-
return {
|
|
2315
|
-
type: "metering",
|
|
2316
|
-
data: { credits: tokenCount(parsed.usage), unit: str(parsed.unit), unitPlural: str(parsed.unitPlural) }
|
|
2317
|
-
};
|
|
2318
|
-
}
|
|
2319
|
-
return null;
|
|
2793
|
+
function addPlaceholderTools(tools, history) {
|
|
2794
|
+
const historyNames = extractToolNamesFromHistory(history);
|
|
2795
|
+
if (historyNames.size === 0)
|
|
2796
|
+
return tools;
|
|
2797
|
+
const existing = new Set(tools.map((t) => t.toolSpecification?.name).filter(Boolean));
|
|
2798
|
+
const missing = Array.from(historyNames).filter((n) => !existing.has(n));
|
|
2799
|
+
if (missing.length === 0)
|
|
2800
|
+
return tools;
|
|
2801
|
+
return [
|
|
2802
|
+
...tools,
|
|
2803
|
+
...missing.map((name) => ({
|
|
2804
|
+
toolSpecification: {
|
|
2805
|
+
name,
|
|
2806
|
+
description: "Tool",
|
|
2807
|
+
inputSchema: { json: { type: "object", properties: {} } }
|
|
2808
|
+
}
|
|
2809
|
+
}))
|
|
2810
|
+
];
|
|
2320
2811
|
}
|
|
2321
2812
|
|
|
2322
2813
|
// ../kiro-core/dist/transform.js
|
|
@@ -2628,526 +3119,238 @@ function hasToolResults(entry) {
|
|
|
2628
3119
|
function toolUseIdsOf(entry) {
|
|
2629
3120
|
return (entry?.assistantResponseMessage?.toolUses ?? []).map((tu) => tu.toolUseId).filter(Boolean);
|
|
2630
3121
|
}
|
|
2631
|
-
function hasToolUses(entry) {
|
|
2632
|
-
return toolUseIdsOf(entry).length > 0;
|
|
2633
|
-
}
|
|
2634
|
-
function hasText(entry) {
|
|
2635
|
-
return (entry?.userInputMessage?.content ?? "").trim() !== "";
|
|
2636
|
-
}
|
|
2637
|
-
function toolResultsMatch(toolUseIds, toolResults) {
|
|
2638
|
-
if (toolUseIds.length === 0)
|
|
2639
|
-
return true;
|
|
2640
|
-
if (toolResults.length === 0)
|
|
2641
|
-
return false;
|
|
2642
|
-
const resultIds = new Set(toolResults.map((tr) => tr.toolUseId));
|
|
2643
|
-
const useIds = new Set(toolUseIds);
|
|
2644
|
-
return toolUseIds.every((id) => resultIds.has(id)) && toolResults.every((tr) => useIds.has(tr.toolUseId));
|
|
2645
|
-
}
|
|
2646
|
-
function validateStartsWithUserMessage(entries) {
|
|
2647
|
-
if (entries.length === 0 || !isUserEntry(entries[0])) {
|
|
2648
|
-
return error(KiroValidationRule.STARTS_WITH_USER_MESSAGE, 0);
|
|
2649
|
-
}
|
|
2650
|
-
return null;
|
|
2651
|
-
}
|
|
2652
|
-
function validateEndsWithUserMessage(entries) {
|
|
2653
|
-
if (entries.length === 0 || !isUserEntry(entries[entries.length - 1])) {
|
|
2654
|
-
return error(KiroValidationRule.ENDS_WITH_USER_MESSAGE, entries.length - 1);
|
|
2655
|
-
}
|
|
2656
|
-
return null;
|
|
2657
|
-
}
|
|
2658
|
-
function validateAlternatingMessages(entries) {
|
|
2659
|
-
for (let i = 1; i < entries.length; i++) {
|
|
2660
|
-
if (isUserEntry(entries[i - 1]) && isUserEntry(entries[i])) {
|
|
2661
|
-
return error(KiroValidationRule.ALTERNATING_MESSAGES, i, "Between every two user messages there must be an assistant message");
|
|
2662
|
-
}
|
|
2663
|
-
if (isAssistantEntry(entries[i - 1]) && isAssistantEntry(entries[i])) {
|
|
2664
|
-
return error(KiroValidationRule.ALTERNATING_MESSAGES, i, "Between every two assistant messages there must be a user message");
|
|
2665
|
-
}
|
|
2666
|
-
}
|
|
2667
|
-
return null;
|
|
2668
|
-
}
|
|
2669
|
-
function validateToolUsesAndResults(entries) {
|
|
2670
|
-
for (let i = 0; i < entries.length - 1; i++) {
|
|
2671
|
-
const current = entries[i];
|
|
2672
|
-
const next = entries[i + 1];
|
|
2673
|
-
if (isAssistantEntry(current) && hasToolUses(current) && (!isUserEntry(next) || !toolResultsMatch(toolUseIdsOf(current), toolResultsOf(next)))) {
|
|
2674
|
-
return error(KiroValidationRule.TOOL_USES_AND_RESULTS, i + 1);
|
|
2675
|
-
}
|
|
2676
|
-
if (isAssistantEntry(current) && !hasToolUses(current) && isUserEntry(next) && hasToolResults(next)) {
|
|
2677
|
-
return error(KiroValidationRule.TOOL_RESULTS_AND_NO_USES, i);
|
|
2678
|
-
}
|
|
2679
|
-
}
|
|
2680
|
-
for (let i = 0; i < entries.length; i++) {
|
|
2681
|
-
const entry = entries[i];
|
|
2682
|
-
if (!isUserEntry(entry) || !hasToolResults(entry))
|
|
2683
|
-
continue;
|
|
2684
|
-
const prev = i > 0 ? entries[i - 1] : void 0;
|
|
2685
|
-
if (!isAssistantEntry(prev))
|
|
2686
|
-
return error(KiroValidationRule.TOOL_RESULTS_AND_NO_USES, i);
|
|
2687
|
-
}
|
|
2688
|
-
return null;
|
|
2689
|
-
}
|
|
2690
|
-
function validateToolResultOrphanIds(entries) {
|
|
2691
|
-
for (let i = 1; i < entries.length; i++) {
|
|
2692
|
-
const prev = entries[i - 1];
|
|
2693
|
-
const current = entries[i];
|
|
2694
|
-
if (!isAssistantEntry(prev) || !hasToolUses(prev) || !isUserEntry(current) || !hasToolResults(current))
|
|
2695
|
-
continue;
|
|
2696
|
-
const validIds = new Set(toolUseIdsOf(prev));
|
|
2697
|
-
const toolResults = toolResultsOf(current);
|
|
2698
|
-
const hasOrphan = toolResults.some((tr) => !tr.toolUseId || !validIds.has(tr.toolUseId));
|
|
2699
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2700
|
-
const hasDuplicate = toolResults.some((tr) => {
|
|
2701
|
-
if (!tr.toolUseId)
|
|
2702
|
-
return false;
|
|
2703
|
-
if (seen.has(tr.toolUseId))
|
|
2704
|
-
return true;
|
|
2705
|
-
seen.add(tr.toolUseId);
|
|
2706
|
-
return false;
|
|
2707
|
-
});
|
|
2708
|
-
if (hasOrphan || hasDuplicate)
|
|
2709
|
-
return error(KiroValidationRule.TOOL_RESULTS_ORPHAN_IDS, i);
|
|
2710
|
-
}
|
|
2711
|
-
return null;
|
|
2712
|
-
}
|
|
2713
|
-
function validateNonEmptyUserMessages(entries) {
|
|
2714
|
-
for (let i = 0; i < entries.length; i++) {
|
|
2715
|
-
const entry = entries[i];
|
|
2716
|
-
if (!isUserEntry(entry))
|
|
2717
|
-
continue;
|
|
2718
|
-
if (!hasText(entry) && !hasToolResults(entry)) {
|
|
2719
|
-
return error(KiroValidationRule.NON_EMPTY_USER_MESSAGE, i);
|
|
2720
|
-
}
|
|
2721
|
-
}
|
|
2722
|
-
return null;
|
|
2723
|
-
}
|
|
2724
|
-
function validateKiroToolStructure(entries) {
|
|
2725
|
-
const errors = [validateToolUsesAndResults(entries), validateToolResultOrphanIds(entries)].filter((e) => e !== null);
|
|
2726
|
-
return { valid: errors.length === 0, errors };
|
|
2727
|
-
}
|
|
2728
|
-
function validateKiroConversation(entries) {
|
|
2729
|
-
const errors = [
|
|
2730
|
-
validateStartsWithUserMessage(entries),
|
|
2731
|
-
validateEndsWithUserMessage(entries),
|
|
2732
|
-
validateAlternatingMessages(entries),
|
|
2733
|
-
...validateKiroToolStructure(entries).errors,
|
|
2734
|
-
validateNonEmptyUserMessages(entries)
|
|
2735
|
-
].filter((e) => e !== null);
|
|
2736
|
-
return { valid: errors.length === 0, errors };
|
|
2737
|
-
}
|
|
2738
|
-
function kiroConversationEntries(history, currentUserMessage) {
|
|
2739
|
-
return currentUserMessage ? [...history, { userInputMessage: currentUserMessage }] : [...history];
|
|
2740
|
-
}
|
|
2741
|
-
function repairKiroConversation(entries) {
|
|
2742
|
-
const diagnostics = validateKiroConversation(entries).errors;
|
|
2743
|
-
if (diagnostics.length === 0)
|
|
2744
|
-
return { entries, diagnostics, remaining: [] };
|
|
2745
|
-
const modelId = entries.find((e) => e.userInputMessage?.modelId)?.userInputMessage?.modelId ?? "";
|
|
2746
|
-
let working = [...entries];
|
|
2747
|
-
while (working.length > 0 && (!isUserEntry(working[0]) || hasToolResults(working[0])))
|
|
2748
|
-
working = working.slice(1);
|
|
2749
|
-
const consolidated = [];
|
|
2750
|
-
for (let i = 0; i < working.length; i++) {
|
|
2751
|
-
const entry = working[i];
|
|
2752
|
-
const isToolOnly = isUserEntry(entry) && hasToolResults(entry) && !hasText(entry);
|
|
2753
|
-
if (!isToolOnly) {
|
|
2754
|
-
consolidated.push(entry);
|
|
2755
|
-
continue;
|
|
2756
|
-
}
|
|
2757
|
-
let j = i;
|
|
2758
|
-
const merged = [];
|
|
2759
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2760
|
-
while (j < working.length) {
|
|
2761
|
-
const candidate = working[j];
|
|
2762
|
-
if (!(isUserEntry(candidate) && hasToolResults(candidate) && !hasText(candidate)))
|
|
2763
|
-
break;
|
|
2764
|
-
for (const tr of toolResultsOf(candidate)) {
|
|
2765
|
-
if (tr.toolUseId && seen.has(tr.toolUseId))
|
|
2766
|
-
continue;
|
|
2767
|
-
if (tr.toolUseId)
|
|
2768
|
-
seen.add(tr.toolUseId);
|
|
2769
|
-
merged.push(tr);
|
|
2770
|
-
}
|
|
2771
|
-
j++;
|
|
2772
|
-
}
|
|
2773
|
-
if (j - i === 1) {
|
|
2774
|
-
consolidated.push(entry);
|
|
2775
|
-
} else {
|
|
2776
|
-
const uim = entry.userInputMessage;
|
|
2777
|
-
consolidated.push({
|
|
2778
|
-
userInputMessage: {
|
|
2779
|
-
...uim,
|
|
2780
|
-
userInputMessageContext: { ...uim.userInputMessageContext, toolResults: merged }
|
|
2781
|
-
}
|
|
2782
|
-
});
|
|
2783
|
-
}
|
|
2784
|
-
i = j - 1;
|
|
2785
|
-
}
|
|
2786
|
-
working = consolidated;
|
|
2787
|
-
const repaired = [];
|
|
2788
|
-
for (let i = 0; i < working.length; i++) {
|
|
2789
|
-
const entry = working[i];
|
|
2790
|
-
if (isUserEntry(entry) && hasToolResults(entry)) {
|
|
2791
|
-
const prev = repaired[repaired.length - 1];
|
|
2792
|
-
const validIds = new Set(toolUseIdsOf(prev));
|
|
2793
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2794
|
-
const kept = toolResultsOf(entry).filter((tr) => {
|
|
2795
|
-
if (!tr.toolUseId || !validIds.has(tr.toolUseId) || seen.has(tr.toolUseId))
|
|
2796
|
-
return false;
|
|
2797
|
-
seen.add(tr.toolUseId);
|
|
2798
|
-
return true;
|
|
2799
|
-
});
|
|
2800
|
-
const uim = { ...entry.userInputMessage };
|
|
2801
|
-
if (kept.length === 0) {
|
|
2802
|
-
const { userInputMessageContext, ...rest } = uim;
|
|
2803
|
-
const tools = userInputMessageContext?.tools;
|
|
2804
|
-
repaired.push({
|
|
2805
|
-
userInputMessage: { ...rest, ...tools ? { userInputMessageContext: { tools } } : {} }
|
|
2806
|
-
});
|
|
2807
|
-
} else {
|
|
2808
|
-
repaired.push({
|
|
2809
|
-
userInputMessage: {
|
|
2810
|
-
...uim,
|
|
2811
|
-
userInputMessageContext: { ...uim.userInputMessageContext, toolResults: kept }
|
|
2812
|
-
}
|
|
2813
|
-
});
|
|
2814
|
-
}
|
|
2815
|
-
continue;
|
|
2816
|
-
}
|
|
2817
|
-
repaired.push(entry);
|
|
2818
|
-
if (isAssistantEntry(entry) && hasToolUses(entry)) {
|
|
2819
|
-
const next = working[i + 1];
|
|
2820
|
-
const answered = new Set(isUserEntry(next) ? toolResultsOf(next).map((tr) => tr.toolUseId) : (
|
|
2821
|
-
/* c8 ignore next */
|
|
2822
|
-
[]
|
|
2823
|
-
));
|
|
2824
|
-
const unanswered = toolUseIdsOf(entry).filter((id) => !answered.has(id));
|
|
2825
|
-
if (unanswered.length > 0 && !isUserEntry(next)) {
|
|
2826
|
-
repaired.push(syntheticToolResultEntry(unanswered, modelId));
|
|
2827
|
-
} else if (unanswered.length > 0 && isUserEntry(next)) {
|
|
2828
|
-
const uim = { ...next.userInputMessage };
|
|
2829
|
-
working[i + 1] = {
|
|
2830
|
-
userInputMessage: {
|
|
2831
|
-
...uim,
|
|
2832
|
-
userInputMessageContext: {
|
|
2833
|
-
...uim.userInputMessageContext,
|
|
2834
|
-
toolResults: [...toolResultsOf(next), ...unanswered.map(syntheticFailedToolResult)]
|
|
2835
|
-
}
|
|
2836
|
-
}
|
|
2837
|
-
};
|
|
2838
|
-
}
|
|
2839
|
-
}
|
|
2840
|
-
}
|
|
2841
|
-
const final = repaired.map((entry) => {
|
|
2842
|
-
if (!isUserEntry(entry) || hasText(entry) || hasToolResults(entry))
|
|
2843
|
-
return entry;
|
|
2844
|
-
const uim = entry.userInputMessage;
|
|
2845
|
-
return { userInputMessage: { ...uim, content: EMPTY_CONTENT_PLACEHOLDER } };
|
|
2846
|
-
});
|
|
2847
|
-
return { entries: final, diagnostics, remaining: validateKiroConversation(final).errors };
|
|
2848
|
-
}
|
|
2849
|
-
function syntheticFailedToolResult(toolUseId) {
|
|
2850
|
-
return { toolUseId, content: [{ text: SYNTHETIC_FAILED_TOOL_RESULT_TEXT }], status: "error" };
|
|
2851
|
-
}
|
|
2852
|
-
function syntheticToolResultEntry(toolUseIds, modelId) {
|
|
2853
|
-
return {
|
|
2854
|
-
userInputMessage: {
|
|
2855
|
-
// Empty by design: `toolResults` is the payload. Matches kiro-agent's
|
|
2856
|
-
// `FAILED_TOOL_USE_MESSAGE`, which also ships `content: ''`.
|
|
2857
|
-
content: "",
|
|
2858
|
-
modelId,
|
|
2859
|
-
origin: "KIRO_CLI",
|
|
2860
|
-
userInputMessageContext: { toolResults: toolUseIds.map(syntheticFailedToolResult) }
|
|
2861
|
-
}
|
|
2862
|
-
};
|
|
2863
|
-
}
|
|
2864
|
-
|
|
2865
|
-
// ../kiro-core/dist/host-auth.js
|
|
2866
|
-
init_endpoints();
|
|
2867
|
-
init_oauth();
|
|
2868
|
-
var KIRO_NO_SESSION_MESSAGE = "No Kiro session found. Sign in with `kiro-cli login` (Builder ID, IAM Identity Center, Google, or GitHub), then run /login kiro again \u2014 or paste a Kiro API key below.";
|
|
2869
|
-
async function loginKiroFromSession(callbacks) {
|
|
2870
|
-
callbacks.onProgress?.("Looking for an existing Kiro session\u2026");
|
|
2871
|
-
const existing = await resolveKiroCredentials();
|
|
2872
|
-
if (existing) {
|
|
2873
|
-
callbacks.onProgress?.(`Using the ${existing.authMethod} session from kiro-cli.`);
|
|
2874
|
-
return existing;
|
|
2875
|
-
}
|
|
2876
|
-
if (!callbacks.onPrompt)
|
|
2877
|
-
throw new Error(KIRO_NO_SESSION_MESSAGE);
|
|
2878
|
-
const apiKey = (await callbacks.onPrompt({
|
|
2879
|
-
message: KIRO_NO_SESSION_MESSAGE,
|
|
2880
|
-
placeholder: "ksk_\u2026",
|
|
2881
|
-
allowEmpty: true,
|
|
2882
|
-
secret: true
|
|
2883
|
-
})).trim();
|
|
2884
|
-
if (!apiKey)
|
|
2885
|
-
throw new Error(KIRO_NO_SESSION_MESSAGE);
|
|
2886
|
-
return loginKiroWithApiKey(apiKey, callbacks.onProgress);
|
|
3122
|
+
function hasToolUses(entry) {
|
|
3123
|
+
return toolUseIdsOf(entry).length > 0;
|
|
2887
3124
|
}
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
const region = resolveApiRegion(stored?.region);
|
|
2891
|
-
if (hostKey && (isApiKey(hostKey) || hostKey === stored?.access)) {
|
|
2892
|
-
return { accessToken: hostKey, region, ...stored?.profileArn ? { profileArn: stored.profileArn } : {} };
|
|
2893
|
-
}
|
|
2894
|
-
if (stored) {
|
|
2895
|
-
return {
|
|
2896
|
-
accessToken: stored.access,
|
|
2897
|
-
region,
|
|
2898
|
-
...stored.profileArn ? { profileArn: stored.profileArn } : {}
|
|
2899
|
-
};
|
|
2900
|
-
}
|
|
2901
|
-
if (hostKey)
|
|
2902
|
-
return { accessToken: hostKey, region };
|
|
2903
|
-
throw new Error("Kiro credentials not set. Run `kiro-cli login`, or set KIRO_API_KEY to a `ksk_` API key.");
|
|
3125
|
+
function hasText(entry) {
|
|
3126
|
+
return (entry?.userInputMessage?.content ?? "").trim() !== "";
|
|
2904
3127
|
}
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
// No fallback to `model.id`: that dash-spelled local id is not a valid
|
|
2914
|
-
// Kiro wire id. `""` is falsy, so `resolveKiroModel` runs its own
|
|
2915
|
-
// cache/bootstrap/dot-normalize resolution instead of being
|
|
2916
|
-
// short-circuited by a value that is really just `model.id` again.
|
|
2917
|
-
kiroModelId: model.kiroModelId ?? "",
|
|
2918
|
-
name: model.name,
|
|
2919
|
-
reasoning: model.reasoning,
|
|
2920
|
-
input: [...model.input],
|
|
2921
|
-
cost: { ...model.cost },
|
|
2922
|
-
contextWindow: model.contextWindow ?? 2e5,
|
|
2923
|
-
maxTokens: model.maxTokens ?? 8192
|
|
2924
|
-
},
|
|
2925
|
-
region,
|
|
2926
|
-
...model.kiroProfileArn ? { profileArn: model.kiroProfileArn } : {},
|
|
2927
|
-
...model.additionalModelRequestFieldsSchema ? { additionalModelRequestFieldsSchema: model.additionalModelRequestFieldsSchema } : {}
|
|
2928
|
-
};
|
|
3128
|
+
function toolResultsMatch(toolUseIds, toolResults) {
|
|
3129
|
+
if (toolUseIds.length === 0)
|
|
3130
|
+
return true;
|
|
3131
|
+
if (toolResults.length === 0)
|
|
3132
|
+
return false;
|
|
3133
|
+
const resultIds = new Set(toolResults.map((tr) => tr.toolUseId));
|
|
3134
|
+
const useIds = new Set(toolUseIds);
|
|
3135
|
+
return toolUseIds.every((id) => resultIds.has(id)) && toolResults.every((tr) => useIds.has(tr.toolUseId));
|
|
2929
3136
|
}
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
var INVOKE_OPEN_SEARCH = "<invoke name=";
|
|
2934
|
-
var INVOKE_OPEN_ANYWHERE = /<invoke name="[\w-]+">/;
|
|
2935
|
-
var PARAM_OPEN_ANCHORED = /^<parameter name="([^"]*)">/;
|
|
2936
|
-
var INVOKE_CLOSE = "</invoke>";
|
|
2937
|
-
var PARAM_CLOSE = "</parameter>";
|
|
2938
|
-
var FENCE = "```";
|
|
2939
|
-
function fencedRanges(text) {
|
|
2940
|
-
const ranges = [];
|
|
2941
|
-
let searchFrom = 0;
|
|
2942
|
-
while (true) {
|
|
2943
|
-
const open = text.indexOf(FENCE, searchFrom);
|
|
2944
|
-
if (open < 0)
|
|
2945
|
-
break;
|
|
2946
|
-
const close = text.indexOf(FENCE, open + FENCE.length);
|
|
2947
|
-
if (close < 0) {
|
|
2948
|
-
ranges.push({ start: open, end: text.length });
|
|
2949
|
-
break;
|
|
2950
|
-
}
|
|
2951
|
-
ranges.push({ start: open, end: close + FENCE.length });
|
|
2952
|
-
searchFrom = close + FENCE.length;
|
|
3137
|
+
function validateStartsWithUserMessage(entries) {
|
|
3138
|
+
if (entries.length === 0 || !isUserEntry(entries[0])) {
|
|
3139
|
+
return error(KiroValidationRule.STARTS_WITH_USER_MESSAGE, 0);
|
|
2953
3140
|
}
|
|
2954
|
-
return
|
|
3141
|
+
return null;
|
|
2955
3142
|
}
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
let
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
if (
|
|
2968
|
-
|
|
2969
|
-
if (text.startsWith(INVOKE_CLOSE, cursor)) {
|
|
2970
|
-
const end = cursor + INVOKE_CLOSE.length;
|
|
2971
|
-
if (end < text.length && !/\s/.test(text[end]))
|
|
2972
|
-
return null;
|
|
2973
|
-
return { name: openMatch[1], arguments: args, end };
|
|
3143
|
+
function validateEndsWithUserMessage(entries) {
|
|
3144
|
+
if (entries.length === 0 || !isUserEntry(entries[entries.length - 1])) {
|
|
3145
|
+
return error(KiroValidationRule.ENDS_WITH_USER_MESSAGE, entries.length - 1);
|
|
3146
|
+
}
|
|
3147
|
+
return null;
|
|
3148
|
+
}
|
|
3149
|
+
function validateAlternatingMessages(entries) {
|
|
3150
|
+
for (let i = 1; i < entries.length; i++) {
|
|
3151
|
+
if (isUserEntry(entries[i - 1]) && isUserEntry(entries[i])) {
|
|
3152
|
+
return error(KiroValidationRule.ALTERNATING_MESSAGES, i, "Between every two user messages there must be an assistant message");
|
|
3153
|
+
}
|
|
3154
|
+
if (isAssistantEntry(entries[i - 1]) && isAssistantEntry(entries[i])) {
|
|
3155
|
+
return error(KiroValidationRule.ALTERNATING_MESSAGES, i, "Between every two assistant messages there must be a user message");
|
|
2974
3156
|
}
|
|
2975
|
-
const paramMatch = PARAM_OPEN_ANCHORED.exec(text.substring(cursor));
|
|
2976
|
-
if (!paramMatch)
|
|
2977
|
-
return null;
|
|
2978
|
-
const valueStart = cursor + paramMatch[0].length;
|
|
2979
|
-
const valueEnd = text.indexOf(PARAM_CLOSE, valueStart);
|
|
2980
|
-
if (valueEnd < 0)
|
|
2981
|
-
return null;
|
|
2982
|
-
const value = text.substring(valueStart, valueEnd);
|
|
2983
|
-
if (INVOKE_OPEN_ANYWHERE.test(value))
|
|
2984
|
-
throw new AmbiguousDialectError();
|
|
2985
|
-
args[paramMatch[1]] = value;
|
|
2986
|
-
cursor = valueEnd + PARAM_CLOSE.length;
|
|
2987
3157
|
}
|
|
3158
|
+
return null;
|
|
2988
3159
|
}
|
|
2989
|
-
function
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
while (cursor < text.length) {
|
|
2996
|
-
const openStart = text.indexOf(INVOKE_OPEN_SEARCH, cursor);
|
|
2997
|
-
if (openStart < 0)
|
|
2998
|
-
break;
|
|
2999
|
-
const containingFence = fences.find((range) => openStart >= range.start && openStart < range.end);
|
|
3000
|
-
if (containingFence) {
|
|
3001
|
-
cursor = containingFence.end;
|
|
3002
|
-
continue;
|
|
3160
|
+
function validateToolUsesAndResults(entries) {
|
|
3161
|
+
for (let i = 0; i < entries.length - 1; i++) {
|
|
3162
|
+
const current = entries[i];
|
|
3163
|
+
const next = entries[i + 1];
|
|
3164
|
+
if (isAssistantEntry(current) && hasToolUses(current) && (!isUserEntry(next) || !toolResultsMatch(toolUseIdsOf(current), toolResultsOf(next)))) {
|
|
3165
|
+
return error(KiroValidationRule.TOOL_USES_AND_RESULTS, i + 1);
|
|
3003
3166
|
}
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
block = parseBlockAt(text, openStart);
|
|
3007
|
-
} catch (e) {
|
|
3008
|
-
if (e instanceof AmbiguousDialectError)
|
|
3009
|
-
return untouched;
|
|
3010
|
-
throw e;
|
|
3167
|
+
if (isAssistantEntry(current) && !hasToolUses(current) && isUserEntry(next) && hasToolResults(next)) {
|
|
3168
|
+
return error(KiroValidationRule.TOOL_RESULTS_AND_NO_USES, i);
|
|
3011
3169
|
}
|
|
3012
|
-
if (block === null)
|
|
3013
|
-
return untouched;
|
|
3014
|
-
const nextOpen = text.indexOf(INVOKE_OPEN_SEARCH, block.end);
|
|
3015
|
-
const interstitialEnd = nextOpen < 0 ? text.length : nextOpen;
|
|
3016
|
-
const interstitial = text.substring(block.end, interstitialEnd);
|
|
3017
|
-
if (interstitial.includes(PARAM_CLOSE) || interstitial.includes(INVOKE_CLOSE))
|
|
3018
|
-
return untouched;
|
|
3019
|
-
toolCalls.push({ toolUseId: crypto.randomUUID(), name: block.name, arguments: block.arguments });
|
|
3020
|
-
removals.push({ start: openStart, end: block.end });
|
|
3021
|
-
cursor = block.end;
|
|
3022
3170
|
}
|
|
3023
|
-
let
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3171
|
+
for (let i = 0; i < entries.length; i++) {
|
|
3172
|
+
const entry = entries[i];
|
|
3173
|
+
if (!isUserEntry(entry) || !hasToolResults(entry))
|
|
3174
|
+
continue;
|
|
3175
|
+
const prev = i > 0 ? entries[i - 1] : void 0;
|
|
3176
|
+
if (!isAssistantEntry(prev))
|
|
3177
|
+
return error(KiroValidationRule.TOOL_RESULTS_AND_NO_USES, i);
|
|
3027
3178
|
}
|
|
3028
|
-
return
|
|
3179
|
+
return null;
|
|
3029
3180
|
}
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
if (
|
|
3049
|
-
|
|
3050
|
-
break;
|
|
3051
|
-
}
|
|
3181
|
+
function validateToolResultOrphanIds(entries) {
|
|
3182
|
+
for (let i = 1; i < entries.length; i++) {
|
|
3183
|
+
const prev = entries[i - 1];
|
|
3184
|
+
const current = entries[i];
|
|
3185
|
+
if (!isAssistantEntry(prev) || !hasToolUses(prev) || !isUserEntry(current) || !hasToolResults(current))
|
|
3186
|
+
continue;
|
|
3187
|
+
const validIds = new Set(toolUseIdsOf(prev));
|
|
3188
|
+
const toolResults = toolResultsOf(current);
|
|
3189
|
+
const hasOrphan = toolResults.some((tr) => !tr.toolUseId || !validIds.has(tr.toolUseId));
|
|
3190
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3191
|
+
const hasDuplicate = toolResults.some((tr) => {
|
|
3192
|
+
if (!tr.toolUseId)
|
|
3193
|
+
return false;
|
|
3194
|
+
if (seen.has(tr.toolUseId))
|
|
3195
|
+
return true;
|
|
3196
|
+
seen.add(tr.toolUseId);
|
|
3197
|
+
return false;
|
|
3198
|
+
});
|
|
3199
|
+
if (hasOrphan || hasDuplicate)
|
|
3200
|
+
return error(KiroValidationRule.TOOL_RESULTS_ORPHAN_IDS, i);
|
|
3052
3201
|
}
|
|
3053
|
-
|
|
3054
|
-
const keepNewest = keepNewestBounded && newestImages !== void 0 && newestImages.reduce((size, image) => size + image.source.bytes.length, 0) <= HISTORY_IMAGE_BASE64_LIMIT;
|
|
3055
|
-
return history.map((entry, index) => {
|
|
3056
|
-
if (!entry.userInputMessage?.images || index === newestImageIndex && keepNewest)
|
|
3057
|
-
return entry;
|
|
3058
|
-
const { images: _images, ...rest } = entry.userInputMessage;
|
|
3059
|
-
return { ...entry, userInputMessage: { ...rest } };
|
|
3060
|
-
});
|
|
3202
|
+
return null;
|
|
3061
3203
|
}
|
|
3062
|
-
function
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
for (let i = 0; i < history.length; i++) {
|
|
3067
|
-
const m = history[i];
|
|
3068
|
-
if (!m)
|
|
3204
|
+
function validateNonEmptyUserMessages(entries) {
|
|
3205
|
+
for (let i = 0; i < entries.length; i++) {
|
|
3206
|
+
const entry = entries[i];
|
|
3207
|
+
if (!isUserEntry(entry))
|
|
3069
3208
|
continue;
|
|
3070
|
-
if (
|
|
3209
|
+
if (!hasText(entry) && !hasToolResults(entry)) {
|
|
3210
|
+
return error(KiroValidationRule.NON_EMPTY_USER_MESSAGE, i);
|
|
3211
|
+
}
|
|
3212
|
+
}
|
|
3213
|
+
return null;
|
|
3214
|
+
}
|
|
3215
|
+
function validateKiroToolStructure(entries) {
|
|
3216
|
+
const errors = [validateToolUsesAndResults(entries), validateToolResultOrphanIds(entries)].filter((e) => e !== null);
|
|
3217
|
+
return { valid: errors.length === 0, errors };
|
|
3218
|
+
}
|
|
3219
|
+
function validateKiroConversation(entries) {
|
|
3220
|
+
const errors = [
|
|
3221
|
+
validateStartsWithUserMessage(entries),
|
|
3222
|
+
validateEndsWithUserMessage(entries),
|
|
3223
|
+
validateAlternatingMessages(entries),
|
|
3224
|
+
...validateKiroToolStructure(entries).errors,
|
|
3225
|
+
validateNonEmptyUserMessages(entries)
|
|
3226
|
+
].filter((e) => e !== null);
|
|
3227
|
+
return { valid: errors.length === 0, errors };
|
|
3228
|
+
}
|
|
3229
|
+
function kiroConversationEntries(history, currentUserMessage) {
|
|
3230
|
+
return currentUserMessage ? [...history, { userInputMessage: currentUserMessage }] : [...history];
|
|
3231
|
+
}
|
|
3232
|
+
function repairKiroConversation(entries) {
|
|
3233
|
+
const diagnostics = validateKiroConversation(entries).errors;
|
|
3234
|
+
if (diagnostics.length === 0)
|
|
3235
|
+
return { entries, diagnostics, remaining: [] };
|
|
3236
|
+
const modelId = entries.find((e) => e.userInputMessage?.modelId)?.userInputMessage?.modelId ?? "";
|
|
3237
|
+
let working = [...entries];
|
|
3238
|
+
while (working.length > 0 && (!isUserEntry(working[0]) || hasToolResults(working[0])))
|
|
3239
|
+
working = working.slice(1);
|
|
3240
|
+
const consolidated = [];
|
|
3241
|
+
for (let i = 0; i < working.length; i++) {
|
|
3242
|
+
const entry = working[i];
|
|
3243
|
+
const isToolOnly = isUserEntry(entry) && hasToolResults(entry) && !hasText(entry);
|
|
3244
|
+
if (!isToolOnly) {
|
|
3245
|
+
consolidated.push(entry);
|
|
3071
3246
|
continue;
|
|
3072
|
-
if (m.assistantResponseMessage?.toolUses) {
|
|
3073
|
-
const next = history[i + 1];
|
|
3074
|
-
if (next?.userInputMessage?.userInputMessageContext?.toolResults)
|
|
3075
|
-
result.push(m);
|
|
3076
|
-
} else if (m.userInputMessage?.userInputMessageContext?.toolResults) {
|
|
3077
|
-
const prev = result[result.length - 1];
|
|
3078
|
-
if (prev?.assistantResponseMessage?.toolUses)
|
|
3079
|
-
result.push(m);
|
|
3080
|
-
} else {
|
|
3081
|
-
result.push(m);
|
|
3082
3247
|
}
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3248
|
+
let j = i;
|
|
3249
|
+
const merged = [];
|
|
3250
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3251
|
+
while (j < working.length) {
|
|
3252
|
+
const candidate = working[j];
|
|
3253
|
+
if (!(isUserEntry(candidate) && hasToolResults(candidate) && !hasText(candidate)))
|
|
3254
|
+
break;
|
|
3255
|
+
for (const tr of toolResultsOf(candidate)) {
|
|
3256
|
+
if (tr.toolUseId && seen.has(tr.toolUseId))
|
|
3257
|
+
continue;
|
|
3258
|
+
if (tr.toolUseId)
|
|
3259
|
+
seen.add(tr.toolUseId);
|
|
3260
|
+
merged.push(tr);
|
|
3261
|
+
}
|
|
3262
|
+
j++;
|
|
3263
|
+
}
|
|
3264
|
+
if (j - i === 1) {
|
|
3265
|
+
consolidated.push(entry);
|
|
3266
|
+
} else {
|
|
3267
|
+
const uim = entry.userInputMessage;
|
|
3268
|
+
consolidated.push({
|
|
3269
|
+
userInputMessage: {
|
|
3270
|
+
...uim,
|
|
3271
|
+
userInputMessageContext: { ...uim.userInputMessageContext, toolResults: merged }
|
|
3272
|
+
}
|
|
3273
|
+
});
|
|
3092
3274
|
}
|
|
3275
|
+
i = j - 1;
|
|
3093
3276
|
}
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3277
|
+
working = consolidated;
|
|
3278
|
+
const repaired = [];
|
|
3279
|
+
for (let i = 0; i < working.length; i++) {
|
|
3280
|
+
const entry = working[i];
|
|
3281
|
+
if (isUserEntry(entry) && hasToolResults(entry)) {
|
|
3282
|
+
const prev = repaired[repaired.length - 1];
|
|
3283
|
+
const validIds = new Set(toolUseIdsOf(prev));
|
|
3284
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3285
|
+
const kept = toolResultsOf(entry).filter((tr) => {
|
|
3286
|
+
if (!tr.toolUseId || !validIds.has(tr.toolUseId) || seen.has(tr.toolUseId))
|
|
3287
|
+
return false;
|
|
3288
|
+
seen.add(tr.toolUseId);
|
|
3289
|
+
return true;
|
|
3290
|
+
});
|
|
3291
|
+
const uim = { ...entry.userInputMessage };
|
|
3292
|
+
if (kept.length === 0) {
|
|
3293
|
+
const { userInputMessageContext, ...rest } = uim;
|
|
3294
|
+
const tools = userInputMessageContext?.tools;
|
|
3295
|
+
repaired.push({
|
|
3296
|
+
userInputMessage: { ...rest, ...tools ? { userInputMessageContext: { tools } } : {} }
|
|
3297
|
+
});
|
|
3298
|
+
} else {
|
|
3299
|
+
repaired.push({
|
|
3300
|
+
userInputMessage: {
|
|
3301
|
+
...uim,
|
|
3302
|
+
userInputMessageContext: { ...uim.userInputMessageContext, toolResults: kept }
|
|
3104
3303
|
}
|
|
3105
3304
|
});
|
|
3106
|
-
|
|
3107
|
-
|
|
3305
|
+
}
|
|
3306
|
+
continue;
|
|
3307
|
+
}
|
|
3308
|
+
repaired.push(entry);
|
|
3309
|
+
if (isAssistantEntry(entry) && hasToolUses(entry)) {
|
|
3310
|
+
const next = working[i + 1];
|
|
3311
|
+
const answered = new Set(isUserEntry(next) ? toolResultsOf(next).map((tr) => tr.toolUseId) : (
|
|
3312
|
+
/* c8 ignore next */
|
|
3313
|
+
[]
|
|
3314
|
+
));
|
|
3315
|
+
const unanswered = toolUseIdsOf(entry).filter((id) => !answered.has(id));
|
|
3316
|
+
if (unanswered.length > 0 && !isUserEntry(next)) {
|
|
3317
|
+
repaired.push(syntheticToolResultEntry(unanswered, modelId));
|
|
3318
|
+
} else if (unanswered.length > 0 && isUserEntry(next)) {
|
|
3319
|
+
const uim = { ...next.userInputMessage };
|
|
3320
|
+
working[i + 1] = {
|
|
3321
|
+
userInputMessage: {
|
|
3322
|
+
...uim,
|
|
3323
|
+
userInputMessageContext: {
|
|
3324
|
+
...uim.userInputMessageContext,
|
|
3325
|
+
toolResults: [...toolResultsOf(next), ...unanswered.map(syntheticFailedToolResult)]
|
|
3326
|
+
}
|
|
3327
|
+
}
|
|
3328
|
+
};
|
|
3108
3329
|
}
|
|
3109
3330
|
}
|
|
3110
|
-
result.push(entry);
|
|
3111
3331
|
}
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3332
|
+
const final = repaired.map((entry) => {
|
|
3333
|
+
if (!isUserEntry(entry) || hasText(entry) || hasToolResults(entry))
|
|
3334
|
+
return entry;
|
|
3335
|
+
const uim = entry.userInputMessage;
|
|
3336
|
+
return { userInputMessage: { ...uim, content: EMPTY_CONTENT_PLACEHOLDER } };
|
|
3337
|
+
});
|
|
3338
|
+
return { entries: final, diagnostics, remaining: validateKiroConversation(final).errors };
|
|
3116
3339
|
}
|
|
3117
|
-
function
|
|
3118
|
-
|
|
3119
|
-
if (size > limit) {
|
|
3120
|
-
throw new Error(`Kiro API error: context_length_exceeded (local history ${size} chars / ${history.length} entries exceeds ${limit}-char limit)`);
|
|
3121
|
-
}
|
|
3340
|
+
function syntheticFailedToolResult(toolUseId) {
|
|
3341
|
+
return { toolUseId, content: [{ text: SYNTHETIC_FAILED_TOOL_RESULT_TEXT }], status: "error" };
|
|
3122
3342
|
}
|
|
3123
|
-
function
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3343
|
+
function syntheticToolResultEntry(toolUseIds, modelId) {
|
|
3344
|
+
return {
|
|
3345
|
+
userInputMessage: {
|
|
3346
|
+
// Empty by design: `toolResults` is the payload. Matches kiro-agent's
|
|
3347
|
+
// `FAILED_TOOL_USE_MESSAGE`, which also ships `content: ''`.
|
|
3348
|
+
content: "",
|
|
3349
|
+
modelId,
|
|
3350
|
+
origin: "KIRO_CLI",
|
|
3351
|
+
userInputMessageContext: { toolResults: toolUseIds.map(syntheticFailedToolResult) }
|
|
3129
3352
|
}
|
|
3130
|
-
}
|
|
3131
|
-
return names;
|
|
3132
|
-
}
|
|
3133
|
-
function addPlaceholderTools(tools, history) {
|
|
3134
|
-
const historyNames = extractToolNamesFromHistory(history);
|
|
3135
|
-
if (historyNames.size === 0)
|
|
3136
|
-
return tools;
|
|
3137
|
-
const existing = new Set(tools.map((t) => t.toolSpecification?.name).filter(Boolean));
|
|
3138
|
-
const missing = Array.from(historyNames).filter((n) => !existing.has(n));
|
|
3139
|
-
if (missing.length === 0)
|
|
3140
|
-
return tools;
|
|
3141
|
-
return [
|
|
3142
|
-
...tools,
|
|
3143
|
-
...missing.map((name) => ({
|
|
3144
|
-
toolSpecification: {
|
|
3145
|
-
name,
|
|
3146
|
-
description: "Tool",
|
|
3147
|
-
inputSchema: { json: { type: "object", properties: {} } }
|
|
3148
|
-
}
|
|
3149
|
-
}))
|
|
3150
|
-
];
|
|
3353
|
+
};
|
|
3151
3354
|
}
|
|
3152
3355
|
|
|
3153
3356
|
// ../kiro-core/dist/truncation.js
|
|
@@ -3288,43 +3491,143 @@ ${currentContent}`;
|
|
|
3288
3491
|
wireContent = currentContent || EMPTY_CONTENT_PLACEHOLDER;
|
|
3289
3492
|
wireUimc = uimc?.tools?.length ? { tools: uimc.tools } : void 0;
|
|
3290
3493
|
}
|
|
3291
|
-
if (repair.remaining.length > 0) {
|
|
3292
|
-
const structural = repair.remaining.filter((e) => isKiroToolStructureRule(e.rule));
|
|
3293
|
-
if (structural.length > 0) {
|
|
3294
|
-
console.warn(`[kiro-core] outbound history still violates ${structural.map((e) => `${e.rule}@${e.index}`).join(", ")} after repair \u2014 Kiro may reject this request`);
|
|
3494
|
+
if (repair.remaining.length > 0) {
|
|
3495
|
+
const structural = repair.remaining.filter((e) => isKiroToolStructureRule(e.rule));
|
|
3496
|
+
if (structural.length > 0) {
|
|
3497
|
+
console.warn(`[kiro-core] outbound history still violates ${structural.map((e) => `${e.rule}@${e.index}`).join(", ")} after repair \u2014 Kiro may reject this request`);
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
return {
|
|
3501
|
+
request: {
|
|
3502
|
+
conversationState: {
|
|
3503
|
+
chatTriggerType: "MANUAL",
|
|
3504
|
+
agentTaskType: "vibe",
|
|
3505
|
+
conversationId,
|
|
3506
|
+
currentMessage: {
|
|
3507
|
+
userInputMessage: {
|
|
3508
|
+
content: sanitizeSurrogates(wireContent),
|
|
3509
|
+
modelId: kiroModelId,
|
|
3510
|
+
origin: "KIRO_CLI",
|
|
3511
|
+
...currentImages ? { images: currentImages } : {},
|
|
3512
|
+
...wireUimc ? { userInputMessageContext: wireUimc } : {}
|
|
3513
|
+
}
|
|
3514
|
+
},
|
|
3515
|
+
...wireHistory.length > 0 ? { history: wireHistory } : {}
|
|
3516
|
+
},
|
|
3517
|
+
...params.additionalModelRequestFields ? { additionalModelRequestFields: params.additionalModelRequestFields } : {},
|
|
3518
|
+
profileArn,
|
|
3519
|
+
agentMode: "vibe"
|
|
3520
|
+
},
|
|
3521
|
+
wireHistoryLength: wireHistory.length,
|
|
3522
|
+
wireContentLength: wireContent.length,
|
|
3523
|
+
hasImages: !!currentImages,
|
|
3524
|
+
toolResultCount: wireUimc?.toolResults?.length ?? 0
|
|
3525
|
+
};
|
|
3526
|
+
}
|
|
3527
|
+
|
|
3528
|
+
// ../kiro-core/dist/response-assembler.js
|
|
3529
|
+
init_debug();
|
|
3530
|
+
|
|
3531
|
+
// ../kiro-core/dist/invoke-tool-parser.js
|
|
3532
|
+
var INVOKE_OPEN_ANCHORED = /^<invoke name="([\w-]+)">/;
|
|
3533
|
+
var INVOKE_OPEN_SEARCH = "<invoke name=";
|
|
3534
|
+
var INVOKE_OPEN_ANYWHERE = /<invoke name="[\w-]+">/;
|
|
3535
|
+
var PARAM_OPEN_ANCHORED = /^<parameter name="([^"]*)">/;
|
|
3536
|
+
var INVOKE_CLOSE = "</invoke>";
|
|
3537
|
+
var PARAM_CLOSE = "</parameter>";
|
|
3538
|
+
var FENCE = "```";
|
|
3539
|
+
function fencedRanges(text) {
|
|
3540
|
+
const ranges = [];
|
|
3541
|
+
let searchFrom = 0;
|
|
3542
|
+
while (true) {
|
|
3543
|
+
const open = text.indexOf(FENCE, searchFrom);
|
|
3544
|
+
if (open < 0)
|
|
3545
|
+
break;
|
|
3546
|
+
const close = text.indexOf(FENCE, open + FENCE.length);
|
|
3547
|
+
if (close < 0) {
|
|
3548
|
+
ranges.push({ start: open, end: text.length });
|
|
3549
|
+
break;
|
|
3550
|
+
}
|
|
3551
|
+
ranges.push({ start: open, end: close + FENCE.length });
|
|
3552
|
+
searchFrom = close + FENCE.length;
|
|
3553
|
+
}
|
|
3554
|
+
return ranges;
|
|
3555
|
+
}
|
|
3556
|
+
var AmbiguousDialectError = class extends Error {
|
|
3557
|
+
};
|
|
3558
|
+
function parseBlockAt(text, start) {
|
|
3559
|
+
const openMatch = INVOKE_OPEN_ANCHORED.exec(text.substring(start));
|
|
3560
|
+
if (!openMatch)
|
|
3561
|
+
return null;
|
|
3562
|
+
const args = {};
|
|
3563
|
+
let cursor = start + openMatch[0].length;
|
|
3564
|
+
while (true) {
|
|
3565
|
+
const remainder = text.substring(cursor);
|
|
3566
|
+
const leadingWhitespace = remainder.length - remainder.trimStart().length;
|
|
3567
|
+
if (leadingWhitespace > 0)
|
|
3568
|
+
cursor += leadingWhitespace;
|
|
3569
|
+
if (text.startsWith(INVOKE_CLOSE, cursor)) {
|
|
3570
|
+
const end = cursor + INVOKE_CLOSE.length;
|
|
3571
|
+
if (end < text.length && !/\s/.test(text[end]))
|
|
3572
|
+
return null;
|
|
3573
|
+
return { name: openMatch[1], arguments: args, end };
|
|
3574
|
+
}
|
|
3575
|
+
const paramMatch = PARAM_OPEN_ANCHORED.exec(text.substring(cursor));
|
|
3576
|
+
if (!paramMatch)
|
|
3577
|
+
return null;
|
|
3578
|
+
const valueStart = cursor + paramMatch[0].length;
|
|
3579
|
+
const valueEnd = text.indexOf(PARAM_CLOSE, valueStart);
|
|
3580
|
+
if (valueEnd < 0)
|
|
3581
|
+
return null;
|
|
3582
|
+
const value = text.substring(valueStart, valueEnd);
|
|
3583
|
+
if (INVOKE_OPEN_ANYWHERE.test(value))
|
|
3584
|
+
throw new AmbiguousDialectError();
|
|
3585
|
+
args[paramMatch[1]] = value;
|
|
3586
|
+
cursor = valueEnd + PARAM_CLOSE.length;
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
3589
|
+
function parseInvokeToolCalls(text) {
|
|
3590
|
+
const toolCalls = [];
|
|
3591
|
+
const removals = [];
|
|
3592
|
+
const fences = fencedRanges(text);
|
|
3593
|
+
const untouched = { toolCalls: [], cleanedText: text };
|
|
3594
|
+
let cursor = 0;
|
|
3595
|
+
while (cursor < text.length) {
|
|
3596
|
+
const openStart = text.indexOf(INVOKE_OPEN_SEARCH, cursor);
|
|
3597
|
+
if (openStart < 0)
|
|
3598
|
+
break;
|
|
3599
|
+
const containingFence = fences.find((range) => openStart >= range.start && openStart < range.end);
|
|
3600
|
+
if (containingFence) {
|
|
3601
|
+
cursor = containingFence.end;
|
|
3602
|
+
continue;
|
|
3603
|
+
}
|
|
3604
|
+
let block;
|
|
3605
|
+
try {
|
|
3606
|
+
block = parseBlockAt(text, openStart);
|
|
3607
|
+
} catch (e) {
|
|
3608
|
+
if (e instanceof AmbiguousDialectError)
|
|
3609
|
+
return untouched;
|
|
3610
|
+
throw e;
|
|
3295
3611
|
}
|
|
3612
|
+
if (block === null)
|
|
3613
|
+
return untouched;
|
|
3614
|
+
const nextOpen = text.indexOf(INVOKE_OPEN_SEARCH, block.end);
|
|
3615
|
+
const interstitialEnd = nextOpen < 0 ? text.length : nextOpen;
|
|
3616
|
+
const interstitial = text.substring(block.end, interstitialEnd);
|
|
3617
|
+
if (interstitial.includes(PARAM_CLOSE) || interstitial.includes(INVOKE_CLOSE))
|
|
3618
|
+
return untouched;
|
|
3619
|
+
toolCalls.push({ toolUseId: crypto.randomUUID(), name: block.name, arguments: block.arguments });
|
|
3620
|
+
removals.push({ start: openStart, end: block.end });
|
|
3621
|
+
cursor = block.end;
|
|
3296
3622
|
}
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
currentMessage: {
|
|
3304
|
-
userInputMessage: {
|
|
3305
|
-
content: sanitizeSurrogates(wireContent),
|
|
3306
|
-
modelId: kiroModelId,
|
|
3307
|
-
origin: "KIRO_CLI",
|
|
3308
|
-
...currentImages ? { images: currentImages } : {},
|
|
3309
|
-
...wireUimc ? { userInputMessageContext: wireUimc } : {}
|
|
3310
|
-
}
|
|
3311
|
-
},
|
|
3312
|
-
...wireHistory.length > 0 ? { history: wireHistory } : {}
|
|
3313
|
-
},
|
|
3314
|
-
...params.additionalModelRequestFields ? { additionalModelRequestFields: params.additionalModelRequestFields } : {},
|
|
3315
|
-
profileArn,
|
|
3316
|
-
agentMode: "vibe"
|
|
3317
|
-
},
|
|
3318
|
-
wireHistoryLength: wireHistory.length,
|
|
3319
|
-
wireContentLength: wireContent.length,
|
|
3320
|
-
hasImages: !!currentImages,
|
|
3321
|
-
toolResultCount: wireUimc?.toolResults?.length ?? 0
|
|
3322
|
-
};
|
|
3623
|
+
let cleanedText = text;
|
|
3624
|
+
for (let i = removals.length - 1; i >= 0; i--) {
|
|
3625
|
+
const { start, end } = removals[i];
|
|
3626
|
+
cleanedText = cleanedText.substring(0, start) + cleanedText.substring(end);
|
|
3627
|
+
}
|
|
3628
|
+
return { toolCalls, cleanedText };
|
|
3323
3629
|
}
|
|
3324
3630
|
|
|
3325
|
-
// ../kiro-core/dist/response-assembler.js
|
|
3326
|
-
init_debug();
|
|
3327
|
-
|
|
3328
3631
|
// ../kiro-core/dist/thinking-parser.js
|
|
3329
3632
|
var THINKING_END_TAG = "</thinking>";
|
|
3330
3633
|
var THINKING_TAG_VARIANTS = [
|
|
@@ -4823,65 +5126,272 @@ function getChunkedStream(source) {
|
|
|
4823
5126
|
[Symbol.asyncIterator]: iterator
|
|
4824
5127
|
};
|
|
4825
5128
|
}
|
|
4826
|
-
|
|
4827
|
-
// ../../node_modules/.pnpm/@smithy+core@3.34.1/node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde-universal/getUnmarshalledStream.js
|
|
4828
|
-
function getMessageUnmarshaller(deserializer, toUtf82) {
|
|
4829
|
-
return async function(message) {
|
|
4830
|
-
const { value: messageType } = message.headers[":message-type"];
|
|
4831
|
-
if (messageType === "error") {
|
|
4832
|
-
const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError");
|
|
4833
|
-
unmodeledError.name = message.headers[":error-code"].value;
|
|
4834
|
-
throw unmodeledError;
|
|
4835
|
-
} else if (messageType === "exception") {
|
|
4836
|
-
const code = message.headers[":exception-type"].value;
|
|
4837
|
-
const exception = { [code]: message };
|
|
4838
|
-
const deserializedException = await deserializer(exception);
|
|
4839
|
-
if (deserializedException.$unknown) {
|
|
4840
|
-
const error2 = new Error(toUtf82(message.body));
|
|
4841
|
-
error2.name = code;
|
|
4842
|
-
throw error2;
|
|
4843
|
-
}
|
|
4844
|
-
throw deserializedException[code];
|
|
4845
|
-
} else if (messageType === "event") {
|
|
4846
|
-
const event = {
|
|
4847
|
-
[message.headers[":event-type"].value]: message
|
|
5129
|
+
|
|
5130
|
+
// ../../node_modules/.pnpm/@smithy+core@3.34.1/node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde-universal/getUnmarshalledStream.js
|
|
5131
|
+
function getMessageUnmarshaller(deserializer, toUtf82) {
|
|
5132
|
+
return async function(message) {
|
|
5133
|
+
const { value: messageType } = message.headers[":message-type"];
|
|
5134
|
+
if (messageType === "error") {
|
|
5135
|
+
const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError");
|
|
5136
|
+
unmodeledError.name = message.headers[":error-code"].value;
|
|
5137
|
+
throw unmodeledError;
|
|
5138
|
+
} else if (messageType === "exception") {
|
|
5139
|
+
const code = message.headers[":exception-type"].value;
|
|
5140
|
+
const exception = { [code]: message };
|
|
5141
|
+
const deserializedException = await deserializer(exception);
|
|
5142
|
+
if (deserializedException.$unknown) {
|
|
5143
|
+
const error2 = new Error(toUtf82(message.body));
|
|
5144
|
+
error2.name = code;
|
|
5145
|
+
throw error2;
|
|
5146
|
+
}
|
|
5147
|
+
throw deserializedException[code];
|
|
5148
|
+
} else if (messageType === "event") {
|
|
5149
|
+
const event = {
|
|
5150
|
+
[message.headers[":event-type"].value]: message
|
|
5151
|
+
};
|
|
5152
|
+
const deserialized = await deserializer(event);
|
|
5153
|
+
if (deserialized.$unknown)
|
|
5154
|
+
return;
|
|
5155
|
+
return deserialized;
|
|
5156
|
+
} else {
|
|
5157
|
+
throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`);
|
|
5158
|
+
}
|
|
5159
|
+
};
|
|
5160
|
+
}
|
|
5161
|
+
|
|
5162
|
+
// ../../node_modules/.pnpm/@smithy+core@3.34.1/node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde-universal/EventStreamMarshaller.js
|
|
5163
|
+
var EventStreamMarshaller = class {
|
|
5164
|
+
eventStreamCodec;
|
|
5165
|
+
utfEncoder;
|
|
5166
|
+
constructor({ utf8Encoder, utf8Decoder }) {
|
|
5167
|
+
this.eventStreamCodec = new EventStreamCodec(utf8Encoder, utf8Decoder);
|
|
5168
|
+
this.utfEncoder = utf8Encoder;
|
|
5169
|
+
}
|
|
5170
|
+
deserialize(body, deserializer) {
|
|
5171
|
+
const inputStream = getChunkedStream(body);
|
|
5172
|
+
return new SmithyMessageDecoderStream({
|
|
5173
|
+
messageStream: new MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }),
|
|
5174
|
+
deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder)
|
|
5175
|
+
});
|
|
5176
|
+
}
|
|
5177
|
+
serialize(inputStream, serializer) {
|
|
5178
|
+
return new MessageEncoderStream({
|
|
5179
|
+
messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }),
|
|
5180
|
+
encoder: this.eventStreamCodec,
|
|
5181
|
+
includeEndFrame: true
|
|
5182
|
+
});
|
|
5183
|
+
}
|
|
5184
|
+
};
|
|
5185
|
+
|
|
5186
|
+
// ../kiro-core/dist/response-stream.js
|
|
5187
|
+
init_debug();
|
|
5188
|
+
|
|
5189
|
+
// ../kiro-core/dist/event-parser.js
|
|
5190
|
+
var KIRO_EVENT_KEYS = [
|
|
5191
|
+
"assistantResponseEvent",
|
|
5192
|
+
"codeReferenceEvent",
|
|
5193
|
+
"contextUsageEvent",
|
|
5194
|
+
"documentCitationEvent",
|
|
5195
|
+
"error",
|
|
5196
|
+
"metadataEvent",
|
|
5197
|
+
"meteringEvent",
|
|
5198
|
+
"reasoningContentEvent",
|
|
5199
|
+
"serviceUnavailableError",
|
|
5200
|
+
"throttlingError",
|
|
5201
|
+
"toolResultEvent",
|
|
5202
|
+
"toolUseEvent",
|
|
5203
|
+
"validationError"
|
|
5204
|
+
];
|
|
5205
|
+
var KIRO_EVENT_KEY_SET = new Set(KIRO_EVENT_KEYS);
|
|
5206
|
+
var KIRO_ERROR_MEMBERS = {
|
|
5207
|
+
error: { kind: "internalServer", exception: "InternalServerException" },
|
|
5208
|
+
throttlingError: { kind: "throttling", exception: "ThrottlingException" },
|
|
5209
|
+
validationError: { kind: "validation", exception: "ValidationException" },
|
|
5210
|
+
serviceUnavailableError: { kind: "serviceUnavailable", exception: "ServiceUnavailableException" }
|
|
5211
|
+
};
|
|
5212
|
+
var KIRO_ERROR_TOKENS = {
|
|
5213
|
+
...KIRO_ERROR_MEMBERS,
|
|
5214
|
+
InternalServerException: KIRO_ERROR_MEMBERS.error,
|
|
5215
|
+
ThrottlingException: KIRO_ERROR_MEMBERS.throttlingError,
|
|
5216
|
+
ValidationException: KIRO_ERROR_MEMBERS.validationError,
|
|
5217
|
+
ServiceUnavailableException: KIRO_ERROR_MEMBERS.serviceUnavailableError
|
|
5218
|
+
};
|
|
5219
|
+
function lookupKiroErrorMember(key) {
|
|
5220
|
+
return Object.hasOwn(KIRO_ERROR_TOKENS, key) ? KIRO_ERROR_TOKENS[key] : void 0;
|
|
5221
|
+
}
|
|
5222
|
+
var num = (v) => typeof v === "number" ? v : void 0;
|
|
5223
|
+
var str = (v) => typeof v === "string" ? v : void 0;
|
|
5224
|
+
function tokenCount(value) {
|
|
5225
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
5226
|
+
}
|
|
5227
|
+
function firstTokenCount(source, keys) {
|
|
5228
|
+
for (const key of keys) {
|
|
5229
|
+
const count = tokenCount(source[key]);
|
|
5230
|
+
if (count !== void 0)
|
|
5231
|
+
return count;
|
|
5232
|
+
}
|
|
5233
|
+
return void 0;
|
|
5234
|
+
}
|
|
5235
|
+
var CACHE_READ_KEYS = ["cacheReadInputTokens", "cache_read_input_tokens", "cacheReadTokens"];
|
|
5236
|
+
var CACHE_WRITE_KEYS = [
|
|
5237
|
+
"cacheWriteInputTokens",
|
|
5238
|
+
"cache_creation_input_tokens",
|
|
5239
|
+
"cacheCreationInputTokens",
|
|
5240
|
+
"cacheWriteTokens"
|
|
5241
|
+
];
|
|
5242
|
+
function toolInput(raw) {
|
|
5243
|
+
if (typeof raw === "string")
|
|
5244
|
+
return raw;
|
|
5245
|
+
if (raw && typeof raw === "object" && Object.keys(raw).length > 0) {
|
|
5246
|
+
return JSON.stringify(raw);
|
|
5247
|
+
}
|
|
5248
|
+
return "";
|
|
5249
|
+
}
|
|
5250
|
+
function parseToolUse(parsed) {
|
|
5251
|
+
if (parsed.name && parsed.toolUseId) {
|
|
5252
|
+
return {
|
|
5253
|
+
type: "toolUse",
|
|
5254
|
+
data: {
|
|
5255
|
+
name: parsed.name,
|
|
5256
|
+
toolUseId: parsed.toolUseId,
|
|
5257
|
+
input: toolInput(parsed.input),
|
|
5258
|
+
stop: parsed.stop
|
|
5259
|
+
}
|
|
5260
|
+
};
|
|
5261
|
+
}
|
|
5262
|
+
if (parsed.input !== void 0) {
|
|
5263
|
+
return { type: "toolUseInput", data: { input: toolInput(parsed.input) } };
|
|
5264
|
+
}
|
|
5265
|
+
if (parsed.stop !== void 0)
|
|
5266
|
+
return { type: "toolUseStop", data: { stop: parsed.stop } };
|
|
5267
|
+
return null;
|
|
5268
|
+
}
|
|
5269
|
+
function parseMetadata(parsed) {
|
|
5270
|
+
const tu = parsed.tokenUsage ?? {};
|
|
5271
|
+
const data = {
|
|
5272
|
+
inputTokens: tokenCount(tu.uncachedInputTokens) ?? tokenCount(tu.inputTokens),
|
|
5273
|
+
outputTokens: tokenCount(tu.outputTokens),
|
|
5274
|
+
totalTokens: tokenCount(tu.totalTokens),
|
|
5275
|
+
cacheReadInputTokens: firstTokenCount(tu, CACHE_READ_KEYS),
|
|
5276
|
+
cacheWriteInputTokens: firstTokenCount(tu, CACHE_WRITE_KEYS),
|
|
5277
|
+
contextUsagePercentage: num(tu.contextUsagePercentage),
|
|
5278
|
+
normalizedTokenUsage: num(tu.normalizedTokenUsage),
|
|
5279
|
+
rawStopReason: str(parsed.stopReason),
|
|
5280
|
+
stopDetails: parsed.stopDetails && typeof parsed.stopDetails === "object" ? parsed.stopDetails : void 0
|
|
5281
|
+
};
|
|
5282
|
+
for (const k of Object.keys(data)) {
|
|
5283
|
+
if (data[k] === void 0)
|
|
5284
|
+
delete data[k];
|
|
5285
|
+
}
|
|
5286
|
+
return Object.keys(data).length > 0 ? { type: "usage", data } : null;
|
|
5287
|
+
}
|
|
5288
|
+
function parseError(parsed, kind, fallbackName) {
|
|
5289
|
+
const rawError = parsed.error ?? parsed.Error;
|
|
5290
|
+
const error2 = typeof rawError === "string" ? rawError : rawError !== void 0 ? JSON.stringify(rawError) : str(parsed.name) ?? fallbackName;
|
|
5291
|
+
const message = parsed.message ?? parsed.Message ?? parsed.reason;
|
|
5292
|
+
const data = { error: error2, kind };
|
|
5293
|
+
if (typeof message === "string")
|
|
5294
|
+
data.message = message;
|
|
5295
|
+
const reason = str(parsed.reason);
|
|
5296
|
+
if (reason !== void 0)
|
|
5297
|
+
data.reason = reason;
|
|
5298
|
+
const retryAfterMilliseconds = num(parsed.retryAfterMilliseconds);
|
|
5299
|
+
if (retryAfterMilliseconds !== void 0)
|
|
5300
|
+
data.retryAfterMilliseconds = retryAfterMilliseconds;
|
|
5301
|
+
return { type: "error", data };
|
|
5302
|
+
}
|
|
5303
|
+
function parseKiroEvent(key, parsed) {
|
|
5304
|
+
switch (key) {
|
|
5305
|
+
case "assistantResponseEvent": {
|
|
5306
|
+
const content = str(parsed.content);
|
|
5307
|
+
return content !== void 0 ? { type: "content", data: content } : null;
|
|
5308
|
+
}
|
|
5309
|
+
case "reasoningContentEvent": {
|
|
5310
|
+
const text = str(parsed.text);
|
|
5311
|
+
if (text !== void 0)
|
|
5312
|
+
return { type: "thinkingText", data: text };
|
|
5313
|
+
const signature = str(parsed.signature);
|
|
5314
|
+
if (signature !== void 0)
|
|
5315
|
+
return { type: "thinkingSignature", data: signature };
|
|
5316
|
+
return { type: "ignored", data: { key } };
|
|
5317
|
+
}
|
|
5318
|
+
case "toolUseEvent":
|
|
5319
|
+
return parseToolUse(parsed);
|
|
5320
|
+
case "contextUsageEvent": {
|
|
5321
|
+
const pct = num(parsed.contextUsagePercentage);
|
|
5322
|
+
return pct !== void 0 ? { type: "contextUsage", data: { contextUsagePercentage: pct } } : null;
|
|
5323
|
+
}
|
|
5324
|
+
case "metadataEvent":
|
|
5325
|
+
return parseMetadata(parsed);
|
|
5326
|
+
case "meteringEvent":
|
|
5327
|
+
return {
|
|
5328
|
+
type: "metering",
|
|
5329
|
+
data: { credits: tokenCount(parsed.usage), unit: str(parsed.unit), unitPlural: str(parsed.unitPlural) }
|
|
4848
5330
|
};
|
|
4849
|
-
|
|
4850
|
-
|
|
4851
|
-
|
|
4852
|
-
|
|
4853
|
-
|
|
4854
|
-
|
|
5331
|
+
// Reachable when a member that models an exception is delivered as an
|
|
5332
|
+
// ordinary event frame. The real wire uses exception framing, handled by
|
|
5333
|
+
// parseKiroExceptionFrame, but both routes must agree.
|
|
5334
|
+
case "error":
|
|
5335
|
+
case "throttlingError":
|
|
5336
|
+
case "validationError":
|
|
5337
|
+
case "serviceUnavailableError": {
|
|
5338
|
+
const member = lookupKiroErrorMember(key);
|
|
5339
|
+
return parseError(parsed, member.kind, member.exception);
|
|
4855
5340
|
}
|
|
4856
|
-
|
|
5341
|
+
// Known members with no consumer yet: explicitly ignored, not unparseable.
|
|
5342
|
+
case "codeReferenceEvent":
|
|
5343
|
+
case "documentCitationEvent":
|
|
5344
|
+
case "toolResultEvent":
|
|
5345
|
+
return { type: "ignored", data: { key } };
|
|
5346
|
+
default: {
|
|
5347
|
+
const member = lookupKiroErrorMember(key);
|
|
5348
|
+
if (member)
|
|
5349
|
+
return parseError(parsed, member.kind, member.exception);
|
|
5350
|
+
return parseKiroEventByShape(parsed);
|
|
5351
|
+
}
|
|
5352
|
+
}
|
|
4857
5353
|
}
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
5354
|
+
function parseKiroExceptionFrame(key, parsed) {
|
|
5355
|
+
const member = lookupKiroErrorMember(key);
|
|
5356
|
+
if (!member)
|
|
5357
|
+
return null;
|
|
5358
|
+
const event = parseError(parsed, member.kind, member.exception);
|
|
5359
|
+
return event.data;
|
|
5360
|
+
}
|
|
5361
|
+
function parseKiroEventByShape(parsed) {
|
|
5362
|
+
if (parsed.content !== void 0)
|
|
5363
|
+
return { type: "content", data: parsed.content };
|
|
5364
|
+
if (typeof parsed.text === "string")
|
|
5365
|
+
return { type: "thinkingText", data: parsed.text };
|
|
5366
|
+
if (typeof parsed.signature === "string")
|
|
5367
|
+
return { type: "thinkingSignature", data: parsed.signature };
|
|
5368
|
+
if (parsed.name && parsed.toolUseId)
|
|
5369
|
+
return parseToolUse(parsed);
|
|
5370
|
+
if (parsed.input !== void 0 && !parsed.name) {
|
|
5371
|
+
return { type: "toolUseInput", data: { input: toolInput(parsed.input) } };
|
|
4866
5372
|
}
|
|
4867
|
-
|
|
4868
|
-
|
|
4869
|
-
|
|
4870
|
-
|
|
4871
|
-
|
|
4872
|
-
}
|
|
5373
|
+
if (parsed.stop !== void 0 && parsed.contextUsagePercentage === void 0)
|
|
5374
|
+
return { type: "toolUseStop", data: { stop: parsed.stop } };
|
|
5375
|
+
if (parsed.contextUsagePercentage !== void 0)
|
|
5376
|
+
return { type: "contextUsage", data: { contextUsagePercentage: parsed.contextUsagePercentage } };
|
|
5377
|
+
if (parsed.followupPrompt !== void 0)
|
|
5378
|
+
return { type: "followupPrompt", data: parsed.followupPrompt };
|
|
5379
|
+
if (parsed.tokenUsage !== void 0 || parsed.stopReason !== void 0 || parsed.stopDetails !== void 0) {
|
|
5380
|
+
return parseMetadata(parsed);
|
|
4873
5381
|
}
|
|
4874
|
-
|
|
4875
|
-
return
|
|
4876
|
-
messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }),
|
|
4877
|
-
encoder: this.eventStreamCodec,
|
|
4878
|
-
includeEndFrame: true
|
|
4879
|
-
});
|
|
5382
|
+
if (parsed.error !== void 0 || parsed.Error !== void 0) {
|
|
5383
|
+
return parseError(parsed, "unknown", "unknown");
|
|
4880
5384
|
}
|
|
4881
|
-
|
|
5385
|
+
if (typeof parsed.usage === "number") {
|
|
5386
|
+
return {
|
|
5387
|
+
type: "metering",
|
|
5388
|
+
data: { credits: tokenCount(parsed.usage), unit: str(parsed.unit), unitPlural: str(parsed.unitPlural) }
|
|
5389
|
+
};
|
|
5390
|
+
}
|
|
5391
|
+
return null;
|
|
5392
|
+
}
|
|
4882
5393
|
|
|
4883
5394
|
// ../kiro-core/dist/response-stream.js
|
|
4884
|
-
init_debug();
|
|
4885
5395
|
var IDLE_TIMEOUT = 3e5;
|
|
4886
5396
|
var eventStreamMarshaller = new EventStreamMarshaller({
|
|
4887
5397
|
utf8Encoder: (input) => new TextDecoder().decode(input),
|
|
@@ -5036,22 +5546,15 @@ function readKiroEventStream(body, options) {
|
|
|
5036
5546
|
}
|
|
5037
5547
|
|
|
5038
5548
|
// ../kiro-core/dist/stream.js
|
|
5039
|
-
|
|
5040
|
-
init_debug();
|
|
5041
|
-
init_effort();
|
|
5042
|
-
init_endpoints();
|
|
5043
|
-
init_kiro_cli();
|
|
5044
|
-
init_management();
|
|
5045
|
-
init_models();
|
|
5046
|
-
init_oauth();
|
|
5549
|
+
init_retry();
|
|
5047
5550
|
init_token_type();
|
|
5048
5551
|
|
|
5049
5552
|
// ../kiro-core/dist/transport.js
|
|
5050
5553
|
import { appendFile, mkdir } from "node:fs/promises";
|
|
5051
5554
|
import { homedir as homedir5 } from "node:os";
|
|
5052
|
-
import { join as
|
|
5053
|
-
var CAPACITY_LOG_DIR =
|
|
5054
|
-
var CAPACITY_LOG_FILE =
|
|
5555
|
+
import { join as join6 } from "node:path";
|
|
5556
|
+
var CAPACITY_LOG_DIR = join6(homedir5(), ".ns-kiro-provider", "logs");
|
|
5557
|
+
var CAPACITY_LOG_FILE = join6(CAPACITY_LOG_DIR, "capacity-retries.log");
|
|
5055
5558
|
var capacityLogDirCreated = false;
|
|
5056
5559
|
function logCapacityEvent(message) {
|
|
5057
5560
|
(async () => {
|
|
@@ -5169,6 +5672,9 @@ function describeReturnedContent(kinds) {
|
|
|
5169
5672
|
}
|
|
5170
5673
|
var skipProfileResolutionForTests = false;
|
|
5171
5674
|
var TEST_PROFILE_ARN = "arn:aws:codewhisperer:us-east-1:000000000000:profile/test";
|
|
5675
|
+
function testProfileArnOverride() {
|
|
5676
|
+
return skipProfileResolutionForTests ? TEST_PROFILE_ARN : void 0;
|
|
5677
|
+
}
|
|
5172
5678
|
function throwOnTerminalWireStop(wireStopReason, stopDetails) {
|
|
5173
5679
|
switch (wireStopReason) {
|
|
5174
5680
|
case "MODEL_CONTEXT_WINDOW_EXCEEDED":
|
|
@@ -5180,6 +5686,9 @@ function throwOnTerminalWireStop(wireStopReason, stopDetails) {
|
|
|
5180
5686
|
}
|
|
5181
5687
|
}
|
|
5182
5688
|
async function* streamKiro(request) {
|
|
5689
|
+
yield* streamKiroOnEngine(request, streamKiroInProcess);
|
|
5690
|
+
}
|
|
5691
|
+
async function* streamKiroInProcess(request) {
|
|
5183
5692
|
const { model, signal } = request;
|
|
5184
5693
|
const initialAccessToken = request.accessToken;
|
|
5185
5694
|
if (!initialAccessToken) {
|
|
@@ -5478,7 +5987,167 @@ ${systemPrompt}` : ""}`;
|
|
|
5478
5987
|
}
|
|
5479
5988
|
}
|
|
5480
5989
|
|
|
5990
|
+
// ../kiro-core/dist/engine.js
|
|
5991
|
+
var KIRO_SIDECAR_VENDOR = "kiro";
|
|
5992
|
+
function selectKiroEngine() {
|
|
5993
|
+
return selectBridgeEngine(KIRO_SIDECAR_VENDOR);
|
|
5994
|
+
}
|
|
5995
|
+
function toKiroSidecarRequest(request, conversationId) {
|
|
5996
|
+
const { signal: _signal, ...wire } = request;
|
|
5997
|
+
const kiroModelId = resolveKiroModel(request.model.id, request.model.kiroModelId);
|
|
5998
|
+
const testProfileArn = testProfileArnOverride();
|
|
5999
|
+
return {
|
|
6000
|
+
...wire,
|
|
6001
|
+
model: { ...request.model, kiroModelId },
|
|
6002
|
+
conversationId,
|
|
6003
|
+
profileArnCache: snapshotKiroProfileArnCache(),
|
|
6004
|
+
timeouts: {
|
|
6005
|
+
firstTokenMs: request.model.firstTokenTimeout ?? firstTokenTimeoutForModel(request.model.id),
|
|
6006
|
+
requestHeaderMs: retryConfig.requestHeaderTimeoutMs
|
|
6007
|
+
},
|
|
6008
|
+
capacityRetry: { ...capacityRetryConfig },
|
|
6009
|
+
...testProfileArn ? { testProfileArn } : {}
|
|
6010
|
+
};
|
|
6011
|
+
}
|
|
6012
|
+
async function* postProcess(events, request, conversationId) {
|
|
6013
|
+
let pendingUsage;
|
|
6014
|
+
for await (const event of events) {
|
|
6015
|
+
if (event.type === "usage") {
|
|
6016
|
+
pendingUsage = event;
|
|
6017
|
+
continue;
|
|
6018
|
+
}
|
|
6019
|
+
if (event.type !== "done") {
|
|
6020
|
+
yield event;
|
|
6021
|
+
continue;
|
|
6022
|
+
}
|
|
6023
|
+
const { kiroProfileArns, kiroRuntimeRegion, kiroProfileArn, ...done } = event;
|
|
6024
|
+
applyKiroProfileArnCacheChanges(kiroProfileArns);
|
|
6025
|
+
const region = kiroRuntimeRegion ?? getKiroRegionFromProfileArn(kiroProfileArn) ?? request.model.region;
|
|
6026
|
+
if (!process.env.VITEST && region && kiroProfileArn && isCacheStale(region)) {
|
|
6027
|
+
updateKiroModelsCache(request.accessToken, region, kiroProfileArn).catch((error2) => {
|
|
6028
|
+
console.warn(`[kiro-core] Failed to refresh Kiro model catalog in ${region}: ${formatSafeError(error2)}`);
|
|
6029
|
+
});
|
|
6030
|
+
}
|
|
6031
|
+
if (pendingUsage) {
|
|
6032
|
+
const { kiroWireCache, ...usageEvent } = pendingUsage;
|
|
6033
|
+
if (!done.errorMessage) {
|
|
6034
|
+
const estimatedRead = applyCacheEstimate(conversationId, usageEvent.usage, kiroWireCache ? { cacheReadInputTokens: 0 } : null, request.usageTracking ?? KIRO_USAGE_TRACKING_DISABLED);
|
|
6035
|
+
if (estimatedRead > 0) {
|
|
6036
|
+
debugLog("usage.estimate", {
|
|
6037
|
+
conversationId,
|
|
6038
|
+
estimatedRead,
|
|
6039
|
+
input: usageEvent.usage.input,
|
|
6040
|
+
cacheRead: usageEvent.usage.cacheRead
|
|
6041
|
+
});
|
|
6042
|
+
}
|
|
6043
|
+
}
|
|
6044
|
+
pendingUsage = void 0;
|
|
6045
|
+
yield usageEvent;
|
|
6046
|
+
}
|
|
6047
|
+
yield done;
|
|
6048
|
+
}
|
|
6049
|
+
if (pendingUsage) {
|
|
6050
|
+
const { kiroWireCache: _wire, ...usageEvent } = pendingUsage;
|
|
6051
|
+
yield usageEvent;
|
|
6052
|
+
}
|
|
6053
|
+
}
|
|
6054
|
+
function streamKiroOnEngine(request, inProcess) {
|
|
6055
|
+
if (selectKiroEngine() === "ts" || !request.accessToken)
|
|
6056
|
+
return inProcess(request);
|
|
6057
|
+
const conversationId = request.sessionId ?? crypto.randomUUID();
|
|
6058
|
+
let sidecarRequest;
|
|
6059
|
+
try {
|
|
6060
|
+
sidecarRequest = toKiroSidecarRequest(request, conversationId);
|
|
6061
|
+
} catch {
|
|
6062
|
+
return inProcess(request);
|
|
6063
|
+
}
|
|
6064
|
+
return engineStream({
|
|
6065
|
+
vendor: KIRO_SIDECAR_VENDOR,
|
|
6066
|
+
request: () => sidecarRequest,
|
|
6067
|
+
inProcess: () => inProcess(request),
|
|
6068
|
+
mapError: kiroErrorFromSidecar,
|
|
6069
|
+
transform: (events) => postProcess(events, request, conversationId),
|
|
6070
|
+
...request.signal ? { signal: request.signal } : {}
|
|
6071
|
+
});
|
|
6072
|
+
}
|
|
6073
|
+
|
|
6074
|
+
// ../kiro-core/dist/index.js
|
|
6075
|
+
init_engine_ops();
|
|
6076
|
+
init_errors2();
|
|
6077
|
+
|
|
6078
|
+
// ../kiro-core/dist/host-auth.js
|
|
6079
|
+
init_endpoints();
|
|
6080
|
+
init_oauth();
|
|
6081
|
+
var KIRO_NO_SESSION_MESSAGE = "No Kiro session found. Sign in with `kiro-cli login` (Builder ID, IAM Identity Center, Google, or GitHub), then run /login kiro again \u2014 or paste a Kiro API key below.";
|
|
6082
|
+
async function loginKiroFromSession(callbacks) {
|
|
6083
|
+
callbacks.onProgress?.("Looking for an existing Kiro session\u2026");
|
|
6084
|
+
const existing = await resolveKiroCredentials();
|
|
6085
|
+
if (existing) {
|
|
6086
|
+
callbacks.onProgress?.(`Using the ${existing.authMethod} session from kiro-cli.`);
|
|
6087
|
+
return existing;
|
|
6088
|
+
}
|
|
6089
|
+
if (!callbacks.onPrompt)
|
|
6090
|
+
throw new Error(KIRO_NO_SESSION_MESSAGE);
|
|
6091
|
+
const apiKey = (await callbacks.onPrompt({
|
|
6092
|
+
message: KIRO_NO_SESSION_MESSAGE,
|
|
6093
|
+
placeholder: "ksk_\u2026",
|
|
6094
|
+
allowEmpty: true,
|
|
6095
|
+
secret: true
|
|
6096
|
+
})).trim();
|
|
6097
|
+
if (!apiKey)
|
|
6098
|
+
throw new Error(KIRO_NO_SESSION_MESSAGE);
|
|
6099
|
+
return loginKiroWithApiKey(apiKey, callbacks.onProgress);
|
|
6100
|
+
}
|
|
6101
|
+
async function resolveKiroRequestCredentials(hostKey) {
|
|
6102
|
+
const stored = await resolveKiroCredentials();
|
|
6103
|
+
const region = resolveApiRegion(stored?.region);
|
|
6104
|
+
if (hostKey && (isApiKey(hostKey) || hostKey === stored?.access)) {
|
|
6105
|
+
return { accessToken: hostKey, region, ...stored?.profileArn ? { profileArn: stored.profileArn } : {} };
|
|
6106
|
+
}
|
|
6107
|
+
if (stored) {
|
|
6108
|
+
return {
|
|
6109
|
+
accessToken: stored.access,
|
|
6110
|
+
region,
|
|
6111
|
+
...stored.profileArn ? { profileArn: stored.profileArn } : {}
|
|
6112
|
+
};
|
|
6113
|
+
}
|
|
6114
|
+
if (hostKey)
|
|
6115
|
+
return { accessToken: hostKey, region };
|
|
6116
|
+
throw new Error("Kiro credentials not set. Run `kiro-cli login`, or set KIRO_API_KEY to a `ksk_` API key.");
|
|
6117
|
+
}
|
|
6118
|
+
|
|
6119
|
+
// ../kiro-core/dist/host-model.js
|
|
6120
|
+
init_models();
|
|
6121
|
+
function toKiroModelForHost(model, region) {
|
|
6122
|
+
const known = getCachedModels(region).find((candidate) => candidate.id === model.id);
|
|
6123
|
+
return {
|
|
6124
|
+
...known ?? {
|
|
6125
|
+
id: model.id,
|
|
6126
|
+
// No fallback to `model.id`: that dash-spelled local id is not a valid
|
|
6127
|
+
// Kiro wire id. `""` is falsy, so `resolveKiroModel` runs its own
|
|
6128
|
+
// cache/bootstrap/dot-normalize resolution instead of being
|
|
6129
|
+
// short-circuited by a value that is really just `model.id` again.
|
|
6130
|
+
kiroModelId: model.kiroModelId ?? "",
|
|
6131
|
+
name: model.name,
|
|
6132
|
+
reasoning: model.reasoning,
|
|
6133
|
+
input: [...model.input],
|
|
6134
|
+
cost: { ...model.cost },
|
|
6135
|
+
contextWindow: model.contextWindow ?? 2e5,
|
|
6136
|
+
maxTokens: model.maxTokens ?? 8192
|
|
6137
|
+
},
|
|
6138
|
+
region,
|
|
6139
|
+
...model.kiroProfileArn ? { profileArn: model.kiroProfileArn } : {},
|
|
6140
|
+
...model.additionalModelRequestFieldsSchema ? { additionalModelRequestFieldsSchema: model.additionalModelRequestFieldsSchema } : {}
|
|
6141
|
+
};
|
|
6142
|
+
}
|
|
6143
|
+
|
|
5481
6144
|
// ../kiro-core/dist/index.js
|
|
6145
|
+
init_kiro_cli();
|
|
6146
|
+
init_kiro_ide();
|
|
6147
|
+
init_management();
|
|
6148
|
+
init_models();
|
|
6149
|
+
init_oauth();
|
|
6150
|
+
init_retry();
|
|
5482
6151
|
init_types();
|
|
5483
6152
|
|
|
5484
6153
|
// ../kiro-core/dist/usage.js
|
|
@@ -5543,6 +6212,10 @@ async function fetchRawUsage(auth, profileArn) {
|
|
|
5543
6212
|
});
|
|
5544
6213
|
}
|
|
5545
6214
|
async function fetchKiroUsage(credentials) {
|
|
6215
|
+
const { runKiroOp: runKiroOp2 } = await Promise.resolve().then(() => (init_engine_ops(), engine_ops_exports));
|
|
6216
|
+
return runKiroOp2("usage", () => ({ credentials }), () => fetchKiroUsageInProcess(credentials));
|
|
6217
|
+
}
|
|
6218
|
+
async function fetchKiroUsageInProcess(credentials) {
|
|
5546
6219
|
const auth = { accessToken: credentials.access, region: resolveApiRegion(credentials.region) };
|
|
5547
6220
|
const raw = await fetchRawUsage(auth, credentials.profileArn);
|
|
5548
6221
|
const usageBuckets = raw.usageBreakdownList?.length ? raw.usageBreakdownList.map(mapBucket) : raw.usageBreakdown ? [mapBucket(raw.usageBreakdown, 0)] : [];
|