@humain/humain-code 0.4.4 → 0.4.6
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 +41 -0
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/anthropic-messages-OHNAMPAM.js +69 -0
- package/dist/bundle/chunks/{azure-openai-responses-OJKB2O3D.js → azure-openai-responses-FREWTLSS.js} +6 -5
- package/dist/bundle/chunks/bedrock-converse-stream.js +61 -55
- package/dist/bundle/chunks/{chunk-VZV7GLZT.js → chunk-2NX3BVH6.js} +6 -5
- package/dist/bundle/chunks/{chunk-JCLZBP27.js → chunk-BBBBZ5HY.js} +2 -2
- package/dist/bundle/chunks/{chunk-T2IF7HO3.js → chunk-FP2SXW5M.js} +129 -121
- package/dist/bundle/chunks/{chunk-O2WQYQO4.js → chunk-IMR3ZJM5.js} +1 -1
- package/dist/bundle/chunks/{chunk-PEZZKT73.js → chunk-KLIRQQH5.js} +1 -1
- package/dist/bundle/chunks/{chunk-2KKLZK2N.js → chunk-LFXFQLII.js} +1 -1
- package/dist/bundle/chunks/{chunk-ERT2BD7V.js → chunk-PBBQBIHY.js} +1 -1
- package/dist/bundle/chunks/{chunk-HDP4USTE.js → chunk-RXHSJSYY.js} +1 -1
- package/dist/bundle/chunks/{chunk-524BLM37.js → chunk-SKIP6KJV.js} +1 -1
- package/dist/bundle/chunks/{chunk-Q5TQLAOM.js → chunk-UBQSONVR.js} +1 -1
- package/dist/bundle/chunks/{chunk-PI3NYWSK.js → chunk-UTMYL2YO.js} +8 -6
- package/dist/bundle/chunks/{chunk-VS3OEOQ4.js → chunk-UU4WS4BQ.js} +57 -57
- package/dist/bundle/chunks/{chunk-T45HXZW7.js → chunk-VQTXF23B.js} +8 -8
- package/dist/bundle/chunks/{chunk-RTFCP3VQ.js → chunk-WPLW452J.js} +1 -1
- package/dist/bundle/chunks/chunk-YTVFIA3A.js +2 -0
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-3QIT2RE2.js → cloudflare-workers-ai-system-one-YPOLSCPT.js} +1 -1
- package/dist/bundle/chunks/{compat-U2AA66JI.js → compat-LJ4ZIVJZ.js} +3 -3
- package/dist/bundle/chunks/{dist-SIXP5HVD.js → dist-QHFJK4TH.js} +2 -2
- package/dist/bundle/chunks/{dist-NKHGTDJG.js → dist-UAQRGPZO.js} +520 -464
- package/dist/bundle/chunks/{event-streams-PKTMLNE5.js → event-streams-CGCQQL5M.js} +1 -1
- package/dist/bundle/chunks/{execute-KEUC5IWA.js → execute-MFIDTEMB.js} +1 -1
- package/dist/bundle/chunks/{extract-WUAT5T4V.js → extract-EWN2GRAC.js} +2 -2
- package/dist/bundle/chunks/google-generative-ai-TS4ZE2RO.js +21 -0
- package/dist/bundle/chunks/google-vertex-MJK2SMNE.js +25 -0
- package/dist/bundle/chunks/{host-SPBJ4YAA.js → host-3OGMFGBY.js} +1 -1
- package/dist/bundle/chunks/mistral-conversations-5HCMHK6E.js +43 -0
- package/dist/bundle/chunks/{openai-codex-responses-B7CTZNPK.js → openai-codex-responses-5AJAJHTK.js} +5 -5
- package/dist/bundle/chunks/{openai-completions-2FYSVT4M.js → openai-completions-65RRYKEQ.js} +35 -34
- package/dist/bundle/chunks/{openai-decisions-BLNICGXO.js → openai-decisions-MKH4OJHH.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-APOZMFDL.js → openai-responses-72W3PGZ7.js} +4 -4
- package/dist/bundle/chunks/{pi-messages-WNFZL3B7.js → pi-messages-RLLYRBDT.js} +8 -8
- package/dist/bundle/chunks/{typesafe-system-one-L7FINSCN.js → typesafe-system-one-PAYJECQK.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-6XA5HC3B.js → virtual-modules-LWYOTTHQ.js} +2 -2
- package/dist/bundle/cli-runtime.js +2 -2
- package/dist/bundle/flow/assets/profiles/anthropic.json +3 -3
- package/dist/bundle/flow/assets/profiles/openai.json +3 -3
- package/dist/bundle/flow/assets/profiles/oss-first.json +3 -3
- package/dist/bundle/flow/assets/profiles/premium.json +92 -8
- package/dist/bundle/flow/package.json +1 -1
- package/dist/bundle/index.js +4 -4
- package/dist/bundle/rpc-entry.js +2 -2
- package/dist/core/agent-session.d.ts +2 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +2 -0
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/usage-totals.d.ts +2 -0
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +5 -1
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +18 -0
- package/dist/humain/node-http.d.ts.map +1 -1
- package/dist/humain/node-http.js +29 -0
- package/dist/humain/node-http.js.map +1 -1
- package/dist/humain/trace-capture/index.d.ts.map +1 -1
- package/dist/humain/trace-capture/index.js +15 -12
- package/dist/humain/trace-capture/index.js.map +1 -1
- package/docs/flow-profiles.md +2 -0
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/dist/bundle/chunks/anthropic-messages-RKOVHQPW.js +0 -67
- package/dist/bundle/chunks/google-generative-ai-MDUVUFFQ.js +0 -20
- package/dist/bundle/chunks/google-vertex-UQGG6LEW.js +0 -24
- package/dist/bundle/chunks/mistral-conversations-56EA73FO.js +0 -42
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,46 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.4.6] - 2026-10-11
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- Flow sizing uses classifier policy `unified-regex-v5` in all built-in profiles: an entire hello-world starter request ("make a hello world app") sizes small, British `colour` edits count as bounded edits, multi-section or multi-service requests count as complexity, and migrating a database schema counts as high risk. Thresholds are unchanged.
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- Checked `/flow` runs dispatch independent review and real QA when required deterministic checks are unavailable, instead of skipping review and emitting a synthetic QA failure. Eligible unavailable checks require review and QA PASS and produce an `unverified_checks_unavailable` warning naming the check; ineligible checks remain `verification_unavailable`, and real check, review, or QA failures still fail. Checked runs whose checks pass keep the review-only path and emit no QA verdict without a QA attempt.
|
|
12
|
+
- A Flow control retry is no longer refused as `budget_exhausted` when the prior attempt's cost is incomplete; the retry proceeds on the known spend.
|
|
13
|
+
|
|
14
|
+
## [0.4.5] - 2026-10-11
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Built-in Premium (v3) keeps verified provider twins ahead of model changes, adds broader role-specific backup chains, and uses `openai-codex/gpt-6.1-sol` as final recovery for large leads, architects, security reviewers and QA. Quota failures can exhaust the finite frozen candidate list without the transient-failure switch ceiling hiding the last backup.
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- Flow counts only structured `## Files Changed` / `## Changed` list items as change claims. File names mentioned in report prose, and anything a read-only role (recon, architect, reviewer) reports, no longer count, so they no longer fail runs as `unsafe_scope`.
|
|
23
|
+
- A structured claim inside the candidate that git did not observe as changed is a warning on the run (`claims_not_observed` event, run log, notification and summary line), not a verification-target block. A claim of an absolute path outside the candidate, or an unobserved claim next to a tool event that wrote outside the candidate, still blocks.
|
|
24
|
+
- Bare basename claims (`App.tsx`) resolve against the unique observed change (`src/web/App.tsx`) instead of counting as out-of-tree.
|
|
25
|
+
- Verification reports the run-start checkout identity (HEAD and tree) for a run that changed nothing, instead of `HEAD none, tree none`.
|
|
26
|
+
- A verified no-op run settles `succeeded`: with no observed changes, the mandatory independent review and QA are still dispatched (QA judges that the goal is already satisfied) and the run settles by their verdicts, including the `unverified_checks_unavailable` warning when no deterministic checks exist. A review or QA FAIL, or a missing verdict, still fails.
|
|
27
|
+
- `route_bound` never labels a non-primary model as primary, and nested models the lead chooses itself use the new `lead_selected` binding.
|
|
28
|
+
- A deterministic check whose command or dependencies are missing in the workspace (exit 127 `command not found`, no `node_modules`, bare-specifier module not found) is classified unavailable, not failed, when the goal forbids installs or lockfile changes or the run is a verified no-op. Independent review and QA PASS then settle `succeeded` with an `unverified_checks_unavailable` warning that names the check; a check that runs and fails still fails. Logs and telemetry carry only the check name and a reason enum.
|
|
29
|
+
- Inline code spans (for example `` `<!-- x -->` ``) no longer invalidate `/flow` review verdicts or QA reports; raw HTML and code fences outside inline code stay rejected.
|
|
30
|
+
- Blank lines between `## Verdict` and the final `PASS`/`FAIL` line are accepted.
|
|
31
|
+
- Review prompts carry a single output contract ending in the Verdict section, instead of a generic Completed / Files Changed suffix that conflicted with it.
|
|
32
|
+
- A missing or invalid review verdict settles `review_verdict_missing` instead of `unsafe_scope` or `qa_failed`.
|
|
33
|
+
- Contracts add the `review_verdict_missing` and `verification_unavailable` failure classes (additive).
|
|
34
|
+
- Review and QA verdict parsing keeps the strict raw-text check when text outside inline code spans still contains link, table or URL markup, so code spans cannot hide markup the parser rejects.
|
|
35
|
+
- A PASS review recovered after an invalid first review settles like an equivalent first-pass PASS, including the `unverified_checks_unavailable` warning when no deterministic checks exist.
|
|
36
|
+
- When required checks cannot be verified (for example a dev server or runtime check is unavailable), the independent reviewer is still dispatched, and a run whose verification still cannot complete settles `verification_unavailable` naming the check instead of `unsafe_scope`.
|
|
37
|
+
- For an approved plan or sketch input the architect only staffs the supplied work, and QA prompts no longer carry the generic output-format suffix that conflicted with their `QA_STATUS_JSON` contract.
|
|
38
|
+
- Flow scope checks now block with `observation_unavailable` when the directory of a mutating shell command cannot be established (`cd ~`/`$VAR`/`-`, `cd link/..`, `popd`, `cd x || cd y`), and treat `pushd`, `env -C`/`--chdir` and `git -C` like `cd`; relative `cd .. && touch x` escapes and option-bearing `cd -P /x` fail closed, refusal ledgers no longer follow a symlinked run directory, and exit-127 "command not found" output (bash, dash, zsh formats) is tolerated only when the named command is neither a shell builtin nor resolvable.
|
|
39
|
+
- Fixed `/flow` starts refused before dispatch (invalid model configuration, refused admission or input path, profile residency) to record their single `run_settled` event in the local Flow ledger `events.jsonl`, fsynced before the RPC frame, in TUI, print and RPC modes.
|
|
40
|
+
- Monthly spend limit and cap errors now trigger Flow quota failover. Quota-failed provider/model routes stay excluded for that dispatch, which advances through healthy frozen backups without retrying or waiting on exhausted routes.
|
|
41
|
+
- Provider adapters mark missing or malformed required usage counters as incomplete before defaulting numeric fields. Session totals, subagent results, trace capture and Flow RPC/session ingestion preserve that provenance, so partial usage is not mistaken for complete zero-cost usage. Failed and aborted attempts retain their reported usage, while streamed and persisted evidence is reconciled without duplicate charging.
|
|
42
|
+
- HUMAIN Node terminal diagnostics redact API-key values from diagnostic messages, stacks, codes and nested details.
|
|
43
|
+
|
|
3
44
|
## [0.4.4] - 2026-10-10
|
|
4
45
|
|
|
5
46
|
### 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-VQTXF23B.js";import"./chunks/chunk-DUZY4PDA.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";process.exitCode=await runAgentMonitorCommand(process.env);
|
|
@@ -0,0 +1,69 @@
|
|
|
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-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-4X774RBJ.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream,
|
|
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\
|
|
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
|
+
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
|
+
`));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="\
|
|
8
|
+
mid-conversation-output-config-2026-07-01",THINKING_BINDING_CONTROLS_BETA="thinking-binding-controls-2026-08-01",INLINE_TOOLS_BETA="inline-tools-2026-09-15",DEFERRED_TOOL_PLACEHOLDER={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function shouldUseServerSideFallbackBeta(model){return(model.compat?.allowedFallbackModels?.length??0)>0}function getAnthropicCompat(model){
|
|
9
|
+
let isOpenRouter=model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:model.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:model.compat?.sendSessionAffinityHeaders??isOpenRouter,sessionAffinityFormat:model.compat?.sessionAffinityFormat??(isOpenRouter?"openrouter":void 0),supportsCacheControlOnTools:model.compat?.supportsCacheControlOnTools??!0,supportsTemperature:model.
|
|
10
|
+
compat?.supportsTemperature??!0,allowEmptySignature:model.compat?.allowEmptySignature??!1,supportsStrictTools:model.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:model.compat?.supportsMidConvoToolChanges??!1}}function mergeHeaders(...headerSources){let merged={};for(let headers of headerSources)headers&&Object.assign(merged,headers);return merged}function mergeClientHeaders(...headerSources){return mergeHeaders(
|
|
11
|
+
{"User-Agent":getPiUserAgent()},...headerSources)}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function hasRequestAuth(apiKey,headers){return!!apiKey||hasHeader(headers,"authorization")||hasHeader(headers,"x-api-key")||hasHeader(headers,"cf-aig-authorization")}function assertRequestAuth(provider,apiKey,headers){if(!hasRequestAuth(
|
|
12
|
+
apiKey,headers))throw new Error(`No API key for provider: ${provider}`)}var PiAnthropic=class extends Anthropic{_shouldResolveDefaultCredentials(){return!1}};function getAnthropicFederation(model,apiKey,headers,env){if(model.provider!=="anthropic"||hasRequestAuth(apiKey,headers))return;let federationRuleId=getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV,env),organizationId=getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV,env),identityTokenFile=getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,
|
|
13
|
+
env);if(!(!federationRuleId||!organizationId||!identityTokenFile))return{organization_id:organizationId,workspace_id:getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV,env),authentication:{type:"oidc_federation",federation_rule_id:federationRuleId,service_account_id:getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,env),identity_token:{source:"file",path:identityTokenFile}}}}var federationClient,ANTHROPIC_MESSAGE_EVENTS=new Set(["message_start","message_delta","message_stop","content_block_start",
|
|
14
|
+
"content_block_delta","content_block_stop"]);function flushSseEvent(state){if(!state.event&&state.data.length===0)return null;let event={event:state.event,data:state.data.join(`
|
|
15
|
+
`),raw:[...state.raw]};return state.event=null,state.data=[],state.raw=[],event}function decodeSseLine(line,state){if(line==="")return flushSseEvent(state);if(state.raw.push(line),line.startsWith(":"))return null;let delimiterIndex=line.indexOf(":"),fieldName=delimiterIndex===-1?line:line.slice(0,delimiterIndex),value=delimiterIndex===-1?"":line.slice(delimiterIndex+1);return value.startsWith(" ")&&(value=value.slice(1)),fieldName==="event"?state.event=value:fieldName==="data"&&state.data.push(value),
|
|
16
|
+
null}function nextLineBreakIndex(text){let carriageReturnIndex=text.indexOf("\r"),newlineIndex=text.indexOf(`
|
|
17
|
+
`);return carriageReturnIndex===-1?newlineIndex:newlineIndex===-1?carriageReturnIndex:Math.min(carriageReturnIndex,newlineIndex)}function consumeLine(text){let lineBreakIndex=nextLineBreakIndex(text);if(lineBreakIndex===-1)return null;let nextIndex=lineBreakIndex+1;return text[lineBreakIndex]==="\r"&&text[nextIndex]===`
|
|
18
|
+
`&&(nextIndex+=1),{line:text.slice(0,lineBreakIndex),rest:text.slice(nextIndex)}}async function*iterateSseMessages(body,signal){let reader=body.getReader(),decoder=new TextDecoder,state={event:null,data:[],raw:[]},buffer="";try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let consumed2=consumeLine(buffer);for(;consumed2;){buffer=consumed2.rest;let event=decodeSseLine(consumed2.line,state);
|
|
19
|
+
event&&(yield event),consumed2=consumeLine(buffer)}}buffer+=decoder.decode();let consumed=consumeLine(buffer);for(;consumed;){buffer=consumed.rest;let event=decodeSseLine(consumed.line,state);event&&(yield event),consumed=consumeLine(buffer)}if(buffer.length>0){let event=decodeSseLine(buffer,state);event&&(yield event)}let trailingEvent=flushSseEvent(state);trailingEvent&&(yield trailingEvent)}finally{reader.releaseLock()}}async function*iterateAnthropicEvents(response,signal){if(!response.body)
|
|
20
|
+
throw new Error("Attempted to iterate over an Anthropic response with no body");let sawMessageStart=!1,sawMessageEnd=!1;for await(let sse of iterateSseMessages(response.body,signal)){if(sse.event==="error")throw new Error(sse.data);if(ANTHROPIC_MESSAGE_EVENTS.has(sse.event??""))try{let event=parseJsonWithRepair(sse.data);event.type==="message_start"?sawMessageStart=!0:event.type==="message_stop"&&(sawMessageEnd=!0),yield event}catch(error){let message=error instanceof Error?error.message:String(
|
|
21
|
+
error);throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`)}}if(sawMessageStart&&!sawMessageEnd)throw new Error("Anthropic stream ended before message_stop")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getAnthropicCompat(model).supportsMidConvoSystemMessages),currentTools=getCurrentTools(normalizedContext.messages);return(async()=>{let providerThinkingLevel=model.
|
|
22
|
+
compat?.supportsMidConvoEffort?options?.effort??"high":void 0,output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,...providerThinkingLevel===void 0?{}:{providerThinkingLevel},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 client,isOAuth,usageModel=model,inputUsageIncomplete=!0,optionalUsage={},inputTransformations;if(options?.
|
|
23
|
+
client)client=options.client,isOAuth=!1;else{let apiKey=options?.apiKey,federation=getAnthropicFederation(model,apiKey,options?.headers,options?.env);federation||assertRequestAuth(model.provider,apiKey,options?.headers);let copilotDynamicHeaders;if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(normalizedContext.messages);copilotDynamicHeaders=buildCopilotDynamicHeaders({messages:normalizedContext.messages,hasImages})}let cacheSessionId=resolveCacheRetention(options?.cacheRetention,
|
|
24
|
+
options?.env)==="none"?void 0:options?.sessionId,created=createClient(model,apiKey,options?.headers,options?.fetch,copilotDynamicHeaders,cacheSessionId,federation);client=created.client,isOAuth=created.isOAuthToken}let params=buildParams(model,normalizedContext,isOAuth,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params={...nextParams,stream:!0});let observe=createRequestObserver(options,{api:model.api,provider:model.provider,model:model.id,operation:"chat"}),
|
|
25
|
+
observeMiddleware=async(request,next,ctx)=>(ctx.options!==void 0&&typeof request.body=="string"&&await observe(request.body),next(request)),requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},...options?.onRequest?{middleware:[observeMiddleware]}:{},maxRetries:0},response=await retryProviderRequest(()=>client.beta.messages.create(params,requestOptions).asResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,
|
|
26
|
+
signal:options?.signal});await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let blocks=output.content;for await(let event of iterateAnthropicEvents(response,options?.signal))if(await options?.onProviderStreamEvent?.(event,model),event.type==="message_start"){output.responseId=event.message.id;let transformations=event.message.input_transformations;Array.isArray(transformations)&&(inputTransformations=transformations);
|
|
27
|
+
let responseModel=event.message.model;responseModel!==model.id&&(output.responseModel=responseModel);let fallbackCost=responseModel===model.id?void 0:model.compat?.allowedFallbackModels?.find(fallback=>fallback.provider===model.provider&&fallback.model===responseModel)?.cost;usageModel=fallbackCost?{...model,id:responseModel,cost:fallbackCost}:model,inputUsageIncomplete=hasIncompleteUsage([event.message.usage?.input_tokens]),optionalUsage.cacheRead=event.message.usage?.cache_read_input_tokens,optionalUsage.
|
|
28
|
+
cacheWrite=event.message.usage?.cache_creation_input_tokens,optionalUsage.cacheWrite1h=event.message.usage?.cache_creation?.ephemeral_1h_input_tokens,output.usage.input=event.message.usage?.input_tokens||0,output.usage.output=event.message.usage?.output_tokens||0,output.usage.cacheRead=event.message.usage?.cache_read_input_tokens||0,output.usage.cacheWrite=event.message.usage?.cache_creation_input_tokens||0,output.usage.cacheWrite1h=event.message.usage?.cache_creation?.ephemeral_1h_input_tokens||
|
|
29
|
+
0,output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(usageModel,output.usage)}else if(event.type==="content_block_start"){if(event.content_block.type==="fallback"){if(output.content.length>0)throw new Error("Anthropic performed an unsupported mid-output model fallback");continue}if(event.content_block.type==="text"){let block={type:"text",text:event.content_block.text??"",index:event.index};output.content.push(block),stream2.
|
|
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
|
+
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
|
+
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=parseStreamingJson(block.partialJson),stream2.push({type:"toolcall_delta",contentIndex:index,delta:event.delta.partial_json,partial:output}))}else if(event.
|
|
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,content:block.text,partial:output}):block.type===
|
|
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),event.delta.stop_reason){output.rawStopReason=
|
|
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=event.usage.output_tokens),event.usage.cache_read_input_tokens!==
|
|
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;cacheCreation?.ephemeral_1h_input_tokens!==void 0&&
|
|
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.usage.input_tokens,...Object.values(optionalUsage)])),
|
|
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 reason");if(output.stopReason==="aborted"||output.stopReason===
|
|
40
|
+
"error")throw new Error(output.errorMessage||"An unknown error occurred");inputTransformations&&inputTransformations.length>0&&appendAssistantMessageDiagnostic(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){
|
|
41
|
+
for(let block of output.content)delete block.index,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"\
|
|
42
|
+
low";case"medium":return"medium";case"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(
|
|
43
|
+
model,options.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
|
+
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
|
+
{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
|
+
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{
|
|
47
|
+
client:new PiAnthropic({apiKey:apiKey??null,authToken:null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders}),isOAuthToken:!1}}function getBetaFeatures(model,context,isOAuthToken2,nativeToolChanges,options){let configuredFeatures;for(let headers of[model.headers,options?.headers])for(let[name,value]of Object.entries(headers??{}))name.toLowerCase()==="anthropic-beta"&&(configuredFeatures=value);if(configuredFeatures===null)return[];if(configuredFeatures!==void 0)return[...new Set(
|
|
48
|
+
configuredFeatures.split(",").map(feature=>feature.trim()).filter(feature=>feature.length>0))];let features=[];return isOAuthToken2&&features.push("claude-code-20250219","oauth-2025-04-20"),shouldUseFineGrainedToolStreamingBeta(model,context)&&features.push(FINE_GRAINED_TOOL_STREAMING_BETA),model.reasoning&&options?.thinkingEnabled===!0&&(options.interleavedThinking??!0)&&model.compat?.forceAdaptiveThinking!==!0&&features.push(INTERLEAVED_THINKING_BETA),shouldUseServerSideFallbackBeta(model)&&features.
|
|
49
|
+
push(SERVER_SIDE_FALLBACK_BETA),model.compat?.supportsMidConvoEffort===!0&&features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA,THINKING_BINDING_CONTROLS_BETA),nativeToolChanges&&features.push(INLINE_TOOLS_BETA),[...new Set(features)]}function buildParams(model,context,isOAuthToken2,options){let{cacheControl}=getCacheControl(model,options?.cacheRetention,options?.env),compat=getAnthropicCompat(model),initialSystemMessage=getInitialSystemMessage(context.messages),initialSystemText=initialSystemMessage?
|
|
50
|
+
getSystemMessageText(initialSystemMessage):"",transformedMessages=transformMessages(context.messages,model,normalizeToolCallId),conversationMessages=initialSystemMessage?transformedMessages.slice(1):transformedMessages,initialTools=initialSystemMessage?.toolsAdded??[],nativeToolChanges=compat.supportsMidConvoSystemMessages&&compat.supportsMidConvoToolChanges&&initialTools.length>0,converted=convertMessages(conversationMessages,isOAuthToken2,cacheControl,compat.allowEmptySignature,model.compat?.supportsMidConvoEffort===
|
|
51
|
+
!0?model.provider:void 0,nativeToolChanges?tools=>convertTools(tools,isOAuthToken2,compat.supportsEagerToolInputStreaming,compat.supportsStrictTools):void 0),activeEffort=options?.effort??"high",betaFeatures=getBetaFeatures(model,context,isOAuthToken2,nativeToolChanges,options),params={model:model.id,messages:model.compat?.supportsMidConvoEffort===!0?insertThinkingLevelMessages(converted,activeEffort):converted.messages,max_tokens:options?.maxTokens??model.maxTokens,stream:!0,...betaFeatures.length>
|
|
52
|
+
0?{betas:betaFeatures}:{}};isOAuthToken2?(params.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...cacheControl?{cache_control:cacheControl}:{}}],initialSystemText&¶ms.system.push({type:"text",text:sanitizeSurrogates(initialSystemText),...cacheControl?{cache_control:cacheControl}:{}})):initialSystemText&&(params.system=[{type:"text",text:sanitizeSurrogates(initialSystemText),...cacheControl?{cache_control:cacheControl}:{}}]),options?.temperature!==void 0&&
|
|
53
|
+
!options?.thinkingEnabled&&model.compat?.supportsMidConvoEffort!==!0&&compat.supportsTemperature&&(params.temperature=options.temperature);let toolCacheControl=compat.supportsCacheControlOnTools?cacheControl:void 0;if(nativeToolChanges)params.tools=[...convertTools(initialTools,isOAuthToken2,compat.supportsEagerToolInputStreaming,compat.supportsStrictTools,toolCacheControl),DEFERRED_TOOL_PLACEHOLDER];else{let tools=getCurrentTools(context.messages);tools.length>0&&(params.tools=convertTools(tools,
|
|
54
|
+
isOAuthToken2,compat.supportsEagerToolInputStreaming,compat.supportsStrictTools,toolCacheControl))}if(model.compat?.supportsMidConvoEffort===!0)params.thinking={type:"adaptive",display:options?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_block"}},params.output_config={effort:"high"};else if(model.reasoning)if(options?.thinkingEnabled){let display=options.thinkingDisplay??"summarized";model.compat?.forceAdaptiveThinking===!0?(params.thinking={type:"adaptive",display},
|
|
55
|
+
options.effort&&(params.output_config={effort:options.effort})):params.thinking={type:"enabled",budget_tokens:options.thinkingBudgetTokens||1024,display}}else options?.thinkingEnabled===!1&&model.thinkingLevelMap?.off!==null&&(params.thinking={type:"disabled"});if(options?.metadata){let userId=options.metadata.user_id;typeof userId=="string"&&(params.metadata={user_id:userId})}options?.toolChoice&&(typeof options.toolChoice=="string"?params.tool_choice={type:options.toolChoice}:params.tool_choice=
|
|
56
|
+
options.toolChoice);let allowedFallbackModels=model.compat?.allowedFallbackModels;return allowedFallbackModels&&allowedFallbackModels.length>0&&(params.fallbacks=allowedFallbackModels.map(fallback=>({model:fallback.model}))),params}function normalizeToolCallId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function convertToolResult(msg){return{type:"tool_result",tool_use_id:msg.toolCallId,content:convertContentBlocks(msg.content),is_error:msg.isError}}function convertMessages(transformedMessages,isOAuthToken2,cacheControl,allowEmptySignature=!1,managedProvider,convertToolDefinitions){
|
|
57
|
+
let params=[],assistantLevels=new Map,pendingSystemMessages=[],flushPendingSystemMessages=()=>{params.push(...pendingSystemMessages),pendingSystemMessages.length=0};for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(msg.role==="system"){let text=renderSystemMessageUpdate(msg),blocks=[];if(text.length>0&&blocks.push({type:"text",text:sanitizeSurrogates(text)}),convertToolDefinitions){let added=msg.toolsAdded??[],redefined=new Set(added.map(tool=>tool.name));for(let tool of msg.
|
|
58
|
+
toolsRemoved??[])redefined.has(tool.name)||blocks.push({type:"tool_removal",tool:{type:"tool_reference",name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name}});for(let definition of convertToolDefinitions(added))blocks.push({type:"tool_addition",tool:{type:"tool_definition",definition}})}blocks.length>0&&pendingSystemMessages.push({role:"system",content:blocks})}else if(msg.role==="user")if(typeof msg.content=="string")msg.content.trim().length>0&¶ms.push({role:"user",content:sanitizeSurrogates(
|
|
59
|
+
msg.content)});else{let filteredBlocks=msg.content.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image",source:{type:"base64",media_type:item.mimeType,data:item.data}}).filter(b=>b.type==="text"?b.text.trim().length>0:!0);if(filteredBlocks.length===0)continue;params.push({role:"user",content:filteredBlocks})}else if(msg.role==="assistant"){flushPendingSystemMessages();let blocks=[];for(let block of msg.content)if(block.type==="text"){if(block.text.trim().length===
|
|
60
|
+
0)continue;blocks.push({type:"text",text:sanitizeSurrogates(block.text)})}else if(block.type==="thinking"){if(block.redacted){blocks.push({type:"redacted_thinking",data:block.thinkingSignature});continue}let thinkingSignature=block.thinkingSignature,hasThinkingSignature=!!thinkingSignature&&thinkingSignature.trim().length>0;if(block.thinking.trim().length===0&&!hasThinkingSignature)continue;hasThinkingSignature?blocks.push({type:"thinking",thinking:sanitizeSurrogates(block.thinking),signature:thinkingSignature}):
|
|
61
|
+
blocks.push(allowEmptySignature?{type:"thinking",thinking:sanitizeSurrogates(block.thinking),signature:""}:{type:"text",text:sanitizeSurrogates(block.thinking)})}else block.type==="toolCall"&&blocks.push({type:"tool_use",id:block.id,name:isOAuthToken2?toClaudeCodeName(block.name):block.name,input:block.arguments??{}});if(blocks.length===0)continue;let messageIndex=params.length;params.push({role:"assistant",content:blocks}),managedProvider!==void 0&&msg.api==="anthropic-messages"&&msg.provider===
|
|
62
|
+
managedProvider&&isAnthropicEffort(msg.providerThinkingLevel)&&assistantLevels.set(messageIndex,msg.providerThinkingLevel)}else if(msg.role==="toolResult"){let toolResults=[],j=i;for(;j<transformedMessages.length&&transformedMessages[j].role==="toolResult";)toolResults.push(convertToolResult(transformedMessages[j])),j++;i=j-1,params.push({role:"user",content:toolResults})}}if(flushPendingSystemMessages(),cacheControl&¶ms.length>0){let lastMessage=params[params.length-1];if(lastMessage.role===
|
|
63
|
+
"user"||lastMessage.role==="system")if(Array.isArray(lastMessage.content)){let lastBlock=lastMessage.content[lastMessage.content.length-1];lastBlock&&(lastBlock.type==="text"||lastBlock.type==="image"||lastBlock.type==="tool_result"||lastBlock.type==="tool_addition"||lastBlock.type==="tool_removal")&&(lastBlock.cache_control=cacheControl)}else typeof lastMessage.content=="string"&&(lastMessage.content=[{type:"text",text:lastMessage.content,cache_control:cacheControl}])}return{messages:params,assistantLevels}}
|
|
64
|
+
function isAnthropicEffort(value){return value==="low"||value==="medium"||value==="high"||value==="xhigh"||value==="max"}function insertThinkingLevelMessages(converted,activeEffort){let messages=[];for(let index=0;index<converted.messages.length;index++){let historicalEffort=converted.assistantLevels.get(index);historicalEffort!==void 0&&messages.push({role:"system",content:[],output_config:{effort:historicalEffort}}),messages.push(converted.messages[index])}return messages.push({role:"system",content:[],
|
|
65
|
+
output_config:{effort:activeEffort}}),messages}function shouldUseFineGrainedToolStreamingBeta(model,context){return getCurrentTools(context.messages).length>0&&!getAnthropicCompat(model).supportsEagerToolInputStreaming}var ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),ANTHROPIC_STRICT_STRING_FORMATS=new Set(["date-time","time","date","dura\
|
|
66
|
+
tion","email","hostname","uri","ipv4","ipv6","uuid"]),isAnthropicStrictUnsupportedKeyword=(key,value)=>ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS.has(key)?!0:key==="minItems"?value!==0&&value!==1:key==="format"?typeof value!="string"||!ANTHROPIC_STRICT_STRING_FORMATS.has(value):!1;function convertTools(tools,isOAuthToken2,supportsEagerToolInputStreaming,supportsStrictTools,cacheControl){return tools?tools.map((tool,index)=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictTools,isAnthropicStrictUnsupportedKeyword),
|
|
67
|
+
parameters=getJsonSchemaToolParameters(tool,strict),schema=parameters,legacyInputSchema={type:"object",properties:schema.properties??{},required:schema.required??[]},inputSchema=strict===!0?{...parameters,...legacyInputSchema}:legacyInputSchema;return{name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name,description:tool.description,...supportsEagerToolInputStreaming?{eager_input_streaming:!0}:{},...strict===!0?{strict:!0}:{},input_schema:inputSchema,...cacheControl&&index===tools.length-1?{cache_control:cacheControl}:
|
|
68
|
+
{}}}):[]}function mapStopReason(reason,stopDetails){switch(reason){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:stopDetails?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error",errorMessage:"Provider stopped with: sensitive"};default:
|
|
69
|
+
throw new Error(`Unhandled stop reason: ${reason}`)}}export{stream,streamSimple};
|
package/dist/bundle/chunks/{azure-openai-responses-OJKB2O3D.js → azure-openai-responses-FREWTLSS.js}
RENAMED
|
@@ -1,9 +1,10 @@
|
|
|
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-L2ZPNLYD.js";import{createRequestObserver,headersToRecord,observeFetch}from"./chunk-II2442A2.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-CIA6V3BP.js";import"./chunk-FACBDLFU.js";import"./chunk-4X774RBJ.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-UTMYL2YO.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-4X774RBJ.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";
|
|
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
|
+
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
|
+
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.
|
|
7
|
+
timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,
|
|
7
8
|
grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialJson,
|
|
8
9
|
delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatAzureOpenAIError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(
|
|
9
10
|
model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,apiKey,options,fetch){let headers={"User-Agent":getPiUserAgent(),...model.headers};options?.headers&&Object.assign(headers,options.headers);let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(
|