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
@@ -5,8 +5,7 @@ import {
5
5
  } from "../services/geminiThoughtSignatureStore.ts";
6
6
  import {
7
7
  convertFinishReason,
8
- normalizeOpenAICompatibleFinishReasonString,
9
- } from "../utils/finishReason.ts";
8
+ normalizeOpenAICompatibleFinishReasonString, toClaudeMessageId } from "../utils/finishReason.ts";
10
9
  import { containsTextualToolCallMarker } from "../utils/textualToolCall.ts";
11
10
  import { getAnyReasoningValue } from "../utils/reasoningFields.ts";
12
11
 
@@ -670,17 +669,24 @@ function convertOpenAINonStreamingToClaude(openaiResponse: JsonRecord): JsonReco
670
669
  input_tokens: Math.max(0, promptTokens - cacheRead - cacheCreate),
671
670
  output_tokens: toNumber(usageSrc.completion_tokens, 0),
672
671
  };
673
- if (cacheRead > 0) claudeUsage.cache_read_input_tokens = cacheRead;
674
- if (cacheCreate > 0) claudeUsage.cache_creation_input_tokens = cacheCreate;
672
+ // The Messages API always reports both cache counters (0 when nothing was cached).
673
+ claudeUsage.cache_creation_input_tokens = cacheCreate;
674
+ claudeUsage.cache_read_input_tokens = cacheRead;
675
+
676
+ // A stop sequence that ended the answer (reported by the upstream step on the choice).
677
+ const stopSequence =
678
+ typeof choiceObj.stop_sequence === "string" && stopReason === "end_turn"
679
+ ? choiceObj.stop_sequence
680
+ : null;
675
681
 
676
682
  const claudeResponse: JsonRecord = {
677
- id: toString(openaiResponse.id, `msg_${Date.now()}`),
683
+ id: toClaudeMessageId(openaiResponse.id),
678
684
  type: "message",
679
685
  role: "assistant",
680
686
  model: toString(openaiResponse.model, "claude"),
681
687
  content,
682
- stop_reason: stopReason,
683
- stop_sequence: null,
688
+ stop_reason: stopSequence !== null ? "stop_sequence" : stopReason,
689
+ stop_sequence: stopSequence,
684
690
  usage: claudeUsage,
685
691
  };
686
692
 
@@ -193,6 +193,8 @@ export function parseSSEToOpenAIResponse(rawSSE, fallbackModel) {
193
193
  const accumulatedToolCalls = new Map<string, AccumulatedToolCall>();
194
194
  let unknownToolCallSeq = 0;
195
195
  let finishReason = "stop";
196
+ // The stop sequence that ended the answer, when the upstream step reports one.
197
+ let stopSequence: string | null = null;
196
198
  let usage = null;
197
199
 
198
200
  const getToolCallKey = (toolCall: Record<string, unknown>) => {
@@ -259,6 +261,7 @@ export function parseSSEToOpenAIResponse(rawSSE, fallbackModel) {
259
261
 
260
262
  if (choice?.finish_reason) {
261
263
  finishReason = choice.finish_reason;
264
+ if (typeof choice.stop_sequence === "string") stopSequence = choice.stop_sequence;
262
265
  }
263
266
  if (chunk?.usage && typeof chunk.usage === "object") {
264
267
  usage = chunk.usage;
@@ -295,6 +298,7 @@ export function parseSSEToOpenAIResponse(rawSSE, fallbackModel) {
295
298
  index: 0,
296
299
  message,
297
300
  finish_reason: finishReason,
301
+ ...(stopSequence !== null ? { stop_sequence: stopSequence } : {}),
298
302
  },
299
303
  ],
300
304
  };
@@ -263,6 +263,11 @@ export function claudeToOpenAIRequest(model, body, stream, credentials: unknown
263
263
  } else {
264
264
  result.reasoning_effort = "xhigh";
265
265
  }
266
+ } else if (keepMaxEffort && body.thinking?.type === "disabled") {
267
+ // Kiro's newest models think on their own unless told otherwise: carry "thinking off"
268
+ // to the openai -> kiro step (Claude Code's helper calls, such as the auto-mode safety
269
+ // check, send it and expect a fast answer).
270
+ result.reasoning_effort = "none";
266
271
  }
267
272
 
268
273
  return result;
@@ -11,7 +11,11 @@ import {
11
11
  normalizeKiroToolSchema,
12
12
  serializeToolResultContent,
13
13
  } from "./openai-to-kiro/messageHelpers.ts";
14
- import { kiroEffortForModel, resolveKiroModelAlias } from "./openai-to-kiro/adaptiveThinking.ts";
14
+ import {
15
+ kiroEffortForModel,
16
+ resolveKiroModelAlias,
17
+ supportsKiroAdaptiveThinking,
18
+ } from "./openai-to-kiro/adaptiveThinking.ts";
15
19
 
16
20
  /**
17
21
  * Anthropic's direct-provider `[1m]` context-1m beta suffix. Kiro is AWS
@@ -888,7 +892,48 @@ export function buildKiroPayload(model, body, stream, credentials) {
888
892
  }
889
893
  }
890
894
 
895
+ // Kiro ignores `inferenceConfig.maxTokens` and has no stop sequences (measured 2026-11-10:
896
+ // max 1 still answers in full). The executor applies both to the answer itself; this field
897
+ // never leaves TRouteAI (the executor's transformRequest only forwards Kiro's own fields).
898
+ const clientStop = (Array.isArray(body.stop) ? body.stop : [body.stop]).filter(
899
+ (s: unknown): s is string => typeof s === "string" && s.length > 0
900
+ );
901
+ const clientMaxTokens = Number(body.max_tokens ?? body.max_completion_tokens);
902
+ if (clientStop.length > 0 || clientMaxTokens > 0) {
903
+ (payload as Record<string, unknown>)._clientLimits = {
904
+ ...(clientStop.length > 0 ? { stop: clientStop } : {}),
905
+ ...(clientMaxTokens > 0 ? { maxTokens: Math.floor(clientMaxTokens) } : {}),
906
+ };
907
+ }
908
+
909
+ // Thinking switched off by the client (`reasoning_effort: "none"`, Anthropic
910
+ // `thinking: {type: "disabled"}`). Kiro's schema only knows "adaptive" (a "disabled" value
911
+ // gets 400), and without any field Opus 5.5 thinks by itself: measured 2026-11-10 on a
912
+ // 140 KB prompt, 8.5-10.5 s with a reasoning block against 4.9 s with the lowest effort and
913
+ // hidden thinking. So that is what "off" becomes; every model of the table accepts it.
914
+ if (!kiroEffort && !requestedEffort && isKiroThinkingSwitchedOff(body)) {
915
+ if (supportsKiroAdaptiveThinking(normalizedModel)) {
916
+ payload.additionalModelRequestFields = {
917
+ output_config: { effort: "low" },
918
+ thinking: { type: "adaptive", display: "omitted" },
919
+ };
920
+ if (payload.inferenceConfig) {
921
+ delete payload.inferenceConfig.temperature;
922
+ delete payload.inferenceConfig.topP;
923
+ if (Object.keys(payload.inferenceConfig).length === 0) delete payload.inferenceConfig;
924
+ }
925
+ }
926
+ }
927
+
891
928
  return payload;
892
929
  }
893
930
 
931
+ function isKiroThinkingSwitchedOff(body: Record<string, unknown>): boolean {
932
+ if (typeof body.reasoning_effort === "string") {
933
+ return body.reasoning_effort.toLowerCase() === "none";
934
+ }
935
+ const thinking = body.thinking as Record<string, unknown> | undefined;
936
+ return !!thinking && typeof thinking === "object" && thinking.type === "disabled";
937
+ }
938
+
894
939
  register(FORMATS.OPENAI, FORMATS.KIRO, buildKiroPayload, null);
@@ -4,7 +4,7 @@ import { CLAUDE_OAUTH_TOOL_PREFIX } from "../request/openai-to-claude.ts";
4
4
  import { hasToolCallShim, applyToolCallShimToBuffer } from "../helpers/toolCallShim.ts";
5
5
  import { appendToolCallArgumentDelta } from "../../utils/toolCallArguments.ts";
6
6
  import { randomUUID } from "node:crypto";
7
- import { convertFinishReason } from "../../utils/finishReason.ts";
7
+ import { convertFinishReason, toClaudeMessageId } from "../../utils/finishReason.ts";
8
8
  import {
9
9
  isInternalReasoningPlaceholder,
10
10
  stripInternalReasoningPlaceholder,
@@ -178,6 +178,7 @@ export function openaiToClaudeResponse(chunk, state) {
178
178
  state.messageId =
179
179
  chunk.extend_fields?.requestId || chunk.extend_fields?.traceId || `msg_${Date.now()}`;
180
180
  }
181
+ state.messageId = toClaudeMessageId(state.messageId);
181
182
  state.model = chunk.model || "unknown";
182
183
  state.nextBlockIndex = 0;
183
184
  state._pendingXmlToolCalls = [];
@@ -192,7 +193,12 @@ export function openaiToClaudeResponse(chunk, state) {
192
193
  content: [],
193
194
  stop_reason: null,
194
195
  stop_sequence: null,
195
- usage: { input_tokens: 0, output_tokens: 0 },
196
+ usage: {
197
+ input_tokens: 0,
198
+ output_tokens: 0,
199
+ cache_creation_input_tokens: 0,
200
+ cache_read_input_tokens: 0,
201
+ },
196
202
  },
197
203
  });
198
204
  }
@@ -479,6 +485,9 @@ export function openaiToClaudeResponse(chunk, state) {
479
485
 
480
486
  // Mark finish for later usage injection in stream.js
481
487
  state.finishReason = overrideFinishReason;
488
+ if (typeof choice.stop_sequence === "string" && overrideFinishReason === "stop") {
489
+ state.stopSequence = choice.stop_sequence;
490
+ }
482
491
 
483
492
  // Real usage often arrives in a later usage-only chunk; wait for it (or the flush).
484
493
  if (state.usage) {
@@ -499,7 +508,10 @@ function emitClaudeFinal(state, results) {
499
508
  state.awaitingClaudeFinish = false;
500
509
  results.push({
501
510
  type: "message_delta",
502
- delta: { stop_reason: convertFinishReason(state.finishReason) },
511
+ delta:
512
+ typeof state.stopSequence === "string"
513
+ ? { stop_reason: "stop_sequence", stop_sequence: state.stopSequence }
514
+ : { stop_reason: convertFinishReason(state.finishReason), stop_sequence: null },
503
515
  usage: state.usage || { input_tokens: 0, output_tokens: 0 },
504
516
  });
505
517
  results.push({ type: "message_stop" });
@@ -80,6 +80,14 @@ export function normalizeOpenAICompatibleFinishReasonString(
80
80
  return typeof normalized === "string" && normalized ? normalized : fallback;
81
81
  }
82
82
 
83
+ /** Message ids of the Messages API start with `msg_`; other upstream ids are prefixed. */
84
+ export function toClaudeMessageId(id: unknown): string {
85
+ const raw = typeof id === "string" || typeof id === "number" ? String(id) : "";
86
+ if (raw.startsWith("msg_")) return raw;
87
+ const tail = raw.replace(/^chatcmpl-/, "").replace(/[^A-Za-z0-9_-]/g, "");
88
+ return `msg_${tail || Date.now()}`;
89
+ }
90
+
83
91
  // Map an OpenAI finish_reason to a Claude stop_reason. Shared by the streaming
84
92
  // and non-streaming OpenAI -> Claude paths.
85
93
  export function convertFinishReason(reason: unknown): string {
@@ -137,6 +137,7 @@ function buildOpenAISummary(events: StructuredSSEEvent[], fallbackModel?: string
137
137
  const keyAliases = new Map<string, string>();
138
138
  let unknownToolCallSeq = 0;
139
139
  let finishReason = "stop";
140
+ let stopSequence: string | null = null;
140
141
  let usage: JsonRecord | null = null;
141
142
 
142
143
  const getToolCallKey = (toolCall: JsonRecord) => {
@@ -222,6 +223,7 @@ function buildOpenAISummary(events: StructuredSSEEvent[], fallbackModel?: string
222
223
 
223
224
  if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
224
225
  finishReason = choice.finish_reason;
226
+ if (typeof choice.stop_sequence === "string") stopSequence = choice.stop_sequence;
225
227
  }
226
228
  if (chunk.usage && typeof chunk.usage === "object") {
227
229
  usage = { ...asRecord(chunk.usage) };
@@ -254,6 +256,7 @@ function buildOpenAISummary(events: StructuredSSEEvent[], fallbackModel?: string
254
256
  index: 0,
255
257
  message,
256
258
  finish_reason: finishReason,
259
+ ...(stopSequence !== null ? { stop_sequence: stopSequence } : {}),
257
260
  },
258
261
  ],
259
262
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trouteai",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "Self-hosted AI router and LLM gateway: one OpenAI- and Anthropic-compatible API for many AI providers, with API keys, fallback combos and usage-limit routing.",
5
5
  "keywords": [
6
6
  "ai",
@@ -1,4 +1,5 @@
1
1
  import { handleChat } from "@/sse/handlers/chat";
2
+ import { withAnthropicErrorShape } from "@/shared/utils/anthropicErrorShape";
2
3
  import { initTranslators } from "@trouteai/open-sse/translator/index.ts";
3
4
  import { withInjectionGuard } from "@/middleware/promptInjectionGuard";
4
5
  import { requireJsonContentType } from "@/shared/middleware/requireJsonContentType";
@@ -77,4 +78,9 @@ async function postHandler(request: any, context: any, preParsedBody: any = null
77
78
  return await handleChat(request, null, preParsedBody);
78
79
  }
79
80
 
80
- export const POST = withInjectionGuard(postHandler);
81
+ const guardedPost = withInjectionGuard(postHandler);
82
+
83
+ // Errors leave this route in the Messages API's own shape ({type: "error", error: {type, ...}}).
84
+ export async function POST(request: any, context: any) {
85
+ return withAnthropicErrorShape(await guardedPost(request, context));
86
+ }
@@ -1,3 +1,4 @@
1
+ import { anthropicErrorTypeForStatus } from "@/shared/utils/anthropicErrorShape";
1
2
  import {
2
3
  SESSION_MAX_AGE_SECONDS,
3
4
  SESSION_REVOKED_ERROR_CODE,
@@ -88,9 +89,14 @@ function rejectionResponse(
88
89
  classification: RouteClassification,
89
90
  requestId: string
90
91
  ): NextResponse {
92
+ // The Anthropic-format routes answer in the Messages API's error shape
93
+ // ({type: "error", error: {type, message}}); the other fields stay.
94
+ const anthropicRoute = /\/v1\/messages(\/|$)/.test(classification.normalizedPath);
91
95
  const response = NextResponse.json(
92
96
  {
97
+ ...(anthropicRoute ? { type: "error" } : {}),
93
98
  error: {
99
+ ...(anthropicRoute ? { type: anthropicErrorTypeForStatus(outcome.status) } : {}),
94
100
  code: outcome.code,
95
101
  message: outcome.message,
96
102
  correlation_id: requestId,
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Error answers of the Anthropic-format routes in the Messages API's own shape:
3
+ * { "type": "error", "error": { "type": "<error type>", "message": "..." } }
4
+ * Clients written for api.anthropic.com (SDKs, Claude Code) read `type` and `error.type`.
5
+ * Existing fields (code, correlation_id, upstream_details, ...) are kept; the message is not
6
+ * touched, because Claude Code matches on its wording.
7
+ */
8
+ const ANTHROPIC_ERROR_TYPES = new Set([
9
+ "invalid_request_error",
10
+ "authentication_error",
11
+ "billing_error",
12
+ "permission_error",
13
+ "not_found_error",
14
+ "request_too_large",
15
+ "rate_limit_error",
16
+ "api_error",
17
+ "timeout_error",
18
+ "overloaded_error",
19
+ ]);
20
+
21
+ export function anthropicErrorTypeForStatus(status: number): string {
22
+ if (status === 400 || status === 415 || status === 422) return "invalid_request_error";
23
+ if (status === 401) return "authentication_error";
24
+ if (status === 402) return "billing_error";
25
+ if (status === 403) return "permission_error";
26
+ if (status === 404) return "not_found_error";
27
+ if (status === 413) return "request_too_large";
28
+ if (status === 429) return "rate_limit_error";
29
+ if (status === 504 || status === 408) return "timeout_error";
30
+ if (status === 529 || status === 503) return "overloaded_error";
31
+ return status >= 500 ? "api_error" : "invalid_request_error";
32
+ }
33
+
34
+ /** A model id this router cannot route is "not found", as on the Messages API (404). */
35
+ const UNKNOWN_MODEL_PATTERN = /Unable to determine provider for model/i;
36
+
37
+ export function toAnthropicErrorBody(
38
+ status: number,
39
+ body: unknown
40
+ ): { status: number; body: Record<string, unknown> } | null {
41
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
42
+ const src = body as Record<string, unknown>;
43
+ const inner =
44
+ src.error && typeof src.error === "object" && !Array.isArray(src.error)
45
+ ? (src.error as Record<string, unknown>)
46
+ : null;
47
+ const message =
48
+ typeof inner?.message === "string"
49
+ ? inner.message
50
+ : typeof src.error === "string"
51
+ ? src.error
52
+ : typeof src.message === "string"
53
+ ? src.message
54
+ : "";
55
+ if (!message) return null;
56
+
57
+ let outStatus = status;
58
+ let type = typeof inner?.type === "string" ? inner.type : "";
59
+ if (status === 400 && UNKNOWN_MODEL_PATTERN.test(message)) {
60
+ outStatus = 404;
61
+ type = "not_found_error";
62
+ }
63
+ if (!ANTHROPIC_ERROR_TYPES.has(type)) type = anthropicErrorTypeForStatus(outStatus);
64
+
65
+ const { error: _error, message: _message, ...rest } = src;
66
+ return {
67
+ status: outStatus,
68
+ body: { type: "error", error: { ...(inner || {}), type, message }, ...rest },
69
+ };
70
+ }
71
+
72
+ /** Rewrites a JSON error Response; anything else (success, streams, non-JSON) passes untouched. */
73
+ export async function withAnthropicErrorShape(response: Response): Promise<Response> {
74
+ if (!response || response.status < 400) return response;
75
+ const contentType = response.headers.get("content-type") || "";
76
+ if (!contentType.includes("json")) return response;
77
+ let parsed: unknown;
78
+ try {
79
+ parsed = JSON.parse(await response.clone().text());
80
+ } catch {
81
+ return response;
82
+ }
83
+ if ((parsed as { type?: unknown })?.type === "error") return response;
84
+ const shaped = toAnthropicErrorBody(response.status, parsed);
85
+ if (!shaped) return response;
86
+ const headers = new Headers(response.headers);
87
+ headers.delete("content-length");
88
+ return new Response(JSON.stringify(shaped.body), { status: shaped.status, headers });
89
+ }
@@ -1,3 +0,0 @@
1
- module.exports=[290539,e=>{"use strict";var t=e.i(747909),r=e.i(174017),a=e.i(996250),n=e.i(759756),i=e.i(561916),s=e.i(174677),o=e.i(869741),l=e.i(316795),u=e.i(487718),c=e.i(995169),d=e.i(47587),p=e.i(666012),h=e.i(570101),f=e.i(626937),v=e.i(10372),w=e.i(193695),m=e.i(509580);e.i(52474);var g=e.i(600220);let R=new t.AppRouteRouteModule({definition:{kind:r.f.APP_ROUTE,page:"/api/v1/messages/route",pathname:"/api/v1/messages",filename:"route",bundlePath:""},distDir:".build/next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/v1/messages/route.ts",nextConfigOutput:"",userland:()=>e.r(809306),...{}}),{workAsyncStorage:y,workUnitAsyncStorage:x,serverHooks:C}=R;async function T(e,t,r){r.requestMeta&&(0,n.R)(e,r.requestMeta),R.isDev&&(0,n.i)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let a="/api/v1/messages/route";a=a.replace(/\/index$/,"")||"/";let{instrumentation:s}=await R.ensureInstrumentation(e,{deferSpans:!0});return R.traceRequest(e,{tracer:(0,i.v)(),spanName:`${e.method||"GET"} ${a}`,httpTarget:e.url,instrumentation:s},(n,i)=>E(e,t,r,a,!1,n,i))}async function E(e,t,a,y,x,C,T){let E=await R.prepare(e,t,{srcPage:y,multiZoneDraftMode:x});if(!E)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:P,deploymentId:b,params:A,nextConfig:O,parsedUrl:S,isDraftMode:U,prerenderManifest:k,routerServerContext:_,isOnDemandRevalidate:I,revalidateOnlyGenerated:M,resolvedPathname:q,clientReferenceManifest:N,serverActionsManifest:j,previewProps:H}=E,D=(0,o.f)(y),L=!!k.routes[q]&&(R.isDev||(0,m.f)(q,R.cacheOwner,k.routes[q])),G=!!(k.dynamicRoutes[D]||L),$=async()=>((null==_?void 0:_.render404)?await _.render404(e,t,S,!1):t.end("This page could not be found"),null);if(G&&!U){let e=k.dynamicRoutes[D];if(e&&!1===e.fallback&&!L){if(O.adapterPath)return await $();throw new w.NoFallbackError}}let F=null;!G||R.isDev||U||(F="/index"===(F=q)?"/":F),j&&N&&(0,s.f)({page:y,clientReferenceManifest:N,serverActionsManifest:j});let B=e.method||"GET",J=(0,i.v)(),K=!!(null==_?void 0:_.isWrappedByNextServer),W=!!(0,n.w)(e,"minimalMode"),Q=(0,n.w)(e,"incrementalCache")||await R.getIncrementalCache(e,O,H,k,W);null==Q||Q.resetRequestCache(),globalThis.__incrementalCache=Q;let V={params:A,previewProps:H,renderOpts:{experimental:{authInterrupts:!!O.experimental.authInterrupts,useCacheTimeout:O.experimental.useCacheTimeout,durableUseCacheEntries:!!O.experimental.durableUseCacheEntries},cacheComponents:!!O.cacheComponents,validationLevel:O.experimental.instantInsights.validationLevel,isDraftMode:U,incrementalCache:Q,hmrRefreshHash:(0,n.w)(e,"hmrRefreshHash"),cacheLifeProfiles:O.cacheLife,staticPageGenerationTimeout:O.staticPageGenerationTimeout,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0},sharedContext:{buildId:P,deploymentId:b}},z=new l.x(e),X=new l.e(t),Y=u.k.fromNodeNextRequest(z,(0,u.t)(t)),Z=async({previousCacheEntry:r})=>{try{if(!W&&I&&M&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=null===F?await R.handle(Y,V):await R.prerender(Y,V);e.fetchMetrics=V.renderOpts.fetchMetrics;let i=V.renderOpts.pendingWaitUntil;i&&a.waitUntil&&(a.waitUntil(i),i=void 0);let s=V.renderOpts.collectedTags;if(!G)return await (0,p.f)(z,X,n,i),null;{let e=await n.blob(),t=(0,h.S)(n.headers);s&&(t[v.M]=s),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==V.renderOpts.collectedRevalidate&&!(V.renderOpts.collectedRevalidate>=v.Q)&&V.renderOpts.collectedRevalidate,a=void 0===V.renderOpts.collectedExpire||V.renderOpts.collectedExpire>=v.Q?!1!==r&&r>0?O.expireTime:void 0:V.renderOpts.collectedExpire;return{value:{kind:g.x.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await R.onRequestError(e,t,{routerKind:"App Router",routePath:y,routeType:"route",revalidateReason:(0,d.f)({isStaticGeneration:null!==F,isOnDemandRevalidate:I})},!1,_),t}},ee=async n=>{try{var s,o;let n=await R.handleResponse({req:e,nextConfig:O,cacheKey:F,routeKind:r.f.APP_ROUTE,isFallback:!1,previewProps:H,prerenderManifest:k,isRoutePPREnabled:!1,isOnDemandRevalidate:I,revalidateOnlyGenerated:M,responseGenerator:Z,waitUntil:a.waitUntil,isMinimalMode:W});if(null!==n&&"error"in n)throw n.error;if(!G)return;if((null==n||null==(s=n.value)?void 0:s.kind)!==g.x.APP_ROUTE)throw Error(`Invariant: app-route received invalid cache entry ${null==n||null==(o=n.value)?void 0:o.kind}`);W||t.setHeader("x-nextjs-cache",I?"REVALIDATED":n.isMiss?"MISS":n.isStale?"STALE":"HIT"),U&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let i=(0,h.G)(n.value.headers);W&&G||i.delete(v.M),!n.cacheControl||t.getHeader("Cache-Control")||i.get("Cache-Control")||i.set("Cache-Control",(0,f.f)(n.cacheControl)),await (0,p.f)(z,X,new Response(n.value.body,{headers:i,status:n.value.status||200}));return}catch(r){if(r instanceof w.NoFallbackError||await R.onRequestError(e,r,{routerKind:"App Router",routePath:D,routeType:"route",revalidateReason:(0,d.f)({isStaticGeneration:null!==F,isOnDemandRevalidate:I})},!1,_),G)throw r;if(t.headersSent){if(n){let e=r instanceof Error?r:Error("Unknown app route error");n.recordException(e),n.setStatus({code:i.J.ERROR,message:e.message}),n.setAttribute("error.type",e.name)}t.writableEnded||t.destroyed||t.end()}else await (0,p.f)(z,X,new Response(null,{status:500}));return}finally{(()=>{if(!n)return;let e=t.statusCode;n.setAttributes({"http.status_code":e,"next.rsc":!1}),e&&e>=500&&(n.setStatus({code:i.J.ERROR}),n.setAttribute("error.type",e.toString()));let r=J.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==c.q.handleRequest)return console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route")||D,s=`${B} ${a}`;n.setAttributes({"next.route":a,"http.route":a,"next.span_name":s}),n.updateName(s),T&&T!==n&&(T.setAttribute("http.route",a),T.updateName(s))})()}};K||void 0===e.url||null==C||C.setAttribute("http.target",e.url),await ee(C)}e.s(["handler",0,T,"patchFetch",0,function(){return(0,a.f)({workAsyncStorage:y,workUnitAsyncStorage:x})},"routeModule",0,R,"serverHooks",0,C,"workAsyncStorage",0,y,"workUnitAsyncStorage",0,x])},809306,e=>e.a(async(t,r)=>{try{var a=e.i(10641),n=e.i(352812),i=e.i(111294),s=e.i(676671),o=e.i(422520),l=e.i(942756),u=t([a,n,i,l]);[a,n,i,l]=u.then?(await u)():u;let h=!1;async function c(){h||(await (0,n.J)(),h=!0,console.log("[SSE] Translators initialized for /v1/messages"))}async function d(){return new Response(null,{headers:{"Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"*"}})}async function p(e,t,r=null){let n=(0,s.f)(e);if(n)return n;if(await c(),String(e.headers?.get?.("accept")||"").toLowerCase().includes("text/event-stream")){let t;try{let a=r??await e.clone().json().catch(()=>null);t=a?.model}catch{}return await (0,o.a)((0,a.f)(e,null,r),{signal:e.signal,thresholdMs:(0,l.f)(t),keepaliveFrame:o.n})}return await (0,a.f)(e,null,r)}let f=(0,i.u)(p);e.s(["OPTIONS",0,d,"POST",0,f]),r()}catch(e){r(e)}},!1),676671,e=>{"use strict";var t=e.i(224010);e.s(["f",0,function(e){let r=e.method.toUpperCase();return"POST"!==r&&"PUT"!==r&&"PATCH"!==r||(e.headers.get("content-type")??"").trim().toLowerCase().startsWith("application/json")?null:new Response(JSON.stringify({error:{message:"Content-Type must be application/json",type:"invalid_request_error",code:"unsupported_media_type"}}),{status:415,headers:{...t.g,"Content-Type":"application/json"}})}])}];
2
-
3
- //# sourceMappingURL=_0ox6qf339bblb._.js.map