trouteai 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/.build/next/BUILD_ID +1 -1
  2. package/.build/next/build-manifest.json +3 -3
  3. package/.build/next/fallback-build-manifest.json +3 -3
  4. package/.build/next/server/app/(dashboard)/dashboard/activity/page_client-reference-manifest.js +1 -1
  5. package/.build/next/server/app/(dashboard)/dashboard/analytics/combo-health/page_client-reference-manifest.js +1 -1
  6. package/.build/next/server/app/(dashboard)/dashboard/analytics/page_client-reference-manifest.js +1 -1
  7. package/.build/next/server/app/(dashboard)/dashboard/analytics/utilization/page_client-reference-manifest.js +1 -1
  8. package/.build/next/server/app/(dashboard)/dashboard/api-manager/page_client-reference-manifest.js +1 -1
  9. package/.build/next/server/app/(dashboard)/dashboard/audit/page_client-reference-manifest.js +1 -1
  10. package/.build/next/server/app/(dashboard)/dashboard/auto-combo/page_client-reference-manifest.js +1 -1
  11. package/.build/next/server/app/(dashboard)/dashboard/cache/page_client-reference-manifest.js +1 -1
  12. package/.build/next/server/app/(dashboard)/dashboard/combos/[id]/page_client-reference-manifest.js +1 -1
  13. package/.build/next/server/app/(dashboard)/dashboard/combos/live/page_client-reference-manifest.js +1 -1
  14. package/.build/next/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
  15. package/.build/next/server/app/(dashboard)/dashboard/combos/playground/page_client-reference-manifest.js +1 -1
  16. package/.build/next/server/app/(dashboard)/dashboard/costs/budget/page_client-reference-manifest.js +1 -1
  17. package/.build/next/server/app/(dashboard)/dashboard/costs/page_client-reference-manifest.js +1 -1
  18. package/.build/next/server/app/(dashboard)/dashboard/costs/pricing/page_client-reference-manifest.js +1 -1
  19. package/.build/next/server/app/(dashboard)/dashboard/costs/quota-share/page_client-reference-manifest.js +1 -1
  20. package/.build/next/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
  21. package/.build/next/server/app/(dashboard)/dashboard/health/page_client-reference-manifest.js +1 -1
  22. package/.build/next/server/app/(dashboard)/dashboard/limits/page_client-reference-manifest.js +1 -1
  23. package/.build/next/server/app/(dashboard)/dashboard/logs/activity/page_client-reference-manifest.js +1 -1
  24. package/.build/next/server/app/(dashboard)/dashboard/logs/console/page_client-reference-manifest.js +1 -1
  25. package/.build/next/server/app/(dashboard)/dashboard/logs/page_client-reference-manifest.js +1 -1
  26. package/.build/next/server/app/(dashboard)/dashboard/logs/proxy/page_client-reference-manifest.js +1 -1
  27. package/.build/next/server/app/(dashboard)/dashboard/logs/timeline/page_client-reference-manifest.js +1 -1
  28. package/.build/next/server/app/(dashboard)/dashboard/media-providers/[kind]/[id]/page_client-reference-manifest.js +1 -1
  29. package/.build/next/server/app/(dashboard)/dashboard/media-providers/[kind]/page_client-reference-manifest.js +1 -1
  30. package/.build/next/server/app/(dashboard)/dashboard/media-providers/page_client-reference-manifest.js +1 -1
  31. package/.build/next/server/app/(dashboard)/dashboard/onboarding/page_client-reference-manifest.js +1 -1
  32. package/.build/next/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
  33. package/.build/next/server/app/(dashboard)/dashboard/playground/page_client-reference-manifest.js +1 -1
  34. package/.build/next/server/app/(dashboard)/dashboard/provider-stats/page_client-reference-manifest.js +1 -1
  35. package/.build/next/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
  36. package/.build/next/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
  37. package/.build/next/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
  38. package/.build/next/server/app/(dashboard)/dashboard/quota/page_client-reference-manifest.js +1 -1
  39. package/.build/next/server/app/(dashboard)/dashboard/runtime/page_client-reference-manifest.js +1 -1
  40. package/.build/next/server/app/(dashboard)/dashboard/settings/advanced/page_client-reference-manifest.js +1 -1
  41. package/.build/next/server/app/(dashboard)/dashboard/settings/ai/page_client-reference-manifest.js +1 -1
  42. package/.build/next/server/app/(dashboard)/dashboard/settings/appearance/page_client-reference-manifest.js +1 -1
  43. package/.build/next/server/app/(dashboard)/dashboard/settings/cache/page_client-reference-manifest.js +1 -1
  44. package/.build/next/server/app/(dashboard)/dashboard/settings/feature-flags/page_client-reference-manifest.js +1 -1
  45. package/.build/next/server/app/(dashboard)/dashboard/settings/general/page_client-reference-manifest.js +1 -1
  46. package/.build/next/server/app/(dashboard)/dashboard/settings/page_client-reference-manifest.js +1 -1
  47. package/.build/next/server/app/(dashboard)/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
  48. package/.build/next/server/app/(dashboard)/dashboard/settings/resilience/page_client-reference-manifest.js +1 -1
  49. package/.build/next/server/app/(dashboard)/dashboard/settings/routing/page_client-reference-manifest.js +1 -1
  50. package/.build/next/server/app/(dashboard)/dashboard/settings/security/page_client-reference-manifest.js +1 -1
  51. package/.build/next/server/app/(dashboard)/dashboard/settings/sidebar/page_client-reference-manifest.js +1 -1
  52. package/.build/next/server/app/(dashboard)/dashboard/system/page_client-reference-manifest.js +1 -1
  53. package/.build/next/server/app/(dashboard)/dashboard/system/proxy/page_client-reference-manifest.js +1 -1
  54. package/.build/next/server/app/(dashboard)/dashboard/usage/page_client-reference-manifest.js +1 -1
  55. package/.build/next/server/app/(dashboard)/home/page_client-reference-manifest.js +1 -1
  56. package/.build/next/server/app/400/page_client-reference-manifest.js +1 -1
  57. package/.build/next/server/app/401/page_client-reference-manifest.js +1 -1
  58. package/.build/next/server/app/403/page_client-reference-manifest.js +1 -1
  59. package/.build/next/server/app/408/page_client-reference-manifest.js +1 -1
  60. package/.build/next/server/app/429/page_client-reference-manifest.js +1 -1
  61. package/.build/next/server/app/500/page_client-reference-manifest.js +1 -1
  62. package/.build/next/server/app/502/page_client-reference-manifest.js +1 -1
  63. package/.build/next/server/app/503/page_client-reference-manifest.js +1 -1
  64. package/.build/next/server/app/_global-error.html +1 -1
  65. package/.build/next/server/app/_global-error.rsc +1 -1
  66. package/.build/next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  67. package/.build/next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  68. package/.build/next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  69. package/.build/next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  70. package/.build/next/server/app/api/v1/messages/route.js +10 -10
  71. package/.build/next/server/app/auth/callback/page_client-reference-manifest.js +1 -1
  72. package/.build/next/server/app/callback/page_client-reference-manifest.js +1 -1
  73. package/.build/next/server/app/connect/codex/[token]/page_client-reference-manifest.js +1 -1
  74. package/.build/next/server/app/forbidden/page_client-reference-manifest.js +1 -1
  75. package/.build/next/server/app/forgot-password/page_client-reference-manifest.js +1 -1
  76. package/.build/next/server/app/login/page_client-reference-manifest.js +1 -1
  77. package/.build/next/server/app/maintenance/page_client-reference-manifest.js +1 -1
  78. package/.build/next/server/app/offline/page_client-reference-manifest.js +1 -1
  79. package/.build/next/server/app/page_client-reference-manifest.js +1 -1
  80. package/.build/next/server/chunks/{1q96_modules_@aws-sdk_nested-clients_dist-es_submodules_signin_index_1q3t40dvo4--p.js → 1q96_modules_@aws-sdk_nested-clients_dist-es_submodules_signin_index_1b-oarr-rdyrt.js} +1 -1
  81. package/.build/next/server/chunks/{[root-of-the-server]__09miz4mr315ge._.js → [root-of-the-server]__06a582l--8gfi._.js} +2 -2
  82. package/.build/next/server/chunks/{[root-of-the-server]__03ce1fmn0qpsk._.js → [root-of-the-server]__12ww6_t3hg59j._.js} +2 -2
  83. package/.build/next/server/chunks/{[root-of-the-server]__0jcn_nom11qn8._.js → [root-of-the-server]__1idr_msgwldj7._.js} +2 -2
  84. package/.build/next/server/chunks/_0-eumrsx9uwoc._.js +3 -3
  85. package/.build/next/server/chunks/{_0v8bztyjzmwju._.js → _040sjflhcim3n._.js} +2 -2
  86. package/.build/next/server/chunks/_0_owpim-84v6c._.js +1 -1
  87. package/.build/next/server/chunks/_0b_i4b8q0n1wz._.js +15 -17
  88. package/.build/next/server/chunks/_0cnrejialoejq._.js +15 -17
  89. package/.build/next/server/chunks/{_029oc7_2cayf9._.js → _0iclxqeesd_hr._.js} +1 -1
  90. package/.build/next/server/chunks/_0jzperkk-1ag9._.js +1 -1
  91. package/.build/next/server/chunks/_0ma7hnwk4_v5i._.js +1 -1
  92. package/.build/next/server/chunks/_0nntu-lmwlb6z._.js +1 -1
  93. package/.build/next/server/chunks/{_17i9uubpwxtr6._.js → _0ozkcut9ays1g._.js} +1 -1
  94. package/.build/next/server/chunks/_0srkl-vgqcos7._.js +1 -1
  95. package/.build/next/server/chunks/_16an60huh6tbs._.js +1 -1
  96. package/.build/next/server/chunks/_188c9_xzcpc31._.js +1 -1
  97. package/.build/next/server/chunks/_1g8ka5zb3up7z._.js +3 -0
  98. package/.build/next/server/chunks/_1mf3kg0sol0_p._.js +15 -17
  99. package/.build/next/server/chunks/_1wos-_82xr837._.js +15 -17
  100. package/.build/next/server/chunks/_1zcs33t-he7xd._.js +1 -1
  101. package/.build/next/server/chunks/_1zmyssg1ql6gl._.js +1 -1
  102. package/.build/next/server/chunks/{node_modules_0pkok82ldrbvy._.js → node_modules_0u4h-ppwf7yix._.js} +1 -1
  103. package/.build/next/server/chunks/{node_modules_@aws-sdk_1v244fqkm56j8._.js → node_modules_@aws-sdk_0r_t1m5o9vn66._.js} +2 -2
  104. package/.build/next/server/chunks/{node_modules_@aws-sdk_credential-provider-sso_dist-es_loadSso_1_ik1zykfz6zp.js → node_modules_@aws-sdk_credential-provider-sso_dist-es_loadSso_092bd6v9u3x5d.js} +1 -1
  105. package/.build/next/server/chunks/{node_modules_ioredis_built_index_15mwjswq7fcc7.js → node_modules_ioredis_built_index_1agrynr6yap-q.js} +1 -1
  106. package/.build/next/server/chunks/open-sse_02t7zn7htyw-9._.js +1 -1
  107. package/.build/next/server/chunks/open-sse_03goq14q0_x4f._.js +1 -1
  108. package/.build/next/server/chunks/open-sse_03ipq-9xg4l9m._.js +1 -1
  109. package/.build/next/server/chunks/open-sse_0bl-irqke65hd._.js +1 -1
  110. package/.build/next/server/chunks/open-sse_1b6ivsct5ejh3._.js +1 -1
  111. package/.build/next/server/chunks/open-sse_1r2up99lm4jtz._.js +1 -1
  112. package/.build/next/server/chunks/{open-sse_services_1s729m6to90v4._.js → open-sse_services_0k5f57mkiskrt._.js} +1 -1
  113. package/.build/next/server/chunks/src_0jsr5vm5qt_kk._.js +1 -1
  114. package/.build/next/server/chunks/src_1p24y5m9owsdz._.js +1 -1
  115. package/.build/next/server/chunks/{src_lib_plugins_manager_ts_1ydcm2zxi9w3m._.js → src_lib_plugins_manager_ts_03te14cdfjqt1._.js} +2 -2
  116. package/.build/next/server/chunks/{src_lib_quota_2002143jitgx6._.js → src_lib_quota_0wb8erb76zq-0._.js} +1 -1
  117. package/.build/next/server/chunks/{src_lib_quota_quotaKey_ts_1x4r4ykpvtsng._.js → src_lib_quota_quotaKey_ts_1mpll1mny1n6b._.js} +1 -1
  118. package/.build/next/server/chunks/{src_lib_usage_callLogs_ts_0qnepwt2wta77._.js → src_lib_usage_callLogs_ts_1sie3xbxc5_10._.js} +1 -1
  119. package/.build/next/server/chunks/src_shared_constants_1vndx1xsi1o3x._.js +1 -1
  120. package/.build/next/server/chunks/{src_shared_services_0wme2znpr6_8s._.js → src_shared_services_1vt2-qejrwg77._.js} +1 -1
  121. package/.build/next/server/chunks/{src_shared_services_modelSyncScheduler_ts_0z9wckeen9uzt._.js → src_shared_services_modelSyncScheduler_ts_0zan1i5wv3x1s._.js} +1 -1
  122. package/.build/next/server/chunks/ssr/_0rb4h6lptmehu._.js +1 -1
  123. package/.build/next/server/middleware-build-manifest.js +3 -3
  124. package/.build/next/server/middleware.js +2 -2
  125. package/.build/next/server/pages/500.html +1 -1
  126. package/.build/next/static/chunks/{1osm01_w12rhk.js → 0v_saoyx2w57z.js} +1 -1
  127. package/open-sse/executors/kiro.ts +491 -86
  128. package/open-sse/handlers/responseTranslator.ts +13 -7
  129. package/open-sse/handlers/sseParser.ts +4 -0
  130. package/open-sse/translator/request/claude-to-openai.ts +5 -0
  131. package/open-sse/translator/request/openai-to-kiro.ts +46 -1
  132. package/open-sse/translator/response/openai-to-claude.ts +15 -3
  133. package/open-sse/utils/finishReason.ts +8 -0
  134. package/open-sse/utils/streamPayloadCollector.ts +3 -0
  135. package/package.json +1 -1
  136. package/src/app/api/v1/messages/route.ts +7 -1
  137. package/src/server/authz/pipeline.ts +6 -0
  138. package/src/shared/utils/anthropicErrorShape.ts +89 -0
  139. package/.build/next/server/chunks/_0ox6qf339bblb._.js +0 -3
  140. /package/.build/next/static/{9h-Y9U1tfaZmzr5AGgiYn → i-vPbUKTIijARm707KH3L}/_buildManifest.js +0 -0
  141. /package/.build/next/static/{9h-Y9U1tfaZmzr5AGgiYn → i-vPbUKTIijARm707KH3L}/_clientMiddlewareManifest.js +0 -0
  142. /package/.build/next/static/{9h-Y9U1tfaZmzr5AGgiYn → i-vPbUKTIijARm707KH3L}/_ssgManifest.js +0 -0
