Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(claude): add Amazon Bedrock as a Claude engine
Thi54a7f8d1aab6
diff --git a/server/claude-bedrock.test.ts b/server/claude-bedrock.test.tsnew file mode 100644index 0000000000..700c836b56--- /dev/null+++ b/server/claude-bedrock.test.ts@@ -0,0 +1,149 @@+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { officialModels } from "./agent-endpoint-models.ts";+import {+ claudeBedrockSchema,+ claudeBedrockUpdateSchema,+ claudeBedrockInfo,+ isClaudeBedrock,+ newClaudeBedrock,+ updateClaudeBedrock,+ withClaudeBedrockInfo,+} from "./claude-bedrock.ts";+import { isClaudeEndpoint } from "./claude-endpoints.ts";+import { DATA_DIR } from "./config.ts";++const BASE = {+ displayName: "Bedrock US",+ awsProfile: "bedrock-prod",+ awsRegion: "us-east-1",+};++const cfg = () => ({+ instances: {+ claude: { driver: "claudeAgent", environment: { ANTHROPIC_AUTH_TOKEN: "parent-secret" }, config: { cli: "claude-wrapper" } },+ other: { driver: "codex", config: { cli: "codex-wrapper" } },+ },+}) as never;++describe("Claude on Amazon Bedrock", () => {+ it("creates its own instance with Bedrock routing, its own directory and no AWS/Anthropic secret", () => {+ const source = cfg();+ const { instanceId, instances } = newClaudeBedrock(source, { ...BASE, opusModel: "global.anthropic.claude-opus-5-5" });+ const entry = instances[instanceId];++ expect(instanceId).toMatch(/^claude-[0-9a-f-]{36}$/);+ expect(entry).toMatchObject({+ driver: "claudeAgent",+ displayName: "Bedrock US",+ access: "custom",+ config: {+ cli: "claude-wrapper",+ configDir: join(DATA_DIR, "providers", instanceId),+ bedrock: true,+ },+ environment: {+ CLAUDE_CODE_USE_BEDROCK: "1",+ AWS_PROFILE: "bedrock-prod",+ AWS_REGION: "us-east-1",+ ANTHROPIC_DEFAULT_OPUS_MODEL: "global.anthropic.claude-opus-5-5",+ },+ });+ expect(entry.environment).not.toHaveProperty("ANTHROPIC_API_KEY");+ expect(entry.environment).not.toHaveProperty("ANTHROPIC_AUTH_TOKEN");+ expect(entry.environment).not.toHaveProperty("requireApiKey");+ expect((entry.config as { requireApiKey?: boolean }).requireApiKey).toBeUndefined();+ // No model named: the default catalog is every official model under Bedrock's cross-region prefix.+ expect((entry.config as { endpointModels: string[] }).endpointModels).toEqual(officialModels(false).map((id) => `global.anthropic.${id}`));+ // The caller's config is left as it was: the fleet is copied, not edited.+ expect(Object.keys((source as { instances: object }).instances)).toEqual(["claude", "other"]);+ });++ it("inherits the installed binary from whichever Claude account sets one, never a Bedrock sibling's", () => {+ const { instanceId, instances } = newClaudeBedrock({+ instances: {+ claude: { driver: "claudeAgent", config: {} },+ "claude-work": { driver: "claudeAgent", config: { cli: "/opt/claude/bin/claude" } },+ "claude-bedrock-other": { driver: "claudeAgent", config: { cli: "/opt/claude/bin/claude-bedrock-fixture", bedrock: true } },+ },+ } as never, BASE);+ expect((instances[instanceId].config as { cli?: string }).cli).toBe("/opt/claude/bin/claude");+ });++ it("uses an explicit model as the only catalog entry when none of the tiers are set", () => {+ const { instanceId, instances } = newClaudeBedrock(cfg(), { ...BASE, model: "global.anthropic.claude-sonnet-5-5" });+ expect((instances[instanceId].config as { endpointModels: string[] }).endpointModels).toEqual(["global.anthropic.claude-sonnet-5-5"]);+ expect(instances[instanceId].environment?.ANTHROPIC_MODEL).toBe("global.anthropic.claude-sonnet-5-5");+ });++ it("reports only the profile, region and models to a client; never an AWS or Anthropic secret", () => {+ const { instanceId, instances } = newClaudeBedrock(cfg(), { ...BASE, model: "global.anthropic.claude-sonnet-5-5" });+ const info = claudeBedrockInfo(instances[instanceId]);+ expect(info).toEqual({+ awsProfile: "bedrock-prod",+ awsRegion: "us-east-1",+ models: ["global.anthropic.claude-sonnet-5-5"],+ opusModel: "", sonnetModel: "", haikuModel: "", smallFastModel: "",+ });+ const described = withClaudeBedrockInfo([{ instanceId }, { instanceId: "claude" }], instances) as Array<Record<string, unknown>>;+ expect(JSON.stringify(described)).not.toMatch(/AKIA|aws_secret|session_token/i);+ expect(described[0]).toMatchObject({ claudeBedrock: { awsProfile: "bedrock-prod", awsRegion: "us-east-1" } });+ expect(described[0]).not.toHaveProperty("url");+ expect(described[1]).not.toHaveProperty("claudeBedrock");+ expect(isClaudeBedrock(instances[instanceId])).toBe(true);+ expect(isClaudeBedrock(instances.claude)).toBe(false);+ });++ it("is never mistaken for a custom endpoint, even though both set endpointModels", () => {+ const { instanceId, instances } = newClaudeBedrock(cfg(), BASE);+ expect(isClaudeEndpoint(instances[instanceId])).toBe(false);+ expect(isClaudeBedrock(instances[instanceId])).toBe(true);+ });++ it("edits in place; an omitted field keeps its saved profile, region and models", () => {+ const { instanceId, instances } = newClaudeBedrock(cfg(), { ...BASE, opusModel: "global.anthropic.claude-opus-5-5" });+ const updated = updateClaudeBedrock({ instances }, instanceId, { awsRegion: "eu-west-1" });+ const entry = updated.instances[instanceId];+ expect(entry.environment).toMatchObject({+ AWS_PROFILE: "bedrock-prod",+ AWS_REGION: "eu-west-1",+ ANTHROPIC_DEFAULT_OPUS_MODEL: "global.anthropic.claude-opus-5-5",+ });+ // Nothing else in the fleet moves.+ expect(updated.instances.claude).toEqual(instances.claude);+ });++ it("clears a model tier left empty", () => {+ const { instanceId, instances } = newClaudeBedrock(cfg(), { ...BASE, opusModel: "global.anthropic.claude-opus-5-5" });+ const updated = updateClaudeBedrock({ instances }, instanceId, { opusModel: "" });+ expect(updated.instances[instanceId].environment).not.toHaveProperty("ANTHROPIC_DEFAULT_OPUS_MODEL");+ });++ it("rejects a non-Bedrock Claude instance and an unknown id", () => {+ const { instances } = newClaudeBedrock(cfg(), BASE);+ expect(() => updateClaudeBedrock({ instances }, "claude", { awsRegion: "eu-west-1" })).toThrow(/not an Amazon Bedrock engine/);+ expect(() => updateClaudeBedrock({ instances }, "missing", { awsRegion: "eu-west-1" })).toThrow(/unknown instance/);+ });++ it("validates the profile, region, display name and model ids before anything is saved", () => {+ for (const body of [+ { ...BASE, awsProfile: "" },+ { ...BASE, awsProfile: "has space" },+ { ...BASE, awsRegion: "not-a-region" },+ { ...BASE, awsRegion: "US-EAST-1" },+ { ...BASE, model: "has space" },+ { ...BASE, model: "" },+ { ...BASE, model: "default" },+ { ...BASE, displayName: "Bad\nname" },+ { ...BASE, displayName: "" },+ { ...BASE, token: "sk-should-not-exist" },+ ]) {+ expect(claudeBedrockSchema.safeParse(body).success, JSON.stringify(body)).toBe(false);+ }+ expect(claudeBedrockSchema.safeParse(BASE).success).toBe(true);+ expect(claudeBedrockUpdateSchema.safeParse({}).success).toBe(false);+ expect(claudeBedrockUpdateSchema.safeParse({ awsRegion: "not-a-region" }).success).toBe(false);+ expect(claudeBedrockUpdateSchema.safeParse({ awsRegion: "eu-west-1" }).success).toBe(true);+ });+});diff --git a/server/claude-bedrock.ts b/server/claude-bedrock.tsnew file mode 100644index 0000000000..fdc97544bf--- /dev/null+++ b/server/claude-bedrock.ts@@ -0,0 +1,177 @@+// Claude Code on Amazon Bedrock: the person names an AWS profile and region from this computer's own+// ~/.aws config, and the instance runs with CLAUDE_CODE_USE_BEDROCK=1. The AWS SDK inside Claude Code+// resolves that profile's SSO or credential_process itself; OpenMausBot stores no AWS secret.+import { randomUUID } from "node:crypto";+import { join } from "node:path";+import { z } from "zod";++import type { ClaudeBedrockInfo } from "../shared/claude-endpoint.ts";+import { assertSeparateClaudeAccount } from "./claude-accounts.ts";+import { DATA_DIR, persistableInstanceConfigs, type AppConfig } from "./config.ts";+import type { InstanceConfig, InstanceConfigMap } from "./contracts.ts";+import { officialModels } from "./agent-endpoint-models.ts";+import { CLAUDE_MODEL_ID } from "./drivers/claude-model-extras.ts";++const displayName = z.string().trim().min(1).max(80).refine((value) => !/\p{Cc}/u.test(value), "Name cannot contain control characters");+const awsProfile = z.string().trim().regex(/^[A-Za-z0-9._+=,@-]{1,128}$/, "Enter the AWS profile name from this computer's ~/.aws config.");+const awsRegion = z.string().trim().regex(/^[a-z]{2}(-[a-z]+)+-\d$/, "Enter an AWS region, such as us-east-1.");+const model = z.string().trim().max(160).regex(CLAUDE_MODEL_ID, "Use the model id Bedrock serves.")+ .refine((value) => value !== "default", "Claude Code reserves `default`; use the model id Bedrock serves.");+const optionalModel = z.union([model, z.literal("")]);++export const claudeBedrockSchema = z.object({+ displayName,+ awsProfile,+ awsRegion,+ model: model.optional(),+ opusModel: optionalModel.optional(),+ sonnetModel: optionalModel.optional(),+ haikuModel: optionalModel.optional(),+ smallFastModel: optionalModel.optional(),+}).strict();++export const claudeBedrockUpdateSchema = z.object({+ displayName: displayName.optional(),+ awsProfile: awsProfile.optional(),+ awsRegion: awsRegion.optional(),+ model: model.optional(),+ opusModel: optionalModel.optional(),+ sonnetModel: optionalModel.optional(),+ haikuModel: optionalModel.optional(),+ smallFastModel: optionalModel.optional(),+}).strict().refine((value) => Object.keys(value).length > 0, "No settings supplied");++type BedrockFields = z.infer<typeof claudeBedrockUpdateSchema>;+/** Environment/model generation always runs once the profile and region are resolved. */+type ResolvedBedrockFields = BedrockFields & { awsProfile: string; awsRegion: string };++const TIERS = [+ ["opusModel", "ANTHROPIC_DEFAULT_OPUS_MODEL"],+ ["sonnetModel", "ANTHROPIC_DEFAULT_SONNET_MODEL"],+ ["haikuModel", "ANTHROPIC_DEFAULT_HAIKU_MODEL"],+ ["smallFastModel", "ANTHROPIC_SMALL_FAST_MODEL"],+] as const;++function rawConfig(entry: InstanceConfig): Record<string, unknown> {+ return entry.config && typeof entry.config === "object" && !Array.isArray(entry.config)+ ? entry.config as Record<string, unknown> : {};+}++/** A Claude instance that runs Claude Code on Amazon Bedrock, rather than a named Claude account or a custom endpoint. */+export function isClaudeBedrock(entry: InstanceConfig | undefined): boolean {+ return entry?.driver === "claudeAgent" && rawConfig(entry).bedrock === true;+}++export type { ClaudeBedrockInfo };++/** What the settings UI may know about a Bedrock instance: its profile, region and models; never a secret. */+export function claudeBedrockInfo(entry: InstanceConfig): ClaudeBedrockInfo {+ const config = rawConfig(entry);+ const environment = entry.environment ?? {};+ return {+ awsProfile: environment.AWS_PROFILE ?? "",+ awsRegion: environment.AWS_REGION ?? "",+ models: Array.isArray(config.endpointModels) ? [...config.endpointModels] : [],+ opusModel: environment.ANTHROPIC_DEFAULT_OPUS_MODEL ?? "",+ sonnetModel: environment.ANTHROPIC_DEFAULT_SONNET_MODEL ?? "",+ haikuModel: environment.ANTHROPIC_DEFAULT_HAIKU_MODEL ?? "",+ smallFastModel: environment.ANTHROPIC_SMALL_FAST_MODEL ?? "",+ };+}++/** Adds each Bedrock instance's profile, region and models to the engine list; no secret ever leaves the server. */+export function withClaudeBedrockInfo(described: unknown, configs: InstanceConfigMap): unknown {+ if (!Array.isArray(described)) return described;+ return described.map((instance: { instanceId?: string }) => {+ const entry = instance.instanceId ? configs[instance.instanceId] : undefined;+ return entry && isClaudeBedrock(entry) ? { ...instance, claudeBedrock: claudeBedrockInfo(entry) } : instance;+ });+}++function bedrockEnvironment(fields: ResolvedBedrockFields): Record<string, string> {+ const environment: Record<string, string> = {+ CLAUDE_CODE_USE_BEDROCK: "1",+ AWS_PROFILE: fields.awsProfile,+ AWS_REGION: fields.awsRegion,+ ...(fields.model ? { ANTHROPIC_MODEL: fields.model.trim() } : {}),+ };+ for (const [field, key] of TIERS) {+ const value = fields[field]?.trim();+ if (value) environment[key] = value;+ }+ return environment;+}++function bedrockModels(fields: ResolvedBedrockFields): string[] {+ const tiers = TIERS.map(([field]) => fields[field]?.trim() ?? "").filter(Boolean);+ return [...new Set([(fields.model ?? "").trim(), ...tiers].filter(Boolean))];+}++/** Bedrock's own id for each official model, Claude Code's cross-region inference profile prefix. */+function defaultBedrockModels(): string[] {+ return officialModels(false).map((id) => `global.anthropic.${id}`);+}++/** The installed binary, not another account's environment: Bedrock routes through AWS, never a Claude login. */+function inheritedCli(instances: InstanceConfigMap): string | undefined {+ for (const entry of Object.values(instances)) {+ if (entry.driver !== "claudeAgent" || isClaudeBedrock(entry)) continue;+ const cli = rawConfig(entry).cli;+ if (typeof cli === "string" && cli) return cli;+ }+ return undefined;+}++export function newClaudeBedrock(cfg: AppConfig, body: z.infer<typeof claudeBedrockSchema>) {+ const instances = persistableInstanceConfigs(cfg);+ const instanceId = `claude-${randomUUID()}`;+ const cli = inheritedCli(instances);+ const entry: InstanceConfig = {+ driver: "claudeAgent",+ displayName: body.displayName,+ // Its own credential: an AWS profile, never another Claude instance's sign-in state.+ access: "custom",+ config: {+ ...(cli ? { cli } : {}),+ configDir: join(DATA_DIR, "providers", instanceId),+ bedrock: true,+ endpointModels: body.model ? bedrockModels(body) : defaultBedrockModels(),+ },+ environment: bedrockEnvironment(body),+ };+ assertSeparateClaudeAccount(instances, instanceId, entry);+ instances[instanceId] = entry;+ return { instanceId, instances };+}++/** Changes the Bedrock engine in place; an omitted field keeps its saved value. */+export function updateClaudeBedrock(cfg: AppConfig, instanceId: string, body: BedrockFields) {+ const instances = persistableInstanceConfigs(cfg);+ const entry = instances[instanceId];+ if (!entry) throw Object.assign(new Error("unknown instance"), { status: 404 });+ if (!isClaudeBedrock(entry)) throw Object.assign(new Error("This Claude instance is not an Amazon Bedrock engine."), { status: 400 });+ const saved = claudeBedrockInfo(entry);+ if (!saved.awsProfile || !saved.awsRegion) throw Object.assign(new Error("This engine is missing its AWS profile or region. Remove it and add it again."), { status: 409 });+ const fields: ResolvedBedrockFields = {+ awsProfile: body.awsProfile ?? saved.awsProfile,+ awsRegion: body.awsRegion ?? saved.awsRegion,+ model: body.model ?? entry.environment?.ANTHROPIC_MODEL,+ };+ if (body.displayName !== undefined) fields.displayName = body.displayName;+ for (const [field, key] of TIERS) {+ const value = body[field] !== undefined ? body[field] : entry.environment?.[key];+ if (value !== undefined) fields[field] = value;+ }+ instances[instanceId] = {+ ...entry,+ ...(fields.displayName ? { displayName: fields.displayName } : {}),+ environment: bedrockEnvironment(fields),+ config: {+ ...rawConfig(entry),+ bedrock: true,+ endpointModels: fields.model && (body.model !== undefined || TIERS.some(([field]) => body[field] !== undefined))+ ? bedrockModels(fields) : saved.models,+ },+ };+ return { instances };+}diff --git a/server/claude-endpoints.ts b/server/claude-endpoints.tsindex 1cf7af8aeb..80040ac739 100644--- a/server/claude-endpoints.ts+++ b/server/claude-endpoints.ts@@ -57,9 +57,9 @@ function rawConfig(entry: InstanceConfig): Record<string, unknown> {? entry.config as Record<string, unknown> : {};}-/** A Claude instance the person pointed at another host, rather than a named Claude account. */+/** A Claude instance the person pointed at another host, rather than a named Claude account or Bedrock. */export function isClaudeEndpoint(entry: InstanceConfig | undefined): boolean {- return entry?.driver === "claudeAgent" && Array.isArray(rawConfig(entry).endpointModels);+ return entry?.driver === "claudeAgent" && Array.isArray(rawConfig(entry).endpointModels) && rawConfig(entry).bedrock !== true;}export type { ClaudeEndpointInfo };diff --git a/server/drivers/claude-bedrock-aws.test.ts b/server/drivers/claude-bedrock-aws.test.tsnew file mode 100644index 0000000000..c384a04836--- /dev/null+++ b/server/drivers/claude-bedrock-aws.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";++import { bedrockCredentialError, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";++describe("bedrockCredentialError", () => {+ it("turns a few representative AWS SDK credential failures into one plain next step", () => {+ for (const text of [+ "ExpiredToken: The security token included in the request is expired",+ "UnrecognizedClientException: The security token included in the request is invalid",+ "ExpiredTokenException: the SSO session associated with this profile has expired or is otherwise invalid",+ "Unable to locate credentials. You can configure credentials by running \"aws configure\".",+ "Could not load credentials from any providers",+ "API Error: Could not load AWS credentials · Could not load credentials from any providers. Check or refresh your AWS credentials and try again.",+ ]) {+ expect(bedrockCredentialError(text, "bedrock-prod")).toBe(+ "AWS sign-in for profile bedrock-prod expired. Run `aws sso login --profile bedrock-prod` and try again."+ );+ }+ });++ it("leaves an unrelated failure alone", () => {+ for (const text of [+ "ValidationException: The model is not supported in this region",+ "Claude ended the turn with an error (unknown).",+ "",+ ]) {+ expect(bedrockCredentialError(text, "bedrock-prod")).toBeNull();+ }+ });+});++describe("withBedrockCredentialError", () => {+ const expired = "API Error: Could not load AWS credentials · Could not load credentials from any providers.";+ const env = { AWS_PROFILE: "bedrock-prod" };++ it("replaces a credential failure on a Bedrock instance with the sign-in step", () => {+ expect(withBedrockCredentialError(true, env, expired, { message: expired, text: { key: "x" } })).toEqual({+ message: "AWS sign-in for profile bedrock-prod expired. Run `aws sso login --profile bedrock-prod` and try again.",+ });+ expect(bedrockResultError(true, env, expired)).toContain("aws sso login --profile bedrock-prod");+ });++ it("keeps the original error off Bedrock, without a profile, or for another failure", () => {+ const error = { message: expired };+ expect(withBedrockCredentialError(undefined, env, expired, error)).toBe(error);+ expect(withBedrockCredentialError(true, {}, expired, error)).toBe(error);+ expect(bedrockResultError(true, env, "ValidationException: bad model")).toBe("ValidationException: bad model");+ });+});diff --git a/server/drivers/claude-bedrock-aws.ts b/server/drivers/claude-bedrock-aws.tsnew file mode 100644index 0000000000..79e8ab5400--- /dev/null+++ b/server/drivers/claude-bedrock-aws.ts@@ -0,0 +1,36 @@+/** Inherited AWS variables that outrank AWS_PROFILE in the AWS SDK's own credential resolution, so a Bedrock+ * instance never runs on another instance's (or this machine's shell) AWS credentials. */+export const AWS_CREDENTIAL_ENV_KEYS = [+ "AWS_ACCESS_KEY_ID",+ "AWS_SECRET_ACCESS_KEY",+ "AWS_SESSION_TOKEN",+ "AWS_BEARER_TOKEN_BEDROCK",+ "AWS_DEFAULT_PROFILE",+] as const;++// AWS credential failures surface from the SDK as plain English, not a structured error code; matched by text.+const BEDROCK_CREDENTIAL_ERROR =+ /\bExpiredToken(?:Exception)?\b|security token included in the request is (?:expired|invalid)|sso session associated with this profile has expired|unable to locate credentials|could not load credentials/i;++/** A plain next step for an AWS profile that can no longer authenticate; null when the text is some other failure. */+export function bedrockCredentialError(text: string, awsProfile: string): string | null {+ if (!BEDROCK_CREDENTIAL_ERROR.test(text)) return null;+ return `AWS sign-in for profile ${awsProfile} expired. Run \`aws sso login --profile ${awsProfile}\` and try again.`;+}++/** The turn error to show: the AWS sign-in step when a Bedrock instance's profile failed, else `error` unchanged. */+export function withBedrockCredentialError<T extends { message: string }>(+ bedrock: boolean | undefined,+ environment: Readonly<Record<string, string | undefined>>,+ said: string,+ error: T+): T | { message: string } {+ const awsProfile = bedrock ? environment.AWS_PROFILE : undefined;+ const message = awsProfile ? bedrockCredentialError(said, awsProfile) : null;+ return message ? { message } : error;+}++/** The same choice for a turn's final error text. */+export function bedrockResultError(bedrock: boolean | undefined, environment: Readonly<Record<string, string | undefined>>, message: string): string {+ return withBedrockCredentialError(bedrock, environment, message, { message }).message;+}diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 84637b794c..0b95de1570 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -16,7 +16,7 @@ import { claudeAuthStatus } from "./claude-auth-status.ts";import { projectMcpServers } from "./claude-project-mcp.ts";import { botSettingsFor, withBotSettings } from "./claude-bot-settings.ts";import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";-import { claudeAuthFailure, claudeAuthRecovery } from "./claude-auth-recovery.ts";+import { claudeAuthFailure, claudeAuthRecovery } from "./claude-auth-recovery.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, endpointModelCatalog } from "./claude-model-extras.ts";import { claudeToolSearchSetting } from "./claude-tool-search.ts"; import { unusableBuiltIns } from "./claude-unusable-tools.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";import { claudeElicitations } from "./claude-elicitation.ts";@@ -84,7 +84,7 @@ export const CLAUDE_ACCOUNT_ENV_KEYS = ["ANTHROPIC_CUSTOM_HEADERS","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX",- "CLAUDE_CODE_USE_FOUNDRY",+ "CLAUDE_CODE_USE_FOUNDRY", ...AWS_CREDENTIAL_ENV_KEYS,] as const;export function resolveClaudeConfigDir(configDir?: string, env: NodeJS.ProcessEnv = process.env): string {@@ -272,7 +272,7 @@ export interface ClaudeConfig {permissionMode: "acceptEdits" | "auto" | "bypassPermissions";tools?: string[];disallowedTools?: string[];- requireApiKey?: boolean;+ requireApiKey?: boolean; bedrock?: boolean; // bedrock: Amazon Bedrock through an AWS profile, no secret of its own}export { STATIC_CLAUDE_MODELS };@@ -643,7 +643,7 @@ function decodeConfig(raw: unknown): ClaudeConfig {permissionMode: (mode as ClaudeConfig["permissionMode"]) ?? "acceptEdits",...(tools !== undefined ? { tools } : {}),...(disallowedTools !== undefined ? { disallowedTools } : {}),- ...(o.requireApiKey === true ? { requireApiKey: true } : {}),+ ...(o.requireApiKey === true ? { requireApiKey: true } : {}), ...(o.bedrock === true ? { bedrock: true } : {}),};}@@ -1522,7 +1522,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {}if ((o.is_api_error_message === true || typeof o.error === "string") && text.trim()) {if (session.turn) session.turn.explained = true;- if (!session.turn?.stopRequested) emit({ ...base(threadId, currentTurnId()), type: "runtime.error", ...claudeApiError(o, text) });+ if (!session.turn?.stopRequested) emit({ ...base(threadId, currentTurnId()), type: "runtime.error", ...withBedrockCredentialError(config.bedrock, input.environment, text, claudeApiError(o, text)) });break;}if (session.turn) session.turn.answered = true;@@ -1596,7 +1596,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {o.api_error === "usage_limit_reached" || USAGE_LIMIT.test(String(o.result ?? "")))) reachLimit(o, o.result);if (o.is_error === true && session.turn && !session.turn.settled && !session.turn.explained && !session.turn.stopRequested) {session.turn.explained = true;- emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: claudeResultError(o) });+ emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: bedrockResultError(config.bedrock, input.environment, claudeResultError(o)) });}if (!config.managed) void orgBlocks.refresh();// result.usage is per turn "in streaming-input sessions" (2.1.282) even on a retaineddiff --git a/server/routes/instances.ts b/server/routes/instances.tsindex f9fca7514e..66fd96c746 100644--- a/server/routes/instances.ts+++ b/server/routes/instances.ts@@ -18,6 +18,13 @@ import {updateClaudeEndpoint,withClaudeEndpointInfo,} from "../claude-endpoints.ts";+import {+ claudeBedrockSchema,+ claudeBedrockUpdateSchema,+ newClaudeBedrock,+ updateClaudeBedrock,+ withClaudeBedrockInfo,+} from "../claude-bedrock.ts";import { updateClaudeCli } from "../claude-update.ts";import { persistableInstanceConfigs, saveConfig, withInstanceCli, type AppConfig } from "../config.ts";import { addEndpoint, addEndpointSchema, isAddedEndpoint, withEndpointUrls } from "../openai-compat-endpoints.ts";@@ -65,7 +72,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {botForThread, activeGroupTurnForBot,} = deps;const describeInstances = async () => hostedModels ? deps.describeInstances()- : withEndpointUrls(withCodexEndpointInfo(withClaudeEndpointInfo(await deps.describeInstances(), cfg.instances ?? {}), cfg.instances ?? {}), cfg.instances ?? {});+ : withEndpointUrls(withCodexEndpointInfo(withClaudeBedrockInfo(withClaudeEndpointInfo(await deps.describeInstances(), cfg.instances ?? {}), cfg.instances ?? {}), cfg.instances ?? {}), cfg.instances ?? {});/** Bots, their backups and threads, the new-bot default, or a turn running on it: a provider in use can't go away. */const providerInUse = (instanceId: string): boolean => cfg.defaultModelSelection?.instanceId === instanceId || store.bots.some((bot) =>bot.modelSelection.instanceId === instanceId || bot.fallback?.some(candidate => candidate.instanceId === instanceId) || store.tasks(bot.id).some((task) => task.modelSelection?.instanceId === instanceId)) ||@@ -224,6 +231,51 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {}}+ if (method === "POST" && path === "/api/instances/claude-bedrock") {+ if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {+ return json(res, 415, { error: "content-type must be application/json" });+ }+ const parsed = claudeBedrockSchema.safeParse(await readBody(req, 16384));+ if (!parsed.success) return json(res, 400, { error: parsed.error.issues[0]?.message ?? "Enter a name, an AWS profile and a region." });+ if (providerConfigBusy.get()) return json(res, 409, { error: "provider settings are already being updated" });+ providerConfigBusy.set(true);+ try {+ const { instanceId, instances } = newClaudeBedrock(cfg, parsed.data);+ await persistProviderInstance(instanceId, instances);+ return json(res, 201, { instanceId, instances: await describeInstances() });+ } catch (error) {+ const status = (error as { status?: unknown }).status;+ return json(res, typeof status === "number" ? status : 400, { error: error instanceof Error ? error.message : String(error) });+ } finally { providerConfigBusy.set(false); }+ }++ const bedrockPatch = /^\/api\/instances\/([\w.-]+)\/claude-bedrock$/.exec(path);+ if (method === "PATCH" && bedrockPatch) {+ if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {+ return json(res, 415, { error: "content-type must be application/json" });+ }+ const instanceId = bedrockPatch[1];+ const parsed = claudeBedrockUpdateSchema.safeParse(await readBody(req, 16384));+ if (!parsed.success) return json(res, 400, { error: parsed.error.issues[0]?.message ?? "Check the AWS profile, region and models." });+ if (providerConfigBusy.get()) return json(res, 409, { error: "provider settings are already being updated" });+ if (busyProviderSelections().some((selection) => selection.instanceId === instanceId)) {+ return json(res, 409, { error: "Wait for bots using this engine to finish before changing its settings." });+ }+ providerConfigBusy.set(true);+ providerInstancesChanging.add(instanceId);+ try {+ const { instances } = updateClaudeBedrock(cfg, instanceId, parsed.data);+ await persistProviderInstance(instanceId, instances);+ return json(res, 200, { instances: await describeInstances() });+ } catch (error) {+ const status = (error as { status?: unknown }).status;+ return json(res, typeof status === "number" ? status : 400, { error: error instanceof Error ? error.message : String(error) });+ } finally {+ providerInstancesChanging.delete(instanceId);+ providerConfigBusy.set(false);+ }+ }+if (method === "POST" && path === "/api/instances/claude-accounts") {if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {return json(res, 415, { error: "content-type must be application/json" });diff --git a/shared/claude-endpoint.ts b/shared/claude-endpoint.tsindex dd6180c10e..b4e9f340f8 100644--- a/shared/claude-endpoint.ts+++ b/shared/claude-endpoint.ts@@ -9,6 +9,17 @@ export interface ClaudeEndpointInfo {smallFastModel: string;}+/** Claude Code on Amazon Bedrock, signed in with an AWS profile from this computer's ~/.aws config; holds no secret. */+export interface ClaudeBedrockInfo {+ awsProfile: string;+ awsRegion: string;+ models: string[];+ opusModel: string;+ sonnetModel: string;+ haikuModel: string;+ smallFastModel: string;+}+/** A direct Codex Responses API connection; the key is write-only. */export interface CodexEndpointInfo {baseUrl: string;@@ -19,6 +30,7 @@ export interface CodexEndpointInfo {/** The instance fields only a custom endpoint has. */export interface InstanceEndpointInfo {claudeEndpoint?: ClaudeEndpointInfo;+ claudeBedrock?: ClaudeBedrockInfo;codexEndpoint?: CodexEndpointInfo;url?: string;}diff --git a/src/components/ClaudeBedrock.dom.test.ts b/src/components/ClaudeBedrock.dom.test.tsnew file mode 100644index 0000000000..22e2b75548--- /dev/null+++ b/src/components/ClaudeBedrock.dom.test.ts@@ -0,0 +1,100 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as store from "@/state/store";+import { ClaudeBedrockEndpoints } from "./ClaudeBedrock";++const bedrockInstance = () => ({+ instanceId: "claude-bedrock-fixture",+ driverKind: "claudeAgent",+ displayName: "Claude on Bedrock",+ access: "custom",+ snapshot: { state: "available" },+ models: { default: "", options: [] },+ claudeBedrock: {+ awsProfile: "default", awsRegion: "us-east-1", models: ["global.anthropic.claude-opus-5-5"],+ opusModel: "global.anthropic.claude-opus-5-5", sonnetModel: "", haikuModel: "", smallFastModel: "",+ },+}) as unknown as store.InstanceInfo;++let host: HTMLDivElement;+let root: Root;+let fetchMock: ReturnType<typeof vi.fn>;++function mount(instances: store.InstanceInfo[]) {+ vi.spyOn(store, "useStore").mockReturnValue({+ state: { ...store.initialState, instances, bots: [] },+ dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),+ } as unknown as ReturnType<typeof store.useStore>);+ flushSync(() => root.render(createElement(ClaudeBedrockEndpoints)));+}++function setValue(input: HTMLInputElement, value: string) {+ flushSync(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+}++beforeEach(() => {+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+ fetchMock = vi.fn(async () => new Response(JSON.stringify({ instanceId: "new-id", instances: [] })));+ vi.stubGlobal("fetch", fetchMock);+});++afterEach(() => {+ flushSync(() => root.unmount());+ host.remove();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("adding a Claude on Amazon Bedrock engine", () => {+ it("posts the profile, region and only the filled model fields, trimmed", async () => {+ mount([]);+ flushSync(() => host.querySelector<HTMLButtonElement>("button")!.click());+ const name = host.querySelector<HTMLInputElement>('input[aria-label="Name"]')!;+ const profile = host.querySelector<HTMLInputElement>('input[aria-label="AWS profile"]')!;+ const region = host.querySelector<HTMLInputElement>('input[aria-label="AWS region"]')!;+ setValue(name, " Team Bedrock ");+ setValue(profile, " my-profile ");+ setValue(region, " us-west-2 ");+ const form = host.querySelector<HTMLFormElement>("form")!;+ await flushSync(() => { form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })); });+ await Promise.resolve();+ await Promise.resolve();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [path, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(path).toBe("/api/instances/claude-bedrock");+ expect(init.method).toBe("POST");+ const body = JSON.parse(String(init.body));+ expect(body).toEqual({+ displayName: "Team Bedrock", awsProfile: "my-profile", awsRegion: "us-west-2",+ opusModel: "", sonnetModel: "", haikuModel: "", smallFastModel: "",+ });+ });++ it("clears a saved tier by sending an empty string for it on edit", async () => {+ mount([bedrockInstance()]);+ const editButton = Array.from(host.querySelectorAll("button")).find((b) => b.textContent === "Edit");+ flushSync(() => editButton!.click());+ const opus = host.querySelector<HTMLInputElement>('input[aria-label="Opus model"]');+ expect(opus?.value).toBe("global.anthropic.claude-opus-5-5");+ setValue(opus!, "");+ const form = host.querySelector<HTMLFormElement>("form")!;+ await flushSync(() => { form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })); });+ await Promise.resolve();+ await Promise.resolve();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [path, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(path).toBe("/api/instances/claude-bedrock-fixture/claude-bedrock");+ expect(init.method).toBe("PATCH");+ const body = JSON.parse(String(init.body));+ expect(body.opusModel).toBe("");+ expect(body.awsProfile).toBe("default");+ });+});diff --git a/src/components/ClaudeBedrock.test.ts b/src/components/ClaudeBedrock.test.tsnew file mode 100644index 0000000000..17226019e9--- /dev/null+++ b/src/components/ClaudeBedrock.test.ts@@ -0,0 +1,80 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, describe, expect, it, vi } from "vitest";++import * as store from "@/state/store";+import { ClaudeBedrockEndpoints } from "./ClaudeBedrock";++const bedrock = (extra: Record<string, unknown> = {}) => ({+ instanceId: "claude-bedrock-fixture",+ driverKind: "claudeAgent",+ displayName: "Claude on Bedrock",+ access: "custom",+ snapshot: { state: "available" },+ models: { default: "", options: [] },+ claudeBedrock: {+ awsProfile: "theiconic-claude-primary",+ awsRegion: "us-east-1",+ models: ["global.anthropic.claude-sonnet-5-5"],+ opusModel: "au.anthropic.claude-opus-5-5", sonnetModel: "", haikuModel: "", smallFastModel: "",+ },+ ...extra,+}) as unknown as store.InstanceInfo;++function render(instances: store.InstanceInfo[]) {+ vi.stubGlobal("window", {});+ vi.spyOn(store, "useStore").mockReturnValue({+ state: { ...store.initialState, instances, bots: [] },+ dispatch: vi.fn(),+ flushBotPatches: vi.fn(),+ refreshInstances: vi.fn(),+ refreshModels: vi.fn(),+ } as unknown as ReturnType<typeof store.useStore>);+ return renderToStaticMarkup(createElement(ClaudeBedrockEndpoints));+}++afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });++describe("Claude on Amazon Bedrock settings", () => {+ it("offers the section with nothing configured yet", () => {+ const html = render([]);+ expect(html).toContain("Amazon Bedrock");+ expect(html).toContain("No Amazon Bedrock engines yet.");+ expect(html).toContain("Add Amazon Bedrock");+ });++ it("lists each engine's profile and region, and never a model id outside the form", () => {+ const html = render([bedrock()]);+ expect(html).toContain("Claude on Bedrock");+ expect(html).toContain("Bedrock");+ expect(html).toContain("theiconic-claude-primary");+ expect(html).toContain("us-east-1");+ expect(html).toContain("Edit");+ expect(html).toContain("Remove Claude on Bedrock");+ expect(html).not.toContain("au.anthropic.claude-opus-5-5");+ });++ it("counts a bot that keeps the engine as a fallback", () => {+ const bot = { id: "bot-2", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" },+ fallback: [{ instanceId: "claude-bedrock-fixture", model: "global.anthropic.claude-sonnet-5-5" }] };+ vi.stubGlobal("window", {});+ vi.spyOn(store, "useStore").mockReturnValue({+ state: { ...store.initialState, instances: [bedrock()], bots: [bot] },+ dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),+ } as unknown as ReturnType<typeof store.useStore>);+ const html = renderToStaticMarkup(createElement(ClaudeBedrockEndpoints));+ expect(html).toContain("1 bot(s) use this account");+ });++ it("waits for bots to move off the engine before offering its removal", () => {+ const bot = { id: "bot-1", modelSelection: { instanceId: "claude-bedrock-fixture", model: "global.anthropic.claude-sonnet-5-5" } };+ vi.stubGlobal("window", {});+ vi.spyOn(store, "useStore").mockReturnValue({+ state: { ...store.initialState, instances: [bedrock()], bots: [bot] },+ dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),+ } as unknown as ReturnType<typeof store.useStore>);+ const html = renderToStaticMarkup(createElement(ClaudeBedrockEndpoints));+ expect(html).toContain("1 bot(s) use this account");+ expect(html).toContain("disabled");+ });+});diff --git a/src/components/ClaudeBedrock.tsx b/src/components/ClaudeBedrock.tsxnew file mode 100644index 0000000000..07f9407c36--- /dev/null+++ b/src/components/ClaudeBedrock.tsx@@ -0,0 +1,205 @@+import { useState } from "react";+import { Loader2, Plus, Trash2 } from "lucide-react";++import { api, useStore, type InstanceInfo } from "@/state/store";+import { t } from "@/lib/i18n";+import { cn } from "@/lib/cn";+import { ConfirmDialog } from "./ConfirmDialog";+import { KEY_FIELD } from "./keys/KeyRow";+import { PresetProviderMark } from "./ProviderIcons";++const INPUT = cn(KEY_FIELD, "font-sans");+const TIER_PLACEHOLDER = {+ opusModel: "global.anthropic.claude-opus-5-5",+ sonnetModel: "global.anthropic.claude-sonnet-5-5",+ haikuModel: "global.anthropic.claude-haiku-5-5",+ smallFastModel: "global.anthropic.claude-haiku-5-5",+} as const;+type Tier = keyof typeof TIER_PLACEHOLDER;+const TIERS: Tier[] = ["opusModel", "sonnetModel", "haikuModel", "smallFastModel"];++interface Draft {+ name: string;+ awsProfile: string;+ awsRegion: string;+ model: string;+ opusModel: string;+ sonnetModel: string;+ haikuModel: string;+ smallFastModel: string;+}++const EMPTY: Draft = { name: "Claude on Bedrock", awsProfile: "default", awsRegion: "", model: "", opusModel: "", sonnetModel: "", haikuModel: "", smallFastModel: "" };++const draftOf = (instance: InstanceInfo): Draft => {+ const bedrock = instance.claudeBedrock;+ return {+ name: instance.displayName,+ awsProfile: bedrock?.awsProfile || "default",+ awsRegion: bedrock?.awsRegion ?? "",+ model: "",+ opusModel: bedrock?.opusModel ?? "",+ sonnetModel: bedrock?.sonnetModel ?? "",+ haikuModel: bedrock?.haikuModel ?? "",+ smallFastModel: bedrock?.smallFastModel ?? "",+ };+};++const TIER_LABEL: Record<Tier, "claudeBedrock.opus" | "claudeBedrock.sonnet" | "claudeBedrock.haiku" | "claudeBedrock.smallFast"> = {+ opusModel: "claudeBedrock.opus",+ sonnetModel: "claudeBedrock.sonnet",+ haikuModel: "claudeBedrock.haiku",+ smallFastModel: "claudeBedrock.smallFast",+};++function BedrockForm({ instance, onDone }: { instance?: InstanceInfo; onDone: () => void }) {+ const { dispatch } = useStore();+ const [draft, setDraft] = useState<Draft>(instance ? draftOf(instance) : EMPTY);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const field = (key: keyof Draft) => ({+ value: draft[key],+ onChange: (event: { target: { value: string } }) => setDraft((current) => ({ ...current, [key]: event.target.value })),+ spellCheck: false,+ disabled: saving,+ });+ const ready = Boolean(draft.name.trim() && draft.awsProfile.trim() && draft.awsRegion.trim());++ const save = async () => {+ if (saving || !ready) return;+ setSaving(true);+ setError(null);+ const body = {+ displayName: draft.name.trim(),+ awsProfile: draft.awsProfile.trim(),+ awsRegion: draft.awsRegion.trim(),+ ...(draft.model.trim() ? { model: draft.model.trim() } : {}),+ ...Object.fromEntries(TIERS.map((tier) => [tier, draft[tier].trim()])),+ };+ try {+ const result = instance+ ? await api(`/api/instances/${encodeURIComponent(instance.instanceId)}/claude-bedrock`, { method: "PATCH", body: JSON.stringify(body) })+ : await api("/api/instances/claude-bedrock", { method: "POST", body: JSON.stringify(body) });+ if (Array.isArray(result.instances)) dispatch({ type: "instances", instances: result.instances });+ onDone();+ } catch (cause) {+ setError(cause instanceof Error && cause.message ? cause.message : t("claudeBedrock.failed"));+ } finally {+ setSaving(false);+ }+ };++ return (+ <form data-claude-bedrock-form={instance?.instanceId ?? "new"} className="flex flex-col gap-2 rounded-xl border border-hairline/50 bg-inset p-3"+ onSubmit={(event) => { event.preventDefault(); void save(); }}>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("claudeBedrock.awsHint")}</p>+ <label className="flex flex-col gap-1 text-[12px] font-medium text-ink">+ {t("claudeBedrock.name")}+ <input {...field("name")} maxLength={80} autoFocus aria-label={t("claudeBedrock.name")} className={INPUT} />+ </label>+ <label className="flex flex-col gap-1 text-[12px] font-medium text-ink">+ {t("claudeBedrock.profile")}+ <input {...field("awsProfile")} maxLength={128} placeholder="default" aria-label={t("claudeBedrock.profile")} className={cn(INPUT, "font-mono")} />+ </label>+ <label className="flex flex-col gap-1 text-[12px] font-medium text-ink">+ {t("claudeBedrock.region")}+ <input {...field("awsRegion")} maxLength={32} placeholder="us-east-1" aria-label={t("claudeBedrock.region")} className={cn(INPUT, "font-mono")} />+ </label>+ <label className="flex flex-col gap-1 text-[12px] font-medium text-ink">+ {t("claudeBedrock.model")}+ <input {...field("model")} maxLength={160} placeholder="global.anthropic.claude-sonnet-5-5" aria-label={t("claudeBedrock.model")} className={cn(INPUT, "font-mono")} />+ </label>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("claudeBedrock.modelHint")}</p>+ <details className="rounded-lg border border-hairline/40 px-2.5 py-2">+ <summary className="cursor-pointer text-[12px] font-medium text-ink-secondary outline-none hover:text-ink">{t("claudeBedrock.tiers")}</summary>+ <div className="mt-2 flex flex-col gap-2">+ {TIERS.map((tier) => (+ <label key={tier} className="flex flex-col gap-1 text-[12px] font-medium text-ink">+ {t(TIER_LABEL[tier])}+ <input {...field(tier)} maxLength={160} placeholder={TIER_PLACEHOLDER[tier]} aria-label={t(TIER_LABEL[tier])} className={cn(INPUT, "font-mono")} />+ </label>+ ))}+ </div>+ </details>+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}+ <div className="flex justify-end gap-2">+ <button type="button" onClick={onDone} disabled={saving} className="rounded-lg px-3 py-1.5 text-[12px] text-ink-secondary hover:bg-control disabled:opacity-50">{t("common.cancel")}</button>+ <button type="submit" disabled={saving || !ready} className="flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-[12px] font-semibold text-white hover:brightness-110 disabled:opacity-50">+ {saving && <Loader2 size={13} className="animate-spin" />}{t("common.save")}+ </button>+ </div>+ </form>+ );+}++function BedrockRow({ instance, onEdit }: { instance: InstanceInfo; onEdit: () => void }) {+ const { state, dispatch } = useStore();+ const [confirming, setConfirming] = useState(false);+ const [removing, setRemoving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const usedBy = state.bots.filter((bot) => bot.modelSelection.instanceId === instance.instanceId+ || bot.fallback?.some((candidate) => candidate.instanceId === instance.instanceId)+ || bot.tasks?.some((task) => task.modelSelection?.instanceId === instance.instanceId)).length;+ const bedrock = instance.claudeBedrock;+ const remove = async () => {+ setConfirming(false);+ setRemoving(true);+ setError(null);+ try {+ const result = await api(`/api/instances/${encodeURIComponent(instance.instanceId)}`, { method: "DELETE" });+ if (Array.isArray(result.instances)) dispatch({ type: "instances", instances: result.instances });+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setRemoving(false);+ }+ };+ return (+ <li data-claude-bedrock={instance.instanceId} className="px-3 py-2.5">+ <div className="flex min-h-9 items-center gap-3">+ <PresetProviderMark preset="aws" size={16} className="shrink-0" />+ <div className="min-w-0 flex-1">+ <div className="truncate text-[13px] font-medium text-ink" title={instance.displayName}>{instance.displayName}</div>+ <div className="truncate font-mono text-[11px] text-ink-secondary">{t("claudeBedrock.rowSubtitle", { profile: bedrock?.awsProfile ?? "", region: bedrock?.awsRegion ?? "" })}</div>+ </div>+ <button type="button" onClick={onEdit} disabled={removing} className="shrink-0 rounded-lg px-2.5 py-1.5 text-[12px] font-medium text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-50">+ {t("claudeBedrock.edit")}+ </button>+ <button type="button" disabled={removing || usedBy > 0} onClick={() => setConfirming(true)}+ title={usedBy > 0 ? t("accounts.inUse", { count: String(usedBy) }) : t("accounts.remove")}+ aria-label={t("claudeBedrock.remove", { name: instance.displayName })}+ className="flex size-8 shrink-0 items-center justify-center rounded-lg text-danger hover:bg-danger/10 disabled:cursor-not-allowed disabled:opacity-50">+ {removing ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={14} />}+ </button>+ </div>+ {error && <p role="alert" className="mt-1 text-[12px] text-danger">{error}</p>}+ <ConfirmDialog open={confirming} title={t("accounts.removeTitle", { name: instance.displayName })}+ body={t("claudeBedrock.removeBody")} confirmLabel={t("accounts.remove")} tone="neutral" pending={removing}+ onCancel={() => setConfirming(false)} onConfirm={() => void remove()} />+ </li>+ );+}++export function ClaudeBedrockEndpoints() {+ const { state } = useStore();+ const instances = state.instances.filter((instance) => instance.claudeBedrock);+ const [open, setOpen] = useState<string | null>(null);+ return (+ <div data-claude-bedrock-endpoints="" className="mt-3 space-y-2">+ <div className="text-[13px] leading-[18px] text-ink">{t("claudeBedrock.title")}</div>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("claudeBedrock.hint")}</p>+ {instances.length === 0+ ? <p className="text-[12px] leading-4 text-ink-secondary">{t("claudeBedrock.empty")}</p>+ : <ul className="divide-y divide-hairline/40 rounded-xl border border-hairline/50 bg-panel/40">+ {instances.map((instance) => open === instance.instanceId+ ? <li key={instance.instanceId} className="p-3"><BedrockForm instance={instance} onDone={() => setOpen(null)} /></li>+ : <BedrockRow key={instance.instanceId} instance={instance} onEdit={() => setOpen(instance.instanceId)} />)}+ </ul>}+ {open === "new"+ ? <BedrockForm onDone={() => setOpen(null)} />+ : <button type="button" onClick={() => setOpen("new")} className="flex min-h-8 w-fit items-center gap-1.5 rounded-lg px-2 py-1.5 text-[13px] font-medium text-ink-secondary outline-none hover:bg-control hover:text-ink focus-visible:ring-2 focus-visible:ring-accent">+ <Plus size={14} />{t("claudeBedrock.add")}+ </button>}+ </div>+ );+}diff --git a/src/components/EnginesSettings.test.ts b/src/components/EnginesSettings.test.tsindex 26c900f38f..711df2b62f 100644--- a/src/components/EnginesSettings.test.ts+++ b/src/components/EnginesSettings.test.ts@@ -478,6 +478,33 @@ describe("Settings → Engines → custom Claude endpoints", () => {snapshot: { state: "available", authenticated: true }, models: { default: "model", options: [] },}];fixture.bots = [];- expect(renderToStaticMarkup(createElement(EnginesSettings))).toContain("data-claude-endpoints");+ const html = renderToStaticMarkup(createElement(EnginesSettings));+ expect(html).toContain("data-claude-endpoints");+ expect(html).toContain("data-claude-bedrock-endpoints");+ });++ it("leaves the Bedrock section out of a hosted workspace too", () => {+ vi.stubGlobal("window", {});+ vi.stubGlobal("navigator", { userAgent: "Linux" });+ fixture.instances = [hostedClaude()];+ fixture.bots = [];+ expect(renderToStaticMarkup(createElement(EnginesSettings))).not.toContain("data-claude-bedrock-endpoints");+ });++ it("lists a Bedrock engine as its own row alongside a signed-in Claude account", () => {+ vi.stubGlobal("window", {});+ vi.stubGlobal("navigator", { userAgent: "Linux" });+ fixture.instances = [+ { instanceId: "claude", driverKind: "claudeAgent", displayName: "Claude", snapshot: { state: "available", authenticated: true }, models: { default: "claude-sonnet-5", options: [] } },+ {+ instanceId: "claude-bedrock-1", driverKind: "claudeAgent", displayName: "Claude on Bedrock", access: "custom",+ snapshot: { state: "available" }, models: { default: "", options: [] },+ claudeBedrock: { awsProfile: "default", awsRegion: "us-east-1", models: [], opusModel: "", sonnetModel: "", haikuModel: "", smallFastModel: "" },+ },+ ];+ fixture.bots = [];+ const html = renderToStaticMarkup(createElement(EnginesSettings));+ expect(html).toContain("data-claude-bedrock-endpoints");+ expect(html).toContain('data-claude-bedrock="claude-bedrock-1"');});});diff --git a/src/components/EnginesSettings.tsx b/src/components/EnginesSettings.tsxindex 5508d0a41d..baaa86d368 100644--- a/src/components/EnginesSettings.tsx+++ b/src/components/EnginesSettings.tsx@@ -11,6 +11,7 @@ import { AppCopyNotice } from "./EngineAppCopy";import { forgetAppCopySwitches } from "@/state/engine-install";import { AccountsCard, AddAccount, accountGroupOf, accountsReady, type AccountGroup } from "./EngineAccounts";import { ClaudeEndpoints, CodexEndpoints } from "./ClaudeEndpoints";+import { ClaudeBedrockEndpoints } from "./ClaudeBedrock";import { DEVICE_SIGN_IN_COPY, deviceSignInProvider } from "./DeviceSignIn";import { AntigravityFreeSpace } from "./AntigravityFreeSpace";import { CacheKeepWarmSettings } from "./CacheKeepWarmSettings";@@ -518,7 +519,7 @@ export function EnginesSettings({ simple = false, more }: { simple?: boolean; moconst { state } = useStore();// Leaving Settings ends the "now uses the copy OpenMausBot installed" lines.useEffect(() => forgetAppCopySwitches, []);- const listed = state.instances.filter((i) => i.readOnly || i.cli !== undefined || i.cliDefault !== undefined || i.snapshot.state === "unavailable" || isApiKeyEngine(i) || i.claudeEndpoint !== undefined || i.codexEndpoint !== undefined);+ const listed = state.instances.filter((i) => i.readOnly || i.cli !== undefined || i.cliDefault !== undefined || i.snapshot.state === "unavailable" || isApiKeyEngine(i) || i.claudeEndpoint !== undefined || i.claudeBedrock !== undefined || i.codexEndpoint !== undefined);// A provider's accounts share one card, which takes the place of its first account.const groups = new Map<AccountGroup, InstanceInfo[]>();for (const instance of listed) {@@ -540,13 +541,13 @@ export function EnginesSettings({ simple = false, more }: { simple?: boolean; moconst group = groupOf(instance);return group? <AccountsCard group={group} accounts={groups.get(group)!} bare={bare}- advanced={<>{group === "claude" ? <ClaudeEndpoints /> : <CodexEndpoints />}<EngineAdvanced instance={instance} /></>} />+ advanced={<>{group === "claude" ? <><ClaudeEndpoints /><ClaudeBedrockEndpoints /></> : <CodexEndpoints />}<EngineAdvanced instance={instance} /></>} />: <EngineRow instance={instance} bare={bare} />;};if (simple && more) return <><SimpleEngines rows={rows} isReady={isReady} renderEngine={renderEngine} more={more} />- {orphanEndpoints && <div className="px-4"><ClaudeEndpoints /></div>}+ {orphanEndpoints && <div className="px-4"><ClaudeEndpoints /><ClaudeBedrockEndpoints /></div>}{orphanCodexEndpoints && <div className="px-4"><CodexEndpoints /></div>}</>;@@ -560,7 +561,7 @@ export function EnginesSettings({ simple = false, more }: { simple?: boolean; mo<RefreshEngines /></div><EngineSections instances={rows} isReady={isReady} renderEngine={renderEngine} />- {orphanEndpoints && <div className="px-4"><ClaudeEndpoints /></div>}+ {orphanEndpoints && <div className="px-4"><ClaudeEndpoints /><ClaudeBedrockEndpoints /></div>}{orphanCodexEndpoints && <div className="px-4"><CodexEndpoints /></div>}<HiddenEngines /><CacheKeepWarmSettings />diff --git a/src/locales/en.json b/src/locales/en.jsonindex cc56755085..e2c1ba5b01 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4537,6 +4537,26 @@"claudeEndpoints.remove": "Remove {name}","claudeEndpoints.removeBody": "This removes the endpoint from app settings. The bots that used it need another model.","claudeEndpoints.failed": "Couldn't save the endpoint. Check the fields and try again.",+ "claudeBedrock.title": "Amazon Bedrock",+ "claudeBedrock.hint": "Run this account's bots on Claude through Amazon Bedrock, signed in with an AWS profile from this computer. It is its own engine, so the Claude Code on this computer and its sign-in stay as they are.",+ "claudeBedrock.awsHint": "Uses the AWS profile from this computer's ~/.aws config. Run `aws sso login --profile …` first if it uses SSO.",+ "claudeBedrock.empty": "No Amazon Bedrock engines yet.",+ "claudeBedrock.add": "Add Amazon Bedrock",+ "claudeBedrock.edit": "Edit",+ "claudeBedrock.name": "Name",+ "claudeBedrock.profile": "AWS profile",+ "claudeBedrock.region": "AWS region",+ "claudeBedrock.model": "Model",+ "claudeBedrock.modelHint": "Optional. Leave it empty and OpenMausBot uses Bedrock's standard Claude models. Each bot then picks its own model.",+ "claudeBedrock.tiers": "Model per tier",+ "claudeBedrock.opus": "Opus model",+ "claudeBedrock.sonnet": "Sonnet model",+ "claudeBedrock.haiku": "Haiku model",+ "claudeBedrock.smallFast": "Small-fast model",+ "claudeBedrock.rowSubtitle": "Bedrock · {profile} · {region}",+ "claudeBedrock.remove": "Remove {name}",+ "claudeBedrock.removeBody": "This removes the Bedrock engine from app settings. The bots that used it need another model.",+ "claudeBedrock.failed": "Couldn't save the Bedrock engine. Check the fields and try again.","engines.none": "No model provider apps detected yet.","engines.footer": "Set CLI points a model provider at a specific binary: a versioned build, a wrapper script, or an absolute path. Changes are saved only when the selected provider is idle. Other providers keep running.","engines.freeSpace.title": "Leftover files",