@caupulican/pi-ai 0.93.18 → 0.94.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -529,6 +529,143 @@ function sanitizeBedrockDocument(value) {
529
529
  }
530
530
  return value;
531
531
  }
532
+ const BEDROCK_ROOT_SCHEMA_COMBINATORS = ["anyOf", "oneOf", "allOf"];
533
+ const BEDROCK_OBJECT_SCHEMA_KEYS = new Set([
534
+ "additionalProperties",
535
+ "dependentRequired",
536
+ "maxProperties",
537
+ "minProperties",
538
+ "patternProperties",
539
+ "properties",
540
+ "propertyNames",
541
+ "required",
542
+ "unevaluatedProperties",
543
+ ]);
544
+ const BEDROCK_FLATTENABLE_BRANCH_KEYS = new Set(["properties", "required", "type"]);
545
+ function isSchemaRecord(value) {
546
+ return typeof value === "object" && value !== null && !Array.isArray(value);
547
+ }
548
+ function resolveBedrockLocalSchemaRef(root, reference) {
549
+ const match = reference.match(/^#\/(\$defs|definitions)\/(.+)$/);
550
+ if (!match)
551
+ return undefined;
552
+ let current = root[match[1]];
553
+ for (const rawPart of match[2].split("/")) {
554
+ if (!isSchemaRecord(current))
555
+ return undefined;
556
+ const part = rawPart.replace(/~1/g, "/").replace(/~0/g, "~");
557
+ current = current[part];
558
+ }
559
+ return current;
560
+ }
561
+ function isObjectShapedBedrockSchema(schema, root, visitedRefs = new Set()) {
562
+ if (schema.type === "object")
563
+ return true;
564
+ if (schema.type !== undefined)
565
+ return false;
566
+ if (typeof schema.$ref === "string") {
567
+ if (visitedRefs.has(schema.$ref))
568
+ return false;
569
+ const target = resolveBedrockLocalSchemaRef(root, schema.$ref);
570
+ if (!isSchemaRecord(target))
571
+ return false;
572
+ const nextVisitedRefs = new Set(visitedRefs);
573
+ nextVisitedRefs.add(schema.$ref);
574
+ return isObjectShapedBedrockSchema(target, root, nextVisitedRefs);
575
+ }
576
+ if ([...BEDROCK_OBJECT_SCHEMA_KEYS].some((key) => key in schema))
577
+ return true;
578
+ for (const combinator of BEDROCK_ROOT_SCHEMA_COMBINATORS) {
579
+ const branches = schema[combinator];
580
+ if (Array.isArray(branches) && branches.length > 0) {
581
+ return branches.every((branch) => isSchemaRecord(branch) && isObjectShapedBedrockSchema(branch, root, visitedRefs));
582
+ }
583
+ }
584
+ return false;
585
+ }
586
+ /**
587
+ * Bedrock Converse requires every tool inputSchema.json root to have type "object". TypeBox
588
+ * unions used by tools such as write/edit are represented as top-level anyOf object branches,
589
+ * which is valid JSON Schema but rejected by Bedrock before the model is invoked. Flatten only
590
+ * unions whose every branch is an object; execution still validates against the authoritative
591
+ * union schema after the provider response, so this projection cannot broaden the execution
592
+ * contract.
593
+ */
594
+ function normalizeBedrockToolInputSchema(schema) {
595
+ if (!isSchemaRecord(schema) || schema.type === "object")
596
+ return schema;
597
+ // Never let a root combinator override an explicit non-object root type.
598
+ if (schema.type !== undefined)
599
+ return schema;
600
+ const combinator = BEDROCK_ROOT_SCHEMA_COMBINATORS.find((key) => key in schema);
601
+ if (!combinator) {
602
+ return isObjectShapedBedrockSchema(schema, schema) ? { ...schema, type: "object" } : schema;
603
+ }
604
+ if (!Array.isArray(schema[combinator]) || schema[combinator].length === 0)
605
+ return schema;
606
+ const branches = schema[combinator].filter(isSchemaRecord);
607
+ if (branches.length !== schema[combinator].length)
608
+ return schema;
609
+ if (!branches.every((branch) => isObjectShapedBedrockSchema(branch, schema))) {
610
+ return schema;
611
+ }
612
+ // Preserve references, empty object branches, and branch constraints that cannot be safely
613
+ // represented by the flattened property projection. The added root type is sufficient for
614
+ // Bedrock's wire validator while retaining the authoritative schema semantics.
615
+ if (branches.some((branch) => typeof branch.$ref === "string" ||
616
+ Object.keys(branch).some((key) => !BEDROCK_FLATTENABLE_BRANCH_KEYS.has(key)))) {
617
+ return { ...schema, type: "object" };
618
+ }
619
+ const properties = isSchemaRecord(schema.properties) ? { ...schema.properties } : {};
620
+ const serializedProperties = new Map();
621
+ for (const [key, value] of Object.entries(properties)) {
622
+ serializedProperties.set(key, JSON.stringify(value) ?? "<undefined>");
623
+ }
624
+ for (const branch of branches) {
625
+ if (!isSchemaRecord(branch.properties))
626
+ continue;
627
+ for (const [key, value] of Object.entries(branch.properties)) {
628
+ const serialized = JSON.stringify(value) ?? "<undefined>";
629
+ const previous = serializedProperties.get(key);
630
+ if (previous !== undefined && previous !== serialized) {
631
+ // Flattening would silently discard one branch's constraint. Keep the union intact and
632
+ // add only the object root required by Bedrock.
633
+ return { ...schema, type: "object" };
634
+ }
635
+ serializedProperties.set(key, serialized);
636
+ properties[key] = value;
637
+ }
638
+ }
639
+ if (Object.keys(properties).length === 0)
640
+ return { ...schema, type: "object" };
641
+ const normalized = { ...schema, type: "object", properties };
642
+ delete normalized[combinator];
643
+ const requiredSets = branches.map((branch) => new Set(Array.isArray(branch.required)
644
+ ? branch.required.filter((key) => typeof key === "string")
645
+ : []));
646
+ const rootRequired = Array.isArray(schema.required)
647
+ ? schema.required.filter((key) => typeof key === "string")
648
+ : [];
649
+ if (combinator === "allOf") {
650
+ normalized.required = [...new Set([...rootRequired, ...requiredSets.flatMap((required) => [...required])])];
651
+ }
652
+ else {
653
+ const commonRequired = requiredSets[0] ?? new Set();
654
+ for (const required of requiredSets.slice(1)) {
655
+ for (const key of commonRequired)
656
+ if (!required.has(key))
657
+ commonRequired.delete(key);
658
+ }
659
+ normalized.required = [...new Set([...rootRequired, ...commonRequired])];
660
+ }
661
+ return normalized;
662
+ }
663
+ function isBedrockToolInputSchema(value) {
664
+ return isSchemaRecord(value) && value.type === "object";
665
+ }
666
+ function isExplicitBedrockToolChoice(toolChoice) {
667
+ return typeof toolChoice === "object" && toolChoice !== null && toolChoice.type === "tool";
668
+ }
532
669
  function convertToolResultContent(content) {
533
670
  const result = [];
534
671
  for (const c of content) {
@@ -720,13 +857,20 @@ function convertMessages(context, model, cacheRetention, toolNameMap) {
720
857
  function convertToolConfig(tools, toolChoice, toolNameMap) {
721
858
  if (!tools?.length || toolChoice === "none")
722
859
  return undefined;
723
- const bedrockTools = tools.map((tool) => ({
724
- toolSpec: {
725
- name: toolNameMap.toProviderName(tool.name),
726
- description: tool.description,
727
- inputSchema: { json: tool.parameters },
728
- },
729
- }));
860
+ const bedrockTools = [];
861
+ for (const tool of tools) {
862
+ const inputSchema = normalizeBedrockToolInputSchema(tool.parameters);
863
+ if (!isBedrockToolInputSchema(inputSchema)) {
864
+ throw new Error(`Bedrock tool "${tool.name}" requires an object input schema`);
865
+ }
866
+ bedrockTools.push({
867
+ toolSpec: {
868
+ name: toolNameMap.toProviderName(tool.name),
869
+ description: tool.description,
870
+ inputSchema: { json: inputSchema },
871
+ },
872
+ });
873
+ }
730
874
  let bedrockToolChoice;
731
875
  switch (toolChoice) {
732
876
  case "auto":
@@ -736,8 +880,12 @@ function convertToolConfig(tools, toolChoice, toolNameMap) {
736
880
  bedrockToolChoice = { any: {} };
737
881
  break;
738
882
  default:
739
- if (toolChoice?.type === "tool") {
740
- bedrockToolChoice = { tool: { name: toolNameMap.toProviderName(toolChoice.name) } };
883
+ if (isExplicitBedrockToolChoice(toolChoice)) {
884
+ const name = toolNameMap.toProviderName(toolChoice.name);
885
+ if (!bedrockTools.some((tool) => tool.toolSpec?.name === name)) {
886
+ throw new Error(`Bedrock tool "${toolChoice.name}" is not available in this request`);
887
+ }
888
+ bedrockToolChoice = { tool: { name } };
741
889
  }
742
890
  }
743
891
  return { tools: bedrockTools, toolChoice: bedrockToolChoice };
@@ -1 +1 @@
1
- {"version":3,"file":"amazon-bedrock.js","sourceRoot":"","sources":["../../src/providers/amazon-bedrock.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,oBAAoB,EAEpB,8BAA8B,EAC9B,UAAU,IAAI,iBAAiB,EAE/B,cAAc,EACd,QAAQ,EAKR,gBAAgB,EAChB,qBAAqB,EAErB,WAAW,EAMX,gBAAgB,GAChB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,aAAa,EAAE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AAE,EAAE,MAAM,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["import {\n\tBedrockRuntimeClient,\n\ttype BedrockRuntimeClientConfig,\n\tBedrockRuntimeServiceException,\n\tStopReason as BedrockStopReason,\n\ttype Tool as BedrockTool,\n\tCachePointType,\n\tCacheTTL,\n\ttype ContentBlock,\n\ttype ContentBlockDeltaEvent,\n\ttype ContentBlockStartEvent,\n\ttype ContentBlockStopEvent,\n\tConversationRole,\n\tConverseStreamCommand,\n\ttype ConverseStreamMetadataEvent,\n\tImageFormat,\n\ttype Message,\n\ttype SystemContentBlock,\n\ttype ToolChoice,\n\ttype ToolConfiguration,\n\ttype ToolResultContentBlock,\n\tToolResultStatus,\n} from \"@aws-sdk/client-bedrock-runtime\";\nimport { NodeHttpHandler } from \"@smithy/node-http-handler\";\nimport type { BuildMiddleware, DocumentType, MetadataBearer } from \"@smithy/types\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { createHttpProxyAgentsForTarget } from \"../utils/node-http-proxy.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { createToolNameMap, type ToolNameMap } from \"../utils/tool-names.ts\";\nimport { getRecoverableBedrockSsoError } from \"./bedrock-sso.ts\";\nimport {\n\tapplyProviderPayloadHook,\n\tcommitSuccessfulAssistantParse,\n\tcreateAssistantMessage,\n\tmapStandardThinkingEffort,\n\tresolveCacheRetention,\n\tterminateAssistantStreamWithError,\n} from \"./provider-runtime.ts\";\nimport { adjustMaxTokensForThinking, buildBaseOptions, clampReasoning } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\nexport type BedrockThinkingDisplay = \"summarized\" | \"omitted\";\n\nexport interface BedrockOptions extends StreamOptions {\n\tregion?: string;\n\tprofile?: string;\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\t/* See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-reasoning.html for supported models. */\n\treasoning?: ThinkingLevel;\n\t/* Custom token budgets per thinking level. Overrides default budgets. */\n\tthinkingBudgets?: ThinkingBudgets;\n\t/* Only supported by Claude 4.x models, see https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-extended-thinking.html#claude-messages-extended-thinking-tool-use-interleaved */\n\tinterleavedThinking?: boolean;\n\t/**\n\t * Controls how Claude's thinking content is returned in responses.\n\t * - \"summarized\": Thinking blocks contain summarized thinking text (default here).\n\t * - \"omitted\": Thinking content is redacted but the signature still travels back\n\t * for multi-turn continuity, reducing time-to-first-text-token.\n\t *\n\t * Note: Anthropic's API default for Claude Opus 4.8 and Mythos Preview is\n\t * \"omitted\". We default to \"summarized\" here to keep behavior consistent with\n\t * older Claude 4 models. Only applies to Claude models on Bedrock.\n\t */\n\tthinkingDisplay?: BedrockThinkingDisplay;\n\t/** Key-value pairs attached to the inference request for cost allocation tagging.\n\t * Keys: max 64 chars, no `aws:` prefix. Values: max 256 chars. Max 50 pairs.\n\t * Tags appear in AWS Cost Explorer split cost allocation data.\n\t * @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html */\n\trequestMetadata?: Record<string, string>;\n\t/** Bearer token for Bedrock API key authentication.\n\t * When set, bypasses SigV4 signing and sends Authorization: Bearer <token> instead.\n\t * Requires `bedrock:CallWithBearerToken` IAM permission on the token's identity.\n\t * Set via AWS_BEARER_TOKEN_BEDROCK env var or pass directly.\n\t * @see https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html */\n\tbearerToken?: string;\n}\n\ntype Block = (TextContent | ThinkingContent | ToolCall) & { index?: number; partialJson?: string };\n\nconst EMPTY_TEXT_PLACEHOLDER = \"<empty>\";\n\nexport const streamBedrock: StreamFunction<\"bedrock-converse-stream\", BedrockOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions: BedrockOptions = {},\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\t\tconst output = createAssistantMessage(model);\n\n\t\tconst blocks = output.content as Block[];\n\n\t\tconst config: BedrockRuntimeClientConfig = {\n\t\t\tprofile: options.profile?.trim() || undefined,\n\t\t};\n\t\tconst configuredRegion = getConfiguredBedrockRegion(options);\n\t\tconst configuredProfile = getConfiguredBedrockProfile(options);\n\t\tconst recoveryProfile = configuredProfile ?? \"default\";\n\t\tconst hasConfiguredProfile = configuredProfile !== undefined;\n\t\tconst endpointRegion = getStandardBedrockEndpointRegion(model.baseUrl);\n\t\tconst useExplicitEndpoint = shouldUseExplicitBedrockEndpoint(\n\t\t\tmodel.baseUrl,\n\t\t\tconfiguredRegion,\n\t\t\thasConfiguredProfile,\n\t\t);\n\n\t\t// Only pin standard AWS Bedrock runtime endpoints when no region/profile is configured.\n\t\t// This preserves custom endpoints (VPC/proxy) from #3402 without forcing built-in\n\t\t// catalog defaults such as us-east-1 to override AWS_REGION/AWS_PROFILE.\n\t\tif (useExplicitEndpoint) {\n\t\t\tconfig.endpoint = model.baseUrl;\n\t\t}\n\n\t\t// Resolve bearer token for Bedrock API key auth.\n\t\tconst bearerToken = options.bearerToken || process.env.AWS_BEARER_TOKEN_BEDROCK || undefined;\n\t\tconst useBearerToken = bearerToken !== undefined && process.env.AWS_BEDROCK_SKIP_AUTH !== \"1\";\n\n\t\t// in Node.js/Bun environment only\n\t\tif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\t\t\t// Region resolution: explicit option > env vars > SDK default chain.\n\t\t\t// When AWS_PROFILE is set, we leave region undefined so the SDK can\n\t\t\t// resolve it from AWS profile config. Otherwise fall back to us-east-1.\n\t\t\tif (configuredRegion) {\n\t\t\t\tconfig.region = configuredRegion;\n\t\t\t} else if (endpointRegion && useExplicitEndpoint) {\n\t\t\t\tconfig.region = endpointRegion;\n\t\t\t} else if (!hasConfiguredProfile) {\n\t\t\t\tconfig.region = \"us-east-1\";\n\t\t\t}\n\n\t\t\t// Support proxies that don't need authentication\n\t\t\tif (process.env.AWS_BEDROCK_SKIP_AUTH === \"1\") {\n\t\t\t\tconfig.credentials = {\n\t\t\t\t\taccessKeyId: \"dummy-access-key\",\n\t\t\t\t\tsecretAccessKey: \"dummy-secret-key\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst proxyAgents = createHttpProxyAgentsForTarget(model.baseUrl);\n\t\t\tif (proxyAgents) {\n\t\t\t\t// Bedrock runtime uses NodeHttp2Handler by default since v3.798.0, which is based\n\t\t\t\t// on `http2` module and has no support for http agent.\n\t\t\t\t// Use NodeHttpHandler to support HTTP(S) proxy agents.\n\t\t\t\tconfig.requestHandler = new NodeHttpHandler(proxyAgents);\n\t\t\t} else if (process.env.AWS_BEDROCK_FORCE_HTTP1 === \"1\") {\n\t\t\t\t// Some custom endpoints require HTTP/1.1 instead of HTTP/2\n\t\t\t\tconfig.requestHandler = new NodeHttpHandler();\n\t\t\t}\n\t\t} else {\n\t\t\t// Non-Node environment (browser): fall back to us-east-1 since\n\t\t\t// there's no config file resolution available.\n\t\t\tconfig.region =\n\t\t\t\tconfiguredRegion || (endpointRegion && useExplicitEndpoint ? endpointRegion : undefined) || \"us-east-1\";\n\t\t}\n\n\t\tif (useBearerToken) {\n\t\t\tconfig.token = { token: bearerToken };\n\t\t\tconfig.authSchemePreference = [\"httpBearerAuth\"];\n\t\t}\n\n\t\ttry {\n\t\t\tconst cacheRetention = resolveCacheRetention(options.cacheRetention);\n\t\t\tconst inferenceMaxTokens = options.maxTokens ?? (isAnthropicClaudeModel(model) ? model.maxTokens : undefined);\n\t\t\tconst commandInput = await applyProviderPayloadHook(\n\t\t\t\t{\n\t\t\t\t\tmodelId: model.id,\n\t\t\t\t\tmessages: convertMessages(context, model, cacheRetention, toolNameMap),\n\t\t\t\t\tsystem: buildSystemPrompt(context.systemPrompt, model, cacheRetention),\n\t\t\t\t\tinferenceConfig: {\n\t\t\t\t\t\t...(inferenceMaxTokens !== undefined && { maxTokens: inferenceMaxTokens }),\n\t\t\t\t\t\t...(options.temperature !== undefined && { temperature: options.temperature }),\n\t\t\t\t\t},\n\t\t\t\t\ttoolConfig: convertToolConfig(context.tools, options.toolChoice, toolNameMap),\n\t\t\t\t\tadditionalModelRequestFields: buildAdditionalModelRequestFields(model, options),\n\t\t\t\t\t...(options.requestMetadata !== undefined && { requestMetadata: options.requestMetadata }),\n\t\t\t\t},\n\t\t\t\tmodel,\n\t\t\t\toptions.onPayload,\n\t\t\t);\n\t\t\tlet ssoRecoveryAttempted = false;\n\t\t\twhile (true) {\n\t\t\t\tlet receivedResponse = false;\n\t\t\t\ttry {\n\t\t\t\t\tconst client = new BedrockRuntimeClient(config);\n\t\t\t\t\tif (options.headers && Object.keys(options.headers).length > 0) {\n\t\t\t\t\t\taddCustomHeadersMiddleware(client, options.headers);\n\t\t\t\t\t}\n\t\t\t\t\tconst command = new ConverseStreamCommand(commandInput);\n\t\t\t\t\tconst response = await client.send(command, { abortSignal: options.signal });\n\t\t\t\t\treceivedResponse = true;\n\t\t\t\t\tif (response.$metadata.httpStatusCode !== undefined) {\n\t\t\t\t\t\tconst responseHeaders: Record<string, string> = {};\n\t\t\t\t\t\tif (response.$metadata.requestId) {\n\t\t\t\t\t\t\tresponseHeaders[\"x-amzn-requestid\"] = response.$metadata.requestId;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait options?.onResponse?.(\n\t\t\t\t\t\t\t{ status: response.$metadata.httpStatusCode, headers: responseHeaders },\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!response.stream) {\n\t\t\t\t\t\tthrow new Error(\"Bedrock returned a response without a stream\");\n\t\t\t\t\t}\n\t\t\t\t\tfor await (const item of response.stream) {\n\t\t\t\t\t\tif (item.messageStart) {\n\t\t\t\t\t\t\tif (item.messageStart.role !== ConversationRole.ASSISTANT) {\n\t\t\t\t\t\t\t\tthrow new Error(\"Unexpected assistant message start but got user message start instead\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\t\t} else if (item.contentBlockStart) {\n\t\t\t\t\t\t\thandleContentBlockStart(item.contentBlockStart, blocks, output, stream, toolNameMap);\n\t\t\t\t\t\t} else if (item.contentBlockDelta) {\n\t\t\t\t\t\t\thandleContentBlockDelta(item.contentBlockDelta, blocks, output, stream);\n\t\t\t\t\t\t} else if (item.contentBlockStop) {\n\t\t\t\t\t\t\thandleContentBlockStop(item.contentBlockStop, blocks, output, stream);\n\t\t\t\t\t\t} else if (item.messageStop) {\n\t\t\t\t\t\t\tconst mapped = mapStopReason(item.messageStop.stopReason);\n\t\t\t\t\t\t\toutput.stopReason = mapped.stopReason;\n\t\t\t\t\t\t\tif (mapped.errorMessage) output.errorMessage = mapped.errorMessage;\n\t\t\t\t\t\t\tif (output.stopReason !== \"error\" && output.stopReason !== \"aborted\") {\n\t\t\t\t\t\t\t\tcommitSuccessfulAssistantParse(output);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (item.metadata) {\n\t\t\t\t\t\t\thandleMetadata(item.metadata, model, output);\n\t\t\t\t\t\t} else if (item.internalServerException) {\n\t\t\t\t\t\t\tthrow item.internalServerException;\n\t\t\t\t\t\t} else if (item.modelStreamErrorException) {\n\t\t\t\t\t\t\tthrow item.modelStreamErrorException;\n\t\t\t\t\t\t} else if (item.validationException) {\n\t\t\t\t\t\t\tthrow item.validationException;\n\t\t\t\t\t\t} else if (item.throttlingException) {\n\t\t\t\t\t\t\tthrow item.throttlingException;\n\t\t\t\t\t\t} else if (item.serviceUnavailableException) {\n\t\t\t\t\t\t\tthrow item.serviceUnavailableException;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (output.stopReason === \"error\" || output.stopReason === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t\t\t}\n\n\t\t\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\t\t\tstream.end();\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst ssoError = getRecoverableBedrockSsoError(error);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!ssoRecoveryAttempted &&\n\t\t\t\t\t\t!receivedResponse &&\n\t\t\t\t\t\t!options.signal?.aborted &&\n\t\t\t\t\t\toptions.interactionMode !== \"background\" &&\n\t\t\t\t\t\toptions.onInteractiveAuthRecovery &&\n\t\t\t\t\t\tssoError &&\n\t\t\t\t\t\t!useBearerToken &&\n\t\t\t\t\t\tprocess.env.AWS_BEDROCK_SKIP_AUTH !== \"1\" &&\n\t\t\t\t\t\t(await options.onInteractiveAuthRecovery({\n\t\t\t\t\t\t\tmethod: \"aws-sso\",\n\t\t\t\t\t\t\tproviderId: model.provider,\n\t\t\t\t\t\t\tprofile: recoveryProfile,\n\t\t\t\t\t\t\t...(ssoError.name ? { errorName: ssoError.name } : {}),\n\t\t\t\t\t\t\terrorMessage: ssoError.message,\n\t\t\t\t\t\t\t...(options.signal ? { signal: options.signal } : {}),\n\t\t\t\t\t\t}))\n\t\t\t\t\t) {\n\t\t\t\t\t\tssoRecoveryAttempted = true;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tterminateAssistantStreamWithError(stream, output, options.signal, error, {\n\t\t\t\tformatError: formatBedrockError,\n\t\t\t\tscratchFields: [\"index\", \"partialJson\"],\n\t\t\t});\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Human-readable prefixes for Bedrock SDK exception names.\n * The downstream retry logic in agent-session matches patterns like\n * `server.?error` and `service.?unavailable`, so we preserve the legacy\n * prefix format rather than using the raw SDK exception name.\n */\nconst BEDROCK_ERROR_PREFIXES: Record<string, string> = {\n\tInternalServerException: \"Internal server error\",\n\tModelStreamErrorException: \"Model stream error\",\n\tValidationException: \"Validation error\",\n\tThrottlingException: \"Throttling error\",\n\tServiceUnavailableException: \"Service unavailable\",\n};\n\n/**\n * Format a Bedrock error with a human-readable prefix.\n * AWS SDK exceptions (both from `client.send()` and from stream event items)\n * extend BedrockRuntimeServiceException. We map the `.name` to a stable\n * human-readable prefix so downstream consumers (retry logic, context-overflow\n * detection) can distinguish error categories via simple string matching.\n */\nfunction formatBedrockError(error: unknown): string {\n\tconst norm = normalizeProviderError(error);\n\tconst core =\n\t\t!norm.messageCarriesBody && norm.status !== undefined && norm.body !== undefined\n\t\t\t? `${norm.status}: ${norm.body}`\n\t\t\t: norm.message;\n\tif (error instanceof BedrockRuntimeServiceException) {\n\t\tconst prefix = BEDROCK_ERROR_PREFIXES[error.name] ?? error.name;\n\t\treturn `${prefix}: ${core}`;\n\t}\n\treturn core;\n}\n\n/**\n * Header keys that must never be overwritten by caller-supplied headers.\n * `host` and `x-amz-*` participate in the SigV4 canonical request; `authorization`\n * is owned by SigV4 or the bearer-token path (config.token + authSchemePreference).\n * Compared case-insensitively (caller key is lower-cased before lookup).\n */\nconst RESERVED_HEADER_EXACT = new Set([\"authorization\", \"host\"]);\n\nfunction isReservedHeader(key: string): boolean {\n\tconst lower = key.toLowerCase();\n\treturn lower.startsWith(\"x-amz-\") || RESERVED_HEADER_EXACT.has(lower);\n}\n\n/**\n * Attach caller-supplied headers to the outgoing Bedrock request via a Smithy\n * `build`-step middleware. The `build` step runs after request serialisation but\n * before SigV4 signing, so injected headers are covered by the signature. Reserved\n * SigV4 / auth headers (`x-amz-*`, `authorization`, `host`) are silently skipped;\n * all other caller headers override any existing same-named header on the request.\n */\nfunction addCustomHeadersMiddleware(client: BedrockRuntimeClient, headers: Record<string, string>): void {\n\tconst middleware: BuildMiddleware<object, MetadataBearer> = (next) => async (args) => {\n\t\tconst request = args.request;\n\t\tif (request && typeof request === \"object\" && \"headers\" in request) {\n\t\t\tconst requestHeaders = (request as { headers: Record<string, string> }).headers;\n\t\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\t\tif (!isReservedHeader(key)) {\n\t\t\t\t\trequestHeaders[key] = value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn next(args);\n\t};\n\tclient.middlewareStack.add(middleware, { step: \"build\", name: \"pi-ai-custom-headers\", priority: \"low\" });\n}\n\nexport const streamSimpleBedrock: StreamFunction<\"bedrock-converse-stream\", SimpleStreamOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst base = buildBaseOptions(model, options, undefined);\n\tif (!options?.reasoning || options.reasoning === \"off\") {\n\t\treturn streamBedrock(model, context, { ...base, reasoning: undefined } satisfies BedrockOptions);\n\t}\n\n\tif (isAnthropicClaudeModel(model)) {\n\t\tif (supportsAdaptiveThinking(model.id, model.name)) {\n\t\t\treturn streamBedrock(model, context, {\n\t\t\t\t...base,\n\t\t\t\treasoning: options.reasoning,\n\t\t\t\tthinkingBudgets: options.thinkingBudgets,\n\t\t\t} satisfies BedrockOptions);\n\t\t}\n\n\t\t// Undefined means the caller did not request an output cap; let the helper use the model cap.\n\t\t// Do not coerce to 0 here, or the thinking budget would become the entire maxTokens value.\n\t\tconst adjusted = adjustMaxTokensForThinking(\n\t\t\tbase.maxTokens,\n\t\t\tmodel.maxTokens,\n\t\t\toptions.reasoning,\n\t\t\toptions.thinkingBudgets,\n\t\t);\n\n\t\treturn streamBedrock(model, context, {\n\t\t\t...base,\n\t\t\tmaxTokens: adjusted.maxTokens,\n\t\t\treasoning: options.reasoning,\n\t\t\tthinkingBudgets: {\n\t\t\t\t...(options.thinkingBudgets || {}),\n\t\t\t\t[clampReasoning(options.reasoning)!]: adjusted.thinkingBudget,\n\t\t\t},\n\t\t} satisfies BedrockOptions);\n\t}\n\n\treturn streamBedrock(model, context, {\n\t\t...base,\n\t\treasoning: options.reasoning,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t} satisfies BedrockOptions);\n};\n\nfunction handleContentBlockStart(\n\tevent: ContentBlockStartEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\ttoolNameMap: ToolNameMap,\n): void {\n\tconst index = event.contentBlockIndex!;\n\tconst start = event.start;\n\n\tif (start?.toolUse) {\n\t\tconst block: Block = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: start.toolUse.toolUseId || \"\",\n\t\t\tname: toolNameMap.toOriginalName(start.toolUse.name || \"\"),\n\t\t\targuments: {},\n\t\t\tpartialJson: \"\",\n\t\t\tindex,\n\t\t};\n\t\toutput.content.push(block);\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: blocks.length - 1, partial: output });\n\t}\n}\n\nfunction handleContentBlockDelta(\n\tevent: ContentBlockDeltaEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst contentBlockIndex = event.contentBlockIndex!;\n\tconst delta = event.delta;\n\tlet index = blocks.findIndex((b) => b.index === contentBlockIndex);\n\tlet block = blocks[index];\n\n\tif (delta?.text !== undefined) {\n\t\t// If no text block exists yet, create one, as `handleContentBlockStart` is not sent for text blocks\n\t\tif (!block) {\n\t\t\tconst newBlock: Block = { type: \"text\", text: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tindex = blocks.length - 1;\n\t\t\tblock = blocks[index];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: output });\n\t\t}\n\t\tif (block.type === \"text\") {\n\t\t\tblock.text += delta.text;\n\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: delta.text, partial: output });\n\t\t}\n\t} else if (delta?.toolUse && block?.type === \"toolCall\") {\n\t\tblock.partialJson = (block.partialJson || \"\") + (delta.toolUse.input || \"\");\n\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: delta.toolUse.input || \"\", partial: output });\n\t} else if (delta?.reasoningContent) {\n\t\tlet thinkingBlock = block;\n\t\tlet thinkingIndex = index;\n\n\t\tif (!thinkingBlock) {\n\t\t\tconst newBlock: Block = { type: \"thinking\", thinking: \"\", thinkingSignature: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tthinkingIndex = blocks.length - 1;\n\t\t\tthinkingBlock = blocks[thinkingIndex];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: thinkingIndex, partial: output });\n\t\t}\n\n\t\tif (thinkingBlock?.type === \"thinking\") {\n\t\t\tif (delta.reasoningContent.text) {\n\t\t\t\tthinkingBlock.thinking += delta.reasoningContent.text;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: thinkingIndex,\n\t\t\t\t\tdelta: delta.reasoningContent.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (delta.reasoningContent.redactedContent) {\n\t\t\t\tthinkingBlock.redacted = true;\n\t\t\t\tthinkingBlock.thinkingSignature = appendBase64Bytes(\n\t\t\t\t\tthinkingBlock.thinkingSignature,\n\t\t\t\t\tdelta.reasoningContent.redactedContent,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (delta.reasoningContent.signature) {\n\t\t\t\tthinkingBlock.thinkingSignature =\n\t\t\t\t\t(thinkingBlock.thinkingSignature || \"\") + delta.reasoningContent.signature;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction handleMetadata(\n\tevent: ConverseStreamMetadataEvent,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toutput: AssistantMessage,\n): void {\n\tif (event.usage) {\n\t\toutput.usage.input = event.usage.inputTokens || 0;\n\t\toutput.usage.output = event.usage.outputTokens || 0;\n\t\toutput.usage.cacheRead = event.usage.cacheReadInputTokens || 0;\n\t\toutput.usage.cacheWrite = event.usage.cacheWriteInputTokens || 0;\n\t\toutput.usage.totalTokens = event.usage.totalTokens || output.usage.input + output.usage.output;\n\t\tcalculateCost(model, output.usage);\n\t}\n}\n\nfunction handleContentBlockStop(\n\tevent: ContentBlockStopEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst index = blocks.findIndex((b) => b.index === event.contentBlockIndex);\n\tconst block = blocks[index];\n\tif (!block) return;\n\tdelete (block as Block).index;\n\n\tswitch (block.type) {\n\t\tcase \"text\":\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: output });\n\t\t\tbreak;\n\t\tcase \"thinking\":\n\t\t\tstream.push({ type: \"thinking_end\", contentIndex: index, content: block.thinking, partial: output });\n\t\t\tbreak;\n\t\tcase \"toolCall\":\n\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t\t// carries parsed arguments.\n\t\t\tdelete (block as Block).partialJson;\n\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: output });\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Check if the model supports adaptive thinking (Opus 4.6+, Sonnet 4.6).\n * Checks both model ID and model name to support application inference profiles\n * whose ARNs don't contain the model name.\n */\nfunction getModelMatchCandidates(modelId: string, modelName?: string): string[] {\n\tconst values = modelName ? [modelId, modelName] : [modelId];\n\treturn values.flatMap((value) => {\n\t\tconst lower = value.toLowerCase();\n\t\treturn [lower, lower.replace(/[\\s_.:]+/g, \"-\")];\n\t});\n}\n\nfunction supportsAdaptiveThinking(modelId: string, modelName?: string): boolean {\n\tconst candidates = getModelMatchCandidates(modelId, modelName);\n\treturn candidates.some(\n\t\t(s) =>\n\t\t\ts.includes(\"opus-4-6\") ||\n\t\t\ts.includes(\"opus-4-7\") ||\n\t\t\ts.includes(\"opus-4-8\") ||\n\t\t\ts.includes(\"opus-5\") ||\n\t\t\ts.includes(\"sonnet-4-6\") ||\n\t\t\ts.includes(\"sonnet-5\") ||\n\t\t\ts.includes(\"fable-5\"),\n\t);\n}\n\nfunction supportsNativeXhighEffort(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst candidates = getModelMatchCandidates(model.id, model.name);\n\treturn candidates.some(\n\t\t(s) =>\n\t\t\ts.includes(\"opus-4-7\") ||\n\t\t\ts.includes(\"opus-4-8\") ||\n\t\t\ts.includes(\"opus-5\") ||\n\t\t\ts.includes(\"sonnet-5\") ||\n\t\t\ts.includes(\"fable-5\"),\n\t);\n}\n\nfunction mapThinkingLevelToEffort(\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tlevel: SimpleStreamOptions[\"reasoning\"],\n): \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" {\n\tif (level === \"xhigh\" && supportsNativeXhighEffort(model)) return \"xhigh\";\n\treturn mapStandardThinkingEffort(model, level) as \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n}\n\n/**\n * Check if the model is an Anthropic Claude model on Bedrock.\n * Checks both model ID and model name to support application inference profiles\n * whose ARNs don't contain the model name.\n */\nfunction isAnthropicClaudeModel(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst id = model.id.toLowerCase();\n\tconst name = model.name?.toLowerCase() ?? \"\";\n\treturn (\n\t\tid.includes(\"anthropic.claude\") ||\n\t\tid.includes(\"anthropic/claude\") ||\n\t\tname.includes(\"anthropic.claude\") ||\n\t\tname.includes(\"anthropic/claude\") ||\n\t\tname.includes(\"claude\")\n\t);\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models\n *\n * For base models and system-defined inference profiles the model ID / ARN\n * contains the model name, so we can decide locally.\n *\n * For application inference profiles (whose ARNs don't contain the model name),\n * also checks model.name which is user-controlled via models.json or registerProvider.\n * As a last resort, set AWS_BEDROCK_FORCE_CACHE=1 to enable cache points.\n * Amazon Nova models have automatic caching and don't need explicit cache points.\n */\nfunction supportsPromptCaching(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst candidates = getModelMatchCandidates(model.id, model.name);\n\n\tconst hasClaudeRef = candidates.some((s) => s.includes(\"claude\"));\n\tif (!hasClaudeRef) {\n\t\t// Application inference profiles don't contain the model name in the ARN.\n\t\t// Allow users to force cache points via environment variable.\n\t\tif (typeof process !== \"undefined\" && process.env.AWS_BEDROCK_FORCE_CACHE === \"1\") return true;\n\t\treturn false;\n\t}\n\t// Claude 5 models (fable-5, opus-5, sonnet-5)\n\tif (candidates.some((s) => s.includes(\"fable-5\") || s.includes(\"opus-5\") || s.includes(\"sonnet-5\"))) return true;\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (candidates.some((s) => s.includes(\"-4-\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (candidates.some((s) => s.includes(\"claude-3-7-sonnet\"))) return true;\n\t// Claude 3.5 Haiku\n\tif (candidates.some((s) => s.includes(\"claude-3-5-haiku\"))) return true;\n\treturn false;\n}\n\n/**\n * Check if the model supports thinking signatures in reasoningContent.\n * Only Anthropic Claude models support the signature field.\n * Other models (OpenAI, Qwen, Minimax, Moonshot, etc.) reject it with:\n * \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n *\n * Checks both model ID and model name to support application inference profiles.\n */\nfunction supportsThinkingSignature(model: Model<\"bedrock-converse-stream\">): boolean {\n\treturn isAnthropicClaudeModel(model);\n}\n\nfunction buildSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n): SystemContentBlock[] | undefined {\n\tif (!systemPrompt) return undefined;\n\n\tconst blocks: SystemContentBlock[] = [{ text: sanitizeSurrogates(systemPrompt) }];\n\n\t// Add cache point for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model)) {\n\t\tblocks.push({\n\t\t\tcachePoint: { type: CachePointType.DEFAULT, ...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}) },\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nfunction normalizeToolCallId(id: string): string {\n\tconst sanitized = id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\treturn sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n}\n\nfunction createNonBlankTextBlock(text: string): ContentBlock.TextMember | undefined {\n\tconst sanitized = sanitizeSurrogates(text);\n\treturn sanitized.trim().length === 0 ? undefined : { text: sanitized };\n}\n\nfunction createRequiredTextBlock(text: string): ContentBlock.TextMember {\n\treturn createNonBlankTextBlock(text) ?? { text: EMPTY_TEXT_PLACEHOLDER };\n}\n\nfunction sanitizeBedrockDocument(value: DocumentType): DocumentType {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sanitizeBedrockDocument);\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value)\n\t\t\t\t.filter(([key]) => key.length > 0)\n\t\t\t\t.map(([key, nestedValue]) => [key, sanitizeBedrockDocument(nestedValue)]),\n\t\t);\n\t}\n\treturn value;\n}\n\nfunction convertToolResultContent(content: (TextContent | ImageContent)[]): ToolResultContentBlock[] {\n\tconst result: ToolResultContentBlock[] = [];\n\tfor (const c of content) {\n\t\tif (c.type === \"image\") {\n\t\t\tresult.push({ image: createImageBlock(c.mimeType, c.data) });\n\t\t} else {\n\t\t\tconst textBlock = createNonBlankTextBlock(c.text);\n\t\t\tif (textBlock) result.push(textBlock);\n\t\t}\n\t}\n\tif (result.length === 0) result.push({ text: EMPTY_TEXT_PLACEHOLDER });\n\treturn result;\n}\n\nfunction convertMessages(\n\tcontext: Context,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n\ttoolNameMap: ToolNameMap,\n): Message[] {\n\tconst result: Message[] = [];\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst m = transformedMessages[i];\n\n\t\tswitch (m.role) {\n\t\t\tcase \"user\": {\n\t\t\t\tconst content: ContentBlock[] = [];\n\t\t\t\tif (typeof m.content === \"string\") {\n\t\t\t\t\tcontent.push(createRequiredTextBlock(m.content));\n\t\t\t\t} else {\n\t\t\t\t\tfor (const c of m.content) {\n\t\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\t\tcase \"text\": {\n\t\t\t\t\t\t\t\tconst textBlock = createNonBlankTextBlock(c.text);\n\t\t\t\t\t\t\t\tif (textBlock) content.push(textBlock);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase \"image\":\n\t\t\t\t\t\t\t\tcontent.push({ image: createImageBlock(c.mimeType, c.data) });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (content.length === 0) content.push({ text: EMPTY_TEXT_PLACEHOLDER });\n\t\t\t\t}\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"assistant\": {\n\t\t\t\t// Skip assistant messages with empty content (e.g., from aborted requests)\n\t\t\t\t// Bedrock rejects messages with empty content arrays\n\t\t\t\tif (m.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst contentBlocks: ContentBlock[] = [];\n\t\t\t\tfor (const c of m.content) {\n\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\tcase \"text\": {\n\t\t\t\t\t\t\t// Skip empty text blocks\n\t\t\t\t\t\t\tconst textBlock = createNonBlankTextBlock(c.text);\n\t\t\t\t\t\t\tif (!textBlock) continue;\n\t\t\t\t\t\t\tcontentBlocks.push(textBlock);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"toolCall\":\n\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\ttoolUse: {\n\t\t\t\t\t\t\t\t\ttoolUseId: c.id,\n\t\t\t\t\t\t\t\t\tname: toolNameMap.toProviderName(c.name),\n\t\t\t\t\t\t\t\t\tinput: sanitizeBedrockDocument(c.arguments),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"thinking\": {\n\t\t\t\t\t\t\tif (c.redacted) {\n\t\t\t\t\t\t\t\tif (c.thinkingSignature?.trim()) {\n\t\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\t\tredactedContent: base64ToBytes(c.thinkingSignature),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Skip empty thinking blocks\n\t\t\t\t\t\t\tconst thinking = sanitizeSurrogates(c.thinking);\n\t\t\t\t\t\t\tif (thinking.trim().length === 0) continue;\n\t\t\t\t\t\t\t// Only Anthropic models support the signature field in reasoningText.\n\t\t\t\t\t\t\t// For other models, we omit the signature to avoid errors like:\n\t\t\t\t\t\t\t// \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n\t\t\t\t\t\t\tif (supportsThinkingSignature(model)) {\n\t\t\t\t\t\t\t\t// Signatures arrive after thinking deltas. If a partial or externally\n\t\t\t\t\t\t\t\t// persisted message lacks a signature, Bedrock rejects the replayed\n\t\t\t\t\t\t\t\t// reasoning block. Fall back to plain text, matching Anthropic.\n\t\t\t\t\t\t\t\tif (!c.thinkingSignature || c.thinkingSignature.trim().length === 0) {\n\t\t\t\t\t\t\t\t\tcontentBlocks.push({ text: thinking });\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\t\treasoningText: {\n\t\t\t\t\t\t\t\t\t\t\t\ttext: thinking,\n\t\t\t\t\t\t\t\t\t\t\t\tsignature: c.thinkingSignature,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\treasoningText: { text: thinking },\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Skip if all content blocks were filtered out\n\t\t\t\tif (contentBlocks.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.ASSISTANT,\n\t\t\t\t\tcontent: contentBlocks,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolResult\": {\n\t\t\t\t// Collect all consecutive toolResult messages into a single user message\n\t\t\t\t// Bedrock requires all tool results to be in one message\n\t\t\t\tconst toolResults: ContentBlock.ToolResultMember[] = [];\n\n\t\t\t\t// Add current tool result with all content blocks combined\n\t\t\t\ttoolResults.push({\n\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\ttoolUseId: m.toolCallId,\n\t\t\t\t\t\tcontent: convertToolResultContent(m.content),\n\t\t\t\t\t\tstatus: m.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// Look ahead for consecutive toolResult messages\n\t\t\t\tlet j = i + 1;\n\t\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\t\tconst nextMsg = transformedMessages[j] as ToolResultMessage;\n\t\t\t\t\ttoolResults.push({\n\t\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\t\ttoolUseId: nextMsg.toolCallId,\n\t\t\t\t\t\t\tcontent: convertToolResultContent(nextMsg.content),\n\t\t\t\t\t\t\tstatus: nextMsg.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tj++;\n\t\t\t\t}\n\n\t\t\t\t// Skip the messages we've already processed\n\t\t\t\ti = j - 1;\n\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent: toolResults,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\n\t// Add cache point to the last user message for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model) && result.length > 0) {\n\t\tconst lastMessage = result[result.length - 1];\n\t\tif (lastMessage.role === ConversationRole.USER && lastMessage.content) {\n\t\t\t(lastMessage.content as ContentBlock[]).push({\n\t\t\t\tcachePoint: {\n\t\t\t\t\ttype: CachePointType.DEFAULT,\n\t\t\t\t\t...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}),\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction convertToolConfig(\n\ttools: Tool[] | undefined,\n\ttoolChoice: BedrockOptions[\"toolChoice\"],\n\ttoolNameMap: ToolNameMap,\n): ToolConfiguration | undefined {\n\tif (!tools?.length || toolChoice === \"none\") return undefined;\n\n\tconst bedrockTools: BedrockTool[] = tools.map((tool) => ({\n\t\ttoolSpec: {\n\t\t\tname: toolNameMap.toProviderName(tool.name),\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: { json: tool.parameters as unknown as DocumentType },\n\t\t},\n\t}));\n\n\tlet bedrockToolChoice: ToolChoice | undefined;\n\tswitch (toolChoice) {\n\t\tcase \"auto\":\n\t\t\tbedrockToolChoice = { auto: {} };\n\t\t\tbreak;\n\t\tcase \"any\":\n\t\t\tbedrockToolChoice = { any: {} };\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (toolChoice?.type === \"tool\") {\n\t\t\t\tbedrockToolChoice = { tool: { name: toolNameMap.toProviderName(toolChoice.name) } };\n\t\t\t}\n\t}\n\n\treturn { tools: bedrockTools, toolChoice: bedrockToolChoice };\n}\n\nfunction mapStopReason(reason: string | undefined): { stopReason: StopReason; errorMessage?: string } {\n\tswitch (reason) {\n\t\tcase BedrockStopReason.END_TURN:\n\t\tcase BedrockStopReason.STOP_SEQUENCE:\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase BedrockStopReason.MAX_TOKENS:\n\t\tcase BedrockStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase BedrockStopReason.TOOL_USE:\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tdefault:\n\t\t\treturn reason ? { stopReason: \"error\", errorMessage: reason } : { stopReason: \"error\" };\n\t}\n}\n\nfunction getConfiguredBedrockRegion(options: BedrockOptions): string | undefined {\n\tif (typeof process === \"undefined\") {\n\t\treturn options.region;\n\t}\n\n\treturn options.region || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || undefined;\n}\n\nfunction getConfiguredBedrockProfile(options: BedrockOptions): string | undefined {\n\tif (typeof process === \"undefined\") {\n\t\treturn options.profile?.trim() || undefined;\n\t}\n\n\treturn options.profile?.trim() || process.env.AWS_PROFILE?.trim() || undefined;\n}\n\nfunction getStandardBedrockEndpointRegion(baseUrl: string | undefined): string | undefined {\n\tif (!baseUrl) {\n\t\treturn undefined;\n\t}\n\n\ttry {\n\t\tconst { hostname } = new URL(baseUrl);\n\t\tconst match = hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\\.([a-z0-9-]+)\\.amazonaws\\.com(?:\\.cn)?$/);\n\t\treturn match?.[1];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction shouldUseExplicitBedrockEndpoint(\n\tbaseUrl: string,\n\tconfiguredRegion: string | undefined,\n\thasConfiguredProfile: boolean,\n): boolean {\n\tconst endpointRegion = getStandardBedrockEndpointRegion(baseUrl);\n\tif (!endpointRegion) {\n\t\treturn true;\n\t}\n\n\treturn !configuredRegion && !hasConfiguredProfile;\n}\n\nfunction isGovCloudBedrockTarget(model: Model<\"bedrock-converse-stream\">, options: BedrockOptions): boolean {\n\tconst region = getConfiguredBedrockRegion(options);\n\tif (region?.toLowerCase().startsWith(\"us-gov-\")) {\n\t\treturn true;\n\t}\n\n\tconst modelId = model.id.toLowerCase();\n\treturn modelId.startsWith(\"us-gov.\") || modelId.startsWith(\"arn:aws-us-gov:\");\n}\n\nfunction buildAdditionalModelRequestFields(\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toptions: BedrockOptions,\n): Record<string, DocumentType> | undefined {\n\tif (!options.reasoning || !model.reasoning) {\n\t\treturn undefined;\n\t}\n\n\tif (isAnthropicClaudeModel(model)) {\n\t\t// GovCloud Bedrock currently rejects the Claude thinking.display field.\n\t\t// Omit it there until the GovCloud Converse schema catches up.\n\t\tconst display = isGovCloudBedrockTarget(model, options) ? undefined : (options.thinkingDisplay ?? \"summarized\");\n\t\tconst result: Record<string, DocumentType> = supportsAdaptiveThinking(model.id, model.name)\n\t\t\t? {\n\t\t\t\t\tthinking: { type: \"adaptive\", ...(display !== undefined ? { display } : {}) },\n\t\t\t\t\toutput_config: { effort: mapThinkingLevelToEffort(model, options.reasoning) },\n\t\t\t\t}\n\t\t\t: (() => {\n\t\t\t\t\tconst defaultBudgets: Record<ThinkingLevel, number> = {\n\t\t\t\t\t\tminimal: 1024,\n\t\t\t\t\t\tlow: 2048,\n\t\t\t\t\t\tmedium: 8192,\n\t\t\t\t\t\thigh: 16384,\n\t\t\t\t\t\txhigh: 16384, // Claude doesn't support xhigh, clamp to high\n\t\t\t\t\t\tmax: 16384, // Claude doesn't support max, clamp to high\n\t\t\t\t\t\tultra: 16384, // Ultra maps to Claude's strongest supported non-adaptive wire effort\n\t\t\t\t\t};\n\n\t\t\t\t\t// Custom budgets override defaults (extended levels are not in ThinkingBudgets, use high).\n\t\t\t\t\tconst level =\n\t\t\t\t\t\toptions.reasoning === \"xhigh\" || options.reasoning === \"max\" || options.reasoning === \"ultra\"\n\t\t\t\t\t\t\t? \"high\"\n\t\t\t\t\t\t\t: options.reasoning;\n\t\t\t\t\tconst budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning];\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tthinking: {\n\t\t\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t\t\tbudget_tokens: budget,\n\t\t\t\t\t\t\t...(display !== undefined ? { display } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t})();\n\n\t\tif (!supportsAdaptiveThinking(model.id, model.name) && (options.interleavedThinking ?? true)) {\n\t\t\tresult.anthropic_beta = [\"interleaved-thinking-2025-05-14\"];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\treturn undefined;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) {\n\t\tbinary += String.fromCharCode(byte);\n\t}\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(data: string): Uint8Array {\n\tconst binaryString = atob(data);\n\tconst bytes = new Uint8Array(binaryString.length);\n\tfor (let i = 0; i < binaryString.length; i++) {\n\t\tbytes[i] = binaryString.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n\nfunction appendBase64Bytes(existingBase64: string | undefined, bytes: Uint8Array): string {\n\tif (!existingBase64) return bytesToBase64(bytes);\n\n\tconst existing = base64ToBytes(existingBase64);\n\tconst merged = new Uint8Array(existing.length + bytes.length);\n\tmerged.set(existing);\n\tmerged.set(bytes, existing.length);\n\treturn bytesToBase64(merged);\n}\n\nfunction createImageBlock(mimeType: string, data: string) {\n\tlet format: ImageFormat;\n\tswitch (mimeType) {\n\t\tcase \"image/jpeg\":\n\t\tcase \"image/jpg\":\n\t\t\tformat = ImageFormat.JPEG;\n\t\t\tbreak;\n\t\tcase \"image/png\":\n\t\t\tformat = ImageFormat.PNG;\n\t\t\tbreak;\n\t\tcase \"image/gif\":\n\t\t\tformat = ImageFormat.GIF;\n\t\t\tbreak;\n\t\tcase \"image/webp\":\n\t\t\tformat = ImageFormat.WEBP;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown image type: ${mimeType}`);\n\t}\n\n\treturn { source: { bytes: base64ToBytes(data) }, format };\n}\n"]}
1
+ {"version":3,"file":"amazon-bedrock.js","sourceRoot":"","sources":["../../src/providers/amazon-bedrock.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,oBAAoB,EAEpB,8BAA8B,EAC9B,UAAU,IAAI,iBAAiB,EAE/B,cAAc,EACd,QAAQ,EAKR,gBAAgB,EAChB,qBAAqB,EAErB,WAAW,EAMX,gBAAgB,GAChB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAmB7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAA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Aa,CAAC,KAAK,CAAC,CAAC;IAEjD,MAAM,QAAQ,GAAG,aAAa,CAAC,cAAc,CAAC,CAAC;IAC/C,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,QAAQ,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IAC9D,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACrB,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACnC,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,gBAAgB,CAAC,QAAgB,EAAE,IAAY;IACvD,IAAI,MAAmB,CAAC;IACxB,QAAQ,QAAQ,EAAE,CAAC;QAClB,KAAK,YAAY,CAAC;QAClB,KAAK,WAAW;YACf,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC;YAC1B,MAAM;QACP,KAAK,WAAW;YACf,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC;YACzB,MAAM;QACP,KAAK,WAAW;YACf,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC;YACzB,MAAM;QACP,KAAK,YAAY;YAChB,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC;YAC1B,MAAM;QACP;YACC,MAAM,IAAI,KAAK,CAAC,uBAAuB,QAAQ,EAAE,CAAC,CAAC;IACrD,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,aAAa,CAAC,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["import {\n\tBedrockRuntimeClient,\n\ttype BedrockRuntimeClientConfig,\n\tBedrockRuntimeServiceException,\n\tStopReason as BedrockStopReason,\n\ttype Tool as BedrockTool,\n\tCachePointType,\n\tCacheTTL,\n\ttype ContentBlock,\n\ttype ContentBlockDeltaEvent,\n\ttype ContentBlockStartEvent,\n\ttype ContentBlockStopEvent,\n\tConversationRole,\n\tConverseStreamCommand,\n\ttype ConverseStreamMetadataEvent,\n\tImageFormat,\n\ttype Message,\n\ttype SystemContentBlock,\n\ttype ToolChoice,\n\ttype ToolConfiguration,\n\ttype ToolResultContentBlock,\n\tToolResultStatus,\n} from \"@aws-sdk/client-bedrock-runtime\";\nimport { NodeHttpHandler } from \"@smithy/node-http-handler\";\nimport type { BuildMiddleware, DocumentType, MetadataBearer } from \"@smithy/types\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tImageContent,\n\tModel,\n\tSimpleStreamOptions,\n\tStopReason,\n\tStreamFunction,\n\tStreamOptions,\n\tTextContent,\n\tThinkingBudgets,\n\tThinkingContent,\n\tThinkingLevel,\n\tTool,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\nimport { normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { createHttpProxyAgentsForTarget } from \"../utils/node-http-proxy.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { createToolNameMap, type ToolNameMap } from \"../utils/tool-names.ts\";\nimport { getRecoverableBedrockSsoError } from \"./bedrock-sso.ts\";\nimport {\n\tapplyProviderPayloadHook,\n\tcommitSuccessfulAssistantParse,\n\tcreateAssistantMessage,\n\tmapStandardThinkingEffort,\n\tresolveCacheRetention,\n\tterminateAssistantStreamWithError,\n} from \"./provider-runtime.ts\";\nimport { adjustMaxTokensForThinking, buildBaseOptions, clampReasoning } from \"./simple-options.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\nexport type BedrockThinkingDisplay = \"summarized\" | \"omitted\";\n\nexport interface BedrockOptions extends StreamOptions {\n\tregion?: string;\n\tprofile?: string;\n\ttoolChoice?: \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\t/* See https://docs.aws.amazon.com/bedrock/latest/userguide/inference-reasoning.html for supported models. */\n\treasoning?: ThinkingLevel;\n\t/* Custom token budgets per thinking level. Overrides default budgets. */\n\tthinkingBudgets?: ThinkingBudgets;\n\t/* Only supported by Claude 4.x models, see https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-extended-thinking.html#claude-messages-extended-thinking-tool-use-interleaved */\n\tinterleavedThinking?: boolean;\n\t/**\n\t * Controls how Claude's thinking content is returned in responses.\n\t * - \"summarized\": Thinking blocks contain summarized thinking text (default here).\n\t * - \"omitted\": Thinking content is redacted but the signature still travels back\n\t * for multi-turn continuity, reducing time-to-first-text-token.\n\t *\n\t * Note: Anthropic's API default for Claude Opus 4.8 and Mythos Preview is\n\t * \"omitted\". We default to \"summarized\" here to keep behavior consistent with\n\t * older Claude 4 models. Only applies to Claude models on Bedrock.\n\t */\n\tthinkingDisplay?: BedrockThinkingDisplay;\n\t/** Key-value pairs attached to the inference request for cost allocation tagging.\n\t * Keys: max 64 chars, no `aws:` prefix. Values: max 256 chars. Max 50 pairs.\n\t * Tags appear in AWS Cost Explorer split cost allocation data.\n\t * @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html */\n\trequestMetadata?: Record<string, string>;\n\t/** Bearer token for Bedrock API key authentication.\n\t * When set, bypasses SigV4 signing and sends Authorization: Bearer <token> instead.\n\t * Requires `bedrock:CallWithBearerToken` IAM permission on the token's identity.\n\t * Set via AWS_BEARER_TOKEN_BEDROCK env var or pass directly.\n\t * @see https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html */\n\tbearerToken?: string;\n}\n\ntype Block = (TextContent | ThinkingContent | ToolCall) & { index?: number; partialJson?: string };\n\nconst EMPTY_TEXT_PLACEHOLDER = \"<empty>\";\n\nexport const streamBedrock: StreamFunction<\"bedrock-converse-stream\", BedrockOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions: BedrockOptions = {},\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst toolNameMap = createToolNameMap(context.tools ?? []);\n\t\tconst output = createAssistantMessage(model);\n\n\t\tconst blocks = output.content as Block[];\n\n\t\tconst config: BedrockRuntimeClientConfig = {\n\t\t\tprofile: options.profile?.trim() || undefined,\n\t\t};\n\t\tconst configuredRegion = getConfiguredBedrockRegion(options);\n\t\tconst configuredProfile = getConfiguredBedrockProfile(options);\n\t\tconst recoveryProfile = configuredProfile ?? \"default\";\n\t\tconst hasConfiguredProfile = configuredProfile !== undefined;\n\t\tconst endpointRegion = getStandardBedrockEndpointRegion(model.baseUrl);\n\t\tconst useExplicitEndpoint = shouldUseExplicitBedrockEndpoint(\n\t\t\tmodel.baseUrl,\n\t\t\tconfiguredRegion,\n\t\t\thasConfiguredProfile,\n\t\t);\n\n\t\t// Only pin standard AWS Bedrock runtime endpoints when no region/profile is configured.\n\t\t// This preserves custom endpoints (VPC/proxy) from #3402 without forcing built-in\n\t\t// catalog defaults such as us-east-1 to override AWS_REGION/AWS_PROFILE.\n\t\tif (useExplicitEndpoint) {\n\t\t\tconfig.endpoint = model.baseUrl;\n\t\t}\n\n\t\t// Resolve bearer token for Bedrock API key auth.\n\t\tconst bearerToken = options.bearerToken || process.env.AWS_BEARER_TOKEN_BEDROCK || undefined;\n\t\tconst useBearerToken = bearerToken !== undefined && process.env.AWS_BEDROCK_SKIP_AUTH !== \"1\";\n\n\t\t// in Node.js/Bun environment only\n\t\tif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\t\t\t// Region resolution: explicit option > env vars > SDK default chain.\n\t\t\t// When AWS_PROFILE is set, we leave region undefined so the SDK can\n\t\t\t// resolve it from AWS profile config. Otherwise fall back to us-east-1.\n\t\t\tif (configuredRegion) {\n\t\t\t\tconfig.region = configuredRegion;\n\t\t\t} else if (endpointRegion && useExplicitEndpoint) {\n\t\t\t\tconfig.region = endpointRegion;\n\t\t\t} else if (!hasConfiguredProfile) {\n\t\t\t\tconfig.region = \"us-east-1\";\n\t\t\t}\n\n\t\t\t// Support proxies that don't need authentication\n\t\t\tif (process.env.AWS_BEDROCK_SKIP_AUTH === \"1\") {\n\t\t\t\tconfig.credentials = {\n\t\t\t\t\taccessKeyId: \"dummy-access-key\",\n\t\t\t\t\tsecretAccessKey: \"dummy-secret-key\",\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst proxyAgents = createHttpProxyAgentsForTarget(model.baseUrl);\n\t\t\tif (proxyAgents) {\n\t\t\t\t// Bedrock runtime uses NodeHttp2Handler by default since v3.798.0, which is based\n\t\t\t\t// on `http2` module and has no support for http agent.\n\t\t\t\t// Use NodeHttpHandler to support HTTP(S) proxy agents.\n\t\t\t\tconfig.requestHandler = new NodeHttpHandler(proxyAgents);\n\t\t\t} else if (process.env.AWS_BEDROCK_FORCE_HTTP1 === \"1\") {\n\t\t\t\t// Some custom endpoints require HTTP/1.1 instead of HTTP/2\n\t\t\t\tconfig.requestHandler = new NodeHttpHandler();\n\t\t\t}\n\t\t} else {\n\t\t\t// Non-Node environment (browser): fall back to us-east-1 since\n\t\t\t// there's no config file resolution available.\n\t\t\tconfig.region =\n\t\t\t\tconfiguredRegion || (endpointRegion && useExplicitEndpoint ? endpointRegion : undefined) || \"us-east-1\";\n\t\t}\n\n\t\tif (useBearerToken) {\n\t\t\tconfig.token = { token: bearerToken };\n\t\t\tconfig.authSchemePreference = [\"httpBearerAuth\"];\n\t\t}\n\n\t\ttry {\n\t\t\tconst cacheRetention = resolveCacheRetention(options.cacheRetention);\n\t\t\tconst inferenceMaxTokens = options.maxTokens ?? (isAnthropicClaudeModel(model) ? model.maxTokens : undefined);\n\t\t\tconst commandInput = await applyProviderPayloadHook(\n\t\t\t\t{\n\t\t\t\t\tmodelId: model.id,\n\t\t\t\t\tmessages: convertMessages(context, model, cacheRetention, toolNameMap),\n\t\t\t\t\tsystem: buildSystemPrompt(context.systemPrompt, model, cacheRetention),\n\t\t\t\t\tinferenceConfig: {\n\t\t\t\t\t\t...(inferenceMaxTokens !== undefined && { maxTokens: inferenceMaxTokens }),\n\t\t\t\t\t\t...(options.temperature !== undefined && { temperature: options.temperature }),\n\t\t\t\t\t},\n\t\t\t\t\ttoolConfig: convertToolConfig(context.tools, options.toolChoice, toolNameMap),\n\t\t\t\t\tadditionalModelRequestFields: buildAdditionalModelRequestFields(model, options),\n\t\t\t\t\t...(options.requestMetadata !== undefined && { requestMetadata: options.requestMetadata }),\n\t\t\t\t},\n\t\t\t\tmodel,\n\t\t\t\toptions.onPayload,\n\t\t\t);\n\t\t\tlet ssoRecoveryAttempted = false;\n\t\t\twhile (true) {\n\t\t\t\tlet receivedResponse = false;\n\t\t\t\ttry {\n\t\t\t\t\tconst client = new BedrockRuntimeClient(config);\n\t\t\t\t\tif (options.headers && Object.keys(options.headers).length > 0) {\n\t\t\t\t\t\taddCustomHeadersMiddleware(client, options.headers);\n\t\t\t\t\t}\n\t\t\t\t\tconst command = new ConverseStreamCommand(commandInput);\n\t\t\t\t\tconst response = await client.send(command, { abortSignal: options.signal });\n\t\t\t\t\treceivedResponse = true;\n\t\t\t\t\tif (response.$metadata.httpStatusCode !== undefined) {\n\t\t\t\t\t\tconst responseHeaders: Record<string, string> = {};\n\t\t\t\t\t\tif (response.$metadata.requestId) {\n\t\t\t\t\t\t\tresponseHeaders[\"x-amzn-requestid\"] = response.$metadata.requestId;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait options?.onResponse?.(\n\t\t\t\t\t\t\t{ status: response.$metadata.httpStatusCode, headers: responseHeaders },\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!response.stream) {\n\t\t\t\t\t\tthrow new Error(\"Bedrock returned a response without a stream\");\n\t\t\t\t\t}\n\t\t\t\t\tfor await (const item of response.stream) {\n\t\t\t\t\t\tif (item.messageStart) {\n\t\t\t\t\t\t\tif (item.messageStart.role !== ConversationRole.ASSISTANT) {\n\t\t\t\t\t\t\t\tthrow new Error(\"Unexpected assistant message start but got user message start instead\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\t\t\t\t} else if (item.contentBlockStart) {\n\t\t\t\t\t\t\thandleContentBlockStart(item.contentBlockStart, blocks, output, stream, toolNameMap);\n\t\t\t\t\t\t} else if (item.contentBlockDelta) {\n\t\t\t\t\t\t\thandleContentBlockDelta(item.contentBlockDelta, blocks, output, stream);\n\t\t\t\t\t\t} else if (item.contentBlockStop) {\n\t\t\t\t\t\t\thandleContentBlockStop(item.contentBlockStop, blocks, output, stream);\n\t\t\t\t\t\t} else if (item.messageStop) {\n\t\t\t\t\t\t\tconst mapped = mapStopReason(item.messageStop.stopReason);\n\t\t\t\t\t\t\toutput.stopReason = mapped.stopReason;\n\t\t\t\t\t\t\tif (mapped.errorMessage) output.errorMessage = mapped.errorMessage;\n\t\t\t\t\t\t\tif (output.stopReason !== \"error\" && output.stopReason !== \"aborted\") {\n\t\t\t\t\t\t\t\tcommitSuccessfulAssistantParse(output);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (item.metadata) {\n\t\t\t\t\t\t\thandleMetadata(item.metadata, model, output);\n\t\t\t\t\t\t} else if (item.internalServerException) {\n\t\t\t\t\t\t\tthrow item.internalServerException;\n\t\t\t\t\t\t} else if (item.modelStreamErrorException) {\n\t\t\t\t\t\t\tthrow item.modelStreamErrorException;\n\t\t\t\t\t\t} else if (item.validationException) {\n\t\t\t\t\t\t\tthrow item.validationException;\n\t\t\t\t\t\t} else if (item.throttlingException) {\n\t\t\t\t\t\t\tthrow item.throttlingException;\n\t\t\t\t\t\t} else if (item.serviceUnavailableException) {\n\t\t\t\t\t\t\tthrow item.serviceUnavailableException;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (output.stopReason === \"error\" || output.stopReason === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(output.errorMessage || \"An unknown error occurred\");\n\t\t\t\t\t}\n\n\t\t\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\t\t\tstream.end();\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst ssoError = getRecoverableBedrockSsoError(error);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!ssoRecoveryAttempted &&\n\t\t\t\t\t\t!receivedResponse &&\n\t\t\t\t\t\t!options.signal?.aborted &&\n\t\t\t\t\t\toptions.interactionMode !== \"background\" &&\n\t\t\t\t\t\toptions.onInteractiveAuthRecovery &&\n\t\t\t\t\t\tssoError &&\n\t\t\t\t\t\t!useBearerToken &&\n\t\t\t\t\t\tprocess.env.AWS_BEDROCK_SKIP_AUTH !== \"1\" &&\n\t\t\t\t\t\t(await options.onInteractiveAuthRecovery({\n\t\t\t\t\t\t\tmethod: \"aws-sso\",\n\t\t\t\t\t\t\tproviderId: model.provider,\n\t\t\t\t\t\t\tprofile: recoveryProfile,\n\t\t\t\t\t\t\t...(ssoError.name ? { errorName: ssoError.name } : {}),\n\t\t\t\t\t\t\terrorMessage: ssoError.message,\n\t\t\t\t\t\t\t...(options.signal ? { signal: options.signal } : {}),\n\t\t\t\t\t\t}))\n\t\t\t\t\t) {\n\t\t\t\t\t\tssoRecoveryAttempted = true;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tterminateAssistantStreamWithError(stream, output, options.signal, error, {\n\t\t\t\tformatError: formatBedrockError,\n\t\t\t\tscratchFields: [\"index\", \"partialJson\"],\n\t\t\t});\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\n/**\n * Human-readable prefixes for Bedrock SDK exception names.\n * The downstream retry logic in agent-session matches patterns like\n * `server.?error` and `service.?unavailable`, so we preserve the legacy\n * prefix format rather than using the raw SDK exception name.\n */\nconst BEDROCK_ERROR_PREFIXES: Record<string, string> = {\n\tInternalServerException: \"Internal server error\",\n\tModelStreamErrorException: \"Model stream error\",\n\tValidationException: \"Validation error\",\n\tThrottlingException: \"Throttling error\",\n\tServiceUnavailableException: \"Service unavailable\",\n};\n\n/**\n * Format a Bedrock error with a human-readable prefix.\n * AWS SDK exceptions (both from `client.send()` and from stream event items)\n * extend BedrockRuntimeServiceException. We map the `.name` to a stable\n * human-readable prefix so downstream consumers (retry logic, context-overflow\n * detection) can distinguish error categories via simple string matching.\n */\nfunction formatBedrockError(error: unknown): string {\n\tconst norm = normalizeProviderError(error);\n\tconst core =\n\t\t!norm.messageCarriesBody && norm.status !== undefined && norm.body !== undefined\n\t\t\t? `${norm.status}: ${norm.body}`\n\t\t\t: norm.message;\n\tif (error instanceof BedrockRuntimeServiceException) {\n\t\tconst prefix = BEDROCK_ERROR_PREFIXES[error.name] ?? error.name;\n\t\treturn `${prefix}: ${core}`;\n\t}\n\treturn core;\n}\n\n/**\n * Header keys that must never be overwritten by caller-supplied headers.\n * `host` and `x-amz-*` participate in the SigV4 canonical request; `authorization`\n * is owned by SigV4 or the bearer-token path (config.token + authSchemePreference).\n * Compared case-insensitively (caller key is lower-cased before lookup).\n */\nconst RESERVED_HEADER_EXACT = new Set([\"authorization\", \"host\"]);\n\nfunction isReservedHeader(key: string): boolean {\n\tconst lower = key.toLowerCase();\n\treturn lower.startsWith(\"x-amz-\") || RESERVED_HEADER_EXACT.has(lower);\n}\n\n/**\n * Attach caller-supplied headers to the outgoing Bedrock request via a Smithy\n * `build`-step middleware. The `build` step runs after request serialisation but\n * before SigV4 signing, so injected headers are covered by the signature. Reserved\n * SigV4 / auth headers (`x-amz-*`, `authorization`, `host`) are silently skipped;\n * all other caller headers override any existing same-named header on the request.\n */\nfunction addCustomHeadersMiddleware(client: BedrockRuntimeClient, headers: Record<string, string>): void {\n\tconst middleware: BuildMiddleware<object, MetadataBearer> = (next) => async (args) => {\n\t\tconst request = args.request;\n\t\tif (request && typeof request === \"object\" && \"headers\" in request) {\n\t\t\tconst requestHeaders = (request as { headers: Record<string, string> }).headers;\n\t\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\t\tif (!isReservedHeader(key)) {\n\t\t\t\t\trequestHeaders[key] = value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn next(args);\n\t};\n\tclient.middlewareStack.add(middleware, { step: \"build\", name: \"pi-ai-custom-headers\", priority: \"low\" });\n}\n\nexport const streamSimpleBedrock: StreamFunction<\"bedrock-converse-stream\", SimpleStreamOptions> = (\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst base = buildBaseOptions(model, options, undefined);\n\tif (!options?.reasoning || options.reasoning === \"off\") {\n\t\treturn streamBedrock(model, context, { ...base, reasoning: undefined } satisfies BedrockOptions);\n\t}\n\n\tif (isAnthropicClaudeModel(model)) {\n\t\tif (supportsAdaptiveThinking(model.id, model.name)) {\n\t\t\treturn streamBedrock(model, context, {\n\t\t\t\t...base,\n\t\t\t\treasoning: options.reasoning,\n\t\t\t\tthinkingBudgets: options.thinkingBudgets,\n\t\t\t} satisfies BedrockOptions);\n\t\t}\n\n\t\t// Undefined means the caller did not request an output cap; let the helper use the model cap.\n\t\t// Do not coerce to 0 here, or the thinking budget would become the entire maxTokens value.\n\t\tconst adjusted = adjustMaxTokensForThinking(\n\t\t\tbase.maxTokens,\n\t\t\tmodel.maxTokens,\n\t\t\toptions.reasoning,\n\t\t\toptions.thinkingBudgets,\n\t\t);\n\n\t\treturn streamBedrock(model, context, {\n\t\t\t...base,\n\t\t\tmaxTokens: adjusted.maxTokens,\n\t\t\treasoning: options.reasoning,\n\t\t\tthinkingBudgets: {\n\t\t\t\t...(options.thinkingBudgets || {}),\n\t\t\t\t[clampReasoning(options.reasoning)!]: adjusted.thinkingBudget,\n\t\t\t},\n\t\t} satisfies BedrockOptions);\n\t}\n\n\treturn streamBedrock(model, context, {\n\t\t...base,\n\t\treasoning: options.reasoning,\n\t\tthinkingBudgets: options.thinkingBudgets,\n\t} satisfies BedrockOptions);\n};\n\nfunction handleContentBlockStart(\n\tevent: ContentBlockStartEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\ttoolNameMap: ToolNameMap,\n): void {\n\tconst index = event.contentBlockIndex!;\n\tconst start = event.start;\n\n\tif (start?.toolUse) {\n\t\tconst block: Block = {\n\t\t\ttype: \"toolCall\",\n\t\t\tid: start.toolUse.toolUseId || \"\",\n\t\t\tname: toolNameMap.toOriginalName(start.toolUse.name || \"\"),\n\t\t\targuments: {},\n\t\t\tpartialJson: \"\",\n\t\t\tindex,\n\t\t};\n\t\toutput.content.push(block);\n\t\tstream.push({ type: \"toolcall_start\", contentIndex: blocks.length - 1, partial: output });\n\t}\n}\n\nfunction handleContentBlockDelta(\n\tevent: ContentBlockDeltaEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst contentBlockIndex = event.contentBlockIndex!;\n\tconst delta = event.delta;\n\tlet index = blocks.findIndex((b) => b.index === contentBlockIndex);\n\tlet block = blocks[index];\n\n\tif (delta?.text !== undefined) {\n\t\t// If no text block exists yet, create one, as `handleContentBlockStart` is not sent for text blocks\n\t\tif (!block) {\n\t\t\tconst newBlock: Block = { type: \"text\", text: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tindex = blocks.length - 1;\n\t\t\tblock = blocks[index];\n\t\t\tstream.push({ type: \"text_start\", contentIndex: index, partial: output });\n\t\t}\n\t\tif (block.type === \"text\") {\n\t\t\tblock.text += delta.text;\n\t\t\tstream.push({ type: \"text_delta\", contentIndex: index, delta: delta.text, partial: output });\n\t\t}\n\t} else if (delta?.toolUse && block?.type === \"toolCall\") {\n\t\tblock.partialJson = (block.partialJson || \"\") + (delta.toolUse.input || \"\");\n\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\tstream.push({ type: \"toolcall_delta\", contentIndex: index, delta: delta.toolUse.input || \"\", partial: output });\n\t} else if (delta?.reasoningContent) {\n\t\tlet thinkingBlock = block;\n\t\tlet thinkingIndex = index;\n\n\t\tif (!thinkingBlock) {\n\t\t\tconst newBlock: Block = { type: \"thinking\", thinking: \"\", thinkingSignature: \"\", index: contentBlockIndex };\n\t\t\toutput.content.push(newBlock);\n\t\t\tthinkingIndex = blocks.length - 1;\n\t\t\tthinkingBlock = blocks[thinkingIndex];\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: thinkingIndex, partial: output });\n\t\t}\n\n\t\tif (thinkingBlock?.type === \"thinking\") {\n\t\t\tif (delta.reasoningContent.text) {\n\t\t\t\tthinkingBlock.thinking += delta.reasoningContent.text;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: thinkingIndex,\n\t\t\t\t\tdelta: delta.reasoningContent.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (delta.reasoningContent.redactedContent) {\n\t\t\t\tthinkingBlock.redacted = true;\n\t\t\t\tthinkingBlock.thinkingSignature = appendBase64Bytes(\n\t\t\t\t\tthinkingBlock.thinkingSignature,\n\t\t\t\t\tdelta.reasoningContent.redactedContent,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (delta.reasoningContent.signature) {\n\t\t\t\tthinkingBlock.thinkingSignature =\n\t\t\t\t\t(thinkingBlock.thinkingSignature || \"\") + delta.reasoningContent.signature;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction handleMetadata(\n\tevent: ConverseStreamMetadataEvent,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toutput: AssistantMessage,\n): void {\n\tif (event.usage) {\n\t\toutput.usage.input = event.usage.inputTokens || 0;\n\t\toutput.usage.output = event.usage.outputTokens || 0;\n\t\toutput.usage.cacheRead = event.usage.cacheReadInputTokens || 0;\n\t\toutput.usage.cacheWrite = event.usage.cacheWriteInputTokens || 0;\n\t\toutput.usage.totalTokens = event.usage.totalTokens || output.usage.input + output.usage.output;\n\t\tcalculateCost(model, output.usage);\n\t}\n}\n\nfunction handleContentBlockStop(\n\tevent: ContentBlockStopEvent,\n\tblocks: Block[],\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n): void {\n\tconst index = blocks.findIndex((b) => b.index === event.contentBlockIndex);\n\tconst block = blocks[index];\n\tif (!block) return;\n\tdelete (block as Block).index;\n\n\tswitch (block.type) {\n\t\tcase \"text\":\n\t\t\tstream.push({ type: \"text_end\", contentIndex: index, content: block.text, partial: output });\n\t\t\tbreak;\n\t\tcase \"thinking\":\n\t\t\tstream.push({ type: \"thinking_end\", contentIndex: index, content: block.thinking, partial: output });\n\t\t\tbreak;\n\t\tcase \"toolCall\":\n\t\t\tblock.arguments = parseStreamingJson(block.partialJson);\n\t\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t\t// carries parsed arguments.\n\t\t\tdelete (block as Block).partialJson;\n\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: index, toolCall: block, partial: output });\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Check if the model supports adaptive thinking (Opus 4.6+, Sonnet 4.6).\n * Checks both model ID and model name to support application inference profiles\n * whose ARNs don't contain the model name.\n */\nfunction getModelMatchCandidates(modelId: string, modelName?: string): string[] {\n\tconst values = modelName ? [modelId, modelName] : [modelId];\n\treturn values.flatMap((value) => {\n\t\tconst lower = value.toLowerCase();\n\t\treturn [lower, lower.replace(/[\\s_.:]+/g, \"-\")];\n\t});\n}\n\nfunction supportsAdaptiveThinking(modelId: string, modelName?: string): boolean {\n\tconst candidates = getModelMatchCandidates(modelId, modelName);\n\treturn candidates.some(\n\t\t(s) =>\n\t\t\ts.includes(\"opus-4-6\") ||\n\t\t\ts.includes(\"opus-4-7\") ||\n\t\t\ts.includes(\"opus-4-8\") ||\n\t\t\ts.includes(\"opus-5\") ||\n\t\t\ts.includes(\"sonnet-4-6\") ||\n\t\t\ts.includes(\"sonnet-5\") ||\n\t\t\ts.includes(\"fable-5\"),\n\t);\n}\n\nfunction supportsNativeXhighEffort(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst candidates = getModelMatchCandidates(model.id, model.name);\n\treturn candidates.some(\n\t\t(s) =>\n\t\t\ts.includes(\"opus-4-7\") ||\n\t\t\ts.includes(\"opus-4-8\") ||\n\t\t\ts.includes(\"opus-5\") ||\n\t\t\ts.includes(\"sonnet-5\") ||\n\t\t\ts.includes(\"fable-5\"),\n\t);\n}\n\nfunction mapThinkingLevelToEffort(\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tlevel: SimpleStreamOptions[\"reasoning\"],\n): \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" {\n\tif (level === \"xhigh\" && supportsNativeXhighEffort(model)) return \"xhigh\";\n\treturn mapStandardThinkingEffort(model, level) as \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n}\n\n/**\n * Check if the model is an Anthropic Claude model on Bedrock.\n * Checks both model ID and model name to support application inference profiles\n * whose ARNs don't contain the model name.\n */\nfunction isAnthropicClaudeModel(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst id = model.id.toLowerCase();\n\tconst name = model.name?.toLowerCase() ?? \"\";\n\treturn (\n\t\tid.includes(\"anthropic.claude\") ||\n\t\tid.includes(\"anthropic/claude\") ||\n\t\tname.includes(\"anthropic.claude\") ||\n\t\tname.includes(\"anthropic/claude\") ||\n\t\tname.includes(\"claude\")\n\t);\n}\n\n/**\n * Check if the model supports prompt caching.\n * Supported: Claude 3.5 Haiku, Claude 3.7 Sonnet, Claude 4.x models\n *\n * For base models and system-defined inference profiles the model ID / ARN\n * contains the model name, so we can decide locally.\n *\n * For application inference profiles (whose ARNs don't contain the model name),\n * also checks model.name which is user-controlled via models.json or registerProvider.\n * As a last resort, set AWS_BEDROCK_FORCE_CACHE=1 to enable cache points.\n * Amazon Nova models have automatic caching and don't need explicit cache points.\n */\nfunction supportsPromptCaching(model: Model<\"bedrock-converse-stream\">): boolean {\n\tconst candidates = getModelMatchCandidates(model.id, model.name);\n\n\tconst hasClaudeRef = candidates.some((s) => s.includes(\"claude\"));\n\tif (!hasClaudeRef) {\n\t\t// Application inference profiles don't contain the model name in the ARN.\n\t\t// Allow users to force cache points via environment variable.\n\t\tif (typeof process !== \"undefined\" && process.env.AWS_BEDROCK_FORCE_CACHE === \"1\") return true;\n\t\treturn false;\n\t}\n\t// Claude 5 models (fable-5, opus-5, sonnet-5)\n\tif (candidates.some((s) => s.includes(\"fable-5\") || s.includes(\"opus-5\") || s.includes(\"sonnet-5\"))) return true;\n\t// Claude 4.x models (opus-4, sonnet-4, haiku-4)\n\tif (candidates.some((s) => s.includes(\"-4-\"))) return true;\n\t// Claude 3.7 Sonnet\n\tif (candidates.some((s) => s.includes(\"claude-3-7-sonnet\"))) return true;\n\t// Claude 3.5 Haiku\n\tif (candidates.some((s) => s.includes(\"claude-3-5-haiku\"))) return true;\n\treturn false;\n}\n\n/**\n * Check if the model supports thinking signatures in reasoningContent.\n * Only Anthropic Claude models support the signature field.\n * Other models (OpenAI, Qwen, Minimax, Moonshot, etc.) reject it with:\n * \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n *\n * Checks both model ID and model name to support application inference profiles.\n */\nfunction supportsThinkingSignature(model: Model<\"bedrock-converse-stream\">): boolean {\n\treturn isAnthropicClaudeModel(model);\n}\n\nfunction buildSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n): SystemContentBlock[] | undefined {\n\tif (!systemPrompt) return undefined;\n\n\tconst blocks: SystemContentBlock[] = [{ text: sanitizeSurrogates(systemPrompt) }];\n\n\t// Add cache point for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model)) {\n\t\tblocks.push({\n\t\t\tcachePoint: { type: CachePointType.DEFAULT, ...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}) },\n\t\t});\n\t}\n\n\treturn blocks;\n}\n\nfunction normalizeToolCallId(id: string): string {\n\tconst sanitized = id.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\treturn sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n}\n\nfunction createNonBlankTextBlock(text: string): ContentBlock.TextMember | undefined {\n\tconst sanitized = sanitizeSurrogates(text);\n\treturn sanitized.trim().length === 0 ? undefined : { text: sanitized };\n}\n\nfunction createRequiredTextBlock(text: string): ContentBlock.TextMember {\n\treturn createNonBlankTextBlock(text) ?? { text: EMPTY_TEXT_PLACEHOLDER };\n}\n\nfunction sanitizeBedrockDocument(value: DocumentType): DocumentType {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(sanitizeBedrockDocument);\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value)\n\t\t\t\t.filter(([key]) => key.length > 0)\n\t\t\t\t.map(([key, nestedValue]) => [key, sanitizeBedrockDocument(nestedValue)]),\n\t\t);\n\t}\n\treturn value;\n}\n\nconst BEDROCK_ROOT_SCHEMA_COMBINATORS = [\"anyOf\", \"oneOf\", \"allOf\"] as const;\nconst BEDROCK_OBJECT_SCHEMA_KEYS = new Set([\n\t\"additionalProperties\",\n\t\"dependentRequired\",\n\t\"maxProperties\",\n\t\"minProperties\",\n\t\"patternProperties\",\n\t\"properties\",\n\t\"propertyNames\",\n\t\"required\",\n\t\"unevaluatedProperties\",\n]);\nconst BEDROCK_FLATTENABLE_BRANCH_KEYS = new Set([\"properties\", \"required\", \"type\"]);\n\nfunction isSchemaRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction resolveBedrockLocalSchemaRef(root: Record<string, unknown>, reference: string): unknown {\n\tconst match = reference.match(/^#\\/(\\$defs|definitions)\\/(.+)$/);\n\tif (!match) return undefined;\n\tlet current: unknown = root[match[1]];\n\tfor (const rawPart of match[2].split(\"/\")) {\n\t\tif (!isSchemaRecord(current)) return undefined;\n\t\tconst part = rawPart.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n\t\tcurrent = current[part];\n\t}\n\treturn current;\n}\n\nfunction isObjectShapedBedrockSchema(\n\tschema: Record<string, unknown>,\n\troot: Record<string, unknown>,\n\tvisitedRefs = new Set<string>(),\n): boolean {\n\tif (schema.type === \"object\") return true;\n\tif (schema.type !== undefined) return false;\n\tif (typeof schema.$ref === \"string\") {\n\t\tif (visitedRefs.has(schema.$ref)) return false;\n\t\tconst target = resolveBedrockLocalSchemaRef(root, schema.$ref);\n\t\tif (!isSchemaRecord(target)) return false;\n\t\tconst nextVisitedRefs = new Set(visitedRefs);\n\t\tnextVisitedRefs.add(schema.$ref);\n\t\treturn isObjectShapedBedrockSchema(target, root, nextVisitedRefs);\n\t}\n\tif ([...BEDROCK_OBJECT_SCHEMA_KEYS].some((key) => key in schema)) return true;\n\tfor (const combinator of BEDROCK_ROOT_SCHEMA_COMBINATORS) {\n\t\tconst branches = schema[combinator];\n\t\tif (Array.isArray(branches) && branches.length > 0) {\n\t\t\treturn branches.every(\n\t\t\t\t(branch) => isSchemaRecord(branch) && isObjectShapedBedrockSchema(branch, root, visitedRefs),\n\t\t\t);\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Bedrock Converse requires every tool inputSchema.json root to have type \"object\". TypeBox\n * unions used by tools such as write/edit are represented as top-level anyOf object branches,\n * which is valid JSON Schema but rejected by Bedrock before the model is invoked. Flatten only\n * unions whose every branch is an object; execution still validates against the authoritative\n * union schema after the provider response, so this projection cannot broaden the execution\n * contract.\n */\nfunction normalizeBedrockToolInputSchema(schema: unknown): unknown {\n\tif (!isSchemaRecord(schema) || schema.type === \"object\") return schema;\n\t// Never let a root combinator override an explicit non-object root type.\n\tif (schema.type !== undefined) return schema;\n\n\tconst combinator = BEDROCK_ROOT_SCHEMA_COMBINATORS.find((key) => key in schema);\n\tif (!combinator) {\n\t\treturn isObjectShapedBedrockSchema(schema, schema) ? { ...schema, type: \"object\" } : schema;\n\t}\n\tif (!Array.isArray(schema[combinator]) || schema[combinator].length === 0) return schema;\n\n\tconst branches = schema[combinator].filter(isSchemaRecord);\n\tif (branches.length !== schema[combinator].length) return schema;\n\tif (!branches.every((branch) => isObjectShapedBedrockSchema(branch, schema))) {\n\t\treturn schema;\n\t}\n\t// Preserve references, empty object branches, and branch constraints that cannot be safely\n\t// represented by the flattened property projection. The added root type is sufficient for\n\t// Bedrock's wire validator while retaining the authoritative schema semantics.\n\tif (\n\t\tbranches.some(\n\t\t\t(branch) =>\n\t\t\t\ttypeof branch.$ref === \"string\" ||\n\t\t\t\tObject.keys(branch).some((key) => !BEDROCK_FLATTENABLE_BRANCH_KEYS.has(key)),\n\t\t)\n\t) {\n\t\treturn { ...schema, type: \"object\" };\n\t}\n\n\tconst properties: Record<string, unknown> = isSchemaRecord(schema.properties) ? { ...schema.properties } : {};\n\tconst serializedProperties = new Map<string, string>();\n\tfor (const [key, value] of Object.entries(properties)) {\n\t\tserializedProperties.set(key, JSON.stringify(value) ?? \"<undefined>\");\n\t}\n\tfor (const branch of branches) {\n\t\tif (!isSchemaRecord(branch.properties)) continue;\n\t\tfor (const [key, value] of Object.entries(branch.properties)) {\n\t\t\tconst serialized = JSON.stringify(value) ?? \"<undefined>\";\n\t\t\tconst previous = serializedProperties.get(key);\n\t\t\tif (previous !== undefined && previous !== serialized) {\n\t\t\t\t// Flattening would silently discard one branch's constraint. Keep the union intact and\n\t\t\t\t// add only the object root required by Bedrock.\n\t\t\t\treturn { ...schema, type: \"object\" };\n\t\t\t}\n\t\t\tserializedProperties.set(key, serialized);\n\t\t\tproperties[key] = value;\n\t\t}\n\t}\n\tif (Object.keys(properties).length === 0) return { ...schema, type: \"object\" };\n\n\tconst normalized: Record<string, unknown> = { ...schema, type: \"object\", properties };\n\tdelete normalized[combinator];\n\n\tconst requiredSets = branches.map(\n\t\t(branch) =>\n\t\t\tnew Set(\n\t\t\t\tArray.isArray(branch.required)\n\t\t\t\t\t? branch.required.filter((key): key is string => typeof key === \"string\")\n\t\t\t\t\t: [],\n\t\t\t),\n\t);\n\tconst rootRequired = Array.isArray(schema.required)\n\t\t? schema.required.filter((key): key is string => typeof key === \"string\")\n\t\t: [];\n\tif (combinator === \"allOf\") {\n\t\tnormalized.required = [...new Set([...rootRequired, ...requiredSets.flatMap((required) => [...required])])];\n\t} else {\n\t\tconst commonRequired = requiredSets[0] ?? new Set<string>();\n\t\tfor (const required of requiredSets.slice(1)) {\n\t\t\tfor (const key of commonRequired) if (!required.has(key)) commonRequired.delete(key);\n\t\t}\n\t\tnormalized.required = [...new Set([...rootRequired, ...commonRequired])];\n\t}\n\n\treturn normalized;\n}\n\nfunction isBedrockToolInputSchema(value: unknown): value is Record<string, unknown> {\n\treturn isSchemaRecord(value) && value.type === \"object\";\n}\n\nfunction isExplicitBedrockToolChoice(\n\ttoolChoice: BedrockOptions[\"toolChoice\"],\n): toolChoice is { type: \"tool\"; name: string } {\n\treturn typeof toolChoice === \"object\" && toolChoice !== null && toolChoice.type === \"tool\";\n}\n\nfunction convertToolResultContent(content: (TextContent | ImageContent)[]): ToolResultContentBlock[] {\n\tconst result: ToolResultContentBlock[] = [];\n\tfor (const c of content) {\n\t\tif (c.type === \"image\") {\n\t\t\tresult.push({ image: createImageBlock(c.mimeType, c.data) });\n\t\t} else {\n\t\t\tconst textBlock = createNonBlankTextBlock(c.text);\n\t\t\tif (textBlock) result.push(textBlock);\n\t\t}\n\t}\n\tif (result.length === 0) result.push({ text: EMPTY_TEXT_PLACEHOLDER });\n\treturn result;\n}\n\nfunction convertMessages(\n\tcontext: Context,\n\tmodel: Model<\"bedrock-converse-stream\">,\n\tcacheRetention: CacheRetention,\n\ttoolNameMap: ToolNameMap,\n): Message[] {\n\tconst result: Message[] = [];\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tfor (let i = 0; i < transformedMessages.length; i++) {\n\t\tconst m = transformedMessages[i];\n\n\t\tswitch (m.role) {\n\t\t\tcase \"user\": {\n\t\t\t\tconst content: ContentBlock[] = [];\n\t\t\t\tif (typeof m.content === \"string\") {\n\t\t\t\t\tcontent.push(createRequiredTextBlock(m.content));\n\t\t\t\t} else {\n\t\t\t\t\tfor (const c of m.content) {\n\t\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\t\tcase \"text\": {\n\t\t\t\t\t\t\t\tconst textBlock = createNonBlankTextBlock(c.text);\n\t\t\t\t\t\t\t\tif (textBlock) content.push(textBlock);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase \"image\":\n\t\t\t\t\t\t\t\tcontent.push({ image: createImageBlock(c.mimeType, c.data) });\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (content.length === 0) content.push({ text: EMPTY_TEXT_PLACEHOLDER });\n\t\t\t\t}\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"assistant\": {\n\t\t\t\t// Skip assistant messages with empty content (e.g., from aborted requests)\n\t\t\t\t// Bedrock rejects messages with empty content arrays\n\t\t\t\tif (m.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst contentBlocks: ContentBlock[] = [];\n\t\t\t\tfor (const c of m.content) {\n\t\t\t\t\tswitch (c.type) {\n\t\t\t\t\t\tcase \"text\": {\n\t\t\t\t\t\t\t// Skip empty text blocks\n\t\t\t\t\t\t\tconst textBlock = createNonBlankTextBlock(c.text);\n\t\t\t\t\t\t\tif (!textBlock) continue;\n\t\t\t\t\t\t\tcontentBlocks.push(textBlock);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"toolCall\":\n\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\ttoolUse: {\n\t\t\t\t\t\t\t\t\ttoolUseId: c.id,\n\t\t\t\t\t\t\t\t\tname: toolNameMap.toProviderName(c.name),\n\t\t\t\t\t\t\t\t\tinput: sanitizeBedrockDocument(c.arguments),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"thinking\": {\n\t\t\t\t\t\t\tif (c.redacted) {\n\t\t\t\t\t\t\t\tif (c.thinkingSignature?.trim()) {\n\t\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\t\tredactedContent: base64ToBytes(c.thinkingSignature),\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Skip empty thinking blocks\n\t\t\t\t\t\t\tconst thinking = sanitizeSurrogates(c.thinking);\n\t\t\t\t\t\t\tif (thinking.trim().length === 0) continue;\n\t\t\t\t\t\t\t// Only Anthropic models support the signature field in reasoningText.\n\t\t\t\t\t\t\t// For other models, we omit the signature to avoid errors like:\n\t\t\t\t\t\t\t// \"This model doesn't support the reasoningContent.reasoningText.signature field\"\n\t\t\t\t\t\t\tif (supportsThinkingSignature(model)) {\n\t\t\t\t\t\t\t\t// Signatures arrive after thinking deltas. If a partial or externally\n\t\t\t\t\t\t\t\t// persisted message lacks a signature, Bedrock rejects the replayed\n\t\t\t\t\t\t\t\t// reasoning block. Fall back to plain text, matching Anthropic.\n\t\t\t\t\t\t\t\tif (!c.thinkingSignature || c.thinkingSignature.trim().length === 0) {\n\t\t\t\t\t\t\t\t\tcontentBlocks.push({ text: thinking });\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\t\treasoningText: {\n\t\t\t\t\t\t\t\t\t\t\t\ttext: thinking,\n\t\t\t\t\t\t\t\t\t\t\t\tsignature: c.thinkingSignature,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontentBlocks.push({\n\t\t\t\t\t\t\t\t\treasoningContent: {\n\t\t\t\t\t\t\t\t\t\treasoningText: { text: thinking },\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Skip if all content blocks were filtered out\n\t\t\t\tif (contentBlocks.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.ASSISTANT,\n\t\t\t\t\tcontent: contentBlocks,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolResult\": {\n\t\t\t\t// Collect all consecutive toolResult messages into a single user message\n\t\t\t\t// Bedrock requires all tool results to be in one message\n\t\t\t\tconst toolResults: ContentBlock.ToolResultMember[] = [];\n\n\t\t\t\t// Add current tool result with all content blocks combined\n\t\t\t\ttoolResults.push({\n\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\ttoolUseId: m.toolCallId,\n\t\t\t\t\t\tcontent: convertToolResultContent(m.content),\n\t\t\t\t\t\tstatus: m.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\t// Look ahead for consecutive toolResult messages\n\t\t\t\tlet j = i + 1;\n\t\t\t\twhile (j < transformedMessages.length && transformedMessages[j].role === \"toolResult\") {\n\t\t\t\t\tconst nextMsg = transformedMessages[j] as ToolResultMessage;\n\t\t\t\t\ttoolResults.push({\n\t\t\t\t\t\ttoolResult: {\n\t\t\t\t\t\t\ttoolUseId: nextMsg.toolCallId,\n\t\t\t\t\t\t\tcontent: convertToolResultContent(nextMsg.content),\n\t\t\t\t\t\t\tstatus: nextMsg.isError ? ToolResultStatus.ERROR : ToolResultStatus.SUCCESS,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tj++;\n\t\t\t\t}\n\n\t\t\t\t// Skip the messages we've already processed\n\t\t\t\ti = j - 1;\n\n\t\t\t\tresult.push({\n\t\t\t\t\trole: ConversationRole.USER,\n\t\t\t\t\tcontent: toolResults,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\n\t// Add cache point to the last user message for supported Claude models when caching is enabled\n\tif (cacheRetention !== \"none\" && supportsPromptCaching(model) && result.length > 0) {\n\t\tconst lastMessage = result[result.length - 1];\n\t\tif (lastMessage.role === ConversationRole.USER && lastMessage.content) {\n\t\t\t(lastMessage.content as ContentBlock[]).push({\n\t\t\t\tcachePoint: {\n\t\t\t\t\ttype: CachePointType.DEFAULT,\n\t\t\t\t\t...(cacheRetention === \"long\" ? { ttl: CacheTTL.ONE_HOUR } : {}),\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction convertToolConfig(\n\ttools: Tool[] | undefined,\n\ttoolChoice: BedrockOptions[\"toolChoice\"],\n\ttoolNameMap: ToolNameMap,\n): ToolConfiguration | undefined {\n\tif (!tools?.length || toolChoice === \"none\") return undefined;\n\n\tconst bedrockTools: BedrockTool[] = [];\n\tfor (const tool of tools) {\n\t\tconst inputSchema = normalizeBedrockToolInputSchema(tool.parameters);\n\t\tif (!isBedrockToolInputSchema(inputSchema)) {\n\t\t\tthrow new Error(`Bedrock tool \"${tool.name}\" requires an object input schema`);\n\t\t}\n\t\tbedrockTools.push({\n\t\t\ttoolSpec: {\n\t\t\t\tname: toolNameMap.toProviderName(tool.name),\n\t\t\t\tdescription: tool.description,\n\t\t\t\tinputSchema: { json: inputSchema as DocumentType },\n\t\t\t},\n\t\t});\n\t}\n\tlet bedrockToolChoice: ToolChoice | undefined;\n\tswitch (toolChoice) {\n\t\tcase \"auto\":\n\t\t\tbedrockToolChoice = { auto: {} };\n\t\t\tbreak;\n\t\tcase \"any\":\n\t\t\tbedrockToolChoice = { any: {} };\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (isExplicitBedrockToolChoice(toolChoice)) {\n\t\t\t\tconst name = toolNameMap.toProviderName(toolChoice.name);\n\t\t\t\tif (!bedrockTools.some((tool) => tool.toolSpec?.name === name)) {\n\t\t\t\t\tthrow new Error(`Bedrock tool \"${toolChoice.name}\" is not available in this request`);\n\t\t\t\t}\n\t\t\t\tbedrockToolChoice = { tool: { name } };\n\t\t\t}\n\t}\n\n\treturn { tools: bedrockTools, toolChoice: bedrockToolChoice };\n}\n\nfunction mapStopReason(reason: string | undefined): { stopReason: StopReason; errorMessage?: string } {\n\tswitch (reason) {\n\t\tcase BedrockStopReason.END_TURN:\n\t\tcase BedrockStopReason.STOP_SEQUENCE:\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase BedrockStopReason.MAX_TOKENS:\n\t\tcase BedrockStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:\n\t\t\treturn { stopReason: \"length\" };\n\t\tcase BedrockStopReason.TOOL_USE:\n\t\t\treturn { stopReason: \"toolUse\" };\n\t\tdefault:\n\t\t\treturn reason ? { stopReason: \"error\", errorMessage: reason } : { stopReason: \"error\" };\n\t}\n}\n\nfunction getConfiguredBedrockRegion(options: BedrockOptions): string | undefined {\n\tif (typeof process === \"undefined\") {\n\t\treturn options.region;\n\t}\n\n\treturn options.region || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || undefined;\n}\n\nfunction getConfiguredBedrockProfile(options: BedrockOptions): string | undefined {\n\tif (typeof process === \"undefined\") {\n\t\treturn options.profile?.trim() || undefined;\n\t}\n\n\treturn options.profile?.trim() || process.env.AWS_PROFILE?.trim() || undefined;\n}\n\nfunction getStandardBedrockEndpointRegion(baseUrl: string | undefined): string | undefined {\n\tif (!baseUrl) {\n\t\treturn undefined;\n\t}\n\n\ttry {\n\t\tconst { hostname } = new URL(baseUrl);\n\t\tconst match = hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\\.([a-z0-9-]+)\\.amazonaws\\.com(?:\\.cn)?$/);\n\t\treturn match?.[1];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction shouldUseExplicitBedrockEndpoint(\n\tbaseUrl: string,\n\tconfiguredRegion: string | undefined,\n\thasConfiguredProfile: boolean,\n): boolean {\n\tconst endpointRegion = getStandardBedrockEndpointRegion(baseUrl);\n\tif (!endpointRegion) {\n\t\treturn true;\n\t}\n\n\treturn !configuredRegion && !hasConfiguredProfile;\n}\n\nfunction isGovCloudBedrockTarget(model: Model<\"bedrock-converse-stream\">, options: BedrockOptions): boolean {\n\tconst region = getConfiguredBedrockRegion(options);\n\tif (region?.toLowerCase().startsWith(\"us-gov-\")) {\n\t\treturn true;\n\t}\n\n\tconst modelId = model.id.toLowerCase();\n\treturn modelId.startsWith(\"us-gov.\") || modelId.startsWith(\"arn:aws-us-gov:\");\n}\n\nfunction buildAdditionalModelRequestFields(\n\tmodel: Model<\"bedrock-converse-stream\">,\n\toptions: BedrockOptions,\n): Record<string, DocumentType> | undefined {\n\tif (!options.reasoning || !model.reasoning) {\n\t\treturn undefined;\n\t}\n\n\tif (isAnthropicClaudeModel(model)) {\n\t\t// GovCloud Bedrock currently rejects the Claude thinking.display field.\n\t\t// Omit it there until the GovCloud Converse schema catches up.\n\t\tconst display = isGovCloudBedrockTarget(model, options) ? undefined : (options.thinkingDisplay ?? \"summarized\");\n\t\tconst result: Record<string, DocumentType> = supportsAdaptiveThinking(model.id, model.name)\n\t\t\t? {\n\t\t\t\t\tthinking: { type: \"adaptive\", ...(display !== undefined ? { display } : {}) },\n\t\t\t\t\toutput_config: { effort: mapThinkingLevelToEffort(model, options.reasoning) },\n\t\t\t\t}\n\t\t\t: (() => {\n\t\t\t\t\tconst defaultBudgets: Record<ThinkingLevel, number> = {\n\t\t\t\t\t\tminimal: 1024,\n\t\t\t\t\t\tlow: 2048,\n\t\t\t\t\t\tmedium: 8192,\n\t\t\t\t\t\thigh: 16384,\n\t\t\t\t\t\txhigh: 16384, // Claude doesn't support xhigh, clamp to high\n\t\t\t\t\t\tmax: 16384, // Claude doesn't support max, clamp to high\n\t\t\t\t\t\tultra: 16384, // Ultra maps to Claude's strongest supported non-adaptive wire effort\n\t\t\t\t\t};\n\n\t\t\t\t\t// Custom budgets override defaults (extended levels are not in ThinkingBudgets, use high).\n\t\t\t\t\tconst level =\n\t\t\t\t\t\toptions.reasoning === \"xhigh\" || options.reasoning === \"max\" || options.reasoning === \"ultra\"\n\t\t\t\t\t\t\t? \"high\"\n\t\t\t\t\t\t\t: options.reasoning;\n\t\t\t\t\tconst budget = options.thinkingBudgets?.[level] ?? defaultBudgets[options.reasoning];\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tthinking: {\n\t\t\t\t\t\t\ttype: \"enabled\",\n\t\t\t\t\t\t\tbudget_tokens: budget,\n\t\t\t\t\t\t\t...(display !== undefined ? { display } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t})();\n\n\t\tif (!supportsAdaptiveThinking(model.id, model.name) && (options.interleavedThinking ?? true)) {\n\t\t\tresult.anthropic_beta = [\"interleaved-thinking-2025-05-14\"];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\treturn undefined;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) {\n\t\tbinary += String.fromCharCode(byte);\n\t}\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(data: string): Uint8Array {\n\tconst binaryString = atob(data);\n\tconst bytes = new Uint8Array(binaryString.length);\n\tfor (let i = 0; i < binaryString.length; i++) {\n\t\tbytes[i] = binaryString.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n\nfunction appendBase64Bytes(existingBase64: string | undefined, bytes: Uint8Array): string {\n\tif (!existingBase64) return bytesToBase64(bytes);\n\n\tconst existing = base64ToBytes(existingBase64);\n\tconst merged = new Uint8Array(existing.length + bytes.length);\n\tmerged.set(existing);\n\tmerged.set(bytes, existing.length);\n\treturn bytesToBase64(merged);\n}\n\nfunction createImageBlock(mimeType: string, data: string) {\n\tlet format: ImageFormat;\n\tswitch (mimeType) {\n\t\tcase \"image/jpeg\":\n\t\tcase \"image/jpg\":\n\t\t\tformat = ImageFormat.JPEG;\n\t\t\tbreak;\n\t\tcase \"image/png\":\n\t\t\tformat = ImageFormat.PNG;\n\t\t\tbreak;\n\t\tcase \"image/gif\":\n\t\t\tformat = ImageFormat.GIF;\n\t\t\tbreak;\n\t\tcase \"image/webp\":\n\t\t\tformat = ImageFormat.WEBP;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown image type: ${mimeType}`);\n\t}\n\n\treturn { source: { bytes: base64ToBytes(data) }, format };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caupulican/pi-ai",
3
- "version": "0.93.18",
3
+ "version": "0.94.0",
4
4
  "description": "Unified LLM API with automatic model discovery and provider configuration",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",