@@ -11,6 +11,7 @@ import {
11
11
  getKiroUserAgentHeaders,
12
12
  resolveKiroProfileArn,
13
13
  } from "../config/kiroIdentity.ts";
14
+ import { createHash } from "node:crypto";
14
15
  import { v4 as uuidv4 } from "uuid";
15
16
  import { refreshKiroToken } from "../services/tokenRefresh.ts";
16
17
  import {
@@ -61,6 +62,10 @@ type KiroStreamState = {
61
62
  usage?: UsageSummary;
62
63
  hasReasoningContent?: boolean;
63
64
  reasoningChunkCount?: number;
65
+ // Kiro's own stop reason from `metadataEvent` (END_TURN, MAX_TOKENS, CONTENT_FILTERED, ...).
66
+ stopReason?: string;
67
+ // The client's stop sequence that ended the answer (applied here: Kiro has none).
68
+ stopSequence?: string;
64
69
  // Inline-thinking splitter state (populated only when thinkingExpected=true).
65
70
  thinking?: KiroThinkingState;
66
71
  };
@@ -133,7 +138,11 @@ function buildKiroFinishChunk(
133
138
  {
134
139
  index: 0,
135
140
  delta: {},
136
- finish_reason: state.hasToolCalls ? "tool_calls" : "stop",
141
+ finish_reason: state.hasToolCalls ? "tool_calls" : kiroFinishReason(state.stopReason),
142
+ // Read by the OpenAI -> Claude step (stop_reason "stop_sequence"); ignored elsewhere.
143
+ ...(state.stopSequence !== undefined && !state.hasToolCalls
144
+ ? { stop_sequence: state.stopSequence }
145
+ : {}),
137
146
  },
138
147
  ],
139
148
  };
@@ -147,6 +156,278 @@ function buildKiroFinishChunk(
147
156
 
148
157
  const KIRO_DEFAULT_CONTEXT_WINDOW = 200000;
149
158
 
159
+ /** The client's `stop` / `max_tokens`, stashed by the request builder as `_clientLimits`. */
160
+ export type KiroClientLimits = { stop?: string[]; maxTokens?: number };
161
+
162
+ function readKiroClientLimits(body: unknown): KiroClientLimits | null {
163
+ const raw = (body as JsonRecord | null | undefined)?._clientLimits as JsonRecord | undefined;
164
+ if (!raw || typeof raw !== "object") return null;
165
+ const stop = Array.isArray(raw.stop)
166
+ ? raw.stop.filter((x): x is string => typeof x === "string" && x.length > 0)
167
+ : [];
168
+ const maxTokens = typeof raw.maxTokens === "number" && raw.maxTokens > 0 ? raw.maxTokens : 0;
169
+ if (!stop.length && !maxTokens) return null;
170
+ return { ...(stop.length ? { stop } : {}), ...(maxTokens ? { maxTokens } : {}) };
171
+ }
172
+
173
+ /**
174
+ * Kiro ends every answer with a `metadataEvent` carrying its stop reason. A model refusal is
175
+ * `{"stopReason":"CONTENT_FILTERED","stopDetails":{"refusal":{"category":"CYBER"|
176
+ * "REASONING_EXTRACTION"|...,"explanation":"The selected model cannot continue this
177
+ * conversation. Please select a different model, ..."}}}` with no content frames at all
178
+ * (seen live 2026-11-10 on Claude Opus 5.5 / Sonnet 5.5 / Opus 5).
179
+ */
180
+ export function readKiroStopMetadata(payload: unknown): {
181
+ stopReason: string;
182
+ refused: boolean;
183
+ category: string;
184
+ } | null {
185
+ if (!payload || typeof payload !== "object") return null;
186
+ const p = payload as JsonRecord;
187
+ const stopReason = typeof p.stopReason === "string" ? p.stopReason.toUpperCase() : "";
188
+ const details = p.stopDetails as JsonRecord | undefined;
189
+ const refusal =
190
+ details && typeof details === "object" ? (details.refusal as JsonRecord | undefined) : undefined;
191
+ if (!stopReason && !refusal) return null;
192
+ const category = refusal && typeof refusal.category === "string" ? refusal.category : "";
193
+ return {
194
+ stopReason: stopReason || "CONTENT_FILTERED",
195
+ refused: !!refusal || stopReason === "CONTENT_FILTERED",
196
+ category,
197
+ };
198
+ }
199
+
200
+ /** Kiro stop reason → OpenAI finish_reason ("content_filter" becomes Claude's "refusal"). */
201
+ export function kiroFinishReason(stopReason: string | undefined): string {
202
+ switch (stopReason) {
203
+ case "CONTENT_FILTERED":
204
+ case "GUARDRAIL_INTERVENED":
205
+ return "content_filter";
206
+ case "MAX_TOKENS":
207
+ case "MAX_OUTPUT_TOKENS":
208
+ case "LENGTH":
209
+ return "length";
210
+ default:
211
+ return "stop";
212
+ }
213
+ }
214
+
215
+ /**
216
+ * The model to answer with when Kiro's model refuses a request outright. Kiro's own message says
217
+ * "Please select a different model": the newest Claude models carry extra safeguards that refuse
218
+ * some ordinary agent requests (for example Claude Code's auto-mode safety check, which asks for
219
+ * a `<thinking>` section), while the model one step below answers them. Empty = no fallback.
220
+ * `TROUTEAI_KIRO_REFUSAL_FALLBACK=0` switches this off (the refusal is then passed on as is).
221
+ */
222
+ const KIRO_REFUSAL_FALLBACK: Record<string, string> = {
223
+ "claude-opus-5.5": "claude-opus-4.8",
224
+ "claude-opus-5": "claude-opus-4.8",
225
+ "claude-sonnet-5.5": "claude-sonnet-5",
226
+ };
227
+
228
+ export function kiroRefusalFallbackModel(modelId: string): string {
229
+ if (process.env.TROUTEAI_KIRO_REFUSAL_FALLBACK === "0") return "";
230
+ return KIRO_REFUSAL_FALLBACK[modelId] || "";
231
+ }
232
+
233
+ function kiroCurrentModelId(body: Record<string, unknown> | undefined): string {
234
+ const modelId = kiroCurrentUserMessage(body).modelId;
235
+ return typeof modelId === "string" ? modelId : "";
236
+ }
237
+
238
+ /** The SSE answer for a refusal with no output: an empty turn that stops with "content_filter". */
239
+ function kiroRefusalSseResponse(model: string): Response {
240
+ const base = {
241
+ id: `chatcmpl-${Date.now()}`,
242
+ object: "chat.completion.chunk",
243
+ created: Math.floor(Date.now() / 1000),
244
+ model,
245
+ };
246
+ const frames = [
247
+ { ...base, choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] },
248
+ { ...base, choices: [{ index: 0, delta: {}, finish_reason: "content_filter" }] },
249
+ ];
250
+ const text = frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join("") + "data: [DONE]\n\n";
251
+ return new Response(text, {
252
+ status: 200,
253
+ headers: {
254
+ "Content-Type": "text/event-stream",
255
+ "Cache-Control": "no-cache",
256
+ Connection: "keep-alive",
257
+ },
258
+ });
259
+ }
260
+
261
+ function kiroCurrentUserMessage(body: Record<string, unknown> | undefined): JsonRecord {
262
+ const state = body?.conversationState as JsonRecord | undefined;
263
+ const current = state?.currentMessage as JsonRecord | undefined;
264
+ return (current?.userInputMessage as JsonRecord | undefined) || {};
265
+ }
266
+
267
+ function kiroThinkingDirectiveSent(body: Record<string, unknown> | undefined): boolean {
268
+ const content = kiroCurrentUserMessage(body).content;
269
+ return typeof content === "string" && content.includes("<thinking_mode>enabled</thinking_mode>");
270
+ }
271
+
272
+ function kiroBodyWithModel(
273
+ body: Record<string, unknown> | undefined,
274
+ fromModelId: string,
275
+ toModelId: string
276
+ ): string {
277
+ return JSON.stringify(body)
278
+ .split(`"modelId":${JSON.stringify(fromModelId)}`)
279
+ .join(`"modelId":${JSON.stringify(toModelId)}`);
280
+ }
281
+
282
+ // Helper prompts that a model refused for REASONING_EXTRACTION, kept in memory for a while.
283
+ // Only single-shot requests without tools and history qualify (Claude Code's auto-mode safety
284
+ // check is one): their first 4 KB is the helper's own fixed instruction text, so the key never
285
+ // matches a normal conversation, whose requests always carry tools or history.
286
+ const KIRO_HELPER_REFUSAL_TTL_MS = 30 * 60_000;
287
+ const KIRO_HELPER_REFUSAL_MAX = 200;
288
+ const kiroHelperRefusals = new Map<string, number>();
289
+
290
+ export function kiroHelperPromptKey(body: Record<string, unknown> | undefined): string {
291
+ const state = body?.conversationState as JsonRecord | undefined;
292
+ const history = state?.history;
293
+ if (Array.isArray(history) && history.length > 0) return "";
294
+ const user = kiroCurrentUserMessage(body);
295
+ const context = user.userInputMessageContext as JsonRecord | undefined;
296
+ if (Array.isArray(context?.tools) && context.tools.length > 0) return "";
297
+ if (Array.isArray(context?.toolResults) && context.toolResults.length > 0) return "";
298
+ // The request builder puts per-request lines first (the current time, a thinking directive).
299
+ const content = (typeof user.content === "string" ? user.content : "")
300
+ .replace(/^(?:\[Context: Current time is [^\]\n]*\]|<thinking_mode>[^\n]*)\n\n/, "")
301
+ .replace(/^(?:\[Context: Current time is [^\]\n]*\]|<thinking_mode>[^\n]*)\n\n/, "");
302
+ const modelId = typeof user.modelId === "string" ? user.modelId : "";
303
+ if (content.length < 4096 || !modelId) return "";
304
+ return createHash("sha256").update(modelId).update("\n").update(content.slice(0, 4096)).digest("hex");
305
+ }
306
+
307
+ function kiroHelperRefusalRemembered(key: string): boolean {
308
+ const until = kiroHelperRefusals.get(key);
309
+ if (!until) return false;
310
+ if (until > Date.now()) return true;
311
+ kiroHelperRefusals.delete(key);
312
+ return false;
313
+ }
314
+
315
+ function rememberKiroHelperRefusal(key: string): void {
316
+ if (kiroHelperRefusals.size >= KIRO_HELPER_REFUSAL_MAX) {
317
+ const oldest = kiroHelperRefusals.keys().next().value;
318
+ if (oldest !== undefined) kiroHelperRefusals.delete(oldest);
319
+ }
320
+ kiroHelperRefusals.set(key, Date.now() + KIRO_HELPER_REFUSAL_TTL_MS);
321
+ }
322
+
323
+ function forgetKiroHelperRefusal(key: string): void {
324
+ kiroHelperRefusals.delete(key);
325
+ }
326
+
327
+ const KIRO_CONTENT_EVENTS = new Set([
328
+ "assistantResponseEvent",
329
+ "reasoningContentEvent",
330
+ "toolUseEvent",
331
+ "codeEvent",
332
+ ]);
333
+ const KIRO_PEEK_LIMIT_BYTES = 256 * 1024;
334
+
335
+ /**
336
+ * Read the start of a Kiro answer until it is clear whether the model refused before writing
337
+ * anything. Returns the verdict and a Response that replays the bytes already read, so nothing
338
+ * is lost and nothing is delayed (the first frame Kiro sends is content or the stop metadata).
339
+ */
340
+ export async function peekKiroRefusal(
341
+ response: Response
342
+ ): Promise<{ refused: boolean; category: string; response: Response }> {
343
+ if (!response.body) return { refused: false, category: "", response };
344
+ const reader = response.body.getReader();
345
+ const chunks: Uint8Array[] = [];
346
+ const queue = new ByteQueue();
347
+ let total = 0;
348
+ let refused = false;
349
+ let category = "";
350
+ let decided = false;
351
+ let ended = false;
352
+ try {
353
+ while (!decided && total < KIRO_PEEK_LIMIT_BYTES) {
354
+ const { done, value } = await reader.read();
355
+ if (done) {
356
+ ended = true;
357
+ break;
358
+ }
359
+ if (!value) continue;
360
+ chunks.push(value);
361
+ total += value.length;
362
+ queue.push(value);
363
+ while (queue.length >= 16) {
364
+ const len = queue.peekUint32BE(0);
365
+ if (!len || len < 16 || len > queue.length) break;
366
+ const frame = queue.read(len);
367
+ if (!frame) break;
368
+ const event = parseEventFrame(frame);
369
+ if (!event) continue;
370
+ const type = event.headers[":event-type"] || "";
371
+ if (KIRO_CONTENT_EVENTS.has(type) || event.headers[":message-type"] === "exception") {
372
+ decided = true;
373
+ break;
374
+ }
375
+ if (type === "metadataEvent") {
376
+ const meta = readKiroStopMetadata(event.payload);
377
+ if (meta) {
378
+ decided = true;
379
+ refused = meta.refused;
380
+ category = meta.category;
381
+ break;
382
+ }
383
+ }
384
+ }
385
+ }
386
+ } catch (error) {
387
+ await reader.cancel().catch(() => {});
388
+ throw error;
389
+ }
390
+
391
+ if (refused) {
392
+ // The caller asks another model; this answer is not used.
393
+ await reader.cancel().catch(() => {});
394
+ return { refused, category, response };
395
+ }
396
+
397
+ let index = 0;
398
+ const replay = new ReadableStream<Uint8Array>({
399
+ async pull(controller) {
400
+ if (index < chunks.length) {
401
+ controller.enqueue(chunks[index++]);
402
+ return;
403
+ }
404
+ if (ended) {
405
+ controller.close();
406
+ return;
407
+ }
408
+ try {
409
+ const { done, value } = await reader.read();
410
+ if (done) controller.close();
411
+ else if (value) controller.enqueue(value);
412
+ } catch (error) {
413
+ controller.error(error);
414
+ }
415
+ },
416
+ cancel(reason) {
417
+ return reader.cancel(reason).catch(() => {});
418
+ },
419
+ });
420
+ return {
421
+ refused,
422
+ category,
423
+ response: new Response(replay, {
424
+ status: response.status,
425
+ statusText: response.statusText,
426
+ headers: response.headers,
427
+ }),
428
+ };
429
+ }
430
+
150
431
  function ensureKiroUsage(state: KiroStreamState) {
151
432
  // Output estimate covers text, reasoning, code and tool calls (names + final args).
152
433
  const estimatedOutputTokens = estimateOutputTokens(state.totalContentLength || 0);
@@ -338,7 +619,42 @@ export class KiroExecutor extends BaseExecutor {
338
619
  Record<string, unknown> | undefined;
339
620
  if (profileArn && transformedBody?.conversationState) transformedBody.profileArn = profileArn;
340
621
 
341
- const response = await fetch(url, {
622
+ // A helper prompt (no tools, no history) that this model refused a moment ago for asking
623
+ // it to write out its reasoning will be refused again: go to the fallback model directly
624
+ // and save the refused round trip (about 5 s and a full prompt of credits each time).
625
+ const helperKey = kiroHelperPromptKey(transformedBody);
626
+ const knownRefusalFallback =
627
+ helperKey && kiroHelperRefusalRemembered(helperKey)
628
+ ? kiroRefusalFallbackModel(kiroCurrentModelId(transformedBody))
629
+ : "";
630
+ if (knownRefusalFallback) {
631
+ const direct = await fetch(url, {
632
+ method: "POST",
633
+ headers,
634
+ body: kiroBodyWithModel(
635
+ transformedBody,
636
+ kiroCurrentModelId(transformedBody),
637
+ knownRefusalFallback
638
+ ),
639
+ signal,
640
+ });
641
+ if (direct.ok) {
642
+ const tbDirect = transformedBody as Record<string, unknown>;
643
+ return {
644
+ response: this.transformEventStreamToSSE(direct, model, {
645
+ thinkingExpected: kiroThinkingDirectiveSent(tbDirect),
646
+ limits: readKiroClientLimits(body),
647
+ }),
648
+ url,
649
+ headers,
650
+ transformedBody,
651
+ };
652
+ }
653
+ await direct.body?.cancel().catch(() => {});
654
+ forgetKiroHelperRefusal(helperKey);
655
+ }
656
+
657
+ let response = await fetch(url, {
342
658
  method: "POST",
343
659
  headers,
344
660
  body: JSON.stringify(transformedBody),
@@ -349,6 +665,39 @@ export class KiroExecutor extends BaseExecutor {
349
665
  return { response, url, headers, transformedBody };
350
666
  }
351
667
 
668
+ // A refusal before any output ("The selected model cannot continue this conversation.
669
+ // Please select a different model"): ask the fallback model once, as Kiro suggests. Without
670
+ // a fallback (or when it cannot be asked) the refusal goes to the client as a refusal stop.
671
+ const sentModelId = kiroCurrentModelId(transformedBody);
672
+ const fallbackModelId = kiroRefusalFallbackModel(sentModelId);
673
+ if (fallbackModelId) {
674
+ const peeked = await peekKiroRefusal(response);
675
+ response = peeked.response;
676
+ if (peeked.refused) {
677
+ log?.warn?.(
678
+ "KIRO",
679
+ `${sentModelId} refused this request (${peeked.category || "content filtered"}); asking ${fallbackModelId} instead`
680
+ );
681
+ if (helperKey && peeked.category === "REASONING_EXTRACTION") {
682
+ rememberKiroHelperRefusal(helperKey);
683
+ }
684
+ const retry = await fetch(url, {
685
+ method: "POST",
686
+ headers,
687
+ body: kiroBodyWithModel(transformedBody, sentModelId, fallbackModelId),
688
+ signal,
689
+ });
690
+ if (retry.ok) {
691
+ response = retry;
692
+ } else {
693
+ // The fallback could not be asked (limit, model not on this plan, ...): the answer
694
+ // stays what Kiro gave, a refusal. It must not become an error or a second charge.
695
+ await retry.body?.cancel().catch(() => {});
696
+ return { response: kiroRefusalSseResponse(model), url, headers, transformedBody };
697
+ }
698
+ }
699
+ }
700
+
352
701
  // For Kiro, we need to transform the binary EventStream to SSE.
353
702
  // Create a TransformStream to convert binary to SSE text.
354
703
  //
@@ -358,19 +707,12 @@ export class KiroExecutor extends BaseExecutor {
358
707
  // `reasoningContentEvent` frames. We pass a hint so the transform stream
359
708
  // can split that inline reasoning into the OpenAI `delta.reasoning_content`
360
709
  // channel.
361
- const tb = transformedBody as Record<string, unknown>;
362
- const userContent =
363
- ((
364
- (
365
- (tb?.conversationState as Record<string, unknown>)?.currentMessage as Record<
366
- string,
367
- unknown
368
- >
369
- )?.userInputMessage as Record<string, unknown>
370
- )?.content as string) || "";
371
- const thinkingExpected = userContent.includes("<thinking_mode>enabled</thinking_mode>");
710
+ const thinkingExpected = kiroThinkingDirectiveSent(
711
+ transformedBody as Record<string, unknown>
712
+ );
372
713
  const transformedResponse = this.transformEventStreamToSSE(response, model, {
373
714
  thinkingExpected,
715
+ limits: readKiroClientLimits(body),
374
716
  });
375
717
 
376
718
  return { response: transformedResponse, url, headers, transformedBody };
@@ -393,9 +735,19 @@ export class KiroExecutor extends BaseExecutor {
393
735
  transformEventStreamToSSE(
394
736
  response: Response,
395
737
  model: string,
396
- opts: { thinkingExpected?: boolean } = {}
738
+ opts: { thinkingExpected?: boolean; limits?: KiroClientLimits | null } = {}
397
739
  ) {
398
740
  const thinkingExpected = !!opts.thinkingExpected;
741
+ // The client's stop sequences and max_tokens, applied to the visible text (Kiro applies
742
+ // neither). About 4 characters per token, the same estimate the usage numbers use.
743
+ const stopList = (opts.limits?.stop || []).filter((x) => typeof x === "string" && x.length > 0);
744
+ const maxChars =
745
+ opts.limits?.maxTokens && opts.limits.maxTokens > 0 ? opts.limits.maxTokens * 4 : 0;
746
+ const gated = stopList.length > 0 || maxChars > 0;
747
+ let heldText = "";
748
+ let emittedChars = 0;
749
+ let cut = false;
750
+ let cutAt = 0;
399
751
  const buffer = new ByteQueue();
400
752
  let chunkIndex = 0;
401
753
  const responseId = `chatcmpl-${Date.now()}`;
@@ -416,9 +768,94 @@ export class KiroExecutor extends BaseExecutor {
416
768
  contextWindowTokens: getModelContextLimit("kiro", model) || KIRO_DEFAULT_CONTEXT_WINDOW,
417
769
  };
418
770
 
771
+ type Sink = { enqueue: (chunk: Uint8Array) => void };
772
+ const emitText = (controller: Sink, text: string) => {
773
+ if (!text) return;
774
+ const out: JsonRecord = {
775
+ id: responseId,
776
+ object: "chat.completion.chunk",
777
+ created,
778
+ model,
779
+ choices: [
780
+ {
781
+ index: 0,
782
+ delta: chunkIndex === 0 ? { role: "assistant", content: text } : { content: text },
783
+ finish_reason: null,
784
+ },
785
+ ],
786
+ };
787
+ chunkIndex++;
788
+ controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(out)}\n\n`));
789
+ };
790
+ // Visible text goes through here. With limits it stops at the first stop sequence (holding
791
+ // back a tail that may be the start of one) or at the max_tokens estimate.
792
+ const writeText = (controller: Sink, text: string, final = false) => {
793
+ if (!gated) {
794
+ emitText(controller, text);
795
+ return;
796
+ }
797
+ if (cut) return;
798
+ const buf = heldText + text;
799
+ heldText = "";
800
+ let stopIdx = -1;
801
+ let stopSeq = "";
802
+ for (const seq of stopList) {
803
+ const i = buf.indexOf(seq);
804
+ if (i !== -1 && (stopIdx === -1 || i < stopIdx)) {
805
+ stopIdx = i;
806
+ stopSeq = seq;
807
+ }
808
+ }
809
+ let out = stopIdx !== -1 ? buf.slice(0, stopIdx) : buf;
810
+ if (stopIdx === -1 && !final) {
811
+ let hold = 0;
812
+ for (const seq of stopList) {
813
+ for (let k = Math.min(seq.length - 1, buf.length); k > hold; k--) {
814
+ if (buf.endsWith(seq.slice(0, k))) {
815
+ hold = k;
816
+ break;
817
+ }
818
+ }
819
+ }
820
+ if (hold > 0) {
821
+ heldText = buf.slice(buf.length - hold);
822
+ out = buf.slice(0, buf.length - hold);
823
+ }
824
+ }
825
+ let hitMax = false;
826
+ if (maxChars > 0 && emittedChars + out.length > maxChars) {
827
+ out = out.slice(0, Math.max(0, maxChars - emittedChars));
828
+ hitMax = true;
829
+ }
830
+ if (out) {
831
+ emittedChars += out.length;
832
+ state.totalContentLength = (state.totalContentLength || 0) + out.length;
833
+ emitText(controller, out);
834
+ }
835
+ if (hitMax) state.stopReason = "MAX_TOKENS";
836
+ else if (stopIdx !== -1) state.stopSequence = stopSeq;
837
+ if (hitMax || stopIdx !== -1) {
838
+ cut = true;
839
+ cutAt = Date.now();
840
+ heldText = "";
841
+ }
842
+ };
843
+ // After a cut the rest of Kiro's answer is not needed: finish now and stop reading it.
844
+ const finishEarly = (controller: TransformStreamDefaultController<Uint8Array>) => {
845
+ if (!state.finishEmitted) {
846
+ state.finishEmitted = true;
847
+ ensureKiroUsage(state);
848
+ const finishChunk = buildKiroFinishChunk(state, responseId, created, model, true);
849
+ controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(finishChunk)}\n\n`));
850
+ controller.enqueue(TEXT_ENCODER.encode("data: [DONE]\n\n"));
851
+ }
852
+ controller.terminate();
853
+ };
854
+
419
855
  const transformStream = new TransformStream(
420
856
  {
421
857
  async transform(chunk, controller) {
858
+ if (state.finishEmitted) return;
422
859
  buffer.push(chunk);
423
860
 
424
861
  // Parse events from buffer
@@ -475,6 +912,16 @@ export class KiroExecutor extends BaseExecutor {
475
912
  if (!state.totalContentLength) state.totalContentLength = 0;
476
913
  if (!state.contextUsagePercentage) state.contextUsagePercentage = 0;
477
914
 
915
+ // After a stop sequence / max_tokens cut only the closing usage frames matter;
916
+ // they normally follow at once. Do not wait long for a model that keeps writing.
917
+ if (cut && KIRO_CONTENT_EVENTS.has(eventType)) {
918
+ if (Date.now() - cutAt > 2500) {
919
+ finishEarly(controller);
920
+ return;
921
+ }
922
+ continue;
923
+ }
924
+
478
925
  // Native reasoning frames. Verified against the live CodeWhisperer
479
926
  // stream (2026-07): with adaptive thinking enabled (via
480
927
  // additionalModelRequestFields), Kiro streams reasoning as a dedicated
@@ -534,7 +981,8 @@ export class KiroExecutor extends BaseExecutor {
534
981
  continue;
535
982
  }
536
983
  // Raw length before the inline <thinking> split, so text and reasoning count once.
537
- state.totalContentLength += content.length;
984
+ // With client limits the text is counted as it is written (writeText).
985
+ if (!gated) state.totalContentLength += content.length;
538
986
 
539
987
  if (thinkingExpected && state.thinking) {
540
988
  // Claude on Kiro emits reasoning inline as `<thinking>…</thinking>`
@@ -545,29 +993,10 @@ export class KiroExecutor extends BaseExecutor {
545
993
  splitInlineThinking(
546
994
  thinkingState,
547
995
  content,
548
- (text) => {
549
- if (!text) return;
550
- const chunk: JsonRecord = {
551
- id: responseId,
552
- object: "chat.completion.chunk",
553
- created,
554
- model,
555
- choices: [
556
- {
557
- index: 0,
558
- delta:
559
- chunkIndex === 0
560
- ? { role: "assistant", content: text }
561
- : { content: text },
562
- finish_reason: null,
563
- },
564
- ],
565
- };
566
- chunkIndex++;
567
- controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(chunk)}\n\n`));
568
- },
996
+ (text) => writeText(controller, text),
569
997
  (reasoning) => {
570
998
  if (!reasoning) return;
999
+ if (gated) state.totalContentLength = (state.totalContentLength || 0) + reasoning.length;
571
1000
  state.hasReasoningContent = true;
572
1001
  const reasoningDelta: JsonRecord =
573
1002
  (state.reasoningChunkCount ?? 0) === 0 && chunkIndex === 0
@@ -592,42 +1021,14 @@ export class KiroExecutor extends BaseExecutor {
592
1021
  }
593
1022
  );
594
1023
  } else {
595
- const chunk: JsonRecord = {
596
- id: responseId,
597
- object: "chat.completion.chunk",
598
- created,
599
- model,
600
- choices: [
601
- {
602
- index: 0,
603
- delta: chunkIndex === 0 ? { role: "assistant", content } : { content },
604
- finish_reason: null,
605
- },
606
- ],
607
- };
608
- chunkIndex++;
609
- controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(chunk)}\n\n`));
1024
+ writeText(controller, content);
610
1025
  }
611
1026
  }
612
1027
 
613
1028
  // Handle codeEvent
614
1029
  if (eventType === "codeEvent" && event.payload?.content) {
615
- state.totalContentLength += String(event.payload.content).length;
616
- const chunk: JsonRecord = {
617
- id: responseId,
618
- object: "chat.completion.chunk",
619
- created,
620
- model,
621
- choices: [
622
- {
623
- index: 0,
624
- delta: { content: event.payload.content },
625
- finish_reason: null,
626
- },
627
- ],
628
- };
629
- chunkIndex++;
630
- controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(chunk)}\n\n`));
1030
+ if (!gated) state.totalContentLength += String(event.payload.content).length;
1031
+ writeText(controller, String(event.payload.content));
631
1032
  }
632
1033
 
633
1034
  // Handle toolUseEvent
@@ -732,6 +1133,13 @@ export class KiroExecutor extends BaseExecutor {
732
1133
  }
733
1134
  }
734
1135
 
1136
+ // Kiro's stop reason (END_TURN, MAX_TOKENS, CONTENT_FILTERED + refusal details).
1137
+ if (eventType === "metadataEvent") {
1138
+ const meta = readKiroStopMetadata(event.payload);
1139
+ // After our own cut (stop sequence / max_tokens) that cut is the stop reason.
1140
+ if (meta && !cut) state.stopReason = meta.stopReason;
1141
+ }
1142
+
735
1143
  // Handle messageStopEvent
736
1144
  if (eventType === "messageStopEvent") {
737
1145
  flushBufferedToolArgs(state, controller, { responseId, created, model });
@@ -750,6 +1158,10 @@ export class KiroExecutor extends BaseExecutor {
750
1158
  state.contextUsagePercentage = contextUsage;
751
1159
  // Mark that we received context usage event
752
1160
  state.hasContextUsage = true;
1161
+ if (cut) {
1162
+ finishEarly(controller);
1163
+ return;
1164
+ }
753
1165
  }
754
1166
 
755
1167
  // Handle meteringEvent - mark that we received it
@@ -812,18 +1224,7 @@ export class KiroExecutor extends BaseExecutor {
812
1224
  const thinkingState = state.thinking;
813
1225
  flushPendingThinking(
814
1226
  thinkingState,
815
- (text) => {
816
- if (!text) return;
817
- const chunk: JsonRecord = {
818
- id: responseId,
819
- object: "chat.completion.chunk",
820
- created,
821
- model,
822
- choices: [{ index: 0, delta: { content: text }, finish_reason: null }],
823
- };
824
- chunkIndex++;
825
- controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(chunk)}\n\n`));
826
- },
1227
+ (text) => writeText(controller, text),
827
1228
  (reasoning) => {
828
1229
  if (!reasoning) return;
829
1230
  const chunk: JsonRecord = {
@@ -841,13 +1242,17 @@ export class KiroExecutor extends BaseExecutor {
841
1242
  );
842
1243
  }
843
1244
 
844
- // Emit finish chunk if not already sent
845
- if (!state.finishEmitted) {
846
- state.finishEmitted = true;
847
- ensureKiroUsage(state);
848
- const finishChunk = buildKiroFinishChunk(state, responseId, created, model, true);
849
- controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(finishChunk)}\n\n`));
850
- }
1245
+ // Text held back as a possible start of a stop sequence that never completed.
1246
+ if (gated && !cut) writeText(controller, "", true);
1247
+
1248
+ // Already finished early (stop sequence / max_tokens): nothing more to send.
1249
+ if (state.finishEmitted) return;
1250
+
1251
+ // Emit the finish chunk
1252
+ state.finishEmitted = true;
1253
+ ensureKiroUsage(state);
1254
+ const finishChunk = buildKiroFinishChunk(state, responseId, created, model, true);
1255
+ controller.enqueue(TEXT_ENCODER.encode(`data: ${JSON.stringify(finishChunk)}\n\n`));
851
1256
 
852
1257
  // Send final done message
853
1258
  controller.enqueue(TEXT_ENCODER.encode("data: [DONE]\n\n"));