@humain/humain-code 0.4.8 → 0.4.9
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.
- package/CHANGELOG.md +22 -0
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/{anthropic-messages-YMPB2HJ7.js → anthropic-messages-UNHXXOD4.js} +3 -3
- package/dist/bundle/chunks/{azure-openai-responses-PDHOT7UC.js → azure-openai-responses-4QRYJCC2.js} +2 -2
- package/dist/bundle/chunks/bedrock-converse-stream.js +70 -47
- package/dist/bundle/chunks/{chunk-TIAXGIMN.js → chunk-4LAKI5IL.js} +9 -9
- package/dist/bundle/chunks/{chunk-II2442A2.js → chunk-5CDES42D.js} +1 -1
- package/dist/bundle/chunks/{chunk-IMR3ZJM5.js → chunk-5XD3DHYL.js} +1 -1
- package/dist/bundle/chunks/{chunk-GNOKILVU.js → chunk-6FVNSW6B.js} +88 -65
- package/dist/bundle/chunks/{chunk-RXHSJSYY.js → chunk-6KAMTNN3.js} +1 -1
- package/dist/bundle/chunks/{chunk-SKIP6KJV.js → chunk-7Z5MWPYE.js} +1 -1
- package/dist/bundle/chunks/{chunk-WPLW452J.js → chunk-DZ5C66IU.js} +1 -1
- package/dist/bundle/chunks/{chunk-2W5PWUPO.js → chunk-EDKZRYWJ.js} +2 -2
- package/dist/bundle/chunks/{chunk-ROSZII6E.js → chunk-EMYNPLY5.js} +1 -1
- package/dist/bundle/chunks/{chunk-PYU5BR3Z.js → chunk-JOKJ3CEL.js} +2 -2
- package/dist/bundle/chunks/chunk-MVYV6MJY.js +23 -0
- package/dist/bundle/chunks/{chunk-ILRBME2Y.js → chunk-P4YMUUSK.js} +314 -311
- package/dist/bundle/chunks/{chunk-PBBQBIHY.js → chunk-RBKDBF5G.js} +1 -1
- package/dist/bundle/chunks/{chunk-YURQPD6Y.js → chunk-RYC5BYVE.js} +1 -2
- package/dist/bundle/chunks/chunk-VEYTRNQC.js +5 -0
- package/dist/bundle/chunks/{chunk-OTXURGIO.js → chunk-YKZGL4MB.js} +1 -1
- package/dist/bundle/chunks/chunk-Z33NNMNB.js +6 -0
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-YPOLSCPT.js → cloudflare-workers-ai-system-one-FZ3UQCZ7.js} +1 -1
- package/dist/bundle/chunks/{compat-J5FTRJ6S.js → compat-HEUVP6UJ.js} +3 -3
- package/dist/bundle/chunks/{dist-6FQCCUSC.js → dist-NU2EIVT6.js} +485 -446
- package/dist/bundle/chunks/{dist-N7XDUAAO.js → dist-VNSMKBZ6.js} +3 -3
- package/dist/bundle/chunks/{extract-56PXVZVW.js → extract-PYRMDATF.js} +2 -2
- package/dist/bundle/chunks/{google-generative-ai-TS4ZE2RO.js → google-generative-ai-H2F5Y5H2.js} +2 -2
- package/dist/bundle/chunks/{google-vertex-MJK2SMNE.js → google-vertex-LFWD2AOO.js} +3 -3
- package/dist/bundle/chunks/host-6ZA6LK4C.js +2 -0
- package/dist/bundle/chunks/{llama-cpp-classify-5KAR326J.js → llama-cpp-classify-AGCW7HYN.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-XA2ZGSAH.js → mistral-conversations-D74NZ65O.js} +2 -2
- package/dist/bundle/chunks/{openai-codex-responses-Y6NRWMOI.js → openai-codex-responses-JAAA7MSS.js} +3 -3
- package/dist/bundle/chunks/{openai-completions-FY77MIZH.js → openai-completions-PGPMGQPU.js} +34 -33
- package/dist/bundle/chunks/{openai-decisions-MKH4OJHH.js → openai-decisions-QQ4MEABI.js} +1 -1
- package/dist/bundle/chunks/openai-responses-FG2R2M4L.js +23 -0
- package/dist/bundle/chunks/{openrouter-images-R3QMMLPH.js → openrouter-images-NTBP3UUE.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-LYJZPRST.js → pi-messages-JD4O7KIP.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-PAYJECQK.js → typesafe-system-one-TTC7YCO3.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-TT2VTOSY.js → virtual-modules-NPWQ6NBS.js} +2 -2
- package/dist/bundle/cli-runtime.js +2 -2
- package/dist/bundle/flow/assets/contract.json +1 -1
- package/dist/bundle/flow/package.json +1 -1
- package/dist/bundle/index.js +5 -5
- package/dist/bundle/rpc-entry.js +2 -2
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +353 -29
- package/docs/flow.md +12 -9
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/dist/bundle/chunks/chunk-AKA7HNO3.js +0 -4
- package/dist/bundle/chunks/chunk-JYWVRJYG.js +0 -6
- package/dist/bundle/chunks/chunk-MEIYGK5O.js +0 -6
- package/dist/bundle/chunks/host-2ARI7PQ5.js +0 -2
- package/dist/bundle/chunks/openai-responses-LNSCERKH.js +0 -23
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.4.9] - 2026-10-13
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Added ten historical LARGE Flow eval tasks (five Forge and five HUMAIN Code tasks) with complete reference patches, protected checks, provenance, and base-fail/reference-pass evidence. Eval reports include per-configuration false-pass metrics (PLARGE).
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- SMALL and MEDIUM Flow runs use one implementer followed by deterministic checks, without LLM triage, architects, scouts, leads, independent review, LLM QA, or repair agents. An explicit `SCOPE_GROWTH: large` report can request one gated escalation to LARGE; classified MEDIUM remains visible in telemetry (PSMALL).
|
|
12
|
+
- SMALL and MEDIUM runs with no discovered checks, or only provably unavailable non-passing checks, can succeed with `evidence_status: unverified_checks_unavailable` and a warning, never as verified. No LLM verdict substitutes for a missing check. Real check failures still fail; pre-existing failures remain warnings, and recovery still requires real checks (PSMALL).
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- Flow process custody tracks owned kernel process generations and observed descendants instead of shared session markers. Native and traced retries require affirmative custody evidence; unresolved owned processes block launches, while unrelated or settled generations do not. Historical reuse requires the complete matching discovered check set to pass with no blocked or present custody (PCUSTODY).
|
|
17
|
+
- Flow scope validation resolves safe directory navigation such as `cd packages/logger/../..` against the filesystem while continuing to block unknown directories, logical/physical symlink disagreement, and foreign writes (PSMALL).
|
|
18
|
+
- Flow verification fails when a deterministic check's process custody is unresolved (replay-blocked, or owned process tree present or unknown), including SMALL runs that would otherwise pass unverified, and never dispatches a review over such a check.
|
|
19
|
+
- OpenAI Completions/Responses and Bedrock preserve sanitized connection, DNS, TLS, and timeout evidence as `provider_unreachable` through sessions, Flow health/failover, RPC, and durable telemetry. Incomplete or missing cost evidence remains unknown and blocks same-route transport replay, transient resume, and lead repair; HTFIX17 failover may still try each other frozen route once (PERR).
|
|
20
|
+
|
|
21
|
+
- HTERR provider diagnostics retain HTTP status and useful denial reasons while keeping displayed errors within 4000 characters, including oversized structured metadata and repeated normalization.
|
|
22
|
+
- HTERR error sanitization redacts credential values in header records, credential-looking object keys and protocol-relative URLs before bounding diagnostics, without retaining raw provider errors in retry-delay failures.
|
|
23
|
+
- OpenAI completions and Responses HTTP 403 failures are terminal for both provider and outer assistant retries, even when retry headers or wrapped gateway messages suggest retrying.
|
|
24
|
+
|
|
3
25
|
## [0.4.8] - 2026-10-13
|
|
4
26
|
|
|
5
27
|
### Fixed
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{runAgentMonitorCommand}from"./chunks/chunk-
|
|
2
|
+
import{runAgentMonitorCommand}from"./chunks/chunk-4LAKI5IL.js";import"./chunks/chunk-3E4SMILM.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";process.exitCode=await runAgentMonitorCommand(process.env);
|
package/dist/bundle/chunks/{anthropic-messages-YMPB2HJ7.js → anthropic-messages-UNHXXOD4.js}
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-JEJQVFWK.js";import{retryProviderRequest}from"./chunk-
|
|
3
|
-
import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-KQM7ZGL6.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{parseJsonWithRepair,parseStreamingJson,parseStreamingJsonWhileStreaming}from"./chunk-GVVRXZHN.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,getSystemMessageText,
|
|
4
|
-
import{AssistantMessageEventStream
|
|
2
|
+
import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-JEJQVFWK.js";import{retryProviderRequest}from"./chunk-Z33NNMNB.js";import"./chunk-MVYV6MJY.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-5XD3DHYL.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{
|
|
3
|
+
createRequestObserver,headersToRecord}from"./chunk-5CDES42D.js";import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-KQM7ZGL6.js";import{getProviderEnvValue}from"./chunk-FACBDLFU.js";import{parseJsonWithRepair,parseStreamingJson,parseStreamingJsonWhileStreaming}from"./chunk-GVVRXZHN.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,getSystemMessageText,
|
|
4
|
+
renderSystemMessageUpdate,resolveTranscript}from"./chunk-DZ5C66IU.js";import{AssistantMessageEventStream}from"./chunk-RYC5BYVE.js";import{appendAssistantMessageDiagnostic}from"./chunk-VEYTRNQC.js";import{Anthropic}from"./chunk-BKJU56SM.js";import"./chunk-JXWJOIH4.js";function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("HUMAIN_TERMINAL_CACHE_RETENTION",env)==="long"||getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}function getCacheControl(model,cacheRetention,env){let retention=resolveCacheRetention(cacheRetention,env);if(retention==="none")return{retention};let ttl=retention==="long"&&getAnthropicCompat(model).supportsLongCacheRetention?"1h":void 0;return{retention,cacheControl:{type:"ephemera\
|
|
5
5
|
l",...ttl&&{ttl}}}}var claudeCodeVersion="2.1.280",claudeCodeTools=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],ccToolLookup=new Map(claudeCodeTools.map(t=>[t.toLowerCase(),t])),toClaudeCodeName=name=>ccToolLookup.get(name.toLowerCase())??name,fromClaudeCodeName=(name,tools)=>{if(tools&&tools.length>0){let lowerName=name.toLowerCase(),matchedTool=tools.find(tool=>tool.
|
|
6
6
|
name.toLowerCase()===lowerName);if(matchedTool)return matchedTool.name}return name};function convertContentBlocks(content){if(!content.some(c=>c.type==="image"))return sanitizeSurrogates(content.map(c=>c.text).join(`
|
|
7
7
|
`));let blocks=content.map(block=>block.type==="text"?{type:"text",text:sanitizeSurrogates(block.text)}:{type:"image",source:{type:"base64",media_type:block.mimeType,data:block.data}});return blocks.some(b=>b.type==="text")||blocks.unshift({type:"text",text:"(see attached image)"}),blocks}var FINE_GRAINED_TOOL_STREAMING_BETA="fine-grained-tool-streaming-2025-05-14",INTERLEAVED_THINKING_BETA="interleaved-thinking-2025-05-14",SERVER_SIDE_FALLBACK_BETA="server-side-fallback-2026-07-01",MID_CONVERSATION_OUTPUT_CONFIG_BETA="\
|
package/dist/bundle/chunks/{azure-openai-responses-PDHOT7UC.js → azure-openai-responses-4QRYJCC2.js}
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-
|
|
3
|
-
import"./chunk-YTVFIA3A.js";import"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord,observeFetch}from"./chunk-
|
|
2
|
+
import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-EDKZRYWJ.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-UW4GMZL3.js";import{retryProviderRequest}from"./chunk-Z33NNMNB.js";import{formatProviderError,normalizeProviderError}from"./chunk-MVYV6MJY.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent,resolveSamplingParams}from"./chunk-5XD3DHYL.js";
|
|
3
|
+
import"./chunk-YTVFIA3A.js";import"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord,observeFetch}from"./chunk-5CDES42D.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-CIA6V3BP.js";import"./chunk-FACBDLFU.js";import"./chunk-GVVRXZHN.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-DZ5C66IU.js";import{AssistantMessageEventStream}from"./chunk-RYC5BYVE.js";import"./chunk-VEYTRNQC.js";
|
|
4
4
|
import"./chunk-JXWJOIH4.js";var AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode","azure"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function formatAzureOpenAIError(error){return formatProviderError(normalizeProviderError(error),"Azure OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"\
|
|
5
5
|
assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{usageIncomplete:!0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let observe=createRequestObserver(options,{api:model.api,provider:model.provider,model:model.id,operation:"chat"}),client=createClient(
|
|
6
6
|
model,apiKey,options,observeFetch(options?.fetch,observe)),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,normalizedContext,options,deploymentName,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.
|
|
@@ -1418,10 +1418,26 @@ this.finalResultPromise=new Promise(resolve=>{this.resolveFinalResult=resolve})}
|
|
|
1418
1418
|
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/
|
|
1419
1419
|
1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==
|
|
1420
1420
|
void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i5=requestedIndex;i5<EXTENDED_THINKING_LEVELS.length;i5++){let candidate=EXTENDED_THINKING_LEVELS[i5];if(availableLevels.includes(candidate))return candidate}for(let i5=requestedIndex-1;i5>=0;i5--){let candidate=EXTENDED_THINKING_LEVELS[i5];
|
|
1421
|
-
if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:safeJsonStringify(error2),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1421
|
+
if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}var MAX_PROVIDER_ERROR_BODY_CHARS=4e3,MAX_PROVIDER_ERROR_INPUT_CHARS=64*1024,OVERSIZED_ERROR_TEXT="Provider error text exceeded 65536 characters",UNPARSEABLE_ERROR_TEXT="Unparseable structured provider error";function normalizeProviderError(error2){if(!(error2 instanceof Error))return{message:truncateErrorText(safeJsonStringify(error2),MAX_PROVIDER_ERROR_BODY_CHARS),messageCarriesBody:!1};let sdkError=error2,status=extractStatus(sdkError),body=extractBody(sdkError),message=body==="[REDACTED]"?body:
|
|
1422
|
+
truncateErrorText(error2.message,MAX_PROVIDER_ERROR_BODY_CHARS),transport=transportEvidence(error2);transport.transportCode&&TRANSPORT_CODES.has(transport.transportCode)&&!message.includes(transport.transportCode)&&(message=truncateErrorText(`${message} (${transport.transportCode})`,MAX_PROVIDER_ERROR_BODY_CHARS));let messageCarriesBody=body===void 0||message!=="[REDACTED]"&&message.includes(body);return{status,body,message,messageCarriesBody,...transport}}function transportEvidence(error2){let candidate=error2,
|
|
1423
|
+
transportCode,transportName;for(let depth=0;depth<8&&candidate&&typeof candidate=="object";depth++){let nested=candidate,status=extractStatus(nested);if(status!==void 0&&status>=400||nested.name==="AbortError"||nested.constructor?.name==="APIUserAbortError")return{};typeof nested.code=="string"&&TRANSPORT_CODES.has(nested.code)&&(transportCode??=nested.code);for(let name of[nested.name,nested.constructor?.name])["TimeoutError","APIConnectionTimeoutError","APIConnectionError"].includes(name)&&(transportName??=
|
|
1424
|
+
name);candidate=nested.cause}return transportCode??=transportName,transportCode?{transportCode}:{}}function appendProviderTransportDiagnostic(message,error2){message.stopReason!=="error"||!error2.transportCode||appendAssistantMessageDiagnostic(message,{type:"provider_transport_error",timestamp:Date.now(),details:{reason:"provider_unreachable",code:error2.transportCode}})}function extractStatus(error2){return[error2.statusCode,error2.status,error2.$metadata?.httpStatusCode,error2.$response?.statusCode].
|
|
1425
|
+
find(value=>typeof value=="number"&&Number.isInteger(value)&&value>=100&&value<=599)}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=sanitizeErrorText(bodyText).trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.$response?.
|
|
1426
|
+
body;if(typeof responseBody=="string")return responseBody;if(responseBody instanceof Uint8Array)return responseBody.byteLength>MAX_PROVIDER_ERROR_INPUT_CHARS?OVERSIZED_ERROR_TEXT:new TextDecoder().decode(responseBody);if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!=
|
|
1427
|
+
"object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function truncateErrorText(text,maxChars){let clean=sanitizeErrorText(text),cap=Number.isFinite(maxChars)?Math.max(0,Math.floor(maxChars)):MAX_PROVIDER_ERROR_BODY_CHARS;if(clean.length<=cap)return clean;let start=clean.search(/[{[]/);if(start>=0)try{let parsed=JSON.parse(clean.slice(start));clean=clean.slice(0,start)+summarizeErrorValue(parsed)}catch{}let suffix="... [truncated]";return cap<suffix.length?suffix.slice(0,cap):`${clean.slice(0,cap-suffix.length).replace(/\[[^\]]*$/,"")}${suffix}`}function safeJsonStringify(value){
|
|
1428
|
+
try{let serialized=JSON.stringify(value,(key,nested)=>{if(nested!==null&&typeof nested=="object"&&hasSensitiveLabel(nested,!0))return Array.isArray(nested)?["[REDACTED]"]:"[REDACTED]";let label=normalizeErrorLabel(key);if(hasAmbiguousErrorControls(key)||SENSITIVE_KEY.test(label)||/headers?/i.test(label)||Array.isArray(nested)&&nested.some(item=>typeof item=="string"&&SENSITIVE_KEY.test(normalizeErrorLabel(item)))||nested!==null&&typeof nested=="object"&&Object.entries(nested).some(([name,item])=>typeof item==
|
|
1429
|
+
"string"&&SENSITIVE_HEADER_NAME.test(normalizeErrorLabel(item))||/^(?:name|key|header|header[-_]?name|header[-_]?key|field[-_]?name|label|identifier)$/i.test(normalizeErrorLabel(name))&&hasSensitiveLabel(item)))return"[REDACTED]";if(Array.isArray(nested)&&hasSensitiveLabel(nested))return["[REDACTED]"];if(nested!==null&&typeof nested=="object"&&!Array.isArray(nested)){let entries=Object.entries(nested);if(entries.some(([name])=>sanitizePlainText(name)!==stripErrorControls(name)))return Object.fromEntries(
|
|
1430
|
+
entries.map(([name,value2])=>sanitizePlainText(name)!==stripErrorControls(name)?[sanitizePlainText(name),"[REDACTED]"]:[name,value2]))}return typeof nested=="string"?sanitizeErrorText(nested):nested});return serialized!==void 0&&serialized.length>MAX_PROVIDER_ERROR_INPUT_CHARS?truncateErrorText(summarizeErrorValue(JSON.parse(serialized)),MAX_PROVIDER_ERROR_BODY_CHARS):serialized===void 0?sanitizePlainText(String(value)):serialized}catch{return"[Unserializable provider error]"}}function summarizeErrorValue(value){
|
|
1431
|
+
if(typeof value=="string")try{return summarizeErrorValue(JSON.parse(value))}catch{return sanitizePlainText(value)}if(value===null||typeof value!="object")return String(value);let entries=Object.entries(value),reasons=["message","error","reason","detail"];entries.sort(([left],[right])=>(reasons.includes(left)?reasons.indexOf(left):reasons.length)-(reasons.includes(right)?reasons.indexOf(right):reasons.length));let parts=[],length=0;for(let[,nested]of entries){let part=truncateErrorText(summarizeErrorValue(
|
|
1432
|
+
nested),MAX_PROVIDER_ERROR_BODY_CHARS);if(parts.push(part),length+=part.length+2,length>=MAX_PROVIDER_ERROR_BODY_CHARS)break}return truncateErrorText(parts.join("; "),MAX_PROVIDER_ERROR_BODY_CHARS)}var TRANSPORT_CODES=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE","EPROTO","CERT_HAS_EXPIRED","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE","ERR_TLS_CERT_ALTNAME_INVALID","UND_ERR_CONNECT_TIME\
|
|
1433
|
+
OUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET"]),SENSITIVE_KEY=/(?:authorization|cookie|(?:api[-_\s]*key)|token|password|passwd|secret|credential|signature|private[-_\s]*key)/i,SENSITIVE_HEADER_NAME=/^(?:[a-z0-9]+[-_])*(?:authorization|cookie|(?:api|private|secret)[-_\s]*key|(?:access|refresh|session|security)[-_\s]*token|token|password|passwd|secret|credentials?|signature)$/i;function sanitizeErrorText(text){if(text.length>MAX_PROVIDER_ERROR_INPUT_CHARS)return OVERSIZED_ERROR_TEXT;
|
|
1434
|
+
try{let parsed=JSON.parse(text);if(parsed!==null&&typeof parsed=="object")return safeJsonStringify(parsed);if(typeof parsed=="string")return sanitizeErrorText(parsed)}catch{let start=text.search(/[{[]/);if(start>0)try{let parsed=JSON.parse(text.slice(start));return sanitizePlainText(text.slice(0,start))+safeJsonStringify(parsed)}catch{}}return sanitizePlainText(text)}function hasSensitiveLabel(value,ambiguityOnly=!1){let pending=[value],seen=new Set,scanned=0;for(;pending.length>0;){if(++scanned>
|
|
1435
|
+
1024)return!0;let item=pending.pop();if(typeof item=="string"){if(item.length>MAX_PROVIDER_ERROR_INPUT_CHARS||hasAmbiguousErrorControls(item)||!ambiguityOnly&&SENSITIVE_HEADER_NAME.test(normalizeErrorLabel(item)))return!0;try{let decoded=JSON.parse(ambiguityOnly?item:stripErrorControls(item," "));(typeof decoded=="string"||decoded!==null&&typeof decoded=="object")&&pending.push(decoded)}catch{let sanitized=sanitizePlainText(item);if(ambiguityOnly?sanitized===UNPARSEABLE_ERROR_TEXT:sanitized!==stripErrorControls(
|
|
1436
|
+
item))return!0}}if(item!==null&&typeof item=="object"){if(seen.has(item))return!0;seen.add(item);let entries=Object.entries(item);if(entries.length*2+pending.length>1024)return!0;for(let[name,nested]of entries){if(ambiguityOnly&&hasAmbiguousErrorKey(name))return!0;ambiguityOnly||pending.push(name),pending.push(nested)}}}return!1}function hasAmbiguousErrorKey(name){return name.length>MAX_PROVIDER_ERROR_INPUT_CHARS||name!==normalizeErrorLabel(name)||sanitizePlainText(name)===UNPARSEABLE_ERROR_TEXT}
|
|
1437
|
+
function normalizeErrorLabel(text){return stripErrorControls(text).replace(/[\s\p{Default_Ignorable_Code_Point}]/gu,"").trim().replace(/:+$/,"").trim()}var ERROR_TERMINAL_SEQUENCES=/(?:\x1b\]|\x9d)[\s\S]*?(?:\x07|\x1b\\|\x9c|$)|\x1b[PX^_][\s\S]*?(?:\x1b\\|$)|(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]|\x1b[@-_]/g,ERROR_CONTROLS=/[\x00-\x08\x0b-\x1f\x7f-\x9f\p{Cf}\p{Default_Ignorable_Code_Point}]/gu;function hasAmbiguousErrorControls(text){return text.replace(ERROR_TERMINAL_SEQUENCES,sequence2=>(sequence2.startsWith(
|
|
1438
|
+
"\x1B[")||sequence2.startsWith("\x9B"))&&sequence2.endsWith("m")?"":sequence2).search(ERROR_CONTROLS)>=0}function stripErrorControls(text,replacement=""){return text.replace(ERROR_TERMINAL_SEQUENCES,replacement).replace(ERROR_CONTROLS,replacement)}function sanitizePlainText(text){if(text.length>MAX_PROVIDER_ERROR_INPUT_CHARS)return OVERSIZED_ERROR_TEXT;let boundaries=stripErrorControls(text," "),clean=stripErrorControls(text);if((/[@?#<>]/.test(clean)||clean.split(/\s+/).some(part=>{let start=part.
|
|
1439
|
+
search(/(?:https?|wss?|ftp):|[/\\]/i);return start>=0&&/["']/.test(part.slice(start))}))&&/(?:https?|wss?|ftp):|[/\\]/i.test(clean.replace(/\s/g,"")))return"[REDACTED]";if(/\\["/bfnrtu]/i.test(boundaries))return UNPARSEABLE_ERROR_TEXT;let structure=clean.replaceAll("[REDACTED]","").replaceAll("[truncated]","").replace(/\b[a-z_$][\w$]*(?:\[\d+\])+/gi,"");if(/[{}[\]]/.test(structure))return UNPARSEABLE_ERROR_TEXT;if(hasAmbiguousErrorControls(text)||SENSITIVE_KEY.test(normalizeErrorLabel(clean))||/\b(?:B\s*e\s*a\s*r\s*e\s*r|B\s*a\s*s\s*i\s*c)\s/i.
|
|
1440
|
+
test(boundaries)||/\b(?:B\s*e\s*a\s*r\s*e\s*r|B\s*a\s*s\s*i\s*c)\s/i.test(clean))return"[REDACTED]";let tokenText=clean.replace(/[\t\n\u2028\u2029]/g,"");return tokenText.replace(/[\w-]+(?:\.[\w-]+)*/g,token=>{let segments=token.split(".");return/\b(?:sk-|glpat-|gh[pousr]_|github_pat_|xox[baprs]-)[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[\w-]{35}/.test(token)||segments.length>=3&&/\beyJ[\w-]+$/.test(segments[0])?"[REDACTED]":token})===tokenText?clean:"[REDACTED]"}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t","u"]);function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
|
|
1425
1441
|
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${char.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function repairJson(json){let repaired="",runStart=0,inString=!1;for(let index=0;index<json.length;index++){let code=json.charCodeAt(index);if(!inString){code===34&&(inString=!0);continue}if(code===34){inString=!1;continue}if(code===92){let nextChar=json[index+1];if(nextChar!==void 0&&VALID_JSON_ESCAPES.has(nextChar)){index+=1;continue}repaired+=`${json.slice(runStart,
|
|
1426
1442
|
index)}\\\\`,runStart=index+1;continue}code<=31&&(repaired+=json.slice(runStart,index)+escapeControlCharacter(json[index]),runStart=index+1)}return runStart===0?json:repaired+json.slice(runStart)}function parseJsonWithRepair(json){try{return JSON.parse(json)}catch(error2){let repairedJson=repairJson(json);if(repairedJson!==json)return JSON.parse(repairedJson);throw error2}}function parseStreamingJson(partialJson){if(!partialJson||partialJson.trim()==="")return{};try{return parseJsonWithRepair(partialJson)}catch{
|
|
1427
1443
|
try{return(0,import_partial_json.parse)(partialJson)??{}}catch{try{return(0,import_partial_json.parse)(repairJson(partialJson))??{}}catch{return{}}}}}var lengthsParsedWhileStreaming=new WeakMap;function parseStreamingJsonWhileStreaming(block,partialJson,current){let length=partialJson?.length??0,parsed=lengthsParsedWhileStreaming.get(block);return current!==void 0&&parsed!==void 0&&length-parsed<(parsed<1024?1:parsed>>3)?current:(lengthsParsedWhileStreaming.set(block,length),parseStreamingJson(partialJson))}var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env2){return env2?.[name]||
|
|
@@ -1460,7 +1476,7 @@ input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timesta
|
|
|
1460
1476
|
configuredRegion,hasAmbientConfiguredProfile);useExplicitEndpoint&&(config.endpoint=model.baseUrl);let skipAuth=getProviderEnvValue("AWS_BEDROCK_SKIP_AUTH",options.env)==="1",bearerToken=options.bearerToken||options.apiKey||getProviderEnvValue("AWS_BEARER_TOKEN_BEDROCK",options.env)||void 0,useBearerToken=bearerToken!==void 0&&!skipAuth;if(typeof process<"u"&&(process.versions?.node||process.versions?.bun)){let arnRegionMatch=model.id.match(/^arn:aws(?:-[a-z0-9-]+)?:bedrock:([a-z0-9-]+):/);arnRegionMatch?
|
|
1461
1477
|
config.region=arnRegionMatch[1]:configuredRegion?config.region=configuredRegion:endpointRegion&&useExplicitEndpoint?config.region=endpointRegion:hasAmbientConfiguredProfile||(config.region="us-east-1"),skipAuth&&(config.credentials={accessKeyId:"dummy-access-key",secretAccessKey:"dummy-secret-key"});let credentials=getConfiguredBedrockCredentials(options.env);!skipAuth&&credentials&&!optionsProfile&&(config.credentials=credentials);let proxyUrl=shouldBypassBedrockProxy(model.baseUrl)?void 0:resolveHttpProxyUrlForTarget(
|
|
1462
1478
|
model.baseUrl,options.env);proxyUrl?config.requestHandler=new import_node_http_handler5.NodeHttpHandler({httpAgent:new HttpProxyAgent(proxyUrl),httpsAgent:new HttpsProxyAgent(proxyUrl)}):shouldUseBedrockHttp1Handler(model.baseUrl,options.env)&&(config.requestHandler=new import_node_http_handler5.NodeHttpHandler)}else config.region=configuredRegion||(endpointRegion&&useExplicitEndpoint?endpointRegion:void 0)||"us-east-1";useBearerToken&&(config.token={token:bearerToken},config.authSchemePreference=
|
|
1463
|
-
["httpBearerAuth"]);let responseRequestId,client;try{let supportsStrictMode=model.compat?.supportsStrictMode??!1;client=new import_client_bedrock_runtime.BedrockRuntimeClient(config);let observedRawResponse=!1;
|
|
1479
|
+
["httpBearerAuth"]);let responseRequestId,client;try{let supportsStrictMode=model.compat?.supportsStrictMode??!1;client=new import_client_bedrock_runtime.BedrockRuntimeClient(config);let observedRawResponse=!1;addResponseHeadersMiddleware(client,options.onResponse,model,()=>{observedRawResponse=!0},options.timeoutMs);let customHeaders=providerHeadersToRecord(options.headers);customHeaders&&addCustomHeadersMiddleware(client,customHeaders);let cacheRetention=resolveCacheRetention(options.cacheRetention,
|
|
1464
1480
|
options.env),inferenceMaxTokens=options.maxTokens??(isAnthropicClaudeModel(model)?model.maxTokens:void 0),initialSystemMessage=getInitialSystemMessage(normalizedContext.messages),initialSystemPrompt=initialSystemMessage?getSystemMessageText(initialSystemMessage):void 0,commandInput={modelId:model.id,messages:convertMessages(normalizedContext,model,cacheRetention,options.env),system:buildSystemPrompt(initialSystemPrompt,model,cacheRetention,options.env),inferenceConfig:{...inferenceMaxTokens!==void 0&&
|
|
1465
1481
|
{maxTokens:inferenceMaxTokens},...options.temperature!==void 0&&{temperature:options.temperature}},toolConfig:convertToolConfig(getCurrentTools(normalizedContext.messages),options.toolChoice,supportsStrictMode),additionalModelRequestFields:buildAdditionalModelRequestFields(model,options),...options.requestMetadata!==void 0&&{requestMetadata:options.requestMetadata}},nextCommandInput=await options?.onPayload?.(commandInput,model);nextCommandInput!==void 0&&(commandInput=nextCommandInput),options.
|
|
1466
1482
|
onRequest&&addFinalRequestObserverMiddleware(client,createRequestObserver(options,{api:model.api,provider:model.provider,model:model.id,operation:"chat"}));let command5=new import_client_bedrock_runtime.ConverseStreamCommand(commandInput),response=await client.send(command5,{abortSignal:options.signal});if(responseRequestId=normalizeDiagnosticValue(response.$metadata.requestId),!observedRawResponse&&response.$metadata.httpStatusCode!==void 0){let responseHeaders={};response.$metadata.requestId&&
|
|
@@ -1468,45 +1484,52 @@ onRequest&&addFinalRequestObserverMiddleware(client,createRequestObserver(option
|
|
|
1468
1484
|
contentBlockStart)handleContentBlockStart(item.contentBlockStart,blocks,output,stream2);else if(item.contentBlockDelta)handleContentBlockDelta(item.contentBlockDelta,blocks,output,stream2);else if(item.contentBlockStop)handleContentBlockStop(item.contentBlockStop,blocks,output,stream2);else if(item.messageStop){output.rawStopReason=item.messageStop.stopReason;let{stopReason,errorMessage}=mapStopReason(item.messageStop.stopReason);output.stopReason=stopReason,errorMessage&&(output.errorMessage=errorMessage)}else if(item.
|
|
1469
1485
|
metadata)handleMetadata(item.metadata,model,output);else{if(item.internalServerException)throw item.internalServerException;if(item.modelStreamErrorException)throw item.modelStreamErrorException;if(item.validationException)throw item.validationException;if(item.throttlingException)throw item.throttlingException;if(item.serviceUnavailableException)throw item.serviceUnavailableException}if(options.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error(
|
|
1470
1486
|
"Bedrock stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred");for(let block of output.content)finalizeStreamingBlock(block);stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error2){for(let block of output.content)finalizeStreamingBlock(block);output.stopReason=options.signal?.aborted?"aborted":"error",output.errorMessage=formatBedrockError(error2),
|
|
1471
|
-
output.stopReason==="error"&&appendBedrockFailureDiagnostic(output,error2,responseRequestId),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}finally{client?.destroy?.()}})(),stream2},BEDROCK_ERROR_PREFIXES={InternalServerException:"Internal server error",ModelStreamErrorException:"Model stream error",ValidationException:"Validation error",ThrottlingException:"Throttling error",ServiceUnavailableException:"
|
|
1472
|
-
|
|
1473
|
-
name]??error2.name}: ${core}
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
if(
|
|
1478
|
-
|
|
1479
|
-
{
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1487
|
+
appendProviderTransportDiagnostic(output,normalizeProviderError(error2)),output.stopReason==="error"&&appendBedrockFailureDiagnostic(output,error2,responseRequestId),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}finally{client?.destroy?.()}})(),stream2},BEDROCK_ERROR_PREFIXES={InternalServerException:"Internal server error",ModelStreamErrorException:"Model stream error",ValidationException:"Validation error",ThrottlingException:"Throttling error",ServiceUnavailableException:"\
|
|
1488
|
+
Service unavailable"},BEDROCK_DATA_RETENTION_DOCS_URL="https://docs.aws.amazon.com/bedrock/latest/userguide/data-retention.html";function formatBedrockError(error2){let norm=normalizeProviderError(error2),core=error2 instanceof import_client_bedrock_runtime.BedrockRuntimeServiceException&&error2.name.endsWith("Exception")&&norm.message!=="UnknownError"||norm.status===void 0?norm.message:`${norm.status}: ${norm.body??norm.message.split(`
|
|
1489
|
+
Deserialization error:`)[0]}`,dataRetentionHint=/data retention mode/i.test(core)?` See ${BEDROCK_DATA_RETENTION_DOCS_URL} for supported data retention modes.`:"",prefix=error2 instanceof import_client_bedrock_runtime.BedrockRuntimeServiceException?`${BEDROCK_ERROR_PREFIXES[error2.name]??error2.name}: `:"";return`${truncateErrorText(`${prefix}${core}`,MAX_PROVIDER_ERROR_BODY_CHARS-dataRetentionHint.length)}${dataRetentionHint}`}var MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS=200;function normalizeDiagnosticValue(value){
|
|
1490
|
+
if(typeof value!="string")return;let trimmed=value.trim();if(!(trimmed.length===0||trimmed.length>MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS||!/^[a-zA-Z0-9._:/-]+$/.test(trimmed)||truncateErrorText(trimmed,MAX_BEDROCK_DIAGNOSTIC_VALUE_CHARS)!==trimmed))return trimmed}function extractBedrockErrorCode(error2){if(!(!(error2 instanceof Error)||!error2.name.endsWith("Exception")))return normalizeDiagnosticValue(error2.name)}function appendBedrockFailureDiagnostic(output,error2,fallbackRequestId){let metadata=error2?.
|
|
1491
|
+
$metadata,details={};typeof metadata?.httpStatusCode=="number"&&(details.status=metadata.httpStatusCode);let errorCode=extractBedrockErrorCode(error2);errorCode!==void 0&&(details.errorCode=errorCode);let requestId=normalizeDiagnosticValue(metadata?.requestId)??fallbackRequestId;requestId!==void 0&&(details.requestId=requestId),Object.keys(details).length!==0&&(appendAssistantMessageDiagnostic(output,{type:"bedrock_response_failure",timestamp:Date.now(),details}),typeof details.status=="number"&&
|
|
1492
|
+
details.status>=400&&details.status<=599&&appendAssistantMessageDiagnostic(output,{type:"provider_http_error",timestamp:Date.now(),details:{status:details.status,retryable:details.status===408||details.status===429||details.status>=500}}))}var RESERVED_HEADER_EXACT=new Set(["authorization","host"]);function isReservedHeader(key){let lower=key.toLowerCase();return lower.startsWith("x-amz-")||RESERVED_HEADER_EXACT.has(lower)}function addCustomHeadersMiddleware(client,headers){let middleware=next=>async args=>{
|
|
1493
|
+
let request=args.request;if(request&&typeof request=="object"&&"headers"in request){let requestHeaders=request.headers;for(let[key,value]of Object.entries(headers))isReservedHeader(key)||(requestHeaders[key]=value)}return next(args)};client.middlewareStack.add(middleware,{step:"build",name:"pi-ai-custom-headers",priority:"low"})}function addFinalRequestObserverMiddleware(client,observe){let middleware=next=>async args=>{let body=args.request?.body;return typeof body=="string"?await observe(body):
|
|
1494
|
+
ArrayBuffer.isView(body)&&await observe(new TextDecoder().decode(new Uint8Array(body.buffer,body.byteOffset,body.byteLength))),next(args)};client.middlewareStack.add(middleware,{step:"finalizeRequest",name:"pi-ai-final-request",priority:"low"})}function isSmithyHttpResponse(response){if(!response||typeof response!="object")return!1;let candidate=response;return typeof candidate.statusCode=="number"&&!!candidate.headers&&typeof candidate.headers=="object"}function toProviderResponse(response){if(isSmithyHttpResponse(
|
|
1495
|
+
response))return{status:response.statusCode,headers:{...response.headers}}}function addResponseHeadersMiddleware(client,onResponse,model,onObserved,timeoutMs){if(timeoutMs!==void 0&&(!Number.isFinite(timeoutMs)||timeoutMs<0||timeoutMs>2**31-1))throw new Error("Invalid Bedrock timeoutMs");let middleware=next=>async args=>{let result=await next(args),providerResponse=toProviderResponse(result.response);if(providerResponse&&(onObserved(),await onResponse?.(providerResponse,model)),isSmithyHttpResponse(
|
|
1496
|
+
result.response)&&(result.response.statusCode<200||result.response.statusCode>=300))try{await captureBedrockErrorBody(result.response,timeoutMs)}catch(error2){throw Object.assign(new Error(normalizeProviderError(error2).message),{$metadata:{httpStatusCode:result.response.statusCode,requestId:result.response.headers["x-amzn-requestid"]??result.response.headers["x-amzn-request-id"]}})}return result};client.middlewareStack.add(middleware,{step:"deserialize",name:"pi-ai-response-headers",priority:"l\
|
|
1497
|
+
ow"})}var MAX_BEDROCK_ERROR_BODY_BYTES=64*1024,BEDROCK_MODELED_ERRORS=new Set([...Object.keys(BEDROCK_ERROR_PREFIXES),"AccessDeniedException","ModelErrorException","ModelNotReadyException","ModelTimeoutException","ResourceNotFoundException"]);async function captureBedrockErrorBody(response,timeoutMs){let body=response.body,bytes,oversized=!1;if(typeof body=="string")bytes=new TextEncoder().encode(body.slice(0,MAX_BEDROCK_ERROR_BODY_BYTES)),oversized=body.length>MAX_BEDROCK_ERROR_BODY_BYTES||bytes.
|
|
1498
|
+
byteLength>MAX_BEDROCK_ERROR_BODY_BYTES;else if(body instanceof Uint8Array)bytes=body,oversized=bytes.byteLength>MAX_BEDROCK_ERROR_BODY_BYTES;else if(body&&typeof body=="object"&&Symbol.asyncIterator in body){let readable=body,iterator=readable[Symbol.asyncIterator](),chunks=[],size=0,finished=!1,timer,timeout=timeoutMs?new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error(`Provider error body read timed out after ${timeoutMs}ms`)),timeoutMs)}):void 0;try{for(;;){let next=iterator.
|
|
1499
|
+
next(),item=await(timeout?Promise.race([next,timeout]):next);if(item.done){finished=!0;break}let chunk=item.value,retained=chunk.subarray(0,MAX_BEDROCK_ERROR_BODY_BYTES-size);if(chunks.push(retained),size+=retained.byteLength,retained.byteLength<chunk.byteLength){oversized=!0;break}}}finally{clearTimeout(timer),finished||(readable.destroy?.(),iterator.return?.().catch(()=>{}))}bytes=new Uint8Array(size);let offset=0;for(let chunk of chunks)bytes.set(chunk,offset),offset+=chunk.byteLength}else return;
|
|
1500
|
+
if(oversized){let parsed=parseStreamingJson(new TextDecoder().decode(bytes.subarray(0,MAX_BEDROCK_ERROR_BODY_BYTES))),code=typeof parsed?.__type=="string"?parsed.__type.split("#").pop():void 0;response.body=new TextEncoder().encode(JSON.stringify({...code&&BEDROCK_MODELED_ERRORS.has(code)?{__type:code}:{},message:"Provider error body exceeded 65536 bytes"}))}else response.body=bytes}var streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.
|
|
1501
|
+
toolChoice};if(!options?.reasoning)return stream(model,context,{...base,reasoning:void 0});if(isAnthropicClaudeModel(model)){if(supportsAdaptiveThinking(model.id,model.name))return stream(model,context,{...base,reasoning:options.reasoning,thinkingBudgets:options.thinkingBudgets});let adjusted=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,options.reasoning,options.thinkingBudgets),maxTokens=clampMaxTokensToContext(model,context,adjusted.maxTokens);return stream(model,context,{...base,
|
|
1502
|
+
maxTokens,reasoning:options.reasoning,thinkingBudgets:{...options.thinkingBudgets||{},[clampReasoning(options.reasoning)]:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))}})}return stream(model,context,{...base,reasoning:options.reasoning,thinkingBudgets:options.thinkingBudgets})};function handleContentBlockStart(event,blocks,output,stream2){let index=event.contentBlockIndex,start=event.start;if(start?.toolUse){let block={type:"toolCall",id:start.toolUse.toolUseId||"",name:start.toolUse.
|
|
1503
|
+
name||"",arguments:{},partialJson:"",index};output.content.push(block),stream2.push({type:"toolcall_start",contentIndex:blocks.length-1,partial:output})}}function handleContentBlockDelta(event,blocks,output,stream2){let contentBlockIndex=event.contentBlockIndex,delta=event.delta,index=blocks.findIndex(b5=>b5.index===contentBlockIndex),block=blocks[index];if(delta?.text!==void 0){if(!block){let newBlock={type:"text",text:"",index:contentBlockIndex};output.content.push(newBlock),index=blocks.length-
|
|
1504
|
+
1,block=blocks[index],stream2.push({type:"text_start",contentIndex:index,partial:output})}block.type==="text"&&(block.text+=delta.text,stream2.push({type:"text_delta",contentIndex:index,delta:delta.text,partial:output}))}else if(delta?.toolUse&&block?.type==="toolCall")block.partialJson=(block.partialJson||"")+(delta.toolUse.input||""),block.arguments=parseStreamingJsonWhileStreaming(block,block.partialJson,block.arguments),stream2.push({type:"toolcall_delta",contentIndex:index,delta:delta.toolUse.
|
|
1505
|
+
input||"",partial:output});else if(delta?.reasoningContent){let thinkingBlock=block,thinkingIndex=index;if(!thinkingBlock){let newBlock={type:"thinking",thinking:"",thinkingSignature:"",index:contentBlockIndex};output.content.push(newBlock),thinkingIndex=blocks.length-1,thinkingBlock=blocks[thinkingIndex],stream2.push({type:"thinking_start",contentIndex:thinkingIndex,partial:output})}thinkingBlock?.type==="thinking"&&(delta.reasoningContent.text&&(thinkingBlock.thinking+=delta.reasoningContent.text,
|
|
1506
|
+
stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:delta.reasoningContent.text,partial:output})),delta.reasoningContent.signature&&!thinkingBlock.redacted&&(thinkingBlock.thinkingSignature=(thinkingBlock.thinkingSignature||"")+delta.reasoningContent.signature),delta.reasoningContent.redactedContent?.length&&(thinkingBlock.redacted||(thinkingBlock.redacted=!0,thinkingBlock.thinkingSignature="",thinkingBlock.thinking+=REDACTED_THINKING_PLACEHOLDER,stream2.push({type:"thinking_del\
|
|
1507
|
+
ta",contentIndex:thinkingIndex,delta:REDACTED_THINKING_PLACEHOLDER,partial:output})),thinkingBlock.redactedChunks??=[],thinkingBlock.redactedChunks.push(delta.reasoningContent.redactedContent)))}}function flushRedactedContent(block){block.type!=="thinking"||!block.redactedChunks||(block.thinkingSignature=bytesToBase64(block.redactedChunks),delete block.redactedChunks)}function finalizeStreamingBlock(block){delete block.index,block.type==="toolCall"&&block.partialJson!==void 0&&(block.arguments=parseStreamingJson(
|
|
1508
|
+
block.partialJson)),delete block.partialJson,flushRedactedContent(block)}function handleMetadata(event,model,output){event.usage&&(output.usage.usageIncomplete=hasIncompleteUsage([event.usage.inputTokens,event.usage.outputTokens],[event.usage.totalTokens,event.usage.cacheReadInputTokens,event.usage.cacheWriteInputTokens,...event.usage.cacheDetails?.map(detail=>detail.inputTokens)??[]]),output.usage.input=event.usage.inputTokens||0,output.usage.output=event.usage.outputTokens||0,output.usage.cacheRead=
|
|
1509
|
+
event.usage.cacheReadInputTokens||0,output.usage.cacheWrite=event.usage.cacheWriteInputTokens||0,output.usage.cacheWrite1h=event.usage.cacheDetails?.reduce((total,detail)=>total+(detail.ttl===import_client_bedrock_runtime.CacheTTL.ONE_HOUR?detail.inputTokens??0:0),0),output.usage.totalTokens=event.usage.totalTokens||output.usage.input+output.usage.output,output.usage.usageIncomplete||=hasIncompleteUsage([output.usage.totalTokens],[output.usage.cacheWrite1h]),calculateCost(model,output.usage))}function handleContentBlockStop(event,blocks,output,stream2){
|
|
1510
|
+
let index=blocks.findIndex(b5=>b5.index===event.contentBlockIndex),block=blocks[index];if(block)switch(delete block.index,block.type){case"text":stream2.push({type:"text_end",contentIndex:index,content:block.text,partial:output});break;case"thinking":flushRedactedContent(block),stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output});break;case"toolCall":block.arguments=parseStreamingJson(block.partialJson),delete block.partialJson,stream2.push({type:"toolcall\
|
|
1511
|
+
_end",contentIndex:index,toolCall:block,partial:output});break}}function getModelMatchCandidates(modelId,modelName){return(modelName?[modelId,modelName]:[modelId]).flatMap(value=>{let lower=value.toLowerCase();return[lower,lower.replace(/[\s_.:]+/g,"-")]})}function supportsAdaptiveThinking(modelId,modelName){return getModelMatchCandidates(modelId,modelName).some(s2=>s2.includes("opus-4-6")||s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-4-6")||s2.includes(
|
|
1512
|
+
"sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function supportsNativeXhighEffort(model){return getModelMatchCandidates(model.id,model.name).some(s2=>s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function supportsThinkingBlockBinding(model){return getModelMatchCandidates(model.id,model.name).some(s2=>s2.includes("opus-4-7")||s2.includes("opus-4-8")||s2.includes("opus-5")||s2.includes(
|
|
1513
|
+
"sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function mapThinkingLevelToEffort(model,level){if(level==="xhigh"&&supportsNativeXhighEffort(model))return"xhigh";let mapped=level?model.thinkingLevelMap?.[level]:void 0;if(typeof mapped=="string")return mapped;switch(level){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}function resolveCacheRetention(cacheRetention,env2){return cacheRetention||(getProviderEnvValue("HUMAIN_\
|
|
1514
|
+
TERMINAL_CACHE_RETENTION",env2)==="long"||getProviderEnvValue("PI_CACHE_RETENTION",env2)==="long"?"long":"short")}function isAnthropicClaudeModel(model){let id=model.id.toLowerCase(),name=model.name?.toLowerCase()??"";return id.includes("anthropic.claude")||id.includes("anthropic/claude")||name.includes("anthropic.claude")||name.includes("anthropic/claude")||name.includes("claude")}function supportsPromptCaching(model,env2){let candidates=getModelMatchCandidates(model.id,model.name);return candidates.
|
|
1515
|
+
some(s2=>s2.includes("claude"))?!!(candidates.some(s2=>s2.includes("fable-5")||s2.includes("opus-5")||s2.includes("sonnet-5")||s2.includes("haiku-5"))||candidates.some(s2=>s2.includes("-4-"))||candidates.some(s2=>s2.includes("claude-3-7-sonnet"))||candidates.some(s2=>s2.includes("claude-3-5-haiku"))):getProviderEnvValue("AWS_BEDROCK_FORCE_CACHE",env2)==="1"}function supportsThinkingSignature(model){return isAnthropicClaudeModel(model)}function buildSystemPrompt(systemPrompt,model,cacheRetention,env2){
|
|
1516
|
+
if(!systemPrompt)return;let blocks=[{text:sanitizeSurrogates(systemPrompt)}];return cacheRetention!=="none"&&supportsPromptCaching(model,env2)&&blocks.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,...cacheRetention==="long"?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}}),blocks}function normalizeToolCallId(id){let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");return sanitized.length>64?sanitized.slice(0,64):sanitized}function createNonBlankTextBlock(text){
|
|
1517
|
+
let sanitized=sanitizeSurrogates(text);return sanitized.trim().length===0?void 0:{text:sanitized}}function createRequiredTextBlock(text){return createNonBlankTextBlock(text)??{text:EMPTY_TEXT_PLACEHOLDER}}function sanitizeBedrockDocument(value){return Array.isArray(value)?value.map(sanitizeBedrockDocument):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).filter(([key])=>key.length>0).map(([key,nestedValue])=>[key,sanitizeBedrockDocument(nestedValue)])):value}function convertToolResultContent(content){
|
|
1518
|
+
let result=[];for(let c5 of content)if(c5.type==="image")result.push({image:createImageBlock(c5.mimeType,c5.data)});else{let textBlock=createNonBlankTextBlock(c5.text);textBlock&&result.push(textBlock)}return result.length===0&&result.push({text:EMPTY_TEXT_PLACEHOLDER}),result}function convertMessages(context,model,cacheRetention,env2){let result=[],transformedMessages=transformMessages(withoutInitialSystemMessage(context.messages),model,normalizeToolCallId);for(let i5=0;i5<transformedMessages.length;i5++){
|
|
1519
|
+
let m3=transformedMessages[i5];switch(m3.role){case"user":{let content=[];if(typeof m3.content=="string")content.push(createRequiredTextBlock(m3.content));else{for(let c5 of m3.content)switch(c5.type){case"text":{let textBlock=createNonBlankTextBlock(c5.text);textBlock&&content.push(textBlock);break}case"image":content.push({image:createImageBlock(c5.mimeType,c5.data)});break;default:continue}content.length===0&&content.push({text:EMPTY_TEXT_PLACEHOLDER})}result.push({role:import_client_bedrock_runtime.ConversationRole.
|
|
1520
|
+
USER,content});break}case"assistant":{if(m3.content.length===0)continue;let contentBlocks=[];for(let c5 of m3.content)switch(c5.type){case"text":{let textBlock=createNonBlankTextBlock(c5.text);if(!textBlock)continue;contentBlocks.push(textBlock);break}case"toolCall":contentBlocks.push({toolUse:{toolUseId:c5.id,name:c5.name,input:sanitizeBedrockDocument(c5.arguments)}});break;case"thinking":{if(c5.redacted){let redactedContent=decodeRedactedContent(c5.thinkingSignature);redactedContent?.length&&contentBlocks.
|
|
1521
|
+
push({reasoningContent:{redactedContent}});continue}let thinking=sanitizeSurrogates(c5.thinking);if(thinking.trim().length===0)continue;supportsThinkingSignature(model)?!c5.thinkingSignature||c5.thinkingSignature.trim().length===0?contentBlocks.push({text:thinking}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking,signature:c5.thinkingSignature}}}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking}}});break}default:continue}if(contentBlocks.length===0)continue;
|
|
1522
|
+
result.push({role:import_client_bedrock_runtime.ConversationRole.ASSISTANT,content:contentBlocks});break}case"toolResult":{let toolResults=[];toolResults.push({toolResult:{toolUseId:m3.toolCallId,content:convertToolResultContent(m3.content),status:m3.isError?import_client_bedrock_runtime.ToolResultStatus.ERROR:import_client_bedrock_runtime.ToolResultStatus.SUCCESS}});let j5=i5+1;for(;j5<transformedMessages.length&&transformedMessages[j5].role==="toolResult";){let nextMsg=transformedMessages[j5];
|
|
1523
|
+
toolResults.push({toolResult:{toolUseId:nextMsg.toolCallId,content:convertToolResultContent(nextMsg.content),status:nextMsg.isError?import_client_bedrock_runtime.ToolResultStatus.ERROR:import_client_bedrock_runtime.ToolResultStatus.SUCCESS}}),j5++}i5=j5-1,result.push({role:import_client_bedrock_runtime.ConversationRole.USER,content:toolResults});break}default:continue}}if(cacheRetention!=="none"&&supportsPromptCaching(model,env2)&&result.length>0){let lastMessage=result[result.length-1];lastMessage.
|
|
1524
|
+
role===import_client_bedrock_runtime.ConversationRole.USER&&lastMessage.content&&lastMessage.content.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,...cacheRetention==="long"?{ttl:import_client_bedrock_runtime.CacheTTL.ONE_HOUR}:{}}})}return result}function convertToolConfig(tools,toolChoice,supportsStrictMode){if(!tools?.length||toolChoice==="none")return;let bedrockTools=tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode);return{toolSpec:{
|
|
1525
|
+
name:tool.name,description:tool.description,inputSchema:{json:getJsonSchemaToolParameters(tool,strict)},...strict===!0?{strict:!0}:{}}}}),bedrockToolChoice;switch(toolChoice){case"auto":bedrockToolChoice={auto:{}};break;case"any":bedrockToolChoice={any:{}};break;default:toolChoice?.type==="tool"&&(bedrockToolChoice={tool:{name:toolChoice.name}})}return{tools:bedrockTools,toolChoice:bedrockToolChoice}}function mapStopReason(reason){switch(reason){case import_client_bedrock_runtime.StopReason.END_TURN:case import_client_bedrock_runtime.StopReason.
|
|
1526
|
+
STOP_SEQUENCE:return{stopReason:"stop"};case import_client_bedrock_runtime.StopReason.MAX_TOKENS:case import_client_bedrock_runtime.StopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:return{stopReason:"length"};case import_client_bedrock_runtime.StopReason.TOOL_USE:return{stopReason:"toolUse"};default:return reason?{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}:{stopReason:"error"}}}function getConfiguredBedrockRegion(options){return options.region||getProviderEnvValue("AWS_REGION",options.
|
|
1527
|
+
env)||getProviderEnvValue("AWS_DEFAULT_REGION",options.env)||void 0}function getConfiguredBedrockCredentials(env2){let accessKeyId=getProviderEnvValue("AWS_ACCESS_KEY_ID",env2),secretAccessKey=getProviderEnvValue("AWS_SECRET_ACCESS_KEY",env2);if(!accessKeyId||!secretAccessKey)return;let sessionToken=getProviderEnvValue("AWS_SESSION_TOKEN",env2);return{accessKeyId,secretAccessKey,...sessionToken?{sessionToken}:{}}}function getStandardBedrockEndpointRegion(baseUrl){if(baseUrl)try{let{hostname}=new URL(
|
|
1528
|
+
baseUrl);return hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/)?.[1]}catch{return}}function shouldUseExplicitBedrockEndpoint(baseUrl,configuredRegion,hasAmbientConfiguredProfile){return getStandardBedrockEndpointRegion(baseUrl)?!configuredRegion&&!hasAmbientConfiguredProfile:!0}function shouldUseBedrockHttp1Handler(baseUrl,env2){if(getProviderEnvValue("AWS_BEDROCK_FORCE_HTTP1",env2)==="1")return!0;if(!baseUrl)return!1;try{return new URL(baseUrl).
|
|
1529
|
+
protocol==="http:"}catch{return!1}}function shouldBypassBedrockProxy(baseUrl){if(!baseUrl)return!1;try{let url=new URL(baseUrl);return url.protocol==="http:"&&isLoopbackHostname(url.hostname)}catch{return!1}}function isLoopbackHostname(hostname){return hostname==="localhost"||hostname==="0.0.0.0"||hostname==="[::1]"||hostname.startsWith("127.")}function isGovCloudBedrockTarget(model,options){if(getConfiguredBedrockRegion(options)?.toLowerCase().startsWith("us-gov-"))return!0;let modelId=model.id.
|
|
1530
|
+
toLowerCase();return modelId.startsWith("us-gov.")||modelId.startsWith("arn:aws-us-gov:")}function buildAdditionalModelRequestFields(model,options){if(!options.reasoning||!model.reasoning)return;if(isAnthropicClaudeModel(model)){let isGovCloud=isGovCloudBedrockTarget(model,options),display=isGovCloud?void 0:options.thinkingDisplay??"summarized",useBlockBinding=!isGovCloud&&supportsThinkingBlockBinding(model),result=supportsAdaptiveThinking(model.id,model.name)?{thinking:{type:"adaptive",...display!==
|
|
1531
|
+
void 0?{display}:{},...useBlockBinding?{block_binding:{prefix_mismatch_behavior:"drop_block"}}:{}},output_config:{effort:mapThinkingLevelToEffort(model,options.reasoning)},...useBlockBinding?{anthropic_beta:[THINKING_BINDING_CONTROLS_BETA]}:{}}:(()=>{let defaultBudgets={minimal:1024,low:2048,medium:8192,high:16384,xhigh:16384,max:16384},level=options.reasoning==="xhigh"||options.reasoning==="max"?"high":options.reasoning;return{thinking:{type:"enabled",budget_tokens:options.thinkingBudgets?.[level]??
|
|
1532
|
+
defaultBudgets[options.reasoning],...display!==void 0?{display}:{}}}})();return!supportsAdaptiveThinking(model.id,model.name)&&(options.interleavedThinking??!0)&&(result.anthropic_beta=["interleaved-thinking-2025-05-14"]),result}let candidates=getModelMatchCandidates(model.id,model.name);if(candidates.some(s2=>s2.includes("gpt-oss")))return{reasoning_effort:OPENAI_GPT_OSS_EFFORT[options.reasoning]};if(candidates.some(s2=>s2.includes("gpt-"))){let mapped=model.thinkingLevelMap?.[options.reasoning];
|
|
1533
|
+
return{reasoning:{effort:typeof mapped=="string"?mapped:OPENAI_GPT_EFFORT[options.reasoning]}}}}var OPENAI_GPT_EFFORT={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},OPENAI_GPT_OSS_EFFORT={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"};function createImageBlock(mimeType,data){let format2;switch(mimeType){case"image/jpeg":case"image/jpg":format2=import_client_bedrock_runtime.ImageFormat.JPEG;break;case"image/png":format2=import_client_bedrock_runtime.ImageFormat.
|
|
1534
|
+
PNG;break;case"image/gif":format2=import_client_bedrock_runtime.ImageFormat.GIF;break;case"image/webp":format2=import_client_bedrock_runtime.ImageFormat.WEBP;break;default:throw new Error(`Unknown image type: ${mimeType}`)}return{source:{bytes:base64ToBytes(data)},format:format2}}function base64ToBytes(data){let binaryString=atob(data),bytes=new Uint8Array(binaryString.length);for(let i5=0;i5<binaryString.length;i5++)bytes[i5]=binaryString.charCodeAt(i5);return bytes}function decodeRedactedContent(signature){
|
|
1535
|
+
if(signature)try{return base64ToBytes(signature)}catch{return}}function bytesToBase64(chunks){let binary="";for(let chunk of chunks)for(let i5=0;i5<chunk.length;i5+=32768)binary+=String.fromCharCode(...chunk.subarray(i5,i5+32768));return btoa(binary)}export{stream,streamSimple};
|
|
@@ -5,15 +5,15 @@ Union(values.map(value=>typebox_exports.Literal(value))),StrictObject=properties
|
|
|
5
5
|
0||year%400===0;return day<=(month===2&&leap?29:DAYS_IN_MONTH[month-1]??0)}var FlowTimestampSchema=typebox_exports.Refine(typebox_exports.String({pattern:FLOW_TS_PATTERN}),isRealCalendarDate),FlowMicrousdSchema=typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),FlowCountSchema=typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),FlowPositiveIntSchema=typebox_exports.Integer({minimum:1,maximum:Number.MAX_SAFE_INTEGER}),FlowModelRefSchema=StrictObject({provider:FlowIdSchema,
|
|
6
6
|
model:typebox_exports.String({pattern:FLOW_MODEL_ID_PATTERN})}),FLOW_ROLES=["scout","worker","implementer","lead","lead_large","architect","reviewer","security_reviewer","qa","triage"],FlowRoleSchema=typebox_exports.Union([typebox_exports.Literal("scout"),typebox_exports.Literal("worker"),typebox_exports.Literal("implementer"),typebox_exports.Literal("lead"),typebox_exports.Literal("lead_large"),typebox_exports.Literal("architect"),typebox_exports.Literal("reviewer"),typebox_exports.Literal("sec\
|
|
7
7
|
urity_reviewer"),typebox_exports.Literal("qa"),typebox_exports.Literal("triage")]),partialByRole=schema=>StrictObject({scout:typebox_exports.Optional(schema),worker:typebox_exports.Optional(schema),implementer:typebox_exports.Optional(schema),lead:typebox_exports.Optional(schema),lead_large:typebox_exports.Optional(schema),architect:typebox_exports.Optional(schema),reviewer:typebox_exports.Optional(schema),security_reviewer:typebox_exports.Optional(schema),qa:typebox_exports.Optional(schema),triage:typebox_exports.
|
|
8
|
-
Optional(schema)});var FlowSizeSchema=typebox_exports.Union([typebox_exports.Literal("small"),typebox_exports.Literal("medium"),typebox_exports.Literal("large")]);var FlowFailureClassSchema=typebox_exports.Union([typebox_exports.Literal("provider_error"),typebox_exports.Literal("rate_limit"),typebox_exports.Literal("timeout"),typebox_exports.Literal("check_failed"),typebox_exports.Literal("review_rejected"),typebox_exports.Literal("qa_failed"),typebox_exports.Literal("budget_stop"),typebox_exports.Literal("cancelled"),typebox_exports.Literal("crash"),typebox_exports.Literal("unsafe_scope"),typebox_exports.Literal(
|
|
9
|
-
|
|
10
|
-
"digest_unverifiable")}if(typeof actual!="string")throw new FlowContractError("digest_unverifiable");return actual===expected}var MAX_SNAPSHOT_DEPTH=16,MAX_SNAPSHOT_NODES=1e4,MAX_SNAPSHOT_STRING=65536;function isIndexKey(key,length){let index=Number(key);return Number.isInteger(index)&&index>=0&&index<length&&String(index)===key}function snapshotValue(value,depth,budget){if(budget.nodes+=1,depth>MAX_SNAPSHOT_DEPTH||budget.nodes>MAX_SNAPSHOT_NODES)throw new Error(
|
|
11
|
-
"boolean")return value;if(typeof value=="string"){if(value.length>MAX_SNAPSHOT_STRING||!value.isWellFormed())throw new Error("string");return value}if(typeof value=="number"){if(!Number.isFinite(value))throw new Error("number");return value}if(typeof value!="object")throw new Error("type");if(Array.isArray(value)){let length=value.length;if(length>MAX_SNAPSHOT_NODES)throw new Error("bounds");for(let key of Reflect.ownKeys(value))if(typeof key!="string"||key!==
|
|
12
|
-
"array");let out2=[];for(let index=0;index<length;index+=1){let descriptor=Object.getOwnPropertyDescriptor(value,String(index));if(descriptor===void 0||!("value"in descriptor))throw new Error("array");out2.push(snapshotValue(descriptor.value,depth+1,budget))}return out2}let proto=Object.getPrototypeOf(value);if(proto!==null&&Object.getPrototypeOf(proto)!==null)throw new Error("prototype");let out={};for(let key of Reflect.ownKeys(value)){if(typeof key!=
|
|
13
|
-
"key");let descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor===void 0||!("value"in descriptor)||descriptor.enumerable!==!0)throw new Error("property");descriptor.value!==void 0&&Object.defineProperty(out,key,{value:snapshotValue(descriptor.value,depth+1,budget),enumerable:!0,writable:!0,configurable:!0})}return out}function snapshotFlowData(input){return snapshotValue(input,0,{nodes:0})}function parseFlowData(code,input,validate){let snapshot=trySnapshotFlowData(
|
|
14
|
-
snapshot))throw new FlowContractError(code);return snapshot}function trySnapshotFlowData(code,input){try{return snapshotFlowData(input)}catch{throw new FlowContractError(code)}}function compileFlow(schema){return Compile(schema)}function modelKey(ref){return`${ref.provider}\0${ref.model}`}function hasDuplicateModels(refs){return new Set(refs.map(modelKey)).size!==refs.length}function canonicalFlowJson(value){if(value===null||typeof value=="boolean")return JSON.stringify(
|
|
15
|
-
string"){if(!value.isWellFormed())throw new FlowContractError("canonical_invalid");return JSON.stringify(value)}if(typeof value=="number"){if(!Number.isFinite(value))throw new FlowContractError("canonical_invalid");return JSON.stringify(value)}if(Array.isArray(value))return`[${value.map(canonicalFlowJson).join(",")}]`;if(typeof value!="object")throw new FlowContractError("canonical_invalid");let record=value,parts=[];for(let key of Object.keys(record).sort()){if(!key.isWellFormed())
|
|
16
|
-
"canonical_invalid");record[key]!==void 0&&parts.push(`${JSON.stringify(key)}:${canonicalFlowJson(record[key])}`)}return`{${parts.join(",")}}`}function canonicalWithout(doc,omit){let copy={...doc};return delete copy[omit],canonicalFlowJson(copy)}var SUBAGENT_WORKER_STATUSES=["queued","waiting","running","completed","failed","cancelled","skipped","unresolved"],SUBAGENT_CANCELLATION_OUTCOMES=["none","not_started","direct_worker_terminated","unconfirmed"],SUBAGENT_FAILURE_KINDS=["spawn_failed","process_error","model_error","merge_failed"],SUBAGENT_RUN_MODES=["single","parallel","chain"];var SUBAGENT_PROGRESS_UUID_PATTERN="^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",SUBAGENT_PROGRESS_IDENTIFIER_PATTERN="^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",SUBAGENT_PROGRESS_MODEL_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$",SUBAGENT_PROGRESS_TOOL_CALL_ID_PATTERN="^[\\x21-\\x7E]{1,256}$",SUBAGENT_PROGRESS_TEXT_PATTERN="^[^\\u0000-\\u001F\\u007F-\\u009F\\u00AD\\u034F\\u061C\\u180E\\u200B-\\u200F\\u2028-\\u202E\\u2060-\\u2069\\uFEFF]+$",UUID_REGEX=new RegExp(SUBAGENT_PROGRESS_UUID_PATTERN),
|
|
8
|
+
Optional(schema)});var FlowSizeSchema=typebox_exports.Union([typebox_exports.Literal("small"),typebox_exports.Literal("medium"),typebox_exports.Literal("large")]);var FlowFailureClassSchema=typebox_exports.Union([typebox_exports.Literal("provider_error"),typebox_exports.Literal("provider_unreachable"),typebox_exports.Literal("rate_limit"),typebox_exports.Literal("timeout"),typebox_exports.Literal("check_failed"),typebox_exports.Literal("review_rejected"),typebox_exports.Literal("qa_failed"),typebox_exports.Literal("budget_stop"),typebox_exports.Literal("cancelled"),typebox_exports.Literal("crash"),typebox_exports.Literal("unsafe_scope"),typebox_exports.Literal(
|
|
9
|
+
"stalled"),typebox_exports.Literal("config_invalid"),typebox_exports.Literal("internal"),typebox_exports.Literal("review_verdict_missing"),typebox_exports.Literal("verification_unavailable")]),FlowReasonClassSchema=typebox_exports.Union([FlowFailureClassSchema,typebox_exports.Literal("size_underestimated")]),FlowProfileRefSchema=StrictObject({id:FlowIdSchema,version:FlowPositiveIntSchema,digest:FlowDigestSchema});function verifyFlowDigest(hasher,text,expected){let actual;try{actual=hasher.sha256Hex(
|
|
10
|
+
text)}catch{throw new FlowContractError("digest_unverifiable")}if(typeof actual!="string")throw new FlowContractError("digest_unverifiable");return actual===expected}var MAX_SNAPSHOT_DEPTH=16,MAX_SNAPSHOT_NODES=1e4,MAX_SNAPSHOT_STRING=65536;function isIndexKey(key,length){let index=Number(key);return Number.isInteger(index)&&index>=0&&index<length&&String(index)===key}function snapshotValue(value,depth,budget){if(budget.nodes+=1,depth>MAX_SNAPSHOT_DEPTH||budget.nodes>MAX_SNAPSHOT_NODES)throw new Error(
|
|
11
|
+
"bounds");if(value===null||typeof value=="boolean")return value;if(typeof value=="string"){if(value.length>MAX_SNAPSHOT_STRING||!value.isWellFormed())throw new Error("string");return value}if(typeof value=="number"){if(!Number.isFinite(value))throw new Error("number");return value}if(typeof value!="object")throw new Error("type");if(Array.isArray(value)){let length=value.length;if(length>MAX_SNAPSHOT_NODES)throw new Error("bounds");for(let key of Reflect.ownKeys(value))if(typeof key!="string"||key!==
|
|
12
|
+
"length"&&!isIndexKey(key,length))throw new Error("array");let out2=[];for(let index=0;index<length;index+=1){let descriptor=Object.getOwnPropertyDescriptor(value,String(index));if(descriptor===void 0||!("value"in descriptor))throw new Error("array");out2.push(snapshotValue(descriptor.value,depth+1,budget))}return out2}let proto=Object.getPrototypeOf(value);if(proto!==null&&Object.getPrototypeOf(proto)!==null)throw new Error("prototype");let out={};for(let key of Reflect.ownKeys(value)){if(typeof key!=
|
|
13
|
+
"string"||!key.isWellFormed())throw new Error("key");let descriptor=Object.getOwnPropertyDescriptor(value,key);if(descriptor===void 0||!("value"in descriptor)||descriptor.enumerable!==!0)throw new Error("property");descriptor.value!==void 0&&Object.defineProperty(out,key,{value:snapshotValue(descriptor.value,depth+1,budget),enumerable:!0,writable:!0,configurable:!0})}return out}function snapshotFlowData(input){return snapshotValue(input,0,{nodes:0})}function parseFlowData(code,input,validate){let snapshot=trySnapshotFlowData(
|
|
14
|
+
code,input);if(!validate(snapshot))throw new FlowContractError(code);return snapshot}function trySnapshotFlowData(code,input){try{return snapshotFlowData(input)}catch{throw new FlowContractError(code)}}function compileFlow(schema){return Compile(schema)}function modelKey(ref){return`${ref.provider}\0${ref.model}`}function hasDuplicateModels(refs){return new Set(refs.map(modelKey)).size!==refs.length}function canonicalFlowJson(value){if(value===null||typeof value=="boolean")return JSON.stringify(
|
|
15
|
+
value);if(typeof value=="string"){if(!value.isWellFormed())throw new FlowContractError("canonical_invalid");return JSON.stringify(value)}if(typeof value=="number"){if(!Number.isFinite(value))throw new FlowContractError("canonical_invalid");return JSON.stringify(value)}if(Array.isArray(value))return`[${value.map(canonicalFlowJson).join(",")}]`;if(typeof value!="object")throw new FlowContractError("canonical_invalid");let record=value,parts=[];for(let key of Object.keys(record).sort()){if(!key.isWellFormed())
|
|
16
|
+
throw new FlowContractError("canonical_invalid");record[key]!==void 0&&parts.push(`${JSON.stringify(key)}:${canonicalFlowJson(record[key])}`)}return`{${parts.join(",")}}`}function canonicalWithout(doc,omit){let copy={...doc};return delete copy[omit],canonicalFlowJson(copy)}var SUBAGENT_WORKER_STATUSES=["queued","waiting","running","completed","failed","cancelled","skipped","unresolved"],SUBAGENT_CANCELLATION_OUTCOMES=["none","not_started","direct_worker_terminated","unconfirmed"],SUBAGENT_FAILURE_KINDS=["spawn_failed","process_error","model_error","merge_failed"],SUBAGENT_RUN_MODES=["single","parallel","chain"];var SUBAGENT_PROGRESS_UUID_PATTERN="^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",SUBAGENT_PROGRESS_IDENTIFIER_PATTERN="^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",SUBAGENT_PROGRESS_MODEL_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$",SUBAGENT_PROGRESS_TOOL_CALL_ID_PATTERN="^[\\x21-\\x7E]{1,256}$",SUBAGENT_PROGRESS_TEXT_PATTERN="^[^\\u0000-\\u001F\\u007F-\\u009F\\u00AD\\u034F\\u061C\\u180E\\u200B-\\u200F\\u2028-\\u202E\\u2060-\\u2069\\uFEFF]+$",UUID_REGEX=new RegExp(SUBAGENT_PROGRESS_UUID_PATTERN),
|
|
17
17
|
IDENTIFIER_REGEX=new RegExp(SUBAGENT_PROGRESS_IDENTIFIER_PATTERN),MODEL_REGEX=new RegExp(SUBAGENT_PROGRESS_MODEL_PATTERN),TOOL_CALL_ID_REGEX=new RegExp(SUBAGENT_PROGRESS_TOOL_CALL_ID_PATTERN);function isCanonicalSubagentProgressUuid(value){return typeof value=="string"&&value.length===36&&UUID_REGEX.test(value)}var progressTextEncoder=new TextEncoder;function measureSubagentProgressJson(value){let text;try{text=JSON.stringify(value)}catch{throw invalidSnapshot()}if(typeof text!="string")throw invalidSnapshot();
|
|
18
18
|
return{utf8Bytes:progressTextEncoder.encode(text).length,codeUnits:text.length}}function isForbiddenTextCodeUnit(unit){return unit<=31||unit>=127&&unit<=159||unit===173||unit===847||unit===1564||unit===6158||unit>=8203&&unit<=8207||unit>=8232&&unit<=8238||unit>=8288&&unit<=8297||unit===65279}function isHighSurrogate(unit){return unit>=55296&&unit<=56319}function isLowSurrogate(unit){return unit>=56320&&unit<=57343}function isSubagentPresentationText(value,max){if(typeof value!="string"||value.length===
|
|
19
19
|
0||value.length>max||value!==value.trim())return!1;for(let i=0;i<value.length;i++){let unit=value.charCodeAt(i);if(isHighSurrogate(unit)){if(!isLowSurrogate(value.charCodeAt(i+1)))return!1;i+=1}else if(isLowSurrogate(unit)||isForbiddenTextCodeUnit(unit))return!1}return!0}var SUBAGENT_PRESENTATION_SCAN_WINDOW_CODE_UNITS=4096,WHITESPACE_UNIT_REGEX=/\s/;function isSeparatorAt(input,index){let unit=input.charCodeAt(index);return isHighSurrogate(unit)?!isLowSurrogate(input.charCodeAt(index+1)):isLowSurrogate(
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{uuidv7}from"./chunk-
|
|
2
|
+
import{uuidv7}from"./chunk-VEYTRNQC.js";function headersToRecord(headers){let result={};for(let[key,value]of headers.entries())result[key]=value;return result}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}var noop=async()=>{};function createRequestObserver(options,info){let onRequest=options?.onRequest;if(!onRequest)return noop;let requestId=uuidv7(),submissionNumber=0;return async(body,overrides)=>{submissionNumber++;let value=Object.freeze({requestId,submissionId:uuidv7(),submissionNumber,api:info.api,provider:info.provider,model:info.model,operation:overrides?.operation??info.operation,transport:overrides?.transport??"http",representation:overrides?.representation??"json-body",body});try{await onRequest(
|
|
3
3
|
value)}catch{}}}function observeFetch(baseFetch,observe){return observe===noop?baseFetch:async(input,init)=>(typeof init?.body=="string"&&await observe(init.body),(baseFetch??globalThis.fetch)(input,init))}export{headersToRecord,providerHeadersToRecord,createRequestObserver,observeFetch};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{clampThinkingLevel,getSystemMessageText}from"./chunk-
|
|
2
|
+
import{clampThinkingLevel,getSystemMessageText}from"./chunk-DZ5C66IU.js";function loadNodeOs(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:os")??null}var nodeOs=loadNodeOs();function getPiUserAgent(){return nodeOs?`pi (${nodeOs.platform()} ${nodeOs.release()}; ${nodeOs.arch()})`:"pi (browser)"}var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.
|
|
3
3
|
type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){
|
|
4
4
|
if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.
|
|
5
5
|
anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}
|