@humain/humain-code 0.4.6 → 0.4.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/bun/sandbox-env-setup.js +8 -0
- package/dist/bun/sandbox-env-setup.js.map +1 -1
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/{anthropic-messages-OHNAMPAM.js → anthropic-messages-YMPB2HJ7.js} +14 -13
- package/dist/bundle/chunks/{azure-openai-responses-FREWTLSS.js → azure-openai-responses-PDHOT7UC.js} +2 -2
- package/dist/bundle/chunks/bedrock-converse-stream.js +35 -35
- package/dist/bundle/chunks/{chunk-UTMYL2YO.js → chunk-2W5PWUPO.js} +10 -10
- package/dist/bundle/chunks/{chunk-DUZY4PDA.js → chunk-3E4SMILM.js} +33 -29
- package/dist/bundle/chunks/{chunk-UU4WS4BQ.js → chunk-3TYF6GG6.js} +319 -321
- package/dist/bundle/chunks/{chunk-FP2SXW5M.js → chunk-DAJJK7AP.js} +472 -458
- package/dist/bundle/chunks/{chunk-JQZ7BIAI.js → chunk-F7UMX5BV.js} +25 -22
- package/dist/bundle/chunks/{chunk-E7WGCXWK.js → chunk-GUUAEK6G.js} +1 -1
- package/dist/bundle/chunks/{chunk-4X774RBJ.js → chunk-GVVRXZHN.js} +4 -4
- package/dist/bundle/chunks/{chunk-H5CZL7M5.js → chunk-KRMTBTWU.js} +1 -1
- package/dist/bundle/chunks/{chunk-ICLZNV4V.js → chunk-LQ4S7CRR.js} +79 -67
- package/dist/bundle/chunks/{chunk-KLIRQQH5.js → chunk-OTXURGIO.js} +1 -1
- package/dist/bundle/chunks/{chunk-OXJXKCLB.js → chunk-PMISFIBM.js} +1 -1
- package/dist/bundle/chunks/{chunk-LFXFQLII.js → chunk-ROSZII6E.js} +1 -1
- package/dist/bundle/chunks/{chunk-E22S6D55.js → chunk-SWRU4BOC.js} +1 -1
- package/dist/bundle/chunks/{chunk-VQTXF23B.js → chunk-TIAXGIMN.js} +1 -1
- package/dist/bundle/chunks/{chunk-3ZI2TEVB.js → chunk-UZ5FVVCP.js} +1 -1
- package/dist/bundle/chunks/{chunk-BBBBZ5HY.js → chunk-XRMWWXLF.js} +3 -3
- package/dist/bundle/chunks/{chunk-2NX3BVH6.js → chunk-Z5LYSSTY.js} +2 -2
- package/dist/bundle/chunks/{cli-5YRA5PFB.js → cli-ZKT34WPW.js} +2 -2
- package/dist/bundle/chunks/{compat-LJ4ZIVJZ.js → compat-VPRCBNVL.js} +8 -8
- package/dist/bundle/chunks/{dist-UAQRGPZO.js → dist-4KCNJLEA.js} +153 -143
- package/dist/bundle/chunks/{dist-QHFJK4TH.js → dist-N7XDUAAO.js} +4 -4
- package/dist/bundle/chunks/{easter-egg-3d-ARXMB2RN.js → easter-egg-3d-5KKDWEIA.js} +1 -1
- package/dist/bundle/chunks/{execute-MFIDTEMB.js → execute-OSBDNQU5.js} +1 -1
- package/dist/bundle/chunks/{extract-EWN2GRAC.js → extract-56PXVZVW.js} +2 -2
- package/dist/bundle/chunks/{host-3OGMFGBY.js → host-2ARI7PQ5.js} +1 -1
- package/dist/bundle/chunks/mistral-conversations-XA2ZGSAH.js +43 -0
- package/dist/bundle/chunks/{openai-codex-responses-5AJAJHTK.js → openai-codex-responses-Y6NRWMOI.js} +2 -2
- package/dist/bundle/chunks/{openai-completions-65RRYKEQ.js → openai-completions-FY77MIZH.js} +6 -6
- package/dist/bundle/chunks/{openai-responses-72W3PGZ7.js → openai-responses-LNSCERKH.js} +2 -2
- package/dist/bundle/chunks/{pi-messages-RLLYRBDT.js → pi-messages-LYJZPRST.js} +7 -6
- package/dist/bundle/chunks/{runtime-HBWXEJT3.js → runtime-JFLZUNYP.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-LWYOTTHQ.js → virtual-modules-F76HZAGG.js} +2 -2
- package/dist/bundle/cli-runtime.js +2 -2
- 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/core/tools/renderers/write.d.ts +2 -2
- package/dist/core/tools/renderers/write.d.ts.map +1 -1
- package/dist/core/tools/renderers/write.js +120 -15
- package/dist/core/tools/renderers/write.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +27 -28
- package/dist/humain/flow-loader.d.ts.map +1 -1
- package/dist/humain/flow-loader.js +30 -2
- package/dist/humain/flow-loader.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +2 -0
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
- package/dist/modes/interactive/components/mermaid.js +4 -0
- package/dist/modes/interactive/components/mermaid.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +4 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/child-process.d.ts +8 -0
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +65 -4
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/windows-path.d.ts +9 -0
- package/dist/utils/windows-path.d.ts.map +1 -0
- package/dist/utils/windows-path.js +31 -0
- package/dist/utils/windows-path.js.map +1 -0
- package/docs/tui.md +1 -1
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/dist/bundle/chunks/mistral-conversations-5HCMHK6E.js +0 -43
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.4.7] - 2026-10-12
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- Faster terminal rendering while a reply streams (ported from Pi-Bolt): Markdown is lexed incrementally and only completed messages are fully re-lexed, streamed tool-call arguments are parsed incrementally, moved rows are scrolled instead of redrawn, Mermaid lexing is skipped for messages without Mermaid, and only collapsed write previews are highlighted.
|
|
8
|
+
- The Flow widget shows startup progress and recovered failover attempts.
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- Anthropic `max_tokens` cut-offs are reported as a length stop, not an error.
|
|
13
|
+
- Terminal tool-argument state is finalized when a stream ends, and rendered Markdown is invalidated on every TUI invalidate.
|
|
14
|
+
- On Windows, a bare command is never resolved from the working directory, and interpreter resolution for extensionless scripts is hardened.
|
|
15
|
+
- Flow retries a provider whose usage is incomplete on the next frozen-profile candidate, including listed provider twins, while preserving partial-work handoff. Each unknown-cost route is tried once; exhaustion names incomplete provider usage. Unknown request costs remain null, warn instead of appearing free, and preserve known-spend caps, cancellation, and termination-confirmation gates (HTFIX17).
|
|
16
|
+
- Flow ignores inherited asset overrides from unknown or different CLI releases before lazy loading, while preserving validated same-version child overrides.
|
|
17
|
+
|
|
3
18
|
## [0.4.6] - 2026-10-11
|
|
4
19
|
|
|
5
20
|
### Changed
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import { restoreSandboxEnv } from "./restore-sandbox-env.js";
|
|
2
2
|
// Restore the environment before evaluating modules that read it at startup.
|
|
3
3
|
restoreSandboxEnv();
|
|
4
|
+
// Derived from Pi-Bolt (MIT, Copyright (c) 2026 OpenSec (Pi-Bolt)), commit 36a2080f; modified for HUMAIN Code CLI.
|
|
5
|
+
// Windows: a program named without a path is looked up on PATH only, never in the working directory first. Bun's spawn looks
|
|
6
|
+
// there unless this is set, and takes a .cmd there too, so a repository could have its own git.cmd or npm.cmd run for a bare
|
|
7
|
+
// `git` or `npm` (our own calls, and extensions' exec()). Programs started from here inherit it, so the shells the tools run
|
|
8
|
+
// (cmd.exe) do not look there either; a path such as .\build.cmd still runs what it names.
|
|
9
|
+
if (process.platform === "win32" && !process.env.NoDefaultCurrentDirectoryInExePath) {
|
|
10
|
+
process.env.NoDefaultCurrentDirectoryInExePath = "1";
|
|
11
|
+
}
|
|
4
12
|
//# sourceMappingURL=sandbox-env-setup.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox-env-setup.js","sourceRoot":"","sources":["../../src/bun/sandbox-env-setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7D,6EAA6E;AAC7E,iBAAiB,EAAE,CAAC","sourcesContent":["import { restoreSandboxEnv } from \"./restore-sandbox-env.ts\";\n\n// Restore the environment before evaluating modules that read it at startup.\nrestoreSandboxEnv();\n"]}
|
|
1
|
+
{"version":3,"file":"sandbox-env-setup.js","sourceRoot":"","sources":["../../src/bun/sandbox-env-setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7D,6EAA6E;AAC7E,iBAAiB,EAAE,CAAC;AAEpB,mHAAmH;AACnH,6HAA6H;AAC7H,6HAA6H;AAC7H,6HAA6H;AAC7H,2FAA2F;AAC3F,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,kCAAkC,EAAE,CAAC;IACrF,OAAO,CAAC,GAAG,CAAC,kCAAkC,GAAG,GAAG,CAAC;AACtD,CAAC","sourcesContent":["import { restoreSandboxEnv } from \"./restore-sandbox-env.ts\";\n\n// Restore the environment before evaluating modules that read it at startup.\nrestoreSandboxEnv();\n\n// Derived from Pi-Bolt (MIT, Copyright (c) 2026 OpenSec (Pi-Bolt)), commit 36a2080f; modified for HUMAIN Code CLI.\n// Windows: a program named without a path is looked up on PATH only, never in the working directory first. Bun's spawn looks\n// there unless this is set, and takes a .cmd there too, so a repository could have its own git.cmd or npm.cmd run for a bare\n// `git` or `npm` (our own calls, and extensions' exec()). Programs started from here inherit it, so the shells the tools run\n// (cmd.exe) do not look there either; a path such as .\\build.cmd still runs what it names.\nif (process.platform === \"win32\" && !process.env.NoDefaultCurrentDirectoryInExePath) {\n\tprocess.env.NoDefaultCurrentDirectoryInExePath = \"1\";\n}\n"]}
|
|
@@ -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-TIAXGIMN.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-OHNAMPAM.js → anthropic-messages-YMPB2HJ7.js}
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
2
|
import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-JEJQVFWK.js";import{retryProviderRequest}from"./chunk-MEIYGK5O.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IMR3ZJM5.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord}from"./chunk-II2442A2.js";
|
|
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}from"./chunk-
|
|
4
|
-
appendAssistantMessageDiagnostic}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.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\
|
|
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,renderSystemMessageUpdate,resolveTranscript}from"./chunk-WPLW452J.js";
|
|
4
|
+
import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.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="\
|
|
@@ -30,17 +30,18 @@ cacheWrite=event.message.usage?.cache_creation_input_tokens,optionalUsage.cacheW
|
|
|
30
30
|
push({type:"text_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="thinking"){let block={type:"thinking",thinking:event.content_block.thinking??"",thinkingSignature:event.content_block.signature??"",index:event.index};output.content.push(block),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="redacted_thinking"){let block={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:event.
|
|
31
31
|
content_block.data,redacted:!0,index:event.index};output.content.push(block),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="tool_use"){let block={type:"toolCall",id:event.content_block.id,name:isOAuth?fromClaudeCodeName(event.content_block.name,currentTools):event.content_block.name,arguments:event.content_block.input??{},partialJson:"",index:event.index};output.content.push(block),stream2.push({type:"toolcall_start",
|
|
32
32
|
contentIndex:output.content.length-1,partial:output})}}else if(event.type==="content_block_delta"){if(event.delta.type==="text_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="text"&&(block.text+=event.delta.text,stream2.push({type:"text_delta",contentIndex:index,delta:event.delta.text,partial:output}))}else if(event.delta.type==="thinking_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="thi\
|
|
33
|
-
nking"&&(block.thinking+=event.delta.thinking,stream2.push({type:"thinking_delta",contentIndex:index,delta:event.delta.thinking,partial:output}))}else if(event.delta.type==="input_json_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="toolCall"&&(block.partialJson+=event.delta.partial_json,block.arguments=
|
|
34
|
-
delta.type==="signature_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="thinking"&&(block.thinkingSignature=block.thinkingSignature||"",block.thinkingSignature+=event.delta.signature)}}else if(event.type==="content_block_stop"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&(delete block.index,block.type==="text"?stream2.push({type:"text_end",contentIndex:index,
|
|
35
|
-
"thinking"?stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output}):block.type==="toolCall"&&(block.arguments=parseStreamingJson(block.partialJson),delete block.partialJson,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output})))}else if(event.type==="message_delta"){let transformations=event.input_transformations;if(Array.isArray(transformations)&&(inputTransformations=transformations),
|
|
36
|
-
event.delta.stop_reason;let stopReasonResult=mapStopReason(event.delta.stop_reason,event.delta.stop_details);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}if(event.usage){event.usage.input_tokens!=null&&(output.usage.input=event.usage.input_tokens,inputUsageIncomplete=hasIncompleteUsage([event.usage.input_tokens])),event.usage.output_tokens!=null&&(output.usage.output=
|
|
37
|
-
void 0&&(optionalUsage.cacheRead=event.usage.cache_read_input_tokens),event.usage.cache_read_input_tokens!=null&&(output.usage.cacheRead=event.usage.cache_read_input_tokens),event.usage.cache_creation_input_tokens!==void 0&&(optionalUsage.cacheWrite=event.usage.cache_creation_input_tokens),event.usage.cache_creation_input_tokens!=null&&(output.usage.cacheWrite=event.usage.cache_creation_input_tokens);let cacheCreation=event.usage.cache_creation;
|
|
38
|
-
(optionalUsage.cacheWrite1h=cacheCreation.ephemeral_1h_input_tokens),cacheCreation?.ephemeral_1h_input_tokens!=null&&(output.usage.cacheWrite1h=cacheCreation.ephemeral_1h_input_tokens);let thinkingTokens=event.usage.output_tokens_details?.thinking_tokens;thinkingTokens!==void 0&&(optionalUsage.reasoning=thinkingTokens),event.delta.stop_reason&&(output.usage.usageIncomplete=inputUsageIncomplete||hasIncompleteUsage([event.usage.output_tokens],[event.
|
|
39
|
-
thinkingTokens!=null&&(output.usage.reasoning=thinkingTokens)}output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,output.usage.usageIncomplete||=hasIncompleteUsage([output.usage.totalTokens]),calculateCost(usageModel,output.usage)}if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Anthropic stream ended without a stop
|
|
40
|
-
"error")throw new Error(output.errorMessage||"An unknown error occurred");
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
33
|
+
nking"&&(block.thinking+=event.delta.thinking,stream2.push({type:"thinking_delta",contentIndex:index,delta:event.delta.thinking,partial:output}))}else if(event.delta.type==="input_json_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="toolCall"&&(block.partialJson+=event.delta.partial_json,block.arguments=parseStreamingJsonWhileStreaming(block,block.partialJson,block.arguments),stream2.push({type:"toolcall_delta",contentIndex:index,delta:event.
|
|
34
|
+
delta.partial_json,partial:output}))}else if(event.delta.type==="signature_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="thinking"&&(block.thinkingSignature=block.thinkingSignature||"",block.thinkingSignature+=event.delta.signature)}}else if(event.type==="content_block_stop"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&(delete block.index,block.type==="text"?stream2.push({type:"text_end",contentIndex:index,
|
|
35
|
+
content:block.text,partial:output}):block.type==="thinking"?stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output}):block.type==="toolCall"&&(block.arguments=parseStreamingJson(block.partialJson),delete block.partialJson,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output})))}else if(event.type==="message_delta"){let transformations=event.input_transformations;if(Array.isArray(transformations)&&(inputTransformations=transformations),
|
|
36
|
+
event.delta.stop_reason){output.rawStopReason=event.delta.stop_reason;let stopReasonResult=mapStopReason(event.delta.stop_reason,event.delta.stop_details);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}if(event.usage){event.usage.input_tokens!=null&&(output.usage.input=event.usage.input_tokens,inputUsageIncomplete=hasIncompleteUsage([event.usage.input_tokens])),event.usage.output_tokens!=null&&(output.usage.output=
|
|
37
|
+
event.usage.output_tokens),event.usage.cache_read_input_tokens!==void 0&&(optionalUsage.cacheRead=event.usage.cache_read_input_tokens),event.usage.cache_read_input_tokens!=null&&(output.usage.cacheRead=event.usage.cache_read_input_tokens),event.usage.cache_creation_input_tokens!==void 0&&(optionalUsage.cacheWrite=event.usage.cache_creation_input_tokens),event.usage.cache_creation_input_tokens!=null&&(output.usage.cacheWrite=event.usage.cache_creation_input_tokens);let cacheCreation=event.usage.cache_creation;
|
|
38
|
+
cacheCreation?.ephemeral_1h_input_tokens!==void 0&&(optionalUsage.cacheWrite1h=cacheCreation.ephemeral_1h_input_tokens),cacheCreation?.ephemeral_1h_input_tokens!=null&&(output.usage.cacheWrite1h=cacheCreation.ephemeral_1h_input_tokens);let thinkingTokens=event.usage.output_tokens_details?.thinking_tokens;thinkingTokens!==void 0&&(optionalUsage.reasoning=thinkingTokens),event.delta.stop_reason&&(output.usage.usageIncomplete=inputUsageIncomplete||hasIncompleteUsage([event.usage.output_tokens],[event.
|
|
39
|
+
usage.input_tokens,...Object.values(optionalUsage)])),thinkingTokens!=null&&(output.usage.reasoning=thinkingTokens)}output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,output.usage.usageIncomplete||=hasIncompleteUsage([output.usage.totalTokens]),calculateCost(usageModel,output.usage)}if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Anthropic stream ended without a stop r\
|
|
40
|
+
eason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");for(let block of blocks)if(block.type==="toolCall"&&block.partialJson!==void 0){if(output.stopReason!=="length")throw new Error(`Anthropic stream completed with an unfinished tool call: ${block.name} (${block.id})`);block.arguments=parseStreamingJson(block.partialJson),delete block.partialJson}inputTransformations&&inputTransformations.length>0&&appendAssistantMessageDiagnostic(
|
|
41
|
+
output,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:inputTransformations.map(transformation=>({type:transformation.type??void 0,path:transformation.path??void 0,reason:transformation.reason??void 0}))}}),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content){delete block.index;let partialJson=block.partialJson;block.type==="toolCall"&&partialJson!==void 0&&(block.arguments=parseStreamingJson(
|
|
42
|
+
partialJson)),delete block.partialJson}output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=error instanceof Error?error.message:JSON.stringify(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2};function mapThinkingLevelToEffort(model,level){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"\
|
|
43
|
+
high":return"high";default:return"high"}}var streamSimple=(model,context,options)=>{getAnthropicFederation(model,options?.apiKey,options?.headers,options?.env)||assertRequestAuth(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinkingEnabled:!1});if(model.compat?.forceAdaptiveThinking===!0){let effort=mapThinkingLevelToEffort(model,options.
|
|
44
|
+
reasoning);return stream(model,context,{...base,thinkingEnabled:!0,effort})}let adjusted=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,options.reasoning,options.thinkingBudgets),maxTokens=clampMaxTokensToContext(model,context,adjusted.maxTokens);return stream(model,context,{...base,maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))})};function isOAuthToken(apiKey){return apiKey.startsWith("sk-ant-oat")}function createClient(model,apiKey,optionsHeaders,fetch,dynamicHeaders,sessionId,federation){
|
|
44
45
|
if(model.provider==="github-copilot")return{client:new PiAnthropic({apiKey:null,authToken:apiKey??null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeClientHeaders({accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},model.headers,dynamicHeaders,optionsHeaders)}),isOAuthToken:!1};if(apiKey&&isOAuthToken(apiKey))return{client:new PiAnthropic({apiKey:null,authToken:apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeClientHeaders(
|
|
45
46
|
{accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":`claude-cli/${claudeCodeVersion}`,"x-app":"cli"},model.headers,optionsHeaders)}),isOAuthToken:!0};let compat=getAnthropicCompat(model),sessionAffinityHeaders={};if(sessionId&&compat.sendSessionAffinityHeaders){let header=compat.sessionAffinityFormat==="openrouter"?"x-session-id":"x-session-affinity";sessionAffinityHeaders[header]=sessionId}let defaultHeaders=mergeClientHeaders({accept:"application/json","a\
|
|
46
47
|
nthropic-dangerous-direct-browser-access":"true"},sessionAffinityHeaders,model.headers,optionsHeaders);if(federation){let key=JSON.stringify([model.baseUrl,federation]);if(federationClient?.key!==key||federationClient.fetch!==fetch){let client2=new PiAnthropic({apiKey:null,authToken:null,config:federation,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch});federationClient={key,fetch,client:client2}}return{client:federationClient.client.withOptions({defaultHeaders}),isOAuthToken:!1}}return{
|
package/dist/bundle/chunks/{azure-openai-responses-FREWTLSS.js → azure-openai-responses-PDHOT7UC.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-II2442A2.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-CIA6V3BP.js";import"./chunk-FACBDLFU.js";import"./chunk-
|
|
2
|
+
import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-2W5PWUPO.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-UW4GMZL3.js";import{formatProviderError,normalizeProviderError}from"./chunk-JYWVRJYG.js";import{retryProviderRequest}from"./chunk-MEIYGK5O.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent,resolveSamplingParams}from"./chunk-IMR3ZJM5.js";
|
|
3
|
+
import"./chunk-YTVFIA3A.js";import"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord,observeFetch}from"./chunk-II2442A2.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-CIA6V3BP.js";import"./chunk-FACBDLFU.js";import"./chunk-GVVRXZHN.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.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.
|
|
@@ -1421,10 +1421,10 @@ void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels
|
|
|
1421
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),messageCarriesBody=body===void 0||error2.message.includes(body);return{status,body,message:error2.message,messageCarriesBody}}function extractStatus(error2){if(typeof error2.statusCode=="number")return error2.statusCode;if(typeof error2.status=="number")return error2.status;if(typeof error2.
|
|
1422
1422
|
$metadata?.httpStatusCode=="number")return error2.$metadata.httpStatusCode;if(typeof error2.$response?.statusCode=="number")return error2.$response.statusCode}function extractBody(error2){let bodyText=pickBodyText(error2);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,4e3)}function pickBodyText(error2){if(typeof error2.body=="string")return error2.body;if(isPlainNonEmptyObject(error2.error))return safeJsonStringify(error2.error);let responseBody=error2.
|
|
1423
1423
|
$response?.body;if(typeof responseBody=="string")return 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!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).
|
|
1424
|
-
length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}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
|
|
1425
|
-
`: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="",inString=!1;for(let index=0;index<json.length;index++){let
|
|
1426
|
-
|
|
1427
|
-
|
|
1424
|
+
length>0}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}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
|
+
`: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
|
+
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
|
+
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]||
|
|
1428
1428
|
(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env2){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env2?.[lowercaseKey]||env2?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?
|
|
1429
1429
|
host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.
|
|
1430
1430
|
lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env2){let noProxy=getProxyEnv("no_proxy",env2).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(
|
|
@@ -1479,34 +1479,34 @@ return providerResponse&&(onObserved(),await onResponse(providerResponse,model))
|
|
|
1479
1479
|
{...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,maxTokens,reasoning:options.reasoning,thinkingBudgets:{...options.thinkingBudgets||{},[clampReasoning(options.reasoning)]:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))}})}return stream(model,
|
|
1480
1480
|
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.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){
|
|
1481
1481
|
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-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?.
|
|
1482
|
-
toolUse&&block?.type==="toolCall")block.partialJson=(block.partialJson||"")+(delta.toolUse.input||""),block.arguments=
|
|
1483
|
-
1,thinkingBlock=blocks[thinkingIndex],stream2.push({type:"thinking_start",contentIndex:thinkingIndex,partial:output})}thinkingBlock?.type==="thinking"&&(delta.reasoningContent.text&&(thinkingBlock.thinking+=delta.reasoningContent.text,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:delta.reasoningContent.text,partial:output})),delta.reasoningContent.signature&&!thinkingBlock.redacted&&(thinkingBlock.thinkingSignature=(thinkingBlock.thinkingSignature||
|
|
1484
|
-
signature),delta.reasoningContent.redactedContent?.length&&(thinkingBlock.redacted||(thinkingBlock.redacted=!0,thinkingBlock.thinkingSignature="",thinkingBlock.thinking+=REDACTED_THINKING_PLACEHOLDER,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:REDACTED_THINKING_PLACEHOLDER,partial:output})),thinkingBlock.redactedChunks??=[],thinkingBlock.redactedChunks.push(delta.reasoningContent.redactedContent)))}}function flushRedactedContent(block){block.type!==
|
|
1485
|
-
(block.thinkingSignature=bytesToBase64(block.redactedChunks),delete block.redactedChunks)}function finalizeStreamingBlock(block){delete block.index,delete block.partialJson,flushRedactedContent(block)}function handleMetadata(event,model,output){event.usage&&(output.usage.usageIncomplete=hasIncompleteUsage([event.usage.inputTokens,event.usage.outputTokens],
|
|
1486
|
-
[]]),output.usage.input=event.usage.inputTokens||0,output.usage.output=event.usage.outputTokens||0,output.usage.cacheRead=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.
|
|
1487
|
-
hasIncompleteUsage([output.usage.totalTokens],[output.usage.cacheWrite1h]),calculateCost(model,output.usage))}function handleContentBlockStop(event,blocks,output,stream2){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:"
|
|
1488
|
-
content:block.thinking,partial:output});break;case"toolCall":block.arguments=parseStreamingJson(block.partialJson),delete block.partialJson,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output});break}}function getModelMatchCandidates(modelId,modelName){return(modelName?[modelId,modelName]:[modelId]).flatMap(
|
|
1489
|
-
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("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function supportsNativeXhighEffort(model){return getModelMatchCandidates(model.id,model.name).some(s2=>s2.
|
|
1490
|
-
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 mapThinkingLevelToEffort(model,level){if(level==="xhigh"&&supportsNativeXhighEffort(model))return"
|
|
1491
|
-
high":return"high";default:return"high"}}function resolveCacheRetention(cacheRetention,env2){return cacheRetention||(getProviderEnvValue("HUMAIN_TERMINAL_CACHE_RETENTION",env2)==="long"||getProviderEnvValue("PI_CACHE_RETENTION",env2)==="long"?"long":"short")}function isAnthropicClaudeModel(model){let id=model.id.
|
|
1492
|
-
|
|
1493
|
-
"1"}function supportsThinkingSignature(model){return isAnthropicClaudeModel(model)}function buildSystemPrompt(systemPrompt,model,cacheRetention,env2){if(!systemPrompt)return;let blocks=[{text:sanitizeSurrogates(systemPrompt)}];return cacheRetention!=="none"&&supportsPromptCaching(model,env2)&&blocks.push({
|
|
1494
|
-
let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");return sanitized.length>64?sanitized.slice(0,64):sanitized}function createNonBlankTextBlock(text){let sanitized=sanitizeSurrogates(text);return sanitized.trim().length===0?void 0:{text:sanitized}}function createRequiredTextBlock(text){return createNonBlankTextBlock(
|
|
1495
|
-
Object.entries(value).filter(([key])=>key.length>0).map(([key,nestedValue])=>[key,sanitizeBedrockDocument(nestedValue)])):value}function convertToolResultContent(content){let result=[];for(let c5 of content)if(c5.type==="image")result.push({image:createImageBlock(c5.mimeType,c5.data)});else{let textBlock=createNonBlankTextBlock(
|
|
1496
|
-
let result=[],transformedMessages=transformMessages(withoutInitialSystemMessage(context.messages),model,normalizeToolCallId);for(let i5=0;i5<transformedMessages.length;i5++){let m3=transformedMessages[i5];switch(m3.role){case"user":{let content=[];if(typeof m3.content=="string")content.push(createRequiredTextBlock(m3.content));else{
|
|
1497
|
-
{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.USER,content});break}case"assistant":{if(m3.content.length===0)continue;let contentBlocks=[];for(let c5 of m3.content)switch(c5.type){case"
|
|
1498
|
-
id,name:c5.name,input:sanitizeBedrockDocument(c5.arguments)}});break;case"thinking":{if(c5.redacted){let redactedContent=decodeRedactedContent(c5.thinkingSignature);redactedContent?.length&&contentBlocks.push({reasoningContent:{redactedContent}});continue}let thinking=sanitizeSurrogates(c5.thinking);if(thinking.trim().length===0)
|
|
1499
|
-
reasoningText:{text:thinking,signature:c5.thinkingSignature}}}):contentBlocks.push({reasoningContent:{reasoningText:{text:thinking}}});break}default:continue}if(contentBlocks.length===0)continue;result.push({role:import_client_bedrock_runtime.ConversationRole.ASSISTANT,content:contentBlocks});break}case"toolResult":{let toolResults=[];
|
|
1500
|
-
ERROR:import_client_bedrock_runtime.ToolResultStatus.SUCCESS}});let j5=i5+1;for(;j5<transformedMessages.length&&transformedMessages[j5].role==="toolResult";){let nextMsg=transformedMessages[j5];toolResults.push({toolResult:{toolUseId:nextMsg.toolCallId,content:convertToolResultContent(nextMsg.content),status:nextMsg.isError?import_client_bedrock_runtime.ToolResultStatus.
|
|
1501
|
-
USER,content:toolResults});break}default:continue}}if(cacheRetention!=="none"&&supportsPromptCaching(model,env2)&&result.length>0){let lastMessage=result[result.length-1];lastMessage.role===import_client_bedrock_runtime.ConversationRole.USER&&lastMessage.content&&lastMessage.content.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT
|
|
1502
|
-
if(!tools?.length||toolChoice==="none")return;let bedrockTools=tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode);return{toolSpec:{name:tool.name,description:tool.description,inputSchema:{json:getJsonSchemaToolParameters(tool,strict)},...strict===!0?{strict:!0}:{}}}}),bedrockToolChoice;switch(toolChoice){case"
|
|
1503
|
-
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.STOP_SEQUENCE:return{stopReason:"stop"};case import_client_bedrock_runtime.StopReason.MAX_TOKENS:case import_client_bedrock_runtime.StopReason.
|
|
1504
|
-
return reason?{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}:{stopReason:"error"}}}function getConfiguredBedrockRegion(options){return options.region||getProviderEnvValue("AWS_REGION",options.env)||getProviderEnvValue("AWS_DEFAULT_REGION",options.env)||void 0}function getConfiguredBedrockCredentials(env2){let accessKeyId=getProviderEnvValue(
|
|
1505
|
-
"AWS_SESSION_TOKEN",env2);return{accessKeyId,secretAccessKey,...sessionToken?{sessionToken}:{}}}function getStandardBedrockEndpointRegion(baseUrl){if(baseUrl)try{let{hostname}=new URL(baseUrl);return hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/)?.[1]}catch{return}}function shouldUseExplicitBedrockEndpoint(baseUrl,configuredRegion,hasAmbientConfiguredProfile){
|
|
1506
|
-
|
|
1507
|
-
startsWith("127.")}function isGovCloudBedrockTarget(model,options){if(getConfiguredBedrockRegion(options)?.toLowerCase().startsWith("us-gov-"))return!0;let modelId=model.id.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(
|
|
1508
|
-
"summarized",useBlockBinding=!isGovCloud&&supportsThinkingBlockBinding(model),result=supportsAdaptiveThinking(model.id,model.name)?{thinking:{type:"adaptive",...display!==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={
|
|
1509
|
-
level=options.reasoning==="xhigh"||options.reasoning==="max"?"high":options.reasoning;return{thinking:{type:"enabled",budget_tokens:options.thinkingBudgets?.[level]??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(
|
|
1510
|
-
return{reasoning_effort:OPENAI_GPT_OSS_EFFORT[options.reasoning]};if(candidates.some(s2=>s2.includes("gpt-"))){let mapped=model.thinkingLevelMap?.[options.reasoning];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:"
|
|
1511
|
-
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.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(
|
|
1512
|
-
data),bytes=new Uint8Array(binaryString.length);for(let i5=0;i5<binaryString.length;i5++)bytes[i5]=binaryString.charCodeAt(i5);return bytes}function decodeRedactedContent(signature){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};
|
|
1482
|
+
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.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),
|
|
1483
|
+
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,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:delta.reasoningContent.text,partial:output})),delta.reasoningContent.signature&&!thinkingBlock.redacted&&(thinkingBlock.thinkingSignature=(thinkingBlock.thinkingSignature||
|
|
1484
|
+
"")+delta.reasoningContent.signature),delta.reasoningContent.redactedContent?.length&&(thinkingBlock.redacted||(thinkingBlock.redacted=!0,thinkingBlock.thinkingSignature="",thinkingBlock.thinking+=REDACTED_THINKING_PLACEHOLDER,stream2.push({type:"thinking_delta",contentIndex:thinkingIndex,delta:REDACTED_THINKING_PLACEHOLDER,partial:output})),thinkingBlock.redactedChunks??=[],thinkingBlock.redactedChunks.push(delta.reasoningContent.redactedContent)))}}function flushRedactedContent(block){block.type!==
|
|
1485
|
+
"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(block.partialJson)),delete block.partialJson,flushRedactedContent(block)}function handleMetadata(event,model,output){event.usage&&(output.usage.usageIncomplete=hasIncompleteUsage([event.usage.inputTokens,event.usage.outputTokens],
|
|
1486
|
+
[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=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.
|
|
1487
|
+
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){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_en\
|
|
1488
|
+
d",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_end",contentIndex:index,toolCall:block,partial:output});break}}function getModelMatchCandidates(modelId,modelName){return(modelName?[modelId,modelName]:[modelId]).flatMap(
|
|
1489
|
+
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("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function supportsNativeXhighEffort(model){return getModelMatchCandidates(model.id,model.name).some(s2=>s2.
|
|
1490
|
+
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("sonnet-5")||s2.includes("haiku-5")||s2.includes("fable-5"))}function mapThinkingLevelToEffort(model,level){if(level==="xhigh"&&supportsNativeXhighEffort(model))return"\
|
|
1491
|
+
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_TERMINAL_CACHE_RETENTION",env2)==="long"||getProviderEnvValue("PI_CACHE_RETENTION",env2)==="long"?"long":"short")}function isAnthropicClaudeModel(model){let id=model.id.
|
|
1492
|
+
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.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.
|
|
1493
|
+
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){if(!systemPrompt)return;let blocks=[{text:sanitizeSurrogates(systemPrompt)}];return cacheRetention!=="none"&&supportsPromptCaching(model,env2)&&blocks.push({
|
|
1494
|
+
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){let sanitized=sanitizeSurrogates(text);return sanitized.trim().length===0?void 0:{text:sanitized}}function createRequiredTextBlock(text){return createNonBlankTextBlock(
|
|
1495
|
+
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){let result=[];for(let c5 of content)if(c5.type==="image")result.push({image:createImageBlock(c5.mimeType,c5.data)});else{let textBlock=createNonBlankTextBlock(
|
|
1496
|
+
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++){let m3=transformedMessages[i5];switch(m3.role){case"user":{let content=[];if(typeof m3.content=="string")content.push(createRequiredTextBlock(m3.content));else{
|
|
1497
|
+
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.USER,content});break}case"assistant":{if(m3.content.length===0)continue;let contentBlocks=[];for(let c5 of m3.content)switch(c5.type){case"\
|
|
1498
|
+
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.push({reasoningContent:{redactedContent}});continue}let thinking=sanitizeSurrogates(c5.thinking);if(thinking.trim().length===0)
|
|
1499
|
+
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;result.push({role:import_client_bedrock_runtime.ConversationRole.ASSISTANT,content:contentBlocks});break}case"toolResult":{let toolResults=[];
|
|
1500
|
+
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];toolResults.push({toolResult:{toolUseId:nextMsg.toolCallId,content:convertToolResultContent(nextMsg.content),status:nextMsg.isError?import_client_bedrock_runtime.ToolResultStatus.
|
|
1501
|
+
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.role===import_client_bedrock_runtime.ConversationRole.USER&&lastMessage.content&&lastMessage.content.push({cachePoint:{type:import_client_bedrock_runtime.CachePointType.DEFAULT,
|
|
1502
|
+
...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:{name:tool.name,description:tool.description,inputSchema:{json:getJsonSchemaToolParameters(tool,strict)},...strict===!0?{strict:!0}:{}}}}),bedrockToolChoice;switch(toolChoice){case"\
|
|
1503
|
+
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.STOP_SEQUENCE:return{stopReason:"stop"};case import_client_bedrock_runtime.StopReason.MAX_TOKENS:case import_client_bedrock_runtime.StopReason.
|
|
1504
|
+
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.env)||getProviderEnvValue("AWS_DEFAULT_REGION",options.env)||void 0}function getConfiguredBedrockCredentials(env2){let accessKeyId=getProviderEnvValue(
|
|
1505
|
+
"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(baseUrl);return hostname.toLowerCase().match(/^bedrock-runtime(?:-fips)?\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/)?.[1]}catch{return}}function shouldUseExplicitBedrockEndpoint(baseUrl,configuredRegion,hasAmbientConfiguredProfile){
|
|
1506
|
+
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).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){
|
|
1507
|
+
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.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(
|
|
1508
|
+
model,options),display=isGovCloud?void 0:options.thinkingDisplay??"summarized",useBlockBinding=!isGovCloud&&supportsThinkingBlockBinding(model),result=supportsAdaptiveThinking(model.id,model.name)?{thinking:{type:"adaptive",...display!==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={
|
|
1509
|
+
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]??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(
|
|
1510
|
+
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];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:"h\
|
|
1511
|
+
igh",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.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(
|
|
1512
|
+
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){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};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IMR3ZJM5.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{parseStreamingJson}from"./chunk-
|
|
3
|
-
resolveTranscriptTools}from"./chunk-WPLW452J.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.
|
|
2
|
+
import{shortHash}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IMR3ZJM5.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{parseStreamingJson,parseStreamingJsonWhileStreaming}from"./chunk-GVVRXZHN.js";import{calculateCost,getSystemMessageText,
|
|
3
|
+
renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function convertToolResultOutput(model,content){let textResult=content.
|
|
4
4
|
filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
5
5
|
`),images=content.filter(c=>c.type==="image"),hasText=textResult.length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}function convertResponsesMessages(model,context,allowedToolCallProviders,options){
|
|
6
6
|
let normalizedContext=resolveTranscript(context,options?.supportsMidConvoSystemMessages),messages=[],normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!allowedToolCallProviders.has(model.provider)||!id.includes(
|
|
@@ -24,17 +24,17 @@ slot),stream.push({type:"toolcall_start",contentIndex:slot.contentIndex,partial:
|
|
|
24
24
|
JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{if(sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),response?.id&&(output.responseId=response.id),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens||0,uncachedInput=(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens,totalTokens=response.usage.
|
|
25
25
|
total_tokens??(response.usage.input_tokens||0)+(response.usage.output_tokens||0);output.usage={usageIncomplete:hasIncompleteUsage([response.usage.input_tokens,response.usage.output_tokens,uncachedInput,totalTokens],[response.usage.total_tokens,inputDetails?.cached_tokens,inputDetails?.cache_write_tokens,response.usage.output_tokens_details?.reasoning_tokens]),input:Math.max(0,uncachedInput),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,reasoning:response.
|
|
26
26
|
usage.output_tokens_details?.reasoning_tokens||0,totalTokens,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.
|
|
27
|
-
reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of openaiStream)if(await options?.onProviderStreamEvent?.(
|
|
27
|
+
reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};try{for await(let event of openaiStream)if(await options?.onProviderStreamEvent?.(
|
|
28
28
|
event,model),event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(
|
|
29
29
|
event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
|
|
30
30
|
|
|
31
31
|
`,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:`
|
|
32
32
|
|
|
33
33
|
`,partial:output})}else if(event.type==="response.reasoning_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.output_text.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.
|
|
34
|
-
type==="response.refusal.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.function_call_arguments.delta"){let slot=getSlot(event.output_index,"toolCall");if(!slot||slot.block.partialJson===void 0)continue;slot.block.partialJson+=event.delta,slot.block.arguments=
|
|
35
|
-
slot,event.delta)}else if(event.type==="response.function_call_arguments.done"){let slot=getSlot(event.output_index,"toolCall");if(!slot||slot.block.partialJson===void 0)continue;let previousPartialJson=slot.block.partialJson;if(slot.block.partialJson=event.arguments,slot.block.arguments=parseStreamingJson(slot.block.partialJson),event.arguments.startsWith(previousPartialJson)){let delta=event.arguments.slice(previousPartialJson.length);delta.length>0&&pushToolCallDelta(
|
|
36
|
-
type==="response.custom_tool_call_input.delta"){let slot=getSlot(event.output_index,"toolCall");if(!slot?.block.customInput)continue;pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,getCustomToolCallInput(slot.block)+event.delta,!1))}else if(event.type==="response.custom_tool_call_input.done"){let slot=getSlot(event.output_index,"toolCall");if(!slot?.block.customInput)continue;pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,event.input,!0))}else if(event.
|
|
37
|
-
|
|
34
|
+
type==="response.refusal.delta"){let slot=getSlot(event.output_index,"text");if(!slot)continue;slot.block.text+=event.delta,stream.push({type:"text_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.function_call_arguments.delta"){let slot=getSlot(event.output_index,"toolCall");if(!slot||slot.block.partialJson===void 0)continue;slot.block.partialJson+=event.delta,slot.block.arguments=parseStreamingJsonWhileStreaming(slot.block,slot.block.partialJson,
|
|
35
|
+
slot.block.arguments),pushToolCallDelta(slot,event.delta)}else if(event.type==="response.function_call_arguments.done"){let slot=getSlot(event.output_index,"toolCall");if(!slot||slot.block.partialJson===void 0)continue;let previousPartialJson=slot.block.partialJson;if(slot.block.partialJson=event.arguments,slot.block.arguments=parseStreamingJson(slot.block.partialJson),event.arguments.startsWith(previousPartialJson)){let delta=event.arguments.slice(previousPartialJson.length);delta.length>0&&pushToolCallDelta(
|
|
36
|
+
slot,delta)}}else if(event.type==="response.custom_tool_call_input.delta"){let slot=getSlot(event.output_index,"toolCall");if(!slot?.block.customInput)continue;pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,getCustomToolCallInput(slot.block)+event.delta,!1))}else if(event.type==="response.custom_tool_call_input.done"){let slot=getSlot(event.output_index,"toolCall");if(!slot?.block.customInput)continue;pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,event.input,!0))}else if(event.
|
|
37
|
+
type==="response.output_item.done"){let item=event.item;applyMessagePhaseStopReason(item);let slot=getOrCreateSlot(event.output_index,item);if(item.type==="reasoning"&&slot?.type==="thinking"){let summaryText=item.summary?.map(s=>s.text).join(`
|
|
38
38
|
|
|
39
39
|
`)||"",contentText=item.content?.map(c=>c.text).join(`
|
|
40
40
|
|
|
@@ -42,6 +42,6 @@ utput_item.done"){let item=event.item;applyMessagePhaseStopReason(item);let slot
|
|
|
42
42
|
item.id,item.phase??void 0),stream.push({type:"text_end",contentIndex:slot.contentIndex,content:slot.block.text,partial:output}),outputSlots.delete(event.output_index)):item.type==="function_call"&&slot?.type==="toolCall"&&slot.block.partialJson!==void 0?(slot.block.arguments=parseStreamingJson(item.arguments||slot.block.partialJson||"{}"),item.namespace!==void 0&&(slot.block.namespace=item.namespace),delete slot.block.partialJson,stream.push({type:"toolcall_end",contentIndex:slot.contentIndex,toolCall:slot.
|
|
43
43
|
block,partial:output}),outputSlots.delete(event.output_index)):item.type==="custom_tool_call"&&slot?.type==="toolCall"&&slot.block.customInput&&(pushToolCallDelta(slot,appendCustomToolCallInput(slot.block,item.input??getCustomToolCallInput(slot.block),!0)),item.namespace!==void 0&&(slot.block.namespace=item.namespace),delete slot.block.customInput,stream.push({type:"toolcall_end",contentIndex:slot.contentIndex,toolCall:slot.block,partial:output}),outputSlots.delete(event.output_index))}else if(event.
|
|
44
44
|
type==="response.completed"||event.type==="response.incomplete")finalizeResponse(event.response);else{if(event.type==="error")throw new Error(`Error Code ${event.code}: ${event.message}`||"Unknown error");if(event.type==="response.failed"){sawTerminalResponseEvent=!0,output.rawStopReason=event.response?.status;let error=event.response?.error,details=event.response?.incomplete_details,msg=error?`${error.code||"unknown"}: ${error.message||"no message"}`:details?.reason?`incomplete: ${details.reason}`:
|
|
45
|
-
"Unknown error (no error details in response)";throw new Error(msg)}}if(!sawTerminalResponseEvent)throw new Error("OpenAI Responses stream ended before a terminal response event");if(output.stopReason==="toolUse")for(let block of output.content){if(block.type!=="toolCall")continue;let toolCall=block;if(toolCall.partialJson!==void 0||toolCall.customInput!==void 0)throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`)}}
|
|
46
|
-
if(!status)return{stopReason:"stop"};switch(status){case"completed":return{stopReason:"stop"};case"incomplete":return incompleteReason==="max_output_tokens"?{stopReason:"length"}:{stopReason:"error",errorMessage:incompleteReason?`
|
|
47
|
-
|
|
45
|
+
"Unknown error (no error details in response)";throw new Error(msg)}}if(!sawTerminalResponseEvent)throw new Error("OpenAI Responses stream ended before a terminal response event");if(output.stopReason==="toolUse")for(let block of output.content){if(block.type!=="toolCall")continue;let toolCall=block;if(toolCall.partialJson!==void 0||toolCall.customInput!==void 0)throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`)}}finally{for(let block of output.
|
|
46
|
+
content){if(block.type!=="toolCall")continue;let toolCall=block;toolCall.partialJson!==void 0&&(toolCall.arguments=parseStreamingJson(toolCall.partialJson)),delete toolCall.partialJson,delete toolCall.customInput}}}function mapStopReason(status,incompleteReason){if(!status)return{stopReason:"stop"};switch(status){case"completed":return{stopReason:"stop"};case"incomplete":return incompleteReason==="max_output_tokens"?{stopReason:"length"}:{stopReason:"error",errorMessage:incompleteReason?`Respons\
|
|
47
|
+
e incomplete: ${incompleteReason}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};case"in_progress":case"queued":return{stopReason:"stop"};default:{let _exhaustive=status;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}export{convertResponsesMessages,convertResponsesTools,processResponsesStream};
|