diff --git a/docs/architecture/tla/BedrockErgo.CapabilityOnly.cfg b/docs/architecture/tla/BedrockErgo.CapabilityOnly.cfg new file mode 100644 index 0000000000..ca358fbbc7 --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.CapabilityOnly.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = FALSE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.ConstructorGuard.cfg b/docs/architecture/tla/BedrockErgo.ConstructorGuard.cfg new file mode 100644 index 0000000000..9e30ccef3b --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.ConstructorGuard.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = TRUE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.NoCacheMetadata.cfg b/docs/architecture/tla/BedrockErgo.NoCacheMetadata.cfg new file mode 100644 index 0000000000..65874bafce --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.NoCacheMetadata.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = FALSE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.NoConsent.cfg b/docs/architecture/tla/BedrockErgo.NoConsent.cfg new file mode 100644 index 0000000000..dbcf3f0761 --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.NoConsent.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = FALSE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.NoRequestGuard.cfg b/docs/architecture/tla/BedrockErgo.NoRequestGuard.cfg new file mode 100644 index 0000000000..7641196939 --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.NoRequestGuard.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = FALSE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.NoSaveGuard.cfg b/docs/architecture/tla/BedrockErgo.NoSaveGuard.cfg new file mode 100644 index 0000000000..55f3de399e --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.NoSaveGuard.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = FALSE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.OverrideArn.cfg b/docs/architecture/tla/BedrockErgo.OverrideArn.cfg new file mode 100644 index 0000000000..65c1866f7d --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.OverrideArn.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = FALSE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.RegistryPrices.cfg b/docs/architecture/tla/BedrockErgo.RegistryPrices.cfg new file mode 100644 index 0000000000..2adffa8eae --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.RegistryPrices.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = FALSE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.SelectedRegion.cfg b/docs/architecture/tla/BedrockErgo.SelectedRegion.cfg new file mode 100644 index 0000000000..87996f4435 --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.SelectedRegion.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = FALSE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.UnfixedRouting.cfg b/docs/architecture/tla/BedrockErgo.UnfixedRouting.cfg new file mode 100644 index 0000000000..e54f125475 --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.UnfixedRouting.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = FALSE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.cfg b/docs/architecture/tla/BedrockErgo.cfg new file mode 100644 index 0000000000..d8f1ce32bb --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.cfg @@ -0,0 +1,12 @@ +CONSTANT RoutingFixed = TRUE +CONSTANT ConsentGuard = TRUE +CONSTANT ConstructorGuard = FALSE +CONSTANT SaveGuard = TRUE +CONSTANT RequestGuard = TRUE +CONSTANT SaveRegionFixed = TRUE +CONSTANT SharedPrices = TRUE +CONSTANT PreserveArn = TRUE +CONSTANT GlobalControlFixed = TRUE +CONSTANT CacheMetadataFixed = TRUE +SPECIFICATION Spec +INVARIANT SupportedProfile GlobalConsent ConstructorSafe SaveRejectsInvalid SaveRequestAgree PriceAgreement ExplicitRoutePreserved OpaqueProfileUnknown ExpectedPrices GlobalControlChangesRoute RegularGlobalControlPreserved SystemCacheAgreement DisabledCacheSilent MessageCacheAbsent CacheMetadataReady diff --git a/docs/architecture/tla/BedrockErgo.tla b/docs/architecture/tla/BedrockErgo.tla new file mode 100644 index 0000000000..fa78bc7d45 --- /dev/null +++ b/docs/architecture/tla/BedrockErgo.tla @@ -0,0 +1,132 @@ +---- MODULE BedrockErgo ---- +\* Sources: inference settings, validateApiConfiguration, and validateApiConfigurationExcludingModelErrors. +\* Sinks: handler construction, Save, createMessage, and completePrompt. Both request methods share one model entry. +\* Failures: unsupported routing, Global without consent, constructor rejection, and saving invalid settings. +\* Invariants: SupportedProfile, GlobalConsent, ConstructorSafe, and SaveRejectsInvalid. +\* Scope: aliases, explicit profiles, and opaque ARNs. ARN parsing is an input oracle. +\* AWS acceptance is an input: US and Global profiles are supported. Transport is outside this model. +\* Review: PR #2815 supplied findings. Covered: 2; added: 2; gap: 14. +\* Added: SaveRequestAgree and PriceAgreement. Covered: findings 2 and 7, alias routing and explicit profile consent. +\* Gaps: findings 4-6 and 8-18 need code tests or review, including opaque prices and telemetry. +\* The review preceded these invariants. The blind-first step was not possible. +\* Expected: selected regions cause Save disagreement. Registry prices cause reader disagreement. +\* Property test: validate.spec.ts ARN matrix and useSelectedModel.spec.ts Ergo price matrix. +\* Gate: check.sh BedrockErgo and focused provider, validation, and hook tests. +\* Result: fixed config passes. Each defect config fails. Region and price replays fail on the original code. +\* Findings: the review defects recur. No new defect or false alarm was found. Cost: about 20 minutes. +\* Refactor expectation: one resolver preserves routing, rejection, and prices for each reader. +\* Refactor failures: changing explicit routes or treating opaque estimates as a known profile. +\* Refactor invariants: ExplicitRoutePreserved, OpaqueProfileUnknown, and ExpectedPrices. +\* Refactor property test: bedrock-ergo.test.ts route and price matrices. +\* Refactor result: fixed config passes. All eight defect configs fail. No new defect was found. +\* Replay: overriding explicit ARNs fails 10 resolver cases. Ignoring ARN regions fails 35 cases. +\* Simplification: merge non-US classes. States fall from 324 to 216. Every defect witness remains. +\* Refactor cost: about ten minutes. This model does not prove the code correct. +\* Review round 2: PR #2815 summary. Covered: 1 (finding 6, SaveRequestAgree for opaque ARNs). +\* Added: 1 (finding 1, GlobalControlChangesRoute). Gaps: 6 (findings 2-5, 7-8). +\* Gaps need code, error text, test, render, or other-model checks. The model does not inspect code. +\* Expected: route validity and opaque Save acceptance remain unchanged. No new routing defect is expected. +\* Round 2 result: fixed config passes (216 states). All nine defect configs fail. No new defect was found. +\* Real-code checks: both Save validators accept both opaque ARN classes. Both request guards reject invalid aliases. +\* Visibility source: Bedrock.supportsGlobalInference. Sink: request routing through resolveBedrockErgoRoute. +\* Visibility failure: a custom ARN has a Global control that cannot change its route. +\* Expected: the old capability rule exposes a control for fixed ARN routes. +\* Visibility oracle: routeKind and capability. The model does not parse an ARN. +\* Invariants: GlobalControlChangesRoute and RegularGlobalControlPreserved. Property test: Bedrock.spec.tsx visibility matrix. +\* Replay: the old component fails four visibility rows. The fixed component passes all five ARN rows. +\* Result: the capability-only defect violates GlobalControlChangesRoute. No new defect or false alarm was found. +\* Round 2 cost: about ten minutes. Derive visibility without new state variables. +\* Simplification source: getModel settings. Sinks: cached and uncached model returns, request guards, and prices. +\* Failure: one model reader resolves a different route or loses validity when the cache path changes. +\* Expectation: one local route preserves existing invariants for canonical settings. No new defect is expected. +\* Covered: SaveRequestAgree, ExplicitRoutePreserved, OpaqueProfileUnknown, and ExpectedPrices. +\* The cache selection is outside this model. Check it with the provider route matrix on the real code. +\* Simplification result: fixed config passes (216 states). All nine defect configs fail. No new defect was found. +\* Real-code checks: 360 provider tests and 67 resolver tests pass. Type checking accepts the return without an assertion. +\* Cost: about three minutes. No new state variable or invariant was needed. +\* Review round 3: PR #2815 locale key and label-source findings. Covered: 0; added: 0; gap: 2. +\* Gap: the route model does not read locale catalogs or comments. Use the translation and interpolation checks. +\* Expected: missing keys fail the catalog check. Routing states remain unchanged. +\* Result: catalog check reproduces all 17 missing keys, then passes. Both placeholders exist in all 18 locales. +\* Result: interpolation check and lint pass. TLC passes 216 states; all nine defect configs fail. +\* Cost: about four minutes. No routing defect was found. No model state or invariant was added. +\* Review round 4: local search-review thread, head 806e49d443. Covered: 0; added: 1; gap: 1. +\* Added: enabled cache metadata reaches a system checkpoint. Gap: the size advisory is outside this model. +\* Sources: bedrockModels and awsUsePromptCache. Sinks: supportsAwsPromptCache and ConverseStreamCommand. +\* Failures: missing enabled checkpoints, disabled checkpoints, or checkpoints in unsupported message fields. +\* Expected: absent Ergo cache fields violate SystemCacheAgreement. No new routing defect is expected. +\* The finding was read before this extension. This is a review ratchet, not a blind first invariant. +\* Cache metadata is an input oracle. Prompt sizes are below, at, or above the published minimum. +\* Property test: bedrock.spec.ts Ergo cache matrix checks real request payloads across routes and settings. +\* Replay: missing fields fail SystemCacheAgreement and all 36 initial request-matrix rows on the old code. +\* Result: fixed config passes (216 states). All ten defect configs fail. No new defect or false alarm was found. +\* Real-code checks: 72 cache rows, 417 provider tests, and 67 resolver tests pass. Type checking passes. +\* Simplification: quantify cache inputs without new state variables. The state count remains 216. +\* Cost: about ten minutes. The model does not prove the code correct. +EXTENDS TLC, Naturals +CONSTANT RoutingFixed, ConsentGuard, ConstructorGuard, SaveGuard, RequestGuard, SaveRegionFixed, SharedPrices, PreserveArn, GlobalControlFixed, CacheMetadataFixed +VARIABLE input +Inputs == {i \in [region : {"us", "nonUs"}, global : BOOLEAN, cross : BOOLEAN, + arnRegion : {"none", "us", "nonUs"}, kind : {"alias", "profile", "opaque"}, + namedProfile : {"us", "global", "unknown"}, entry : {"construct", "save", "request"}] : + (i.kind = "profile" /\ i.namedProfile # "unknown" /\ i.arnRegion # "none") \/ + (i.kind = "opaque" /\ i.namedProfile = "unknown" /\ i.arnRegion # "none") \/ + (i.kind = "alias" /\ i.namedProfile = "unknown")} +Init == input \in Inputs +Next == UNCHANGED input +Spec == Init /\ [][Next]_input +EffectiveRegion == IF input.arnRegion = "none" THEN input.region ELSE input.arnRegion +ReaderRegion == IF input.entry = "save" /\ ~SaveRegionFixed THEN input.region ELSE EffectiveRegion +UsProfileAllowed == input.cross /\ ReaderRegion = "us" +ExpectedProfile == IF input.kind = "profile" THEN input.namedProfile + ELSE IF input.kind = "opaque" THEN "unknown" + ELSE IF input.global THEN "global" + ELSE IF input.cross /\ EffectiveRegion = "us" THEN "us" ELSE "reject" +Profile == IF PreserveArn /\ input.kind # "alias" THEN + IF input.kind = "profile" THEN input.namedProfile ELSE "unknown" + ELSE IF RoutingFixed THEN + IF input.global THEN "global" + ELSE IF UsProfileAllowed THEN "us" + ELSE IF ConsentGuard THEN "reject" ELSE "global" + ELSE IF input.cross THEN input.region ELSE "bare" +PriceFor(profile) == IF profile = "us" \/ (profile = "unknown" /\ EffectiveRegion = "us") + THEN "us" ELSE "global" +HandlerPrice == PriceFor(Profile) +ViewPrice == IF SharedPrices THEN PriceFor(Profile) ELSE "global" +Outcome == IF input.entry = "construct" THEN + IF ConstructorGuard /\ Profile = "reject" THEN "error" ELSE "ready" + ELSE IF input.entry = "save" /\ ~SaveGuard THEN "saved" + ELSE IF input.entry = "request" /\ ~RequestGuard /\ Profile = "reject" THEN "bare" + ELSE Profile +SupportedProfile == input.entry = "request" => Outcome \in {"us", "global", "reject", "unknown"} +GlobalConsent == input.kind = "alias" /\ Outcome = "global" => input.global +ConstructorSafe == input.entry = "construct" => Outcome = "ready" +SaveRejectsInvalid == input.entry = "save" /\ input.kind = "alias" /\ ~input.global /\ ~UsProfileAllowed + => Outcome = "reject" + +SaveRequestAgree == input.entry = "save" => Outcome = ExpectedProfile +PriceAgreement == ViewPrice = HandlerPrice +ExplicitRoutePreserved == input.kind = "profile" /\ input.entry = "request" => Outcome = input.namedProfile +OpaqueProfileUnknown == input.kind = "opaque" /\ input.entry = "request" => Outcome = "unknown" +ExpectedPrice == IF ExpectedProfile = "us" \/ (input.kind = "opaque" /\ EffectiveRegion = "us") + THEN "us" ELSE "global" +ExpectedPrices == HandlerPrice = ExpectedPrice /\ ViewPrice = ExpectedPrice +GlobalControls == {i \in [custom : BOOLEAN, routeKind : {"alias", "profile", "opaque", "other"}, + capability : BOOLEAN] : i.routeKind = "other" \/ i.capability} +Visible(i) == IF i.custom /\ GlobalControlFixed THEN i.routeKind = "alias" ELSE i.capability +GlobalControlChangesRoute == input.entry = "save" => \A i \in GlobalControls : i.custom => (Visible(i) = (i.routeKind = "alias")) +RegularGlobalControlPreserved == input.entry = "save" => \A i \in GlobalControls : ~i.custom => (Visible(i) = i.capability) +CacheInputs == [setting : {"unset", "on", "off"}, tokens : {1023, 1024, 2048}] +CacheEnabled(i) == i.setting # "off" +CacheFields == IF CacheMetadataFixed THEN {"system", "tools"} ELSE {} +CacheLimit == IF CacheMetadataFixed THEN 4 ELSE 0 +CacheMinimum == IF CacheMetadataFixed THEN 1024 ELSE 50 +SystemCheckpoint(i) == CacheEnabled(i) /\ "system" \in CacheFields /\ CacheLimit > 0 + /\ i.tokens >= CacheMinimum +MessageCheckpoint(i) == CacheEnabled(i) /\ "messages" \in CacheFields +SystemCacheAgreement == input.entry = "request" => \A i \in CacheInputs : + SystemCheckpoint(i) = (CacheEnabled(i) /\ i.tokens >= 1024) +DisabledCacheSilent == \A i \in CacheInputs : ~CacheEnabled(i) => ~SystemCheckpoint(i) +MessageCacheAbsent == \A i \in CacheInputs : ~MessageCheckpoint(i) +CacheMetadataReady == input.entry = "request" => CacheFields = {"system", "tools"} /\ CacheLimit = 4 /\ CacheMinimum = 1024 +==== diff --git a/packages/types/src/__tests__/bedrock-ergo.test.ts b/packages/types/src/__tests__/bedrock-ergo.test.ts new file mode 100644 index 0000000000..034bfc0602 --- /dev/null +++ b/packages/types/src/__tests__/bedrock-ergo.test.ts @@ -0,0 +1,82 @@ +import { bedrockModels, getBedrockModelInfoWithPrices, resolveBedrockErgoRoute } from "../providers/bedrock.js" + +const ergoId = "amazon.ergo-1.0" +const info = bedrockModels[ergoId] +const regions = ["us-east-1", "eu-west-1", "us-gov-west-1"] as const +const toggles = [undefined, false, true] as const +const aliases = regions.flatMap((region) => + [false, true].flatMap((arn) => + toggles.flatMap((global) => toggles.map((cross) => ({ region, arn, global, cross }))), + ), +) + +describe("Ergo route and price contract", () => { + it.each(aliases)("resolves aliases consistently for %j", ({ region, arn, global, cross }) => { + // Expected profiles use explicit regions, separate from the production prefix lookup. + const profile = global ? "global" : cross && region === "us-east-1" ? "us" : undefined + const route = resolveBedrockErgoRoute({ + apiModelId: arn ? "custom-arn" : ergoId, + awsCustomArn: arn ? `arn:aws:bedrock:${region}::foundation-model/${ergoId}` : undefined, + awsRegion: arn ? (region === "us-east-1" ? "eu-west-1" : "us-east-1") : region, + awsUseGlobalInference: global, + awsUseCrossRegionInference: cross, + awsCustomArnBaseModelId: "other", + }) + expect(route).toEqual({ + kind: "alias", + region, + profile, + valid: !!profile, + requestId: profile ? `${profile}.${ergoId}` : ergoId, + }) + expect(getBedrockModelInfoWithPrices(info, route)).toMatchObject( + profile === "us" + ? { inputPrice: 1.1, outputPrice: 3.3, cacheReadsPrice: 0.033, cacheWritesPrice: 1.375 } + : info, + ) + }) + + it.each(["global", "us"].flatMap((profile) => [false, true].map((enabled) => ({ profile, enabled }))))( + "preserves explicit profiles for %j", + ({ profile, enabled }) => { + const arn = `arn:aws:bedrock:eu-west-1:123456789012:inference-profile/${profile}.${ergoId}` + const route = resolveBedrockErgoRoute({ + awsCustomArn: arn, + awsRegion: "us-east-1", + awsUseGlobalInference: enabled, + awsUseCrossRegionInference: enabled, + }) + expect(route).toEqual({ kind: "profile", region: "eu-west-1", profile, valid: true, requestId: arn }) + expect(getBedrockModelInfoWithPrices(info, route).inputPrice).toBe(profile === "us" ? 1.1 : 1) + }, + ) + + it.each( + ["application-inference-profile", "prompt-router"].flatMap((resource) => + regions.map((region) => ({ resource, region })), + ), + )("keeps opaque routing separate from estimates for %j", ({ resource, region }) => { + const arn = `arn:aws:bedrock:${region}:123456789012:${resource}/example` + const route = resolveBedrockErgoRoute({ + awsCustomArn: arn, + awsCustomArnBaseModelId: ergoId, + awsRegion: "eu-west-1", + awsUseGlobalInference: true, + }) + expect(route).toEqual({ kind: "opaque", region, profile: undefined, valid: true, requestId: arn }) + expect(getBedrockModelInfoWithPrices(info, route).inputPrice).toBe(region === "us-east-1" ? 1.1 : 1) + }) + + it.each([ + { apiModelId: "anthropic.claude-v2" }, + { + awsCustomArn: `arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.${ergoId}`, + awsCustomArnBaseModelId: "other", + }, + { awsCustomArn: "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/example" }, + ])("leaves other models and unknown metadata unchanged for %j", (options) => { + const route = resolveBedrockErgoRoute(options) + expect(route).toBeUndefined() + expect(getBedrockModelInfoWithPrices(info, route)).toBe(info) + }) +}) diff --git a/packages/types/src/providers/bedrock.ts b/packages/types/src/providers/bedrock.ts index e31bce6a44..426aa39bc8 100644 --- a/packages/types/src/providers/bedrock.ts +++ b/packages/types/src/providers/bedrock.ts @@ -17,6 +17,70 @@ export const bedrockDefaultModelId: BedrockModelId = "anthropic.claude-sonnet-4- export const bedrockDefaultPromptRouterModelId: BedrockModelId = "anthropic.claude-3-sonnet-20240229-v1:0" +// US inference prices per million tokens. The registry entry uses Global prices. +export const BEDROCK_ERGO_US_PRICES = { + inputPrice: 1.1, + outputPrice: 3.3, + cacheReadsPrice: 0.033, + cacheWritesPrice: 1.375, +} satisfies Partial + +export function getBedrockInferenceRegionPrefix(region?: string): string | undefined { + return AWS_INFERENCE_PROFILE_MAPPING.find(([pattern]) => region?.startsWith(pattern))?.[1] +} + +export type BedrockErgoRoute = { + kind: "alias" | "profile" | "opaque" + region: string | undefined + requestId: string + profile: "global" | "us" | undefined + valid: boolean +} + +// Save, requests, and prices use the same route. An opaque ARN does not identify its target profile. +export function resolveBedrockErgoRoute(options: { + apiModelId?: string + awsCustomArn?: string + awsCustomArnBaseModelId?: string + awsRegion?: string + awsUseGlobalInference?: boolean + awsUseCrossRegionInference?: boolean +}): BedrockErgoRoute | undefined { + const arn = options.awsCustomArn + const modelId = arn ? resolveBedrockCustomArnBaseModelId(arn, options.awsCustomArnBaseModelId) : options.apiModelId + if (modelId !== "amazon.ergo-1.0") return undefined + + const parts = arn?.split(":") + const region = parts?.[3] || options.awsRegion + if (!arn || isBedrockFoundationModelArn(arn)) { + const profile = options.awsUseGlobalInference + ? "global" + : options.awsUseCrossRegionInference && getBedrockInferenceRegionPrefix(region) === "us." + ? "us" + : undefined + return { + kind: "alias", + region, + profile, + valid: !!profile, + requestId: profile ? `${profile}.amazon.ergo-1.0` : "amazon.ergo-1.0", + } + } + + const [resourceType, resourceId] = parts?.slice(5).join(":").split("/") ?? [] + const kind = resourceType === "inference-profile" ? "profile" : "opaque" + const prefix = kind === "profile" ? resourceId?.split(".")[0] : undefined + const profile = prefix === "us" || prefix === "global" ? prefix : undefined + return { kind, region, profile, valid: true, requestId: arn } +} + +// Regional prices are estimates only when an opaque ARN does not expose its target profile. +export function getBedrockModelInfoWithPrices(info: ModelInfo, route?: BedrockErgoRoute): ModelInfo { + const useUsPrices = + route?.profile === "us" || (route?.kind === "opaque" && getBedrockInferenceRegionPrefix(route.region) === "us.") + return useUsPrices ? { ...info, ...BEDROCK_ERGO_US_PRICES } : info +} + // March, 12 2025 - updated prices to match US-West-2 list price shown at // https://aws.amazon.com/bedrock/pricing, including older models that are part // of the default prompt routers AWS enabled for GA of the promot router @@ -167,6 +231,21 @@ export const bedrockModels = { maxCachePoints: 1, cachableFields: ["system"], }, + "amazon.ergo-1.0": { + maxTokens: 131_072, + contextWindow: 1_000_000, + supportsImages: false, + supportsPromptCache: true, + inputPrice: 1, + outputPrice: 3, + cacheReadsPrice: 0.03, + cacheWritesPrice: 1.25, + // https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + minTokensPerCachePoint: 1024, + maxCachePoints: 4, + cachableFields: ["system", "tools"], + description: "Amazon Ergo 1.0", + }, "anthropic.claude-sonnet-4-20250514-v1:0": { maxTokens: 8192, contextWindow: 200_000, @@ -774,7 +853,8 @@ export const BEDROCK_THINKING_DISABLE_MODEL_IDS = [ ] as const // Amazon Bedrock models that support Global Inference profiles -// As of Nov 2025, AWS supports Global Inference for: +// AWS supports Global Inference for: +// - Amazon Ergo 1.0 // - Claude Sonnet 4 // - Claude Sonnet 4.5 // - Claude Sonnet 4.6 @@ -789,6 +869,7 @@ export const BEDROCK_THINKING_DISABLE_MODEL_IDS = [ // - Claude Haiku 5.5 // - Claude Fable 5 and 5.1 (cross-region inference only — can only be used through an inference profile) export const BEDROCK_GLOBAL_INFERENCE_MODEL_IDS = [ + "amazon.ergo-1.0", "anthropic.claude-sonnet-4-20250514-v1:0", "anthropic.claude-sonnet-4-5-20250929-v1:0", "anthropic.claude-sonnet-4-6", diff --git a/src/api/providers/__tests__/bedrock-inference-profiles.spec.ts b/src/api/providers/__tests__/bedrock-inference-profiles.spec.ts index 4704cbc7d8..0276edd091 100644 --- a/src/api/providers/__tests__/bedrock-inference-profiles.spec.ts +++ b/src/api/providers/__tests__/bedrock-inference-profiles.spec.ts @@ -1,6 +1,6 @@ // npx vitest run src/api/providers/__tests__/bedrock-inference-profiles.spec.ts -import { AWS_INFERENCE_PROFILE_MAPPING } from "@roo-code/types" +import { AWS_INFERENCE_PROFILE_MAPPING, getBedrockInferenceRegionPrefix } from "@roo-code/types" import { AwsBedrockHandler } from "../bedrock" import { ApiHandlerOptions } from "../../../shared/api" @@ -58,70 +58,33 @@ describe("Amazon Bedrock Inference Profiles", () => { }) }) - describe("getPrefixForRegion function", () => { - it("should return correct prefix for US government regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("us-gov-east-1")).toBe("ug.") - expect((handler as any).constructor.getPrefixForRegion("us-gov-west-1")).toBe("ug.") - }) - - it("should return correct prefix for US commercial regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("us-east-1")).toBe("us.") - expect((handler as any).constructor.getPrefixForRegion("us-west-1")).toBe("us.") - expect((handler as any).constructor.getPrefixForRegion("us-west-2")).toBe("us.") - }) - - it("should return correct prefix for European regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("eu-west-1")).toBe("eu.") - expect((handler as any).constructor.getPrefixForRegion("eu-central-1")).toBe("eu.") - expect((handler as any).constructor.getPrefixForRegion("eu-north-1")).toBe("eu.") - expect((handler as any).constructor.getPrefixForRegion("eu-south-1")).toBe("eu.") - }) - - it("should return correct prefix for Asia Pacific regions", () => { - const handler = createHandler() - // Australia regions (Sydney and Melbourne) get au. prefix - expect((handler as any).constructor.getPrefixForRegion("ap-southeast-2")).toBe("au.") - expect((handler as any).constructor.getPrefixForRegion("ap-southeast-4")).toBe("au.") - // Japan regions (Tokyo and Osaka) get jp. prefix - expect((handler as any).constructor.getPrefixForRegion("ap-northeast-1")).toBe("jp.") - expect((handler as any).constructor.getPrefixForRegion("ap-northeast-3")).toBe("jp.") - // Other APAC regions get apac. prefix - expect((handler as any).constructor.getPrefixForRegion("ap-southeast-1")).toBe("apac.") - expect((handler as any).constructor.getPrefixForRegion("ap-south-1")).toBe("apac.") - expect((handler as any).constructor.getPrefixForRegion("ap-east-1")).toBe("apac.") - }) - - it("should return correct prefix for Canada regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("ca-central-1")).toBe("ca.") - expect((handler as any).constructor.getPrefixForRegion("ca-west-1")).toBe("ca.") - }) - - it("should return correct prefix for South America regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("sa-east-1")).toBe("sa.") - }) - - it("should return undefined for unsupported regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("af-south-1")).toBeUndefined() - expect((handler as any).constructor.getPrefixForRegion("me-south-1")).toBeUndefined() - expect((handler as any).constructor.getPrefixForRegion("cn-north-1")).toBeUndefined() - expect((handler as any).constructor.getPrefixForRegion("invalid-region")).toBeUndefined() - }) - - it("should prioritize longer patterns over shorter ones", () => { - const handler = createHandler() - // us-gov- should be matched before us- - expect((handler as any).constructor.getPrefixForRegion("us-gov-east-1")).toBe("ug.") - expect((handler as any).constructor.getPrefixForRegion("us-gov-west-1")).toBe("ug.") - - // Regular us- regions should still work - expect((handler as any).constructor.getPrefixForRegion("us-east-1")).toBe("us.") - expect((handler as any).constructor.getPrefixForRegion("us-west-2")).toBe("us.") + describe("getBedrockInferenceRegionPrefix", () => { + it.each([ + ["us-gov-east-1", "ug."], + ["us-gov-west-1", "ug."], + ["us-east-1", "us."], + ["us-west-1", "us."], + ["us-west-2", "us."], + ["eu-west-1", "eu."], + ["eu-central-1", "eu."], + ["eu-north-1", "eu."], + ["eu-south-1", "eu."], + ["ap-southeast-2", "au."], + ["ap-southeast-4", "au."], + ["ap-northeast-1", "jp."], + ["ap-northeast-3", "jp."], + ["ap-southeast-1", "apac."], + ["ap-south-1", "apac."], + ["ap-east-1", "apac."], + ["ca-central-1", "ca."], + ["ca-west-1", "ca."], + ["sa-east-1", "sa."], + ["af-south-1", undefined], + ["me-south-1", undefined], + ["cn-north-1", undefined], + ["invalid-region", undefined], + ])("maps %s to %s", (region, prefix) => { + expect(getBedrockInferenceRegionPrefix(region)).toBe(prefix) }) }) diff --git a/src/api/providers/__tests__/bedrock.spec.ts b/src/api/providers/__tests__/bedrock.spec.ts index bfe60ee20e..f59d1cbf1a 100644 --- a/src/api/providers/__tests__/bedrock.spec.ts +++ b/src/api/providers/__tests__/bedrock.spec.ts @@ -272,6 +272,162 @@ describe("AwsBedrockHandler", () => { expect(modelInfo.info).toBeDefined() expect(modelInfo.info.maxTokens).toBe(4096) }) + + it("uses the published Ergo Global registry values", () => { + expect(bedrockModels["amazon.ergo-1.0"]).toMatchObject({ + contextWindow: 1_000_000, + maxTokens: 131_072, + supportsImages: false, + supportsPromptCache: true, + inputPrice: 1, + outputPrice: 3, + cacheReadsPrice: 0.03, + cacheWritesPrice: 1.25, + }) + }) + it.each(["foundation-model", "inference-profile", "application-inference-profile", "prompt-router"])( + "keeps non-Ergo %s routing with both options on", + async (resource) => { + const id = "anthropic.claude-3-5-sonnet-20241022-v2:0" + const arn = `arn:aws:bedrock:us-east-1:123456789012:${resource}/${id}` + const provider = new AwsBedrockHandler({ + awsCustomArn: arn, + awsRegion: "us-east-1", + awsUseGlobalInference: true, + awsUseCrossRegionInference: true, + }) + await provider.createMessage("System", [{ role: "user", content: "Hello" }]).next() + expect(mockConverseStreamCommand.mock.calls[0][0].modelId).toBe( + resource === "foundation-model" ? id : arn, + ) + }, + ) + + it.each( + ["application-inference-profile", "prompt-router"].flatMap((resource) => + ["us-east-1", "eu-west-1"].map((awsRegion) => ({ resource, awsRegion })), + ), + )("estimates opaque Ergo profile prices for %j", async ({ resource, awsRegion }) => { + const arn = `arn:aws:bedrock:${awsRegion}:123456789012:${resource}/example` + const provider = new AwsBedrockHandler({ + awsCustomArn: arn, + awsCustomArnBaseModelId: "amazon.ergo-1.0", + awsRegion, + }) + await provider.createMessage("System", [{ role: "user", content: "Hello" }]).next() + expect(mockConverseStreamCommand.mock.calls[0][0].modelId).toBe(arn) + expect(provider.getModel().info).toMatchObject( + awsRegion === "us-east-1" ? { inputPrice: 1.1, outputPrice: 3.3 } : { inputPrice: 1, outputPrice: 3 }, + ) + }) + + it.each(["global", "us"].flatMap((profile) => [false, true].map((enabled) => ({ profile, enabled }))))( + "preserves the Ergo inference-profile ARN for %j", + async ({ profile, enabled }) => { + const arn = `arn:aws:bedrock:us-east-1:123456789012:inference-profile/${profile}.amazon.ergo-1.0` + const ergoHandler = new AwsBedrockHandler({ + awsCustomArn: arn, + awsUseGlobalInference: enabled, + awsUseCrossRegionInference: enabled, + awsRegion: "us-east-1", + awsAccessKey: "test-access-key", + awsSecretKey: "test-secret-key", + }) + await ergoHandler.createMessage("System prompt", [{ role: "user", content: "Hello" }]).next() + expect(mockConverseStreamCommand.mock.calls[0][0].modelId).toBe(arn) + expect(ergoHandler.getModel().info.contextWindow).toBe(1_000_000) + expect(ergoHandler.getModel().info).toMatchObject( + profile === "us" + ? { + inputPrice: 1.1, + outputPrice: 3.3, + cacheReadsPrice: 0.033, + cacheWritesPrice: 1.375, + } + : { inputPrice: 1, outputPrice: 3, cacheReadsPrice: 0.03, cacheWritesPrice: 1.25 }, + ) + }, + ) + + it.each( + [ + "us-east-1", + "us-west-2", + "us-gov-west-1", + "eu-west-1", + "ap-southeast-2", + "ap-northeast-1", + "ca-central-1", + ].flatMap((awsRegion) => + [undefined, false, true].flatMap((awsUseGlobalInference) => + [undefined, false, true].flatMap((awsUseCrossRegionInference) => + [undefined, `arn:aws:bedrock:${awsRegion}::foundation-model/amazon.ergo-1.0`].map( + (awsCustomArn) => ({ + awsCustomArn, + awsRegion, + awsUseGlobalInference, + awsUseCrossRegionInference, + }), + ), + ), + ), + ), + )("sends a supported Ergo profile for %j", async (options) => { + const createHandler = () => + new AwsBedrockHandler({ + apiModelId: options.awsCustomArn ? "custom-arn" : "amazon.ergo-1.0", + awsAccessKey: "test-access-key", + awsSecretKey: "test-secret-key", + ...options, + awsRegion: options.awsCustomArn + ? options.awsRegion === "eu-west-1" + ? "us-east-1" + : "eu-west-1" + : options.awsRegion, + }) + const expectedProfile = options.awsUseGlobalInference + ? "global" + : options.awsUseCrossRegionInference && ["us-east-1", "us-west-2"].includes(options.awsRegion) + ? "us" + : "reject" + const ergoHandler = createHandler() + if (expectedProfile === "reject") { + expect(ergoHandler.getModel().id).toBe("amazon.ergo-1.0") + const expectedError = options.awsCustomArn + ? 'Amazon Ergo 1.0 requires "Use Global inference (auto-select optimal AWS Region)", or an ARN in a US region with "Use cross-region inference".' + : 'Amazon Ergo 1.0 requires "Use Global inference (auto-select optimal AWS Region)", or a US region with "Use cross-region inference".' + await expect( + ergoHandler.createMessage("System prompt", [{ role: "user", content: "Hello" }]).next(), + ).rejects.toThrow(expectedError) + await expect(ergoHandler.completePrompt("Hello")).rejects.toThrow(expectedError) + expect(mockConverseStreamCommand).not.toHaveBeenCalled() + expect(ConverseCommand).not.toHaveBeenCalled() + expect(ergoHandler["client"].send).not.toHaveBeenCalled() + expect(mockCaptureException).not.toHaveBeenCalled() + return + } + await ergoHandler.createMessage("System prompt", [{ role: "user", content: "Hello" }]).next() + expect(mockConverseStreamCommand.mock.calls[0][0]).toMatchObject({ + modelId: `${expectedProfile}.amazon.ergo-1.0`, + inferenceConfig: { maxTokens: expect.any(Number) }, + }) + expect(mockConverseStreamCommand.mock.calls[0][0].inferenceConfig?.maxTokens).toBe(131_072) + await ergoHandler.completePrompt("Hello") + expect(vi.mocked(ConverseCommand).mock.calls[0][0]).toMatchObject({ + modelId: `${expectedProfile}.amazon.ergo-1.0`, + inferenceConfig: { maxTokens: 131_072 }, + }) + expect(ergoHandler.getModel().info).toMatchObject( + expectedProfile === "us" + ? { + inputPrice: 1.1, + outputPrice: 3.3, + cacheReadsPrice: 0.033, + cacheWritesPrice: 1.375, + } + : { inputPrice: 1, outputPrice: 3, cacheReadsPrice: 0.03, cacheWritesPrice: 1.25 }, + ) + }) }) describe("proxy configuration", () => { @@ -364,47 +520,6 @@ describe("AwsBedrockHandler", () => { }) describe("region mapping and cross-region inference", () => { - describe("getPrefixForRegion", () => { - it("should return correct prefix for US regions", () => { - // Access private static method using type casting - const getPrefixForRegion = (AwsBedrockHandler as any).getPrefixForRegion - - expect(getPrefixForRegion("us-east-1")).toBe("us.") - expect(getPrefixForRegion("us-west-2")).toBe("us.") - expect(getPrefixForRegion("us-gov-west-1")).toBe("ug.") - }) - - it("should return correct prefix for EU regions", () => { - const getPrefixForRegion = (AwsBedrockHandler as any).getPrefixForRegion - - expect(getPrefixForRegion("eu-west-1")).toBe("eu.") - expect(getPrefixForRegion("eu-central-1")).toBe("eu.") - expect(getPrefixForRegion("eu-north-1")).toBe("eu.") - }) - - it("should return correct prefix for APAC regions", () => { - const getPrefixForRegion = (AwsBedrockHandler as any).getPrefixForRegion - - // Australia regions (Sydney and Melbourne) get au. prefix - expect(getPrefixForRegion("ap-southeast-2")).toBe("au.") - expect(getPrefixForRegion("ap-southeast-4")).toBe("au.") - // Japan regions (Tokyo and Osaka) get jp. prefix - expect(getPrefixForRegion("ap-northeast-1")).toBe("jp.") - expect(getPrefixForRegion("ap-northeast-3")).toBe("jp.") - // Other APAC regions get apac. prefix - expect(getPrefixForRegion("ap-southeast-1")).toBe("apac.") - expect(getPrefixForRegion("ap-south-1")).toBe("apac.") - }) - - it("should return undefined for unsupported regions", () => { - const getPrefixForRegion = (AwsBedrockHandler as any).getPrefixForRegion - - expect(getPrefixForRegion("unknown-region")).toBeUndefined() - expect(getPrefixForRegion("")).toBeUndefined() - expect(getPrefixForRegion("invalid")).toBeUndefined() - }) - }) - describe("isSystemInferenceProfile", () => { it("should return true for AWS inference profile prefixes", () => { const isSystemInferenceProfile = (AwsBedrockHandler as any).isSystemInferenceProfile @@ -1792,6 +1907,74 @@ describe("AwsBedrockHandler", () => { }) }) + describe("Ergo cache request contract", () => { + const routes: ProviderSettings[] = [ + { apiModelId: "amazon.ergo-1.0", awsUseGlobalInference: true }, + { apiModelId: "amazon.ergo-1.0", awsUseCrossRegionInference: true }, + ...[ + "foundation-model/amazon.ergo-1.0", + "inference-profile/us.amazon.ergo-1.0", + "inference-profile/global.amazon.ergo-1.0", + "application-inference-profile/example", + ].map((resource) => ({ + apiModelId: "custom-arn", + awsCustomArn: `arn:aws:bedrock:us-east-1:123456789012:${resource}`, + awsCustomArnBaseModelId: "amazon.ergo-1.0", + awsUseGlobalInference: true, + })), + ] + const prompts = [ + { system: "Be helpful.", cacheable: false }, + // These prefixes have estimated token counts of 1023 and 1024. + { system: "word ".repeat(783), cacheable: false }, + { system: "word ".repeat(783) + ".", cacheable: true }, + { system: "Follow these coding instructions. ".repeat(400), cacheable: true }, + ] + const cases = routes.flatMap((route) => + [undefined, true, false].flatMap((enabled) => prompts.map((prompt) => ({ route, enabled, ...prompt }))), + ) + + it.each(cases)( + "keeps cache checkpoints in supported fields for %j", + async ({ route, enabled, system, cacheable }) => { + mockConverseStreamCommand.mockClear() + const ergoHandler = new AwsBedrockHandler({ + ...route, + awsRegion: "us-east-1", + awsAccessKey: "test-access-key", + awsSecretKey: "test-secret-key", + awsUsePromptCache: enabled, + }) + const longMessage = "Review this source code carefully. ".repeat(400) + await collectStream( + ergoHandler.createMessage(system, [ + { role: "user", content: longMessage }, + { role: "assistant", content: "I will review the code." }, + { role: "user", content: longMessage }, + ]), + ) + + expect(mockConverseStreamCommand).toHaveBeenCalledTimes(1) + const payload = mockConverseStreamCommand.mock.calls[0][0] + expect(payload.system).toEqual( + enabled !== false && cacheable + ? [{ text: system }, { cachePoint: { type: "default" } }] + : [{ text: system }], + ) + expect(payload.messages).toEqual([ + { role: "user", content: [{ text: longMessage }] }, + { role: "assistant", content: [{ text: "I will review the code." }] }, + { role: "user", content: [{ text: longMessage }] }, + ]) + expect(ergoHandler.getModel().info).toMatchObject({ + minTokensPerCachePoint: 1024, + maxCachePoints: 4, + cachableFields: ["system", "tools"], + }) + }, + ) + }) + describe("prompt cache default behavior", () => { beforeEach(() => { mockConverseStreamCommand.mockReset() @@ -2364,7 +2547,7 @@ describe("AwsBedrockHandler", () => { describe("isAdaptiveThinkingModel detection", () => { // Unit-cover the private guard directly (same pattern the suite uses for - // parseBaseModelId / getPrefixForRegion). This exercises all four model + // parseBaseModelId). This exercises all four model // patterns — including the future-proof sonnet-4-7 / sonnet-4-8 branches // that have no registry entry yet — plus negative cases and prefix stripping. const handler = new AwsBedrockHandler({ diff --git a/src/api/providers/bedrock.ts b/src/api/providers/bedrock.ts index b5b4bda4ac..be74f07693 100644 --- a/src/api/providers/bedrock.ts +++ b/src/api/providers/bedrock.ts @@ -24,6 +24,10 @@ import { type BedrockServiceTier, bedrockDefaultModelId, bedrockModels, + getBedrockModelInfoWithPrices, + getBedrockInferenceRegionPrefix, + resolveBedrockErgoRoute, + type BedrockErgoRoute, bedrockDefaultPromptRouterModelId, BEDROCK_DEFAULT_TEMPERATURE, BEDROCK_MAX_TOKENS, @@ -430,6 +434,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH }, ): ApiStream { const modelConfig = this.getModel() + this.validateInferenceProfile(modelConfig.ergoRoute) const usePromptCache = Boolean( (this.options.awsUsePromptCache ?? true) && this.supportsAwsPromptCache(modelConfig), ) @@ -886,10 +891,22 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH } } + private validateInferenceProfile(ergoRoute?: BedrockErgoRoute): void { + if (ergoRoute && !ergoRoute.valid) { + throw new Error( + this.options.awsCustomArn + ? // Labels: en/settings.json providers.awsGlobalInference and providers.awsCrossRegion. + 'Amazon Ergo 1.0 requires "Use Global inference (auto-select optimal AWS Region)", or an ARN in a US region with "Use cross-region inference".' + : // Labels: en/settings.json providers.awsGlobalInference and providers.awsCrossRegion. + 'Amazon Ergo 1.0 requires "Use Global inference (auto-select optimal AWS Region)", or a US region with "Use cross-region inference".', + ) + } + } + async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + const modelConfig = this.getModel() + this.validateInferenceProfile(modelConfig.ergoRoute) try { - const modelConfig = this.getModel() - const inferenceConfig: BedrockInferenceConfig = { maxTokens: modelConfig.maxTokens || (modelConfig.info.maxTokens as number), // Claude 4.7+ (including 4.8) removed sampling parameters entirely — @@ -1242,6 +1259,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH } override getModel(): { + ergoRoute?: BedrockErgoRoute id: BedrockModelId | string info: ModelInfo maxTokens?: number @@ -1249,6 +1267,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH reasoning?: any reasoningBudget?: number } { + const ergoRoute = resolveBedrockErgoRoute(this.options) if (this.costModelConfig?.id?.trim().length > 0) { // Get model params for cost model config const params = getModelParams({ @@ -1258,7 +1277,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH settings: this.options, defaultTemperature: BEDROCK_DEFAULT_TEMPERATURE, }) - return { ...this.costModelConfig, ...params } + return { ...this.costModelConfig, ...params, ergoRoute } } let modelConfig = undefined @@ -1274,7 +1293,11 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH } else { //a model was selected from the drop down modelConfig = this.getModelById(this.options.apiModelId as string) + } + if (ergoRoute) { + modelConfig.id = ergoRoute.requestId + } else if (!this.options.awsCustomArn) { // Apply Global Inference prefix if enabled and supported (takes precedence over cross-region) const baseIdForGlobal = this.parseBaseModelId(modelConfig.id) if ( @@ -1285,13 +1308,15 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH } // Otherwise, add cross-region inference prefix if enabled else if (this.options.awsUseCrossRegionInference && this.options.awsRegion) { - const prefix = AwsBedrockHandler.getPrefixForRegion(this.options.awsRegion) + const prefix = getBedrockInferenceRegionPrefix(this.options.awsRegion) if (prefix) { modelConfig.id = `${prefix}${modelConfig.id}` } } } + modelConfig.info = getBedrockModelInfoWithPrices(modelConfig.info, ergoRoute) + // Check if 1M context is enabled for supported Claude 4 models // getCapabilityModelId handles cross-region prefixes and custom ARNs const baseModelId = this.getCapabilityModelId(modelConfig.id) @@ -1346,14 +1371,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH } // Don't override maxTokens/contextWindow here; handled in getModelById (and includes user overrides) - return { ...modelConfig, ...params } as { - id: BedrockModelId | string - info: ModelInfo - maxTokens?: number - temperature?: number - reasoning?: any - reasoningBudget?: number - } + return { ...modelConfig, ...params, ergoRoute } } /************************************************************************************ @@ -1452,18 +1470,6 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH * *************************************************************************************/ - private static getPrefixForRegion(region: string): string | undefined { - // Use AWS recommended inference profile prefixes - // Array is pre-sorted by pattern length (descending) to ensure more specific patterns match first - for (const [regionPattern, inferenceProfile] of AWS_INFERENCE_PROFILE_MAPPING) { - if (region.startsWith(regionPattern)) { - return inferenceProfile - } - } - - return undefined - } - private static isSystemInferenceProfile(prefix: string): boolean { // Check if the prefix is defined in AWS_INFERENCE_PROFILE_MAPPING for (const [_, inferenceProfile] of AWS_INFERENCE_PROFILE_MAPPING) { diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a..fd22782226 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -34,11 +34,6 @@ "count": 7 } }, - "api/providers/__tests__/bedrock-inference-profiles.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 27 - } - }, "api/providers/__tests__/bedrock-native-tools.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 19 @@ -51,7 +46,7 @@ }, "api/providers/__tests__/bedrock.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 37 + "count": 33 } }, "api/providers/__tests__/deepseek.spec.ts": { @@ -201,7 +196,7 @@ }, "api/providers/bedrock.ts": { "@typescript-eslint/no-explicit-any": { - "count": 32 + "count": 31 } }, "api/providers/deepseek.ts": { diff --git a/webview-ui/playwright/gallery/stories.tsx b/webview-ui/playwright/gallery/stories.tsx index b0e7fcc144..b7f81f7e46 100644 --- a/webview-ui/playwright/gallery/stories.tsx +++ b/webview-ui/playwright/gallery/stories.tsx @@ -99,6 +99,42 @@ export const stories: Record = { ) }, + "bedrock-ergo-settings": async () => { + const [{ AppProviders }, { default: ApiOptions }, { providerIdentifiers }] = await Promise.all([ + import("../AppProviders"), + import("@/components/settings/ApiOptions"), + import("@roo-code/types"), + ]) + const initialConfig: import("@roo-code/types").ProviderSettings = { + apiProvider: providerIdentifiers.bedrock, + apiModelId: "custom-arn", + awsRegion: "us-east-1", + awsCustomArn: "arn:aws:bedrock:us-east-1::foundation-model/amazon.ergo-1.0", + } + function ErgoSettings() { + const [config, setConfig] = useState(initialConfig) + const [error, setError] = useState() + return ( +
+ + setConfig((previous) => ({ ...previous, [field]: value })) + } + errorMessage={error} + setErrorMessage={setError} + /> +
+ ) + } + return ( + + + + ) + }, + "bedrock-custom-arn": async ({ baseModelId = "" }) => { const [{ AppProviders }, { BedrockCustomArn }, { providerIdentifiers }] = await Promise.all([ import("../AppProviders"), diff --git a/webview-ui/src/components/settings/providers/Bedrock.tsx b/webview-ui/src/components/settings/providers/Bedrock.tsx index df2100681a..a88722a972 100644 --- a/webview-ui/src/components/settings/providers/Bedrock.tsx +++ b/webview-ui/src/components/settings/providers/Bedrock.tsx @@ -11,6 +11,7 @@ import { BEDROCK_GLOBAL_INFERENCE_MODEL_IDS, BEDROCK_SERVICE_TIER_MODEL_IDS, resolveBedrockCustomArnBaseModelId, + resolveBedrockErgoRoute, } from "@roo-code/types" import { useAppTranslation } from "@src/i18n/TranslationContext" @@ -44,7 +45,10 @@ export const Bedrock = ({ apiConfiguration, setApiConfigurationField, selectedMo // Check if the selected model supports Global Inference profile routing const supportsGlobalInference = - !!apiConfiguration.apiModelId && BEDROCK_GLOBAL_INFERENCE_MODEL_IDS.includes(apiConfiguration.apiModelId as any) + apiConfiguration.apiModelId === "custom-arn" + ? resolveBedrockErgoRoute(apiConfiguration)?.kind === "alias" + : !!capabilityModelId && + (BEDROCK_GLOBAL_INFERENCE_MODEL_IDS as readonly string[]).includes(capabilityModelId) // Check if the selected model supports service tiers const supportsServiceTiers = diff --git a/webview-ui/src/components/settings/providers/__tests__/Bedrock.spec.tsx b/webview-ui/src/components/settings/providers/__tests__/Bedrock.spec.tsx index 307696fdd9..4a08379a43 100644 --- a/webview-ui/src/components/settings/providers/__tests__/Bedrock.spec.tsx +++ b/webview-ui/src/components/settings/providers/__tests__/Bedrock.spec.tsx @@ -85,6 +85,42 @@ describe("Bedrock Component", () => { vi.clearAllMocks() }) + it.each([ + ["foundation-model/amazon.ergo-1.0", true], + ["foundation-model/anthropic.claude-sonnet-4-5-20250929-v1:0", false], + ["inference-profile/us.amazon.ergo-1.0", false], + ["application-inference-profile/opaque", false], + ["prompt-router/opaque", false], + ] as const)("shows Global inference for ARN %s: %s", (resource, visible) => { + render( + , + ) + const checkbox = screen.queryByTestId("checkbox-input-settings:providers.awsglobalinference") + if (visible) { + expect(checkbox).toBeInTheDocument() + fireEvent.click(checkbox!) + expect(mockSetApiConfigurationField).toHaveBeenCalledWith("awsUseGlobalInference", true) + } else { + expect(checkbox).not.toBeInTheDocument() + } + }) + + it.each([ + ["amazon.ergo-1.0", true], + ["anthropic.claude-sonnet-4-5-20250929-v1:0", true], + ["amazon.nova-micro-v1:0", false], + ] as const)("keeps Global capability for model %s: %s", (apiModelId, visible) => { + render() + expect(!!screen.queryByTestId("checkbox-input-settings:providers.awsglobalinference")).toBe(visible) + }) + it("should show text field when VPC endpoint checkbox is checked", () => { // Initial render with checkbox unchecked const apiConfiguration: Partial = { diff --git a/webview-ui/src/components/settings/providers/__tests__/BedrockErgo.visual.tsx b/webview-ui/src/components/settings/providers/__tests__/BedrockErgo.visual.tsx new file mode 100644 index 0000000000..a2cfd0f344 --- /dev/null +++ b/webview-ui/src/components/settings/providers/__tests__/BedrockErgo.visual.tsx @@ -0,0 +1,21 @@ +import { expect, test } from "../../../../../playwright/coverage-fixture" +import { applyVisualTheme, visualThemes } from "../../../../../playwright/themes" + +for (const theme of visualThemes.filter(({ name }) => name === "dark" || name === "light")) { + test(`renders the Ergo ARN consent error in the VS Code ${theme.name} theme`, async ({ page }) => { + await page.goto("/") + await page.waitForFunction(() => typeof window.mount === "function") + await page.evaluate(() => window.mount({ story: "bedrock-ergo-settings" })) + const component = page.locator("[data-playwright-mounted]") + await applyVisualTheme(page, theme) + await expect(component.getByTestId("api-error-message")).toContainText("Amazon Ergo 1.0 requires") + await expect( + component.getByText("Use Global inference (auto-select optimal AWS Region)", { exact: true }), + ).toBeVisible() + await page.evaluate(async () => { + await document.fonts.ready + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + }) + await expect(component).toHaveScreenshot(`bedrock-ergo-consent-${theme.name}.png`) + }) +} diff --git a/webview-ui/src/components/settings/providers/__tests__/__screenshots__/bedrock-ergo-consent-dark.png b/webview-ui/src/components/settings/providers/__tests__/__screenshots__/bedrock-ergo-consent-dark.png new file mode 100644 index 0000000000..a2a6f945e0 Binary files /dev/null and b/webview-ui/src/components/settings/providers/__tests__/__screenshots__/bedrock-ergo-consent-dark.png differ diff --git a/webview-ui/src/components/settings/providers/__tests__/__screenshots__/bedrock-ergo-consent-light.png b/webview-ui/src/components/settings/providers/__tests__/__screenshots__/bedrock-ergo-consent-light.png new file mode 100644 index 0000000000..5975152b34 Binary files /dev/null and b/webview-ui/src/components/settings/providers/__tests__/__screenshots__/bedrock-ergo-consent-light.png differ diff --git a/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts b/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts index a1764cfb6f..d84b23d12e 100644 --- a/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts +++ b/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts @@ -746,6 +746,36 @@ describe("useSelectedModel", () => { ) }) + it.each([ + [undefined, true, false, 1, 3], + [undefined, false, true, 1.1, 3.3], + ["foundation-model/amazon.ergo-1.0", false, true, 1.1, 3.3], + ["inference-profile/global.amazon.ergo-1.0", false, true, 1, 3], + ["inference-profile/us.amazon.ergo-1.0", true, false, 1.1, 3.3], + ["application-inference-profile/example", false, false, 1.1, 3.3], + ["prompt-router/example", false, false, 1.1, 3.3], + ] as const)( + "shows Ergo prices for %s with Global=%s and cross-region=%s", + (resource, awsUseGlobalInference, awsUseCrossRegionInference, inputPrice, outputPrice) => { + mockUseRouterModels.mockReturnValue(createRouterModelsResult({})) + mockUseOpenRouterModelProviders.mockReturnValue(createOpenRouterModelProvidersResult({})) + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.bedrock, + apiModelId: resource ? "custom-arn" : "amazon.ergo-1.0", + awsCustomArn: resource ? `arn:aws:bedrock:us-east-1:123456789012:${resource}` : undefined, + awsCustomArnBaseModelId: "amazon.ergo-1.0", + awsRegion: resource ? "eu-west-1" : "us-east-1", + awsUseGlobalInference, + awsUseCrossRegionInference, + }), + { wrapper: createWrapper() }, + ) + expect(result.current.info).toMatchObject({ inputPrice, outputPrice }) + }, + ) + describe("bedrock provider with 1M context", () => { beforeEach(() => { mockUseRouterModels.mockReturnValue(createRouterModelsResult({ openrouter: {}, requesty: {}, litellm: {} })) diff --git a/webview-ui/src/components/ui/hooks/useSelectedModel.ts b/webview-ui/src/components/ui/hooks/useSelectedModel.ts index e535d35cf7..f341abcdd3 100644 --- a/webview-ui/src/components/ui/hooks/useSelectedModel.ts +++ b/webview-ui/src/components/ui/hooks/useSelectedModel.ts @@ -6,6 +6,8 @@ import { type RouterModels, anthropicModels, bedrockModels, + getBedrockModelInfoWithPrices, + resolveBedrockErgoRoute, deepSeekModels, moonshotModels, minimaxModels, @@ -281,6 +283,7 @@ function getSelectedModel({ return getStaticCatalogModel(apiConfiguration.apiModelId, basetenModels, defaultModelId) case providerIdentifiers.bedrock: { const id = apiConfiguration.apiModelId ?? defaultModelId + const ergoRoute = resolveBedrockErgoRoute(apiConfiguration) // A custom ARN takes the capabilities of the model it points to; "Other" mirrors the provider fallback. if (id === "custom-arn") { @@ -300,7 +303,7 @@ function getSelectedModel({ } } - const baseInfo: ModelInfo = bedrockModels[customArnBaseModelId] + const baseInfo = getBedrockModelInfoWithPrices(bedrockModels[customArnBaseModelId], ergoRoute) // Mirror the provider: the 1M context beta switches to the first pricing tier. const use1MContext = (BEDROCK_1M_CONTEXT_MODEL_IDS as readonly string[]).includes(customArnBaseModelId) && @@ -324,7 +327,8 @@ function getSelectedModel({ return { id, info: customArnInfo } } - const baseInfo = bedrockModels[id as keyof typeof bedrockModels] + const registryInfo = bedrockModels[id as keyof typeof bedrockModels] + const baseInfo = registryInfo ? getBedrockModelInfoWithPrices(registryInfo, ergoRoute) : undefined // Apply 1M context for supported Claude 4 models when enabled if (BEDROCK_1M_CONTEXT_MODEL_IDS.includes(id as any) && apiConfiguration.awsBedrock1MContext && baseInfo) { diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index c891ef350d..40af762829 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -1031,7 +1031,9 @@ "modelNotAllowed": "El model '{{model}}' no està permès per al proveïdor '{{provider}}' per la vostra organització", "profileInvalid": "Aquest perfil conté un proveïdor o model que no està permès per la vostra organització", "qwenCodeOauthPath": "Has de proporcionar una ruta vàlida de credencials OAuth", - "zooGatewaySignIn": "Inicia sessió a Zoo Code per utilitzar Zoo Gateway." + "zooGatewaySignIn": "Inicia sessió a Zoo Code per utilitzar Zoo Gateway.", + "bedrockErgoArnInference": "Per a Amazon Ergo 1.0, activa «{{globalOption}}» o utilitza un ARN d’una regió dels EUA amb «{{crossRegionOption}}».", + "bedrockErgoInference": "Per a Amazon Ergo 1.0, activa «{{globalOption}}» o selecciona una regió dels EUA amb «{{crossRegionOption}}»." }, "placeholders": { "apiKey": "Introduïu la clau API...", diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index e2e9f63e10..4b42a2c905 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -1028,7 +1028,9 @@ "modelNotAllowed": "Modell '{{model}}' ist für Anbieter '{{provider}}' von deiner Organisation nicht erlaubt", "profileInvalid": "Dieses Profil enthält einen Anbieter oder ein Modell, das von deiner Organisation nicht erlaubt ist", "qwenCodeOauthPath": "Du musst einen gültigen OAuth-Anmeldedaten-Pfad angeben", - "zooGatewaySignIn": "Melde dich bei Zoo Code an, um Zoo Gateway zu verwenden." + "zooGatewaySignIn": "Melde dich bei Zoo Code an, um Zoo Gateway zu verwenden.", + "bedrockErgoArnInference": "Für Amazon Ergo 1.0 musst du „{{globalOption}}“ aktivieren oder eine ARN aus einer US-Region mit „{{crossRegionOption}}“ verwenden.", + "bedrockErgoInference": "Wähle für Amazon Ergo 1.0 „{{globalOption}}“ oder eine US-Region mit „{{crossRegionOption}}“." }, "placeholders": { "apiKey": "API-Schlüssel eingeben...", diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index 860ffbea17..f495684ccf 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -1101,7 +1101,9 @@ "modelNotAllowed": "Model '{{model}}' is not allowed for provider '{{provider}}' by your organization", "profileInvalid": "This profile contains a provider or model that is not allowed by your organization", "qwenCodeOauthPath": "You must provide a valid OAuth credentials path.", - "zooGatewaySignIn": "Sign in to Zoo Code to use Zoo Gateway." + "zooGatewaySignIn": "Sign in to Zoo Code to use Zoo Gateway.", + "bedrockErgoArnInference": "Amazon Ergo 1.0 requires \"{{globalOption}}\", or an ARN in a US region with \"{{crossRegionOption}}\".", + "bedrockErgoInference": "Amazon Ergo 1.0 requires \"{{globalOption}}\", or a US region with \"{{crossRegionOption}}\"." }, "placeholders": { "apiKey": "Enter API Key...", diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index 7704941410..5379b42c6a 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -1031,7 +1031,9 @@ "modelNotAllowed": "El modelo '{{model}}' no está permitido para el proveedor '{{provider}}' por su organización", "profileInvalid": "Este perfil contiene un proveedor o modelo que no está permitido por su organización", "qwenCodeOauthPath": "Debes proporcionar una ruta válida de credenciales OAuth", - "zooGatewaySignIn": "Inicia sesión en Zoo Code para usar Zoo Gateway." + "zooGatewaySignIn": "Inicia sesión en Zoo Code para usar Zoo Gateway.", + "bedrockErgoArnInference": "Para Amazon Ergo 1.0, activa «{{globalOption}}» o usa un ARN de una región de EE. UU. con «{{crossRegionOption}}».", + "bedrockErgoInference": "Para Amazon Ergo 1.0, activa «{{globalOption}}» o selecciona una región de EE. UU. con «{{crossRegionOption}}»." }, "placeholders": { "apiKey": "Ingrese clave API...", diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index f804a23601..00a6e7a56a 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -1031,7 +1031,9 @@ "modelNotAllowed": "Le modèle '{{model}}' n'est pas autorisé pour le fournisseur '{{provider}}' par votre organisation", "profileInvalid": "Ce profil contient un fournisseur ou un modèle qui n'est pas autorisé par votre organisation", "qwenCodeOauthPath": "Tu dois fournir un chemin valide pour les identifiants OAuth", - "zooGatewaySignIn": "Connectez-vous à Zoo Code pour utiliser Zoo Gateway." + "zooGatewaySignIn": "Connectez-vous à Zoo Code pour utiliser Zoo Gateway.", + "bedrockErgoArnInference": "Pour Amazon Ergo 1.0, activez « {{globalOption}} » ou utilisez un ARN dans une région des États-Unis avec « {{crossRegionOption}} ».", + "bedrockErgoInference": "Pour Amazon Ergo 1.0, activez « {{globalOption}} », ou choisissez une région des États-Unis avec « {{crossRegionOption}} »." }, "placeholders": { "apiKey": "Saisissez la clé API...", diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index f7db8b690a..ca00efd12e 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -1028,7 +1028,9 @@ "modelNotAllowed": "मॉडल '{{model}}' प्रदाता '{{provider}}' के लिए आपके संगठन द्वारा अनुमत नहीं है", "profileInvalid": "इस प्रोफ़ाइल में एक प्रदाता या मॉडल शामिल है जो आपके संगठन द्वारा अनुमत नहीं है", "qwenCodeOauthPath": "आपको एक वैध OAuth क्रेडेंशियल पथ प्रदान करना होगा", - "zooGatewaySignIn": "Zoo Gateway का उपयोग करने के लिए Zoo Code में साइन इन करें।" + "zooGatewaySignIn": "Zoo Gateway का उपयोग करने के लिए Zoo Code में साइन इन करें।", + "bedrockErgoArnInference": "Amazon Ergo 1.0 के लिए \"{{globalOption}}\" चुनें या अमेरिकी क्षेत्र का ARN इस्तेमाल करें और \"{{crossRegionOption}}\" चुनें।", + "bedrockErgoInference": "Amazon Ergo 1.0 के लिए \"{{globalOption}}\" चुनें या अमेरिकी क्षेत्र में \"{{crossRegionOption}}\" चुनें।" }, "placeholders": { "apiKey": "API कुंजी दर्ज करें...", diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index 5867d6d7c0..5b1433c601 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -1025,7 +1025,9 @@ "modelNotAllowed": "Model '{{model}}' tidak diizinkan untuk provider '{{provider}}' oleh organisasi kamu", "profileInvalid": "Profil ini berisi provider atau model yang tidak diizinkan oleh organisasi kamu", "qwenCodeOauthPath": "Kamu harus memberikan jalur kredensial OAuth yang valid", - "zooGatewaySignIn": "Masuk ke Zoo Code untuk menggunakan Zoo Gateway." + "zooGatewaySignIn": "Masuk ke Zoo Code untuk menggunakan Zoo Gateway.", + "bedrockErgoArnInference": "Untuk Amazon Ergo 1.0, aktifkan \"{{globalOption}}\" atau gunakan ARN di Wilayah AS dengan \"{{crossRegionOption}}\".", + "bedrockErgoInference": "Untuk Amazon Ergo 1.0, aktifkan \"{{globalOption}}\", atau pilih Wilayah AS dengan \"{{crossRegionOption}}\"." }, "placeholders": { "apiKey": "Masukkan API Key...", diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index e039482ea8..9917c3f50c 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -1031,7 +1031,9 @@ "modelNotAllowed": "Il modello '{{model}}' non è consentito per il fornitore '{{provider}}' dalla tua organizzazione.", "profileInvalid": "Questo profilo contiene un fornitore o un modello non consentito dalla tua organizzazione.", "qwenCodeOauthPath": "Devi fornire un percorso valido per le credenziali OAuth", - "zooGatewaySignIn": "Accedi a Zoo Code per utilizzare Zoo Gateway." + "zooGatewaySignIn": "Accedi a Zoo Code per utilizzare Zoo Gateway.", + "bedrockErgoArnInference": "Per Amazon Ergo 1.0, attiva «{{globalOption}}» oppure usa un ARN in una regione USA con «{{crossRegionOption}}».", + "bedrockErgoInference": "Per Amazon Ergo 1.0, attiva \"{{globalOption}}\" oppure seleziona una regione USA con \"{{crossRegionOption}}\"." }, "placeholders": { "apiKey": "Inserisci chiave API...", diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index 993a824113..08bc03b109 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -1025,7 +1025,9 @@ "modelNotAllowed": "モデル「{{model}}」はプロバイダー「{{provider}}」に対して組織によって許可されていません", "profileInvalid": "このプロファイルには、組織によって許可されていないプロバイダーまたはモデルが含まれています", "qwenCodeOauthPath": "有効なOAuth認証情報のパスを提供する必要があります", - "zooGatewaySignIn": "Zoo Gatewayを使用するにはZoo Codeにサインインしてください。" + "zooGatewaySignIn": "Zoo Gatewayを使用するにはZoo Codeにサインインしてください。", + "bedrockErgoArnInference": "Amazon Ergo 1.0 では「{{globalOption}}」を有効にするか、米国リージョンの ARN を使用して「{{crossRegionOption}}」を有効にしてください。", + "bedrockErgoInference": "Amazon Ergo 1.0 では「{{globalOption}}」、または米国リージョンで「{{crossRegionOption}}」を有効にしてください。" }, "placeholders": { "apiKey": "API キーを入力...", diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index dfd40fef0c..5062eeec84 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -1025,7 +1025,9 @@ "modelNotAllowed": "모델 '{{model}}'은 제공자 '{{provider}}'에 대해 조직에서 허용되지 않습니다", "profileInvalid": "이 프로필에는 조직에서 허용되지 않는 제공자 또는 모델이 포함되어 있습니다", "qwenCodeOauthPath": "유효한 OAuth 자격 증명 경로를 제공해야 합니다", - "zooGatewaySignIn": "Zoo Gateway를 사용하려면 Zoo Code에 로그인하세요." + "zooGatewaySignIn": "Zoo Gateway를 사용하려면 Zoo Code에 로그인하세요.", + "bedrockErgoArnInference": "Amazon Ergo 1.0에서는 \"{{globalOption}}\"을 활성화하거나 미국 리전의 ARN을 사용하고 \"{{crossRegionOption}}\"을 활성화하세요.", + "bedrockErgoInference": "Amazon Ergo 1.0에서는 \"{{globalOption}}\"을 선택하거나 미국 리전에서 \"{{crossRegionOption}}\"을 선택하세요." }, "placeholders": { "apiKey": "API 키 입력...", diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index eb89ef8a16..04ef25c349 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -1028,7 +1028,9 @@ "modelNotAllowed": "Model '{{model}}' is niet toegestaan voor provider '{{provider}}' door je organisatie", "profileInvalid": "Dit profiel bevat een provider of model dat niet is toegestaan door je organisatie", "qwenCodeOauthPath": "Je moet een geldig OAuth-referentiepad opgeven", - "zooGatewaySignIn": "Log in bij Zoo Code om Zoo Gateway te gebruiken." + "zooGatewaySignIn": "Log in bij Zoo Code om Zoo Gateway te gebruiken.", + "bedrockErgoArnInference": "Schakel voor Amazon Ergo 1.0 \"{{globalOption}}\" in, of gebruik een ARN in een Amerikaanse regio met \"{{crossRegionOption}}\".", + "bedrockErgoInference": "Selecteer voor Amazon Ergo 1.0 \"{{globalOption}}\", of een Amerikaanse regio met \"{{crossRegionOption}}\"." }, "placeholders": { "apiKey": "Voer API-sleutel in...", diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index 7c8a1b7b0f..3ad06f7abd 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -1034,7 +1034,9 @@ "modelNotAllowed": "Model '{{model}}' nie jest dozwolony dla dostawcy '{{provider}}' przez Twoją organizację", "profileInvalid": "Ten profil zawiera dostawcę lub model, który nie jest dozwolony przez Twoją organizację", "qwenCodeOauthPath": "Musisz podać prawidłową ścieżkę do poświadczeń OAuth", - "zooGatewaySignIn": "Zaloguj się do Zoo Code, aby korzystać z Zoo Gateway." + "zooGatewaySignIn": "Zaloguj się do Zoo Code, aby korzystać z Zoo Gateway.", + "bedrockErgoArnInference": "Dla Amazon Ergo 1.0 włącz „{{globalOption}}” lub użyj ARN w regionie USA z opcją „{{crossRegionOption}}”.", + "bedrockErgoInference": "Dla Amazon Ergo 1.0 wybierz „{{globalOption}}” lub region USA z opcją „{{crossRegionOption}}”." }, "placeholders": { "apiKey": "Wprowadź klucz API...", diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index 00373b0c75..e509849c5d 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -1031,7 +1031,9 @@ "modelNotAllowed": "O modelo '{{model}}' não é permitido para o provedor '{{provider}}' pela sua organização", "profileInvalid": "Este perfil contém um provedor ou modelo que não é permitido pela sua organização", "qwenCodeOauthPath": "Você deve fornecer um caminho válido de credenciais OAuth", - "zooGatewaySignIn": "Faça login no Zoo Code para usar o Zoo Gateway." + "zooGatewaySignIn": "Faça login no Zoo Code para usar o Zoo Gateway.", + "bedrockErgoArnInference": "Para Amazon Ergo 1.0, ative \"{{globalOption}}\" ou use um ARN em uma região dos EUA com \"{{crossRegionOption}}\".", + "bedrockErgoInference": "Para Amazon Ergo 1.0, ative \"{{globalOption}}\" ou selecione uma região dos EUA com \"{{crossRegionOption}}\"." }, "placeholders": { "apiKey": "Digite a chave API...", diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 1bf867bd62..98d0a23e08 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -1034,7 +1034,9 @@ "modelNotAllowed": "Модель '{{model}}' не разрешена для провайдера '{{provider}}' вашей организацией", "profileInvalid": "Этот профиль содержит провайдера или модель, которые не разрешены вашей организацией", "qwenCodeOauthPath": "Вы должны указать допустимый путь к учетным данным OAuth", - "zooGatewaySignIn": "Войдите в Zoo Code, чтобы использовать Zoo Gateway." + "zooGatewaySignIn": "Войдите в Zoo Code, чтобы использовать Zoo Gateway.", + "bedrockErgoArnInference": "Для Amazon Ergo 1.0 включите «{{globalOption}}» или используйте ARN в регионе США с параметром «{{crossRegionOption}}».", + "bedrockErgoInference": "Для Amazon Ergo 1.0 включите «{{globalOption}}» или выберите регион США с параметром «{{crossRegionOption}}»." }, "placeholders": { "apiKey": "Введите API-ключ...", diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index 0223b80b2a..f5d53a92ca 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -1028,7 +1028,9 @@ "modelNotAllowed": "Model '{{model}}' sağlayıcı '{{provider}}' için kuruluşunuz tarafından izin verilmiyor", "profileInvalid": "Bu profil, kuruluşunuz tarafından izin verilmeyen bir sağlayıcı veya model içeriyor", "qwenCodeOauthPath": "Geçerli bir OAuth kimlik bilgileri yolu sağlamalısınız", - "zooGatewaySignIn": "Zoo Gateway'i kullanmak için Zoo Code'a giriş yapın." + "zooGatewaySignIn": "Zoo Gateway'i kullanmak için Zoo Code'a giriş yapın.", + "bedrockErgoArnInference": "Amazon Ergo 1.0 için \"{{globalOption}}\" seçeneğini etkinleştirin veya \"{{crossRegionOption}}\" ile bir ABD bölgesindeki ARN’yi kullanın.", + "bedrockErgoInference": "Amazon Ergo 1.0 için \"{{globalOption}}\" seçeneğini veya \"{{crossRegionOption}}\" ile bir ABD bölgesini seçin." }, "placeholders": { "apiKey": "API anahtarını girin...", diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index 09976a50fe..defcd967da 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -1025,7 +1025,9 @@ "modelNotAllowed": "Mô hình '{{model}}' không được phép cho nhà cung cấp '{{provider}}' bởi tổ chức của bạn", "profileInvalid": "Hồ sơ này chứa một nhà cung cấp hoặc mô hình không được phép bởi tổ chức của bạn", "qwenCodeOauthPath": "Bạn phải cung cấp đường dẫn thông tin xác thực OAuth hợp lệ", - "zooGatewaySignIn": "Đăng nhập vào Zoo Code để sử dụng Zoo Gateway." + "zooGatewaySignIn": "Đăng nhập vào Zoo Code để sử dụng Zoo Gateway.", + "bedrockErgoArnInference": "Với Amazon Ergo 1.0, bật \"{{globalOption}}\" hoặc dùng ARN trong khu vực Hoa Kỳ và bật \"{{crossRegionOption}}\".", + "bedrockErgoInference": "Với Amazon Ergo 1.0, bật \"{{globalOption}}\", hoặc chọn khu vực Hoa Kỳ và bật \"{{crossRegionOption}}\"." }, "placeholders": { "apiKey": "Nhập khóa API...", diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index 398b1d6ce0..e4e14e5d3d 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -1025,7 +1025,9 @@ "modelNotAllowed": "模型 '{{model}}' 不允许用于提供商 '{{provider}}',您的组织不允许", "profileInvalid": "此配置文件包含您的组织不允许的提供商或模型", "qwenCodeOauthPath": "您必须提供有效的 OAuth 凭证路径", - "zooGatewaySignIn": "请登录 Zoo Code 以使用 Zoo Gateway。" + "zooGatewaySignIn": "请登录 Zoo Code 以使用 Zoo Gateway。", + "bedrockErgoArnInference": "Amazon Ergo 1.0 需要启用“{{globalOption}}”,或使用美国区域的 ARN 并启用“{{crossRegionOption}}”。", + "bedrockErgoInference": "Amazon Ergo 1.0 需要启用“{{globalOption}}”,或选择美国区域并启用“{{crossRegionOption}}”。" }, "placeholders": { "apiKey": "请输入 API 密钥...", diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index 64c0cc7a17..903fe0585b 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -1052,7 +1052,9 @@ "modelNotAllowed": "模型 '{{model}}' 不允許用於供應商 '{{provider}}',此設定已被組織禁止", "profileInvalid": "此設定檔包含您的組織不允許的供應商或模型", "qwenCodeOauthPath": "您必須提供有效的 OAuth 憑證路徑", - "zooGatewaySignIn": "請登入 Zoo Code 以使用 Zoo Gateway。" + "zooGatewaySignIn": "請登入 Zoo Code 以使用 Zoo Gateway。", + "bedrockErgoArnInference": "Amazon Ergo 1.0 需要啟用「{{globalOption}}」,或使用美國區域的 ARN 並啟用「{{crossRegionOption}}」。", + "bedrockErgoInference": "Amazon Ergo 1.0 需要啟用「{{globalOption}}」,或選取美國區域並啟用「{{crossRegionOption}}」。" }, "placeholders": { "apiKey": "請輸入 API 金鑰...", diff --git a/webview-ui/src/utils/__tests__/validate.spec.ts b/webview-ui/src/utils/__tests__/validate.spec.ts index 816d0cefc5..33284b8322 100644 --- a/webview-ui/src/utils/__tests__/validate.spec.ts +++ b/webview-ui/src/utils/__tests__/validate.spec.ts @@ -26,6 +26,111 @@ const t = ((key: string, options?: Record) => { return key }) as unknown as TFunction +const ergoError = (customArn = false) => + `settings:validation.${customArn ? "bedrockErgoArnInference" : "bedrockErgoInference"} globalOption=settings:providers.awsGlobalInference crossRegionOption=settings:providers.awsCrossRegion` + +describe.each([validateApiConfiguration, validateApiConfigurationExcludingModelErrors])( + "Ergo validation through %s", + (validate) => { + it.each( + ["us-east-1", "eu-west-1", "us-gov-west-1"].flatMap((awsRegion) => + [undefined, false, true].flatMap((awsUseGlobalInference) => + [undefined, false, true].map((awsUseCrossRegionInference) => ({ + awsRegion, + awsUseGlobalInference, + awsUseCrossRegionInference, + })), + ), + ), + )("checks routing before Save for %j", (options) => { + const expected = + options.awsUseGlobalInference || + (options.awsUseCrossRegionInference && options.awsRegion === "us-east-1") + ? undefined + : ergoError() + expect( + validate({ apiProvider: providerIdentifiers.bedrock, apiModelId: "amazon.ergo-1.0", ...options }, t), + ).toBe(expected) + }) + it.each(["global", "us"])("accepts an explicit %s profile ARN without toggles", (profile) => { + expect( + validate( + { + apiProvider: providerIdentifiers.bedrock, + apiModelId: "amazon.ergo-1.0", + awsRegion: "us-east-1", + awsCustomArn: `arn:aws:bedrock:us-east-1:123456789012:inference-profile/${profile}.amazon.ergo-1.0`, + }, + t, + ), + ).toBeUndefined() + }) + it.each([false, true])("validates a foundation-model alias with Global=%s", (awsUseGlobalInference) => { + expect( + validate( + { + apiProvider: providerIdentifiers.bedrock, + awsRegion: "eu-west-1", + awsUseGlobalInference, + awsCustomArn: "arn:aws:bedrock:eu-west-1::foundation-model/amazon.ergo-1.0", + }, + t, + ), + ).toBe(awsUseGlobalInference ? undefined : ergoError(true)) + }) + it.each([ + ["us-east-1", "eu-west-1", ergoError(true)], + ["eu-west-1", "us-east-1", undefined], + ])("uses selected region %s and ARN region %s", (awsRegion, arnRegion, expected) => { + expect( + validate( + { + apiProvider: providerIdentifiers.bedrock, + apiModelId: "custom-arn", + awsRegion, + awsUseCrossRegionInference: true, + awsCustomArn: `arn:aws:bedrock:${arnRegion}::foundation-model/amazon.ergo-1.0`, + }, + t, + ), + ).toBe(expected) + }) + + it.each(["application-inference-profile", "prompt-router"])( + "accepts an opaque %s ARN without toggles", + (resource) => { + expect( + validate( + { + apiProvider: providerIdentifiers.bedrock, + apiModelId: "custom-arn", + awsRegion: "eu-west-1", + awsCustomArn: `arn:aws:bedrock:eu-west-1:123456789012:${resource}/opaque`, + awsCustomArnBaseModelId: "amazon.ergo-1.0", + awsUseGlobalInference: false, + awsUseCrossRegionInference: false, + }, + t, + ), + ).toBeUndefined() + }, + ) + + it("keeps other Bedrock models valid without profile toggles", () => { + expect( + validate( + { + apiProvider: providerIdentifiers.bedrock, + apiModelId: "amazon.nova-micro-v1:0", + awsRegion: "us-east-1", + }, + t, + ), + ).toBeUndefined() + }) + }, +) + describe("Model Validation Functions", () => { const mockRouterModels: RouterModels = { openrouter: { diff --git a/webview-ui/src/utils/validate.ts b/webview-ui/src/utils/validate.ts index aa34fa4e8d..c0864897e3 100644 --- a/webview-ui/src/utils/validate.ts +++ b/webview-ui/src/utils/validate.ts @@ -8,6 +8,7 @@ import { parseOpenAiExtraBody, providerIdentifiers, githubCopilotLanguageModel, + resolveBedrockErgoRoute, } from "@roo-code/types" type OpenAiExtraBodyParseResult = ReturnType @@ -103,11 +104,24 @@ function validateModelsAndKeysProvided( return t("settings:validation.apiKey") } break - case providerIdentifiers.bedrock: + case providerIdentifiers.bedrock: { if (!apiConfiguration.awsRegion) { return t("settings:validation.awsRegion") } + const ergoRoute = resolveBedrockErgoRoute(apiConfiguration) + if (ergoRoute && !ergoRoute.valid) { + return t( + apiConfiguration.awsCustomArn + ? "settings:validation.bedrockErgoArnInference" + : "settings:validation.bedrockErgoInference", + { + globalOption: t("settings:providers.awsGlobalInference"), + crossRegionOption: t("settings:providers.awsCrossRegion"), + }, + ) + } break + } case providerIdentifiers.vertex: if (!apiConfiguration.vertexProjectId || !apiConfiguration.vertexRegion) { return t("settings:validation.googleCloud")