@tansr/cli 0.10.0 → 0.10.2
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/package.json +1 -1
- package/tansr-artifacts.json +596 -578
- package/{tansr-bg-FHDDUMK4.mjs → tansr-bg-QY4G2SNZ.mjs} +2 -2
- package/{tansr-chunk-6NUB6YQJ.mjs → tansr-chunk-2C6JKHKM.mjs} +5 -5
- package/{tansr-chunk-O32ZFMNV.mjs → tansr-chunk-53SL6W6G.mjs} +2 -2
- package/{tansr-chunk-RS3LZ6KA.mjs → tansr-chunk-5T7X32UX.mjs} +2 -2
- package/{tansr-chunk-5YXIDPAQ.mjs → tansr-chunk-6OXR4F5Y.mjs} +2 -2
- package/{tansr-chunk-PQNOMC4A.mjs → tansr-chunk-726Y5F3M.mjs} +2 -2
- package/{tansr-chunk-UIBBDNRB.mjs → tansr-chunk-BCOFZJWA.mjs} +2 -2
- package/{tansr-chunk-WT5YKFE7.mjs → tansr-chunk-C6COFFZK.mjs} +2 -2
- package/{tansr-chunk-4OSB7HBB.mjs → tansr-chunk-CI7LFRTK.mjs} +3 -3
- package/{tansr-chunk-ZGQJIXK7.mjs → tansr-chunk-E67N3BDI.mjs} +2 -2
- package/{tansr-chunk-Z6RSXE57.mjs → tansr-chunk-H6JYYWPW.mjs} +10 -10
- package/{tansr-chunk-VJGAX34A.mjs → tansr-chunk-J2ED6CI4.mjs} +2 -2
- package/{tansr-chunk-2HKJ4JJS.mjs → tansr-chunk-J72JGEKH.mjs} +3 -3
- package/{tansr-chunk-MX3N5PNJ.mjs → tansr-chunk-KSBP64Q5.mjs} +2 -2
- package/tansr-chunk-LSYPDTQG.mjs +22 -0
- package/tansr-chunk-NA22YT73.mjs +5 -0
- package/{tansr-chunk-MKOKKJTO.mjs → tansr-chunk-NCIMR6LB.mjs} +2 -2
- package/tansr-chunk-OB47UYHK.mjs +29 -0
- package/{tansr-chunk-JOAFKQNW.mjs → tansr-chunk-OSK64SU3.mjs} +1 -1
- package/{tansr-chunk-Y4DBYZRC.mjs → tansr-chunk-Q6MUMULP.mjs} +2 -2
- package/{tansr-chunk-YOQS3FJQ.mjs → tansr-chunk-QNHXB55W.mjs} +2 -2
- package/{tansr-chunk-2GVQN2VL.mjs → tansr-chunk-S77B4PI7.mjs} +2 -2
- package/{tansr-chunk-B3GJDJ7R.mjs → tansr-chunk-TYJWMSVW.mjs} +2 -2
- package/tansr-chunk-TZJHQ3TT.mjs +38 -0
- package/{tansr-chunk-A5EC3Z2Z.mjs → tansr-chunk-UAEARRRH.mjs} +2 -2
- package/{tansr-chunk-XAR42OOH.mjs → tansr-chunk-UCG4D6ER.mjs} +2 -2
- package/{tansr-chunk-NKZP22Y6.mjs → tansr-chunk-WGXWBU37.mjs} +2 -2
- package/{tansr-chunk-T2BVA5NV.mjs → tansr-chunk-ZY3IR67Q.mjs} +2 -2
- package/tansr-main-5V46X7QH.mjs +7 -0
- package/tansr-marked.esm-R6UL3675.mjs +68 -0
- package/{tansr-render-RTEKXH54.mjs → tansr-render-PUEISX75.mjs} +2 -2
- package/{tansr-run-acp-entry-OYTDDWDR.mjs → tansr-run-acp-entry-ANNUR7IB.mjs} +3 -3
- package/{tansr-run-approvals-entry-53SR25ZU.mjs → tansr-run-approvals-entry-SLLTFTSX.mjs} +2 -2
- package/{tansr-run-auth-entry-QFMRITYM.mjs → tansr-run-auth-entry-X3SXNPOI.mjs} +2 -2
- package/{tansr-run-doctor-DO6CXMRK.mjs → tansr-run-doctor-RYIQQOOK.mjs} +3 -3
- package/{tansr-run-headless-entry-7TNISK4Y.mjs → tansr-run-headless-entry-I53HJDNX.mjs} +2 -2
- package/tansr-run-init-entry-USPWKDRI.mjs +5 -0
- package/tansr-run-logout-entry-KO7ZL2M5.mjs +5 -0
- package/{tansr-run-mcp-serve-entry-M5N7JSAX.mjs → tansr-run-mcp-serve-entry-YMQH7WSF.mjs} +2 -2
- package/{tansr-run-orchestrate-entry-MFDKPE4I.mjs → tansr-run-orchestrate-entry-YN3M6BWY.mjs} +2 -2
- package/{tansr-run-org-entry-TGWBHE55.mjs → tansr-run-org-entry-STRRZVI4.mjs} +2 -2
- package/{tansr-run-policy-entry-E3XZEYGV.mjs → tansr-run-policy-entry-4ENHRAMQ.mjs} +2 -2
- package/{tansr-run-profile-entry-R2KK52TF.mjs → tansr-run-profile-entry-THJMZ7ZA.mjs} +2 -2
- package/tansr-run-serve-entry-N5PK7ACI.mjs +99 -0
- package/{tansr-run-sessions-entry-PZQIF7KY.mjs → tansr-run-sessions-entry-KIT7PALM.mjs} +2 -2
- package/tansr-run-update-entry-HYSKHBB6.mjs +5 -0
- package/tansr-src-JAODAP53.mjs +143 -0
- package/{tansr-startup-account-WI54Z7UU.mjs → tansr-startup-account-QUJKOV6V.mjs} +4 -4
- package/{tansr-startup-model-2MIOO25G.mjs → tansr-startup-model-SREG5HNN.mjs} +3 -3
- package/tansr-tui-DXGFMSII.mjs +75 -0
- package/tansr.mjs +1 -2
- package/tansrd.mjs +265 -265
- package/tansr-chunk-G5YDZOSH.mjs +0 -38
- package/tansr-chunk-IHFZ4MW7.mjs +0 -5
- package/tansr-chunk-PQHOHOTR.mjs +0 -22
- package/tansr-chunk-WMHXOCGD.mjs +0 -29
- package/tansr-run-init-entry-EJ4UX6S7.mjs +0 -5
- package/tansr-run-logout-entry-YJMC6FYS.mjs +0 -5
- package/tansr-run-serve-entry-JVHHZEKM.mjs +0 -99
- package/tansr-run-update-entry-GOW6DQH3.mjs +0 -5
- package/tansr-src-NSNVE7OD.mjs +0 -206
- package/tansr-tui-LUXKR56D.mjs +0 -75
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
2
|
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
3
|
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{$,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,a,aa,b,ba,c,ca,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./tansr-chunk-
|
|
5
|
-
//# sourceMappingURL=tansr-bg-
|
|
4
|
+
import{$,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_,a,aa,b,ba,c,ca,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./tansr-chunk-OB47UYHK.mjs";import"./tansr-chunk-Q6MUMULP.mjs";import"./tansr-chunk-AMMPDY4V.mjs";import"./tansr-chunk-WGXWBU37.mjs";import"./tansr-chunk-XXBNISJJ.mjs";import"./tansr-chunk-LSYPDTQG.mjs";import"./tansr-chunk-HRKJLVKC.mjs";import"./tansr-chunk-BCOFZJWA.mjs";import"./tansr-chunk-C7GGA5ID.mjs";import"./tansr-chunk-2C6JKHKM.mjs";import"./tansr-chunk-OKAA4BJC.mjs";import"./tansr-chunk-OSK64SU3.mjs";import"./tansr-chunk-ZQ3ZK7IL.mjs";import"./tansr-chunk-I3TOVAA6.mjs";import"./tansr-chunk-F7C6ITED.mjs";import"./tansr-chunk-DIT3PBNB.mjs";import"./tansr-chunk-NA22YT73.mjs";import"./tansr-chunk-QWGSXFEJ.mjs";import"./tansr-chunk-RRAMVVYF.mjs";export{c as BACKGROUND_DIR_NAME,f as BACKGROUND_SELF_HEAL_SOURCES,e as BACKGROUND_TASK_STATUSES,a as BG_MESSAGE_KEY,b as BG_MESSAGE_KEYS,A as BG_RUNNER_ENDPOINT_ENV,B as BG_RUNNER_TOKEN_ENV,Q as BG_TASK_ID_ENV,Z as DEFAULT_KILL_GRACE_MS,_ as KILL_POLL_INTERVAL_MS,X as LOG_TAIL_MAX_BYTES,Y as LOG_TAIL_MAX_LINES,I as PROCESS_IDENTITY_PROBE_TIMEOUT_MS,d as PROMPT_SUMMARY_MAX_CHARS,g as RENAME_RETRY_DELAYS_MS,C as RUNNER_REQUEST_TIMEOUT_MS,L as WORKTREES_DIR_NAME,U as attachBackgroundSessionId,h as backgroundDirPath,k as backgroundFinalSentinelPath,j as backgroundLogPath,i as backgroundRecordPath,K as compareProcessIdentity,R as createRunnerIdentity,z as displayStatusOf,t as finalizeBackgroundRecord,W as finalizeBackgroundTask,l as generateBackgroundTaskId,N as generateWorktreeName,y as isPidAlive,O as isValidWorktreeName,T as killProcessTree,S as launchBackgroundTask,u as listBackgroundRecords,v as listBackgroundRecordsSync,p as parseBackgroundRecord,$ as parseBgArgs,J as probeProcessIdentity,r as readBackgroundRecord,aa as readLogTail,n as redactArgv,x as removeBackgroundRecord,F as requestRunner,H as requestRunnerStop,ca as runBgEntry,D as runnerEndpointFor,P as setupWorktree,V as startBackgroundRunnerEndpoint,E as startRunnerEndpoint,m as summarizePrompt,ba as toDisplayRecord,q as toPublicRecord,s as updateBackgroundRecord,G as verifyRunnerIdentity,M as worktreesDirPath,o as writeBackgroundRecord,w as writeBackgroundRecordSync};
|
|
5
|
+
//# sourceMappingURL=tansr-bg-QY4G2SNZ.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
2
|
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
3
|
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{a as M,b as G,c as $n,d as Ln,e as be,f as Wt,h as Kn,i as Hn,j as zn,k as se,n as Jn,o as Yn,q as Qn,t as Vn,u as Ut}from"./tansr-chunk-JOAFKQNW.mjs";import{a as et,b as tt,i as Z,j as nt,k as Mt,n as St,p as At,q as Ot,r as Pt,s as Bt}from"./tansr-chunk-OKAA4BJC.mjs";import{Fb as rt,Ib as ot,J as Gn,c as d}from"./tansr-chunk-QWGSXFEJ.mjs";import{createHash as ho}from"node:crypto";var Xn="callMeta";function ke(t){if(t===void 0)return;let e=t[Xn];if(typeof e!="object"||e===null)return;let n=e,r=u=>{let l=n[u];return typeof l=="string"&&l.length>0?l:void 0},o=r("requestId"),i=r("purpose"),s=r("compactionId"),a=r("agentId");if(!(o===void 0&&i===void 0&&s===void 0&&a===void 0))return{...o!==void 0?{requestId:o}:{},...i!==void 0?{purpose:i}:{},...s!==void 0?{compactionId:s}:{},...a!==void 0?{agentId:a}:{}}}function Dt(t){let e;try{let n=new URL(t),r=n.pathname.replace(/\/+$/,"");e=`${n.protocol}//${n.host}${r}`.toLowerCase()}catch{e=t.trim().replace(/\/+$/,"").toLowerCase()}return ho("sha256").update(e,"utf8").digest("hex").slice(0,16)}function jt(t){if(t!==void 0)try{t()}catch{}}var go="(unknown)";function yo(t){let e=new Map,n=new WeakMap,r=0,o=s=>s.context.endpointKey??go;return{observer:{onAttemptStarted:s=>{let a=o(s),u=e.get(a)??{total:0,main:0,compaction:0};n.set(s,{total:r,sameEndpoint:u.total,sameEndpointMain:u.main,sameEndpointCompaction:u.compaction}),r+=1,u.total+=1,s.meta?.purpose==="main"?u.main+=1:s.meta?.purpose==="compaction"&&(u.compaction+=1),e.set(a,u)},onAttemptFinished:s=>{let a=s.start,u=o(a),l=e.get(u),c=n.get(a);c!==void 0&&l!==void 0&&(n.delete(a),r=Math.max(0,r-1),l.total=Math.max(0,l.total-1),a.meta?.purpose==="main"?l.main=Math.max(0,l.main-1):a.meta?.purpose==="compaction"&&(l.compaction=Math.max(0,l.compaction-1)),l.total===0&&e.delete(u)),t.onAttempt({...s,inflightAtStart:c??{total:0,sameEndpoint:0,sameEndpointMain:0,sameEndpointCompaction:0}})}},inflightTotal:()=>r}}var Zn=128e3;function qt(t,e,n){return n?.maxContext??e?.maxContext??t?.maxContext}function Re(t,e){if(t===void 0)return e===void 0?void 0:{...e};if(e===void 0)return{...t};let n={...t};for(let[r,o]of Object.entries(e))o!==void 0&&(n[r]=o);return n}function it(t,e){let n={...t};e.maxContext!==void 0&&(n.maxContext=e.maxContext),e.effectiveContext!==void 0&&(n.effectiveContext=e.effectiveContext),e.maxOutput!==void 0&&(n.maxOutput=e.maxOutput),e.reasoning!==void 0&&(n.reasoning=e.reasoning),e.thinkingOptional!==void 0&&(n.thinkingOptional=e.thinkingOptional),e.vision!==void 0&&(n.vision=e.vision),e.toolChoice!==void 0&&(n.toolChoice=e.toolChoice),e.modelModifiers!==void 0&&(n.modelModifiers=[...e.modelModifiers]),e.defaultContextWithoutModifier!==void 0&&(n.defaultContextWithoutModifier=e.defaultContextWithoutModifier),e.hostedTools!==void 0&&(n.hostedTools=[...e.hostedTools]),e.background!==void 0&&(n.background=e.background);let r=Re(t.inputModalities,e.inputModalities);r!==void 0&&(n.inputModalities=r);let o=Re(t.promptCaching,e.promptCaching);o!==void 0&&(n.promptCaching=o);let i=Re(t.thinking,e.thinking);i!==void 0&&(n.thinking=i);let s=Re(t.sampling,e.sampling);s!==void 0&&(n.sampling=s);let a=Re(t.quirks,e.quirks);return a!==void 0&&(n.quirks=a),n}function st(t){let e=t,n=t.inputModalities?.image;n!==void 0?e={...e,vision:n==="supported"}:t.vision!==void 0&&(e={...e,inputModalities:{...t.inputModalities,image:t.vision?"supported":"rejected"}});let r=e.sampling;return r?.temperatureRange!==void 0&&r.temperature===void 0&&(e={...e,sampling:{...r,temperature:{min:r.temperatureRange[0],max:r.temperatureRange[1]}}}),e}function Nt(t,e,n){let r={};return t!==void 0&&(r=it(r,st(t))),e!==void 0&&(r=it(r,st(e))),n!==void 0&&(r=it(r,st(n))),r.maxContext===void 0&&(r.maxContext=Zn),Gn.parse(r)}function Ft(t){let e=t?.inputModalities?.image;return e!==void 0?e:t?.vision!==void 0&&t.vision?"supported":"rejected"}var re=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name=new.target.name}},we=class extends re{alias;constructor(e){super("unknown_alias",`Unknown model alias: "${e}"`),this.alias=e}},ae=class extends re{providerId;ref;constructor(e,n){super("unknown_provider",`Unknown provider: "${e}"${n!==void 0?` (from ref "${n}")`:""}`),this.providerId=e,n!==void 0&&(this.ref=n)}},ee=class extends re{providerId;envVar;constructor(e,n){super("missing_api_key",n!==void 0?`Missing API key for provider "${e}": environment variable "${n}" is not set`:`Missing API key for provider "${e}": profile has no auth.env configured`),this.providerId=e,n!==void 0&&(this.envVar=n)}},xe=class extends re{path;constructor(e){super("cyclic_fallback",`Cyclic fallback chain: ${e.join(" -> ")}`),this.path=e}};function er(t,e){return`${t.toLowerCase()}/${e.toLowerCase()}`}var tr=new Map;function P(t,e,n){tr.set(er(t,e),n)}P("aliyun-maas","qwen3.7-max",{capability:{inputModalities:{image:"rejected"},promptCaching:{mode:"explicit",minCacheableTokens:1024},thinking:{toggleValues:["enabled","disabled"],budgetTokens:"honored",cannotDisable:!1,mustEchoBack:!0,signatureShape:"always_empty"},sampling:{temperature:{min:0,max:2,maxExclusive:!0}},quirks:{systemRoleInMessages:!0,unknownModelFallback:!1,claudeModelNameMapping:!1,stopSequences:"misreported_end_turn",streamUsageLocation:"message_delta"}}});P("aliyun-maas","qwen3-coder-plus",{capability:{maxContext:1e6,maxOutput:65536},pricing:{inputPerMillion:4,cachedInputPerMillion:.4,outputPerMillion:16,tiers:[{upToInputTokens:32768,inputPerMillion:4,cachedInputPerMillion:.4,outputPerMillion:16},{upToInputTokens:131072,inputPerMillion:6,cachedInputPerMillion:.6,outputPerMillion:24},{upToInputTokens:262144,inputPerMillion:10,cachedInputPerMillion:1,outputPerMillion:40},{inputPerMillion:20,cachedInputPerMillion:2,outputPerMillion:100}]}});P("deepseek","deepseek-v4-pro",{capability:{maxContext:1e6,modelModifiers:["[1m]"],defaultContextWithoutModifier:2e5,maxOutput:384e3,inputModalities:{image:"silently_dropped"},promptCaching:{mode:"ignored"},thinking:{budgetTokens:"ignored",effortParam:"output_config.effort",mustEchoBack:!0},sampling:{temperature:{min:0,max:2}},quirks:{unknownModelFallback:!0,claudeModelNameMapping:!0,stopSequences:"honored",minTimeoutMs:6e5}},pricing:{inputPerMillion:3,cachedInputPerMillion:.025,outputPerMillion:6,peakMultiplier:2}});P("deepseek","deepseek-v4-flash",{capability:{maxOutput:384e3}});P("kimi","kimi-k3",{capability:{modelModifiers:["[1m]"],maxOutput:1048576,promptCaching:{mode:"implicit"},thinking:{effortParam:"reasoning_effort",mustEchoBack:!0},sampling:{temperatureFixed:1},vision:!0,inputModalities:{image:"supported"},quirks:{claudeModelNameMapping:!0,modelsEndpoint:!0}},pricing:{inputPerMillion:20,cachedInputPerMillion:2,outputPerMillion:100}});P("kimi","kimi-k2.7-code",{capability:{maxContext:262144,modelModifiers:["[1m]"],promptCaching:{mode:"implicit"},thinking:{cannotDisable:!0,mustEchoBack:!0,signatureShape:"absent"},sampling:{temperatureFixed:1},inputModalities:{image:"supported"},quirks:{claudeModelNameMapping:!0,stopSequences:"misreported_end_turn",maxTokensExcludesReasoning:!1,reasoningTokens:"subset_of_output",modelsEndpoint:!0}}});P("minimax","minimax-m3",{capability:{modelModifiers:["[1m]"],maxOutput:524288,promptCaching:{mode:"explicit",ttlSeconds:300,maxBreakpoints:4},thinking:{toggleValues:["adaptive"],mustEchoBack:!0},sampling:{temperature:{min:0,max:2}},vision:!0,inputModalities:{image:"supported"},quirks:{stopSequences:"ignored",countTokensEndpoint:!0}},pricing:{inputPerMillion:2.1,cachedInputPerMillion:.42,outputPerMillion:8.4}});P("minimax","minimax-m2.7-highspeed",{capability:{modelModifiers:["[1m]"],maxOutput:204800,promptCaching:{mode:"explicit",ttlSeconds:300,maxBreakpoints:4},thinking:{cannotDisable:!0,mustEchoBack:!0},sampling:{temperature:{min:0,max:2}},quirks:{stopSequences:"ignored",countTokensEndpoint:!0}}});P("glm","glm-5.2",{capability:{modelModifiers:["[1m]"],maxOutput:131072,inputModalities:{image:"rejected"},promptCaching:{mode:"implicit"},thinking:{toggleValues:["enabled"],budgetTokens:"honored",effortParam:"reasoning_effort"},sampling:{temperature:{min:0,max:1,minExclusive:!0,maxExclusive:!0}},quirks:{claudeModelNameMapping:!0,minTimeoutMs:3e6,maxTokensExcludesReasoning:!1}},pricing:{inputPerMillion:8,cachedInputPerMillion:2,outputPerMillion:28}});P("doubao","doubao-seed-2-0-pro-260215",{capability:{sampling:{temperature:{min:0,max:2}},quirks:{unknownModelFallback:!1,stopSequences:"ignored",maxTokensExcludesReasoning:!0,reasoningTokens:"subset_of_output"}}});function bo(){return{capability:{vision:!0,inputModalities:{image:"supported"}}}}function ve(){return{capability:{vision:!0,inputModalities:{image:"supported"},promptCaching:{mode:"explicit",minCacheableTokens:1024,ttlSeconds:300,maxBreakpoints:4}}}}P("anthropic","claude-opus-5",ve());P("anthropic","claude-opus-4",ve());P("anthropic","claude-sonnet-5",ve());P("anthropic","claude-sonnet-4-6",ve());P("anthropic","claude-sonnet-4-5",ve());function _e(){return{capability:{...bo().capability,quirks:{reasoningTokens:"subset_of_output"}}}}P("openai","gpt-5",_e());P("openai","gpt-5.4",_e());P("openai","gpt-5.4-pro",_e());P("openai","gpt-5.4-mini",_e());P("openai","gpt-5.5",_e());function Ce(t,e){return tr.get(er(t,e))}function Gt(t){let e=t.indexOf("/");return e<=0||e===t.length-1?null:{providerId:t.slice(0,e),modelOrRole:t.slice(e+1)}}function Ee(t,e){let n=Gt(e);if(n===null)throw new ae(e,e);let r=t.providers[n.providerId];if(r===void 0)throw new ae(n.providerId,e);let o=r.models[n.modelOrRole]??n.modelOrRole,i=Ce(n.providerId,o),s=Nt(i?.capability,r.capability,r.modelCapabilities?.[o]),a=qt(i?.capability,r.capability,r.modelCapabilities?.[o]),u=r.pricing?.[o]??i?.pricing;return{providerId:n.providerId,providerProfile:r,modelName:o,capability:s,...a!==void 0?{declaredMaxContext:a}:{},...u!==void 0?{pricing:u}:{}}}function Te(t,e){if(e.includes("/"))return Ee(t,e);let r=t.modelAliases[e];if(r===void 0)throw new we(e);return Ee(t,r)}function U(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function A(t){return typeof t=="string"?t:void 0}function z(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $t(t,e){let n=[],r={model:t.model.model,max_tokens:t.maxTokens,messages:t.messages.map((i,s)=>vo(i,s,t.model.provider,n))};if(t.system.length>0){let i=0;r.system=t.system.map(s=>{let a=s.cacheable===!0&&i<Ro;return a&&(i+=1),ko(s,a)})}e?.messageCacheBreakpoint===!0&&t.skipCacheWrite!==!0&&(wo(r),xo(r)),t.tools.length>0&&(r.tools=t.tools.map(i=>({name:i.name,description:i.description,input_schema:i.inputSchema}))),t.temperature!==void 0&&(r.temperature=t.temperature),t.stopSequences!==void 0&&t.stopSequences.length>0&&(r.stop_sequences=t.stopSequences);let o=t.thinking?.off===!0?void 0:t.thinking?.budget;return o!==void 0&&(r.thinking={type:"enabled",budget_tokens:o}),{request:r,droppedOpaque:n}}function ko(t,e){return e?{type:"text",text:t.text,cache_control:{type:"ephemeral"}}:{type:"text",text:t.text}}var rr=new Set(["text","tool_use","tool_result","image"]),or=4,Ro=3,nr=16;function ir(t){let e=(t.system??[]).filter(n=>n.cache_control!==void 0).length;for(let n of t.messages)for(let r of n.content)U(r)?.cache_control!==void 0&&(e+=1);return e}function wo(t){if(!(ir(t)>=or))for(let e=t.messages.length-1;e>=0;e--){let n=t.messages[e];if(n===void 0)continue;let r=n.content;for(let o=r.length-1;o>=0;o--){let i=r[o],s=i===void 0?void 0:A(U(i)?.type);if(s!==void 0&&rr.has(s)){r[o]={...i,cache_control:{type:"ephemeral"}};return}}}}function xo(t){if(ir(t)>=or)return;let e=-1;for(let r=t.messages.length-1;r>=0;r--)if(t.messages[r]?.role==="assistant"){e=r;break}if(e<0)return;let n=[];for(let r=e;r<t.messages.length;r++){let o=t.messages[r]?.content??[];for(let i=0;i<o.length;i++)n.push({mi:r,bi:i})}if(!(n.length<=nr))for(let r=nr-1;r>=0;r--){let o=n[r];if(o===void 0)continue;let i=t.messages[o.mi].content,s=i[o.bi],a=U(s),u=A(a?.type);if(u!==void 0&&rr.has(u)&&a?.cache_control===void 0){i[o.bi]={...s,cache_control:{type:"ephemeral"}};return}}}function vo(t,e,n,r){let o=[];return t.blocks.forEach((i,s)=>{if(i.t==="opaque"){i.provider===n?o.push(i.payload):r.push({messageIndex:e,blockIndex:s,provider:i.provider});return}o.push(_o(i))}),{role:t.role,content:o}}function _o(t){switch(t.t){case"text":return{type:"text",text:t.text};case"thinking":return{type:"thinking",thinking:t.text,signature:t.signature??""};case"tool_call":return{type:"tool_use",id:t.id,name:t.name,input:t.args??{}};case"tool_result":{let e={type:"tool_result",tool_use_id:t.callId,content:t.content.map(Co)};return t.isError!==void 0&&(e.is_error=t.isError),e}case"image":return sr(t.mime,t.data)}}function Co(t){return t.t==="text"?{type:"text",text:t.text}:sr(t.mime,t.data)}function sr(t,e){return{type:"image",source:{type:"base64",media_type:t,data:e}}}function Lt(t,e){let n=()=>({t:"opaque",provider:e,payload:t}),r=U(t);if(!r)return n();switch(A(r.type)){case"text":{let o=A(r.text);return o!==void 0?{t:"text",text:o}:n()}case"thinking":{let o=A(r.thinking)??"",i=A(r.signature);return i!==void 0?{t:"thinking",text:o,signature:i}:{t:"thinking",text:o}}case"tool_use":{let o=A(r.id),i=A(r.name);return o===void 0||i===void 0?n():{t:"tool_call",id:o,name:i,args:r.input??{}}}case"image":{let o=U(r.source),i=A(o?.media_type),s=A(o?.data);return i!==void 0&&s!==void 0?{t:"image",mime:i,data:s}:n()}default:return n()}}function Kt(t){let e=U(t);if(!e)return;let n={inputTokens:z(e.input_tokens)??0,outputTokens:z(e.output_tokens)??0},r=z(e.cache_read_input_tokens);r!==void 0&&(n.cacheReadInputTokens=r);let o=z(e.cache_creation_input_tokens);return o!==void 0&&(n.cacheCreationInputTokens=o),n}var at=["saturated","queue_timeout","breaker_open","closed"],Ht="UpstreamGovernorError",B=class extends Error{name=Ht;code;reason;origin;retryAfterMs;constructor(e,n,r={}){let o=`upstream_${e}`,i=r.detail!==void 0?` (${r.detail})`:"";super(`${o}: upstream ${n} ${Eo(e)}${i}`),this.code=o,this.reason=e,this.origin=n,this.retryAfterMs=r.retryAfterMs}};function Eo(t){switch(t){case"saturated":return"is saturated: concurrency and queue limits reached, request rejected before send";case"queue_timeout":return"queue wait timed out, request rejected before send";case"breaker_open":return"circuit breaker is open, request rejected before send";case"closed":return"governor is closed, request rejected before send"}}function ut(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.name===Ht&&typeof e.code=="string"&&e.code.startsWith("upstream_")&&typeof e.reason=="string"}function J(t){if(!ut(t))return;let e=t.retryAfterMs!==void 0&&Number.isFinite(t.retryAfterMs)&&t.retryAfterMs>=0?{retryAfterMs:Math.round(t.retryAfterMs)}:{};switch(t.reason){case"saturated":case"queue_timeout":return{t:"error",kind:"rate_limited",message:t.message,recoverable:!0,...e};case"breaker_open":return{t:"error",kind:"server",message:t.message,recoverable:!0,...e};case"closed":return{t:"error",kind:"server",message:t.message,recoverable:!1}}}var zt=Object.freeze({minMs:1e3,ratio:.2});function Jt(t){if(t===!1)return!1;let e=t?.minMs??zt.minMs,n=t?.ratio??zt.ratio;if(!(e>=0)||!(n>=0))throw new TypeError(`retryAfterJitter.minMs/ratio 必须为非负数,收到 ${e}/${n}`);return{minMs:e,ratio:n}}function lt(t,e,n){if(e===!1)return t;let r=Math.max(e.minMs,e.ratio*t);return t+n()*r}var To=6e5;function j(t){if(!(t===void 0||!Number.isFinite(t)||t<0))return t<=To?t:void 0}function Yt(t,e){if(!Number.isInteger(t)||t<0)throw new TypeError(`attempt 必须为非负整数,收到 ${t}`);if(!(e.baseMs>0)||!(e.maxMs>0))throw new TypeError(`baseMs/maxMs 必须为正数,收到 baseMs=${e.baseMs} maxMs=${e.maxMs}`);let n=e.random??Math.random,r=Math.min(e.maxMs,e.baseMs*2**t),o=n()*r;if(e.retryAfterMs===void 0)return Math.round(o);let i=lt(e.retryAfterMs,Jt(e.retryAfterJitter),n);return Math.round(Math.max(o,i))}var Ie=Object.freeze({initialMs:5e3,capMs:6e4,wallMs:18e4,jitter:!0}),dt=Object.freeze({baseMs:500,maxMs:3e4,maxAttempts:5});function Qt(t={}){let e={initialMs:t.patient?.initialMs??Ie.initialMs,capMs:t.patient?.capMs??Ie.capMs,wallMs:t.patient?.wallMs??Ie.wallMs,jitter:t.patientJitter??Ie.jitter},n={baseMs:t.baseMs??dt.baseMs,maxMs:t.maxMs??dt.maxMs,maxAttempts:t.maxAttempts??dt.maxAttempts,random:t.random??Math.random,patient:e,retryAfterJitter:Jt(t.retryAfterJitter)};if(!Number.isInteger(n.maxAttempts)||n.maxAttempts<1)throw new TypeError(`maxAttempts 必须为 ≥1 的整数,收到 ${n.maxAttempts}`);if(!(n.baseMs>0)||!(n.maxMs>0))throw new TypeError(`baseMs/maxMs 必须为正数,收到 baseMs=${n.baseMs} maxMs=${n.maxMs}`);if(!(e.initialMs>0)||!(e.capMs>0)||!(e.wallMs>0))throw new TypeError(`patient.initialMs/capMs/wallMs 必须为正数,收到 ${e.initialMs}/${e.capMs}/${e.wallMs}`);return n}function Vt(t,e,n,r=Math.random){let o=Math.min(e.capMs,e.initialMs*2**t),i=e.jitter??!0?o*(.5+.5*r()):o;return Math.max(0,Math.min(Math.round(i),n))}var Io=["ENOTFOUND","ECONNREFUSED","ECONNRESET","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_PRX_TLS","UND_ERR_PRX_CONN"],Mo=new Set(Io),lr=new WeakMap,ar=32;function Me(t,e){let n=Object.getOwnPropertyDescriptor(t,e);if(n!==void 0){if(!("value"in n))throw new TypeError;return n.value}}function So(t){let e=new Set,n,r=!0,o=(i,s)=>{if(!r||i===void 0||i===null)return;if(typeof i!="object"||s>cr||e.size>=ar){r=!1;return}if(e.has(i))return;e.add(i);let a=Me(i,"code");if(a!==void 0){if(typeof a!="string"||!Mo.has(a)||n!==void 0&&n!==a){r=!1;return}n=a}o(Me(i,"cause"),s+1);let u=Me(i,"errors");if(u!==void 0){if(!Array.isArray(u)){r=!1;return}let l=Me(u,"length");if(typeof l!="number"||!Number.isInteger(l)||l<0||l>ar){r=!1;return}for(let c=0;c<l&&r;c+=1)o(Me(u,String(c)),s+1)}};return o(t,0),r?n:void 0}function Y(t,e){try{let n=So(e);n!==void 0&&lr.set(t,n)}catch{}return t}function ct(t){return lr.get(t)}var cr=5,ur=4,dr=120;function Ao(t){if(typeof t!="object"||t===null)return typeof t=="string"&&t!==""?t.slice(0,dr):null;let e=t,n=typeof e.hostname=="string"&&e.hostname!==""?e.hostname:typeof e.address=="string"&&e.address!==""?typeof e.port=="number"?`${e.address}:${e.port}`:e.address:typeof e.syscall=="string"&&e.syscall!==""?e.syscall:null;return typeof e.code=="string"&&e.code!==""?n!==null?`${e.code} ${n}`:e.code:typeof e.name=="string"&&e.name!==""&&e.name!=="Error"&&e.name!=="TypeError"&&e.name!=="AggregateError"?e.name:typeof e.message=="string"&&e.message!==""?e.message.slice(0,dr):null}function Q(t){let e=t instanceof Error?t.message:String(t),n=[],r=new Set,o=(i,s)=>{if(i==null||s>cr||n.length>=ur)return;if(typeof i=="object"){if(r.has(i))return;r.add(i)}let a=Ao(i),u=typeof i=="object"&&Array.isArray(i.errors)?i.errors:null,l=u!==null&&u.length>0&&a!==null&&!a.includes(" ");if(a!==null&&!l&&!n.includes(a)&&n.length<ur&&n.push(a),u!==null)for(let c of u)o(c,s+1);typeof i=="object"&&o(i.cause,s+1)};return o(t?.cause,0),n.length===0?e:`${e} (${n.join("; ")})`}var Oo=/prompt is too long|context\s*(length|window|limit)|exceeds?[^.]{0,40}(context|token)|too many tokens|input length|max_tokens[^.]{0,40}exceed/i;function Xt(t){return Oo.test(t)}function pr(t){if(t==null||t==="")return;let e=Number(t);if(Number.isFinite(e))return j(Math.max(0,Math.round(e*1e3)));let n=Date.parse(t);if(!Number.isNaN(n))return j(Math.max(0,n-Date.now()))}function Po(t){let e=t.trim();return e.length>500?`${e.slice(0,500)}…`:e}function Zt(t,e,n){let r=`HTTP ${t}: ${Po(e)}`;if(t===429){let o={t:"error",kind:"rate_limited",message:r,recoverable:!0},i=pr(n);return i!==void 0&&(o.retryAfterMs=i),o}return t===401||t===403?{t:"error",kind:"auth",message:r,recoverable:!1}:t===400&&Xt(e)?{t:"error",kind:"context_overflow",message:r,recoverable:!1}:t>=500?{t:"error",kind:"server",message:r,recoverable:!0}:t>=400?{t:"error",kind:"invalid_request",message:r,recoverable:!1}:{t:"error",kind:"server",message:r,recoverable:!0}}function en(t,e){switch(t){case"rate_limit_error":return{t:"error",kind:"rate_limited",message:e,recoverable:!0};case"overloaded_error":case"api_error":return{t:"error",kind:"server",message:e,recoverable:!0};case"authentication_error":case"permission_error":return{t:"error",kind:"auth",message:e,recoverable:!1};case"invalid_request_error":return Xt(e)?{t:"error",kind:"context_overflow",message:e,recoverable:!1}:{t:"error",kind:"invalid_request",message:e,recoverable:!1};case"not_found_error":return{t:"error",kind:"invalid_request",message:e,recoverable:!1};default:return{t:"error",kind:"server",message:e,recoverable:!0}}}var Bo=/connect.?timeout|UND_ERR_CONNECT_TIMEOUT|\bETIMEDOUT\b/i;function Wo(t){let e=new Set,n=t;for(let r=0;r<5&&typeof n=="object"&&n!==null&&!e.has(n);r+=1){e.add(n);let o=n;for(let i of[o.code,o.name,o.message])if(typeof i=="string"&&Bo.test(i))return!0;n=o.cause}return!1}function pt(t,e="connect"){let n=J(t);if(n!==void 0&&n.t==="error")return n;if(t?.name==="TimeoutError")return Y({t:"error",kind:e==="stream"?"stream_interrupted":"connect",message:"Request timed out",recoverable:!0},t);let o=t instanceof Error?Q(t):typeof t=="string"?t:"unknown network failure",i=e==="stream"?"stream_interrupted":Wo(t)?"connect":"network";return Y({t:"error",kind:i,message:`Network error: ${o}`,recoverable:!0},t)}var te=class{#e=new TextDecoder("utf-8");#t="";#o=!1;#i="";#r=[];#n=0;get comments(){return this.#n}feed(e){let n=typeof e=="string"?e:this.#e.decode(e,{stream:!0});return this.#a(n)}end(){return this.#a(this.#e.decode())}#a(e){this.#o&&e.length>0&&(this.#o=!1,e.startsWith(`
|
|
4
|
+
import{a as et,b as tt,i as Z,j as nt,k as Mt,n as St,p as At,q as Ot,r as Pt,s as Bt}from"./tansr-chunk-OKAA4BJC.mjs";import{a as M,b as G,c as $n,d as Ln,e as be,f as Wt,h as Kn,i as Hn,j as zn,k as se,n as Jn,o as Yn,q as Qn,t as Vn,u as Ut}from"./tansr-chunk-OSK64SU3.mjs";import{Fb as rt,Ib as ot,J as Gn,c as d}from"./tansr-chunk-QWGSXFEJ.mjs";import{createHash as ho}from"node:crypto";var Xn="callMeta";function ke(t){if(t===void 0)return;let e=t[Xn];if(typeof e!="object"||e===null)return;let n=e,r=u=>{let l=n[u];return typeof l=="string"&&l.length>0?l:void 0},o=r("requestId"),i=r("purpose"),s=r("compactionId"),a=r("agentId");if(!(o===void 0&&i===void 0&&s===void 0&&a===void 0))return{...o!==void 0?{requestId:o}:{},...i!==void 0?{purpose:i}:{},...s!==void 0?{compactionId:s}:{},...a!==void 0?{agentId:a}:{}}}function Dt(t){let e;try{let n=new URL(t),r=n.pathname.replace(/\/+$/,"");e=`${n.protocol}//${n.host}${r}`.toLowerCase()}catch{e=t.trim().replace(/\/+$/,"").toLowerCase()}return ho("sha256").update(e,"utf8").digest("hex").slice(0,16)}function jt(t){if(t!==void 0)try{t()}catch{}}var go="(unknown)";function yo(t){let e=new Map,n=new WeakMap,r=0,o=s=>s.context.endpointKey??go;return{observer:{onAttemptStarted:s=>{let a=o(s),u=e.get(a)??{total:0,main:0,compaction:0};n.set(s,{total:r,sameEndpoint:u.total,sameEndpointMain:u.main,sameEndpointCompaction:u.compaction}),r+=1,u.total+=1,s.meta?.purpose==="main"?u.main+=1:s.meta?.purpose==="compaction"&&(u.compaction+=1),e.set(a,u)},onAttemptFinished:s=>{let a=s.start,u=o(a),l=e.get(u),c=n.get(a);c!==void 0&&l!==void 0&&(n.delete(a),r=Math.max(0,r-1),l.total=Math.max(0,l.total-1),a.meta?.purpose==="main"?l.main=Math.max(0,l.main-1):a.meta?.purpose==="compaction"&&(l.compaction=Math.max(0,l.compaction-1)),l.total===0&&e.delete(u)),t.onAttempt({...s,inflightAtStart:c??{total:0,sameEndpoint:0,sameEndpointMain:0,sameEndpointCompaction:0}})}},inflightTotal:()=>r}}var Zn=128e3;function qt(t,e,n){return n?.maxContext??e?.maxContext??t?.maxContext}function Re(t,e){if(t===void 0)return e===void 0?void 0:{...e};if(e===void 0)return{...t};let n={...t};for(let[r,o]of Object.entries(e))o!==void 0&&(n[r]=o);return n}function it(t,e){let n={...t};e.maxContext!==void 0&&(n.maxContext=e.maxContext),e.effectiveContext!==void 0&&(n.effectiveContext=e.effectiveContext),e.maxOutput!==void 0&&(n.maxOutput=e.maxOutput),e.reasoning!==void 0&&(n.reasoning=e.reasoning),e.thinkingOptional!==void 0&&(n.thinkingOptional=e.thinkingOptional),e.vision!==void 0&&(n.vision=e.vision),e.toolChoice!==void 0&&(n.toolChoice=e.toolChoice),e.modelModifiers!==void 0&&(n.modelModifiers=[...e.modelModifiers]),e.defaultContextWithoutModifier!==void 0&&(n.defaultContextWithoutModifier=e.defaultContextWithoutModifier),e.hostedTools!==void 0&&(n.hostedTools=[...e.hostedTools]),e.background!==void 0&&(n.background=e.background);let r=Re(t.inputModalities,e.inputModalities);r!==void 0&&(n.inputModalities=r);let o=Re(t.promptCaching,e.promptCaching);o!==void 0&&(n.promptCaching=o);let i=Re(t.thinking,e.thinking);i!==void 0&&(n.thinking=i);let s=Re(t.sampling,e.sampling);s!==void 0&&(n.sampling=s);let a=Re(t.quirks,e.quirks);return a!==void 0&&(n.quirks=a),n}function st(t){let e=t,n=t.inputModalities?.image;n!==void 0?e={...e,vision:n==="supported"}:t.vision!==void 0&&(e={...e,inputModalities:{...t.inputModalities,image:t.vision?"supported":"rejected"}});let r=e.sampling;return r?.temperatureRange!==void 0&&r.temperature===void 0&&(e={...e,sampling:{...r,temperature:{min:r.temperatureRange[0],max:r.temperatureRange[1]}}}),e}function Nt(t,e,n){let r={};return t!==void 0&&(r=it(r,st(t))),e!==void 0&&(r=it(r,st(e))),n!==void 0&&(r=it(r,st(n))),r.maxContext===void 0&&(r.maxContext=Zn),Gn.parse(r)}function Ft(t){let e=t?.inputModalities?.image;return e!==void 0?e:t?.vision!==void 0&&t.vision?"supported":"rejected"}var re=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name=new.target.name}},we=class extends re{alias;constructor(e){super("unknown_alias",`Unknown model alias: "${e}"`),this.alias=e}},ae=class extends re{providerId;ref;constructor(e,n){super("unknown_provider",`Unknown provider: "${e}"${n!==void 0?` (from ref "${n}")`:""}`),this.providerId=e,n!==void 0&&(this.ref=n)}},ee=class extends re{providerId;envVar;constructor(e,n){super("missing_api_key",n!==void 0?`Missing API key for provider "${e}": environment variable "${n}" is not set`:`Missing API key for provider "${e}": profile has no auth.env configured`),this.providerId=e,n!==void 0&&(this.envVar=n)}},xe=class extends re{path;constructor(e){super("cyclic_fallback",`Cyclic fallback chain: ${e.join(" -> ")}`),this.path=e}};function er(t,e){return`${t.toLowerCase()}/${e.toLowerCase()}`}var tr=new Map;function P(t,e,n){tr.set(er(t,e),n)}P("aliyun-maas","qwen3.7-max",{capability:{inputModalities:{image:"rejected"},promptCaching:{mode:"explicit",minCacheableTokens:1024},thinking:{toggleValues:["enabled","disabled"],budgetTokens:"honored",cannotDisable:!1,mustEchoBack:!0,signatureShape:"always_empty"},sampling:{temperature:{min:0,max:2,maxExclusive:!0}},quirks:{systemRoleInMessages:!0,unknownModelFallback:!1,claudeModelNameMapping:!1,stopSequences:"misreported_end_turn",streamUsageLocation:"message_delta"}}});P("aliyun-maas","qwen3-coder-plus",{capability:{maxContext:1e6,maxOutput:65536},pricing:{inputPerMillion:4,cachedInputPerMillion:.4,outputPerMillion:16,tiers:[{upToInputTokens:32768,inputPerMillion:4,cachedInputPerMillion:.4,outputPerMillion:16},{upToInputTokens:131072,inputPerMillion:6,cachedInputPerMillion:.6,outputPerMillion:24},{upToInputTokens:262144,inputPerMillion:10,cachedInputPerMillion:1,outputPerMillion:40},{inputPerMillion:20,cachedInputPerMillion:2,outputPerMillion:100}]}});P("deepseek","deepseek-v4-pro",{capability:{maxContext:1e6,modelModifiers:["[1m]"],defaultContextWithoutModifier:2e5,maxOutput:384e3,inputModalities:{image:"silently_dropped"},promptCaching:{mode:"ignored"},thinking:{budgetTokens:"ignored",effortParam:"output_config.effort",mustEchoBack:!0},sampling:{temperature:{min:0,max:2}},quirks:{unknownModelFallback:!0,claudeModelNameMapping:!0,stopSequences:"honored",minTimeoutMs:6e5}},pricing:{inputPerMillion:3,cachedInputPerMillion:.025,outputPerMillion:6,peakMultiplier:2}});P("deepseek","deepseek-v4-flash",{capability:{maxOutput:384e3}});P("kimi","kimi-k3",{capability:{modelModifiers:["[1m]"],maxOutput:1048576,promptCaching:{mode:"implicit"},thinking:{effortParam:"reasoning_effort",mustEchoBack:!0},sampling:{temperatureFixed:1},vision:!0,inputModalities:{image:"supported"},quirks:{claudeModelNameMapping:!0,modelsEndpoint:!0}},pricing:{inputPerMillion:20,cachedInputPerMillion:2,outputPerMillion:100}});P("kimi","kimi-k2.7-code",{capability:{maxContext:262144,modelModifiers:["[1m]"],promptCaching:{mode:"implicit"},thinking:{cannotDisable:!0,mustEchoBack:!0,signatureShape:"absent"},sampling:{temperatureFixed:1},inputModalities:{image:"supported"},quirks:{claudeModelNameMapping:!0,stopSequences:"misreported_end_turn",maxTokensExcludesReasoning:!1,reasoningTokens:"subset_of_output",modelsEndpoint:!0}}});P("minimax","minimax-m3",{capability:{modelModifiers:["[1m]"],maxOutput:524288,promptCaching:{mode:"explicit",ttlSeconds:300,maxBreakpoints:4},thinking:{toggleValues:["adaptive"],mustEchoBack:!0},sampling:{temperature:{min:0,max:2}},vision:!0,inputModalities:{image:"supported"},quirks:{stopSequences:"ignored",countTokensEndpoint:!0}},pricing:{inputPerMillion:2.1,cachedInputPerMillion:.42,outputPerMillion:8.4}});P("minimax","minimax-m2.7-highspeed",{capability:{modelModifiers:["[1m]"],maxOutput:204800,promptCaching:{mode:"explicit",ttlSeconds:300,maxBreakpoints:4},thinking:{cannotDisable:!0,mustEchoBack:!0},sampling:{temperature:{min:0,max:2}},quirks:{stopSequences:"ignored",countTokensEndpoint:!0}}});P("glm","glm-5.2",{capability:{modelModifiers:["[1m]"],maxOutput:131072,inputModalities:{image:"rejected"},promptCaching:{mode:"implicit"},thinking:{toggleValues:["enabled"],budgetTokens:"honored",effortParam:"reasoning_effort"},sampling:{temperature:{min:0,max:1,minExclusive:!0,maxExclusive:!0}},quirks:{claudeModelNameMapping:!0,minTimeoutMs:3e6,maxTokensExcludesReasoning:!1}},pricing:{inputPerMillion:8,cachedInputPerMillion:2,outputPerMillion:28}});P("doubao","doubao-seed-2-0-pro-260215",{capability:{sampling:{temperature:{min:0,max:2}},quirks:{unknownModelFallback:!1,stopSequences:"ignored",maxTokensExcludesReasoning:!0,reasoningTokens:"subset_of_output"}}});function bo(){return{capability:{vision:!0,inputModalities:{image:"supported"}}}}function ve(){return{capability:{vision:!0,inputModalities:{image:"supported"},promptCaching:{mode:"explicit",minCacheableTokens:1024,ttlSeconds:300,maxBreakpoints:4}}}}P("anthropic","claude-opus-5",ve());P("anthropic","claude-opus-4",ve());P("anthropic","claude-sonnet-5",ve());P("anthropic","claude-sonnet-4-6",ve());P("anthropic","claude-sonnet-4-5",ve());function _e(){return{capability:{...bo().capability,quirks:{reasoningTokens:"subset_of_output"}}}}P("openai","gpt-5",_e());P("openai","gpt-5.4",_e());P("openai","gpt-5.4-pro",_e());P("openai","gpt-5.4-mini",_e());P("openai","gpt-5.5",_e());function Ce(t,e){return tr.get(er(t,e))}function Gt(t){let e=t.indexOf("/");return e<=0||e===t.length-1?null:{providerId:t.slice(0,e),modelOrRole:t.slice(e+1)}}function Ee(t,e){let n=Gt(e);if(n===null)throw new ae(e,e);let r=t.providers[n.providerId];if(r===void 0)throw new ae(n.providerId,e);let o=r.models[n.modelOrRole]??n.modelOrRole,i=Ce(n.providerId,o),s=Nt(i?.capability,r.capability,r.modelCapabilities?.[o]),a=qt(i?.capability,r.capability,r.modelCapabilities?.[o]),u=r.pricing?.[o]??i?.pricing;return{providerId:n.providerId,providerProfile:r,modelName:o,capability:s,...a!==void 0?{declaredMaxContext:a}:{},...u!==void 0?{pricing:u}:{}}}function Te(t,e){if(e.includes("/"))return Ee(t,e);let r=t.modelAliases[e];if(r===void 0)throw new we(e);return Ee(t,r)}function U(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function A(t){return typeof t=="string"?t:void 0}function z(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $t(t,e){let n=[],r={model:t.model.model,max_tokens:t.maxTokens,messages:t.messages.map((i,s)=>vo(i,s,t.model.provider,n))};if(t.system.length>0){let i=0;r.system=t.system.map(s=>{let a=s.cacheable===!0&&i<Ro;return a&&(i+=1),ko(s,a)})}e?.messageCacheBreakpoint===!0&&t.skipCacheWrite!==!0&&(wo(r),xo(r)),t.tools.length>0&&(r.tools=t.tools.map(i=>({name:i.name,description:i.description,input_schema:i.inputSchema}))),t.temperature!==void 0&&(r.temperature=t.temperature),t.stopSequences!==void 0&&t.stopSequences.length>0&&(r.stop_sequences=t.stopSequences);let o=t.thinking?.off===!0?void 0:t.thinking?.budget;return o!==void 0&&(r.thinking={type:"enabled",budget_tokens:o}),{request:r,droppedOpaque:n}}function ko(t,e){return e?{type:"text",text:t.text,cache_control:{type:"ephemeral"}}:{type:"text",text:t.text}}var rr=new Set(["text","tool_use","tool_result","image"]),or=4,Ro=3,nr=16;function ir(t){let e=(t.system??[]).filter(n=>n.cache_control!==void 0).length;for(let n of t.messages)for(let r of n.content)U(r)?.cache_control!==void 0&&(e+=1);return e}function wo(t){if(!(ir(t)>=or))for(let e=t.messages.length-1;e>=0;e--){let n=t.messages[e];if(n===void 0)continue;let r=n.content;for(let o=r.length-1;o>=0;o--){let i=r[o],s=i===void 0?void 0:A(U(i)?.type);if(s!==void 0&&rr.has(s)){r[o]={...i,cache_control:{type:"ephemeral"}};return}}}}function xo(t){if(ir(t)>=or)return;let e=-1;for(let r=t.messages.length-1;r>=0;r--)if(t.messages[r]?.role==="assistant"){e=r;break}if(e<0)return;let n=[];for(let r=e;r<t.messages.length;r++){let o=t.messages[r]?.content??[];for(let i=0;i<o.length;i++)n.push({mi:r,bi:i})}if(!(n.length<=nr))for(let r=nr-1;r>=0;r--){let o=n[r];if(o===void 0)continue;let i=t.messages[o.mi].content,s=i[o.bi],a=U(s),u=A(a?.type);if(u!==void 0&&rr.has(u)&&a?.cache_control===void 0){i[o.bi]={...s,cache_control:{type:"ephemeral"}};return}}}function vo(t,e,n,r){let o=[];return t.blocks.forEach((i,s)=>{if(i.t==="opaque"){i.provider===n?o.push(i.payload):r.push({messageIndex:e,blockIndex:s,provider:i.provider});return}o.push(_o(i))}),{role:t.role,content:o}}function _o(t){switch(t.t){case"text":return{type:"text",text:t.text};case"thinking":return{type:"thinking",thinking:t.text,signature:t.signature??""};case"tool_call":return{type:"tool_use",id:t.id,name:t.name,input:t.args??{}};case"tool_result":{let e={type:"tool_result",tool_use_id:t.callId,content:t.content.map(Co)};return t.isError!==void 0&&(e.is_error=t.isError),e}case"image":return sr(t.mime,t.data)}}function Co(t){return t.t==="text"?{type:"text",text:t.text}:sr(t.mime,t.data)}function sr(t,e){return{type:"image",source:{type:"base64",media_type:t,data:e}}}function Lt(t,e){let n=()=>({t:"opaque",provider:e,payload:t}),r=U(t);if(!r)return n();switch(A(r.type)){case"text":{let o=A(r.text);return o!==void 0?{t:"text",text:o}:n()}case"thinking":{let o=A(r.thinking)??"",i=A(r.signature);return i!==void 0?{t:"thinking",text:o,signature:i}:{t:"thinking",text:o}}case"tool_use":{let o=A(r.id),i=A(r.name);return o===void 0||i===void 0?n():{t:"tool_call",id:o,name:i,args:r.input??{}}}case"image":{let o=U(r.source),i=A(o?.media_type),s=A(o?.data);return i!==void 0&&s!==void 0?{t:"image",mime:i,data:s}:n()}default:return n()}}function Kt(t){let e=U(t);if(!e)return;let n={inputTokens:z(e.input_tokens)??0,outputTokens:z(e.output_tokens)??0},r=z(e.cache_read_input_tokens);r!==void 0&&(n.cacheReadInputTokens=r);let o=z(e.cache_creation_input_tokens);return o!==void 0&&(n.cacheCreationInputTokens=o),n}var at=["saturated","queue_timeout","breaker_open","closed"],Ht="UpstreamGovernorError",B=class extends Error{name=Ht;code;reason;origin;retryAfterMs;constructor(e,n,r={}){let o=`upstream_${e}`,i=r.detail!==void 0?` (${r.detail})`:"";super(`${o}: upstream ${n} ${Eo(e)}${i}`),this.code=o,this.reason=e,this.origin=n,this.retryAfterMs=r.retryAfterMs}};function Eo(t){switch(t){case"saturated":return"is saturated: concurrency and queue limits reached, request rejected before send";case"queue_timeout":return"queue wait timed out, request rejected before send";case"breaker_open":return"circuit breaker is open, request rejected before send";case"closed":return"governor is closed, request rejected before send"}}function ut(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.name===Ht&&typeof e.code=="string"&&e.code.startsWith("upstream_")&&typeof e.reason=="string"}function J(t){if(!ut(t))return;let e=t.retryAfterMs!==void 0&&Number.isFinite(t.retryAfterMs)&&t.retryAfterMs>=0?{retryAfterMs:Math.round(t.retryAfterMs)}:{};switch(t.reason){case"saturated":case"queue_timeout":return{t:"error",kind:"rate_limited",message:t.message,recoverable:!0,...e};case"breaker_open":return{t:"error",kind:"server",message:t.message,recoverable:!0,...e};case"closed":return{t:"error",kind:"server",message:t.message,recoverable:!1}}}var zt=Object.freeze({minMs:1e3,ratio:.2});function Jt(t){if(t===!1)return!1;let e=t?.minMs??zt.minMs,n=t?.ratio??zt.ratio;if(!(e>=0)||!(n>=0))throw new TypeError(`retryAfterJitter.minMs/ratio 必须为非负数,收到 ${e}/${n}`);return{minMs:e,ratio:n}}function lt(t,e,n){if(e===!1)return t;let r=Math.max(e.minMs,e.ratio*t);return t+n()*r}var To=6e5;function j(t){if(!(t===void 0||!Number.isFinite(t)||t<0))return t<=To?t:void 0}function Yt(t,e){if(!Number.isInteger(t)||t<0)throw new TypeError(`attempt 必须为非负整数,收到 ${t}`);if(!(e.baseMs>0)||!(e.maxMs>0))throw new TypeError(`baseMs/maxMs 必须为正数,收到 baseMs=${e.baseMs} maxMs=${e.maxMs}`);let n=e.random??Math.random,r=Math.min(e.maxMs,e.baseMs*2**t),o=n()*r;if(e.retryAfterMs===void 0)return Math.round(o);let i=lt(e.retryAfterMs,Jt(e.retryAfterJitter),n);return Math.round(Math.max(o,i))}var Ie=Object.freeze({initialMs:5e3,capMs:6e4,wallMs:18e4,jitter:!0}),dt=Object.freeze({baseMs:500,maxMs:3e4,maxAttempts:5});function Qt(t={}){let e={initialMs:t.patient?.initialMs??Ie.initialMs,capMs:t.patient?.capMs??Ie.capMs,wallMs:t.patient?.wallMs??Ie.wallMs,jitter:t.patientJitter??Ie.jitter},n={baseMs:t.baseMs??dt.baseMs,maxMs:t.maxMs??dt.maxMs,maxAttempts:t.maxAttempts??dt.maxAttempts,random:t.random??Math.random,patient:e,retryAfterJitter:Jt(t.retryAfterJitter)};if(!Number.isInteger(n.maxAttempts)||n.maxAttempts<1)throw new TypeError(`maxAttempts 必须为 ≥1 的整数,收到 ${n.maxAttempts}`);if(!(n.baseMs>0)||!(n.maxMs>0))throw new TypeError(`baseMs/maxMs 必须为正数,收到 baseMs=${n.baseMs} maxMs=${n.maxMs}`);if(!(e.initialMs>0)||!(e.capMs>0)||!(e.wallMs>0))throw new TypeError(`patient.initialMs/capMs/wallMs 必须为正数,收到 ${e.initialMs}/${e.capMs}/${e.wallMs}`);return n}function Vt(t,e,n,r=Math.random){let o=Math.min(e.capMs,e.initialMs*2**t),i=e.jitter??!0?o*(.5+.5*r()):o;return Math.max(0,Math.min(Math.round(i),n))}var Io=["ENOTFOUND","ECONNREFUSED","ECONNRESET","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_PRX_TLS","UND_ERR_PRX_CONN"],Mo=new Set(Io),lr=new WeakMap,ar=32;function Me(t,e){let n=Object.getOwnPropertyDescriptor(t,e);if(n!==void 0){if(!("value"in n))throw new TypeError;return n.value}}function So(t){let e=new Set,n,r=!0,o=(i,s)=>{if(!r||i===void 0||i===null)return;if(typeof i!="object"||s>cr||e.size>=ar){r=!1;return}if(e.has(i))return;e.add(i);let a=Me(i,"code");if(a!==void 0){if(typeof a!="string"||!Mo.has(a)||n!==void 0&&n!==a){r=!1;return}n=a}o(Me(i,"cause"),s+1);let u=Me(i,"errors");if(u!==void 0){if(!Array.isArray(u)){r=!1;return}let l=Me(u,"length");if(typeof l!="number"||!Number.isInteger(l)||l<0||l>ar){r=!1;return}for(let c=0;c<l&&r;c+=1)o(Me(u,String(c)),s+1)}};return o(t,0),r?n:void 0}function Y(t,e){try{let n=So(e);n!==void 0&&lr.set(t,n)}catch{}return t}function ct(t){return lr.get(t)}var cr=5,ur=4,dr=120;function Ao(t){if(typeof t!="object"||t===null)return typeof t=="string"&&t!==""?t.slice(0,dr):null;let e=t,n=typeof e.hostname=="string"&&e.hostname!==""?e.hostname:typeof e.address=="string"&&e.address!==""?typeof e.port=="number"?`${e.address}:${e.port}`:e.address:typeof e.syscall=="string"&&e.syscall!==""?e.syscall:null;return typeof e.code=="string"&&e.code!==""?n!==null?`${e.code} ${n}`:e.code:typeof e.name=="string"&&e.name!==""&&e.name!=="Error"&&e.name!=="TypeError"&&e.name!=="AggregateError"?e.name:typeof e.message=="string"&&e.message!==""?e.message.slice(0,dr):null}function Q(t){let e=t instanceof Error?t.message:String(t),n=[],r=new Set,o=(i,s)=>{if(i==null||s>cr||n.length>=ur)return;if(typeof i=="object"){if(r.has(i))return;r.add(i)}let a=Ao(i),u=typeof i=="object"&&Array.isArray(i.errors)?i.errors:null,l=u!==null&&u.length>0&&a!==null&&!a.includes(" ");if(a!==null&&!l&&!n.includes(a)&&n.length<ur&&n.push(a),u!==null)for(let c of u)o(c,s+1);typeof i=="object"&&o(i.cause,s+1)};return o(t?.cause,0),n.length===0?e:`${e} (${n.join("; ")})`}var Oo=/prompt is too long|context\s*(length|window|limit)|exceeds?[^.]{0,40}(context|token)|too many tokens|input length|max_tokens[^.]{0,40}exceed/i;function Xt(t){return Oo.test(t)}function pr(t){if(t==null||t==="")return;let e=Number(t);if(Number.isFinite(e))return j(Math.max(0,Math.round(e*1e3)));let n=Date.parse(t);if(!Number.isNaN(n))return j(Math.max(0,n-Date.now()))}function Po(t){let e=t.trim();return e.length>500?`${e.slice(0,500)}…`:e}function Zt(t,e,n){let r=`HTTP ${t}: ${Po(e)}`;if(t===429){let o={t:"error",kind:"rate_limited",message:r,recoverable:!0},i=pr(n);return i!==void 0&&(o.retryAfterMs=i),o}return t===401||t===403?{t:"error",kind:"auth",message:r,recoverable:!1}:t===400&&Xt(e)?{t:"error",kind:"context_overflow",message:r,recoverable:!1}:t>=500?{t:"error",kind:"server",message:r,recoverable:!0}:t>=400?{t:"error",kind:"invalid_request",message:r,recoverable:!1}:{t:"error",kind:"server",message:r,recoverable:!0}}function en(t,e){switch(t){case"rate_limit_error":return{t:"error",kind:"rate_limited",message:e,recoverable:!0};case"overloaded_error":case"api_error":return{t:"error",kind:"server",message:e,recoverable:!0};case"authentication_error":case"permission_error":return{t:"error",kind:"auth",message:e,recoverable:!1};case"invalid_request_error":return Xt(e)?{t:"error",kind:"context_overflow",message:e,recoverable:!1}:{t:"error",kind:"invalid_request",message:e,recoverable:!1};case"not_found_error":return{t:"error",kind:"invalid_request",message:e,recoverable:!1};default:return{t:"error",kind:"server",message:e,recoverable:!0}}}var Bo=/connect.?timeout|UND_ERR_CONNECT_TIMEOUT|\bETIMEDOUT\b/i;function Wo(t){let e=new Set,n=t;for(let r=0;r<5&&typeof n=="object"&&n!==null&&!e.has(n);r+=1){e.add(n);let o=n;for(let i of[o.code,o.name,o.message])if(typeof i=="string"&&Bo.test(i))return!0;n=o.cause}return!1}function pt(t,e="connect"){let n=J(t);if(n!==void 0&&n.t==="error")return n;if(t?.name==="TimeoutError")return Y({t:"error",kind:e==="stream"?"stream_interrupted":"connect",message:"Request timed out",recoverable:!0},t);let o=t instanceof Error?Q(t):typeof t=="string"?t:"unknown network failure",i=e==="stream"?"stream_interrupted":Wo(t)?"connect":"network";return Y({t:"error",kind:i,message:`Network error: ${o}`,recoverable:!0},t)}var te=class{#e=new TextDecoder("utf-8");#t="";#o=!1;#i="";#r=[];#n=0;get comments(){return this.#n}feed(e){let n=typeof e=="string"?e:this.#e.decode(e,{stream:!0});return this.#a(n)}end(){return this.#a(this.#e.decode())}#a(e){this.#o&&e.length>0&&(this.#o=!1,e.startsWith(`
|
|
5
5
|
`)&&(e=e.slice(1)));let n=this.#t+e,r=[],o=0;for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);s===10?(this.#u(n.slice(o,i),r),o=i+1):s===13&&(this.#u(n.slice(o,i),r),i+1<n.length?n.charCodeAt(i+1)===10&&i++:this.#o=!0,o=i+1)}return this.#t=n.slice(o),r}#u(e,n){if(e===""){this.#r.length>0&&n.push({event:this.#i,data:this.#r.join(`
|
|
6
6
|
`)}),this.#i="",this.#r=[];return}if(e.startsWith(":")){this.#n+=1;return}let r=e.indexOf(":"),o,i;r===-1?(o=e,i=""):(o=e.slice(0,r),i=e.slice(r+1),i.startsWith(" ")&&(i=i.slice(1))),o==="event"?this.#i=i:o==="data"&&this.#r.push(i)}},ue=class{#e;#t=null;#o;#i;#r=new Map;#n=!1;constructor(e){this.#e=e}get sawMessageStop(){return this.#n}get blockSignatures(){return this.#r}push(e){let n;try{n=JSON.parse(e.data)}catch{return[]}let r=U(n);if(!r)return[];switch(e.event!==""?e.event:A(r.type)??""){case"ping":return[];case"message_start":{let i=U(r.message),s=U(i?.usage);return s&&(this.#o=s),[{t:"message_start",model:A(i?.model)??""}]}case"content_block_start":{let i=z(r.index);return i===void 0?[]:[{t:"block_start",index:i,block:Lt(r.content_block,this.#e)}]}case"content_block_delta":{let i=z(r.index),s=U(r.delta);if(i===void 0||!s)return[];switch(A(s.type)){case"text_delta":return[{t:"text_delta",index:i,text:A(s.text)??""}];case"thinking_delta":return[{t:"thinking_delta",index:i,text:A(s.thinking)??""}];case"input_json_delta":return[{t:"tool_args_delta",index:i,json:A(s.partial_json)??""}];case"signature_delta":{let a=A(s.signature)??"";return this.#r.set(i,(this.#r.get(i)??"")+a),[{t:"signature_delta",index:i,text:a}]}default:return[]}}case"content_block_stop":{let i=z(r.index);return i===void 0?[]:[{t:"block_stop",index:i}]}case"message_delta":{let i=A(U(r.delta)?.stop_reason);i!==void 0&&(this.#t=i);let s=U(r.usage);return s&&(this.#i={...this.#o,...s}),[]}case"message_stop":{this.#n=!0;let i={t:"message_stop",stopReason:this.#t??"end_turn"},s=Kt(this.#i??this.#o);return s&&(i.usage=s),[i]}case"error":{let i=U(r.error);return[en(A(i?.type)??"unknown",A(i?.message)??"stream error")]}default:return[]}}};var mr="2023-06-01",Se=class{#e;#t;#o;#i;#r;constructor(e){this.#e=`${e.baseUrl.replace(/\/+$/,"")}/v1/messages`,this.#t=e.apiKey,this.#o=e.defaultHeaders??{},this.#i=e.fetchImpl??fetch,this.#r=e.messageCacheBreakpoint??!1}#n(){let e=this.#t;return typeof e=="function"?e():e}async*stream(e,n){let r;try{r=this.#n()}catch(b){yield{t:"error",kind:"auth",message:b instanceof Error?b.message:String(b),recoverable:!1};return}let{request:o}=$t(e,{messageCacheBreakpoint:this.#r}),i={"content-type":"application/json","anthropic-version":mr,...this.#o,"x-api-key":r},s=[];n?.signal&&s.push(n.signal),n?.timeoutMs!==void 0&&s.push(AbortSignal.timeout(n.timeoutMs));let a=s.length>0?AbortSignal.any(s):void 0,u;try{u=await this.#i(this.#e,{method:"POST",headers:i,body:JSON.stringify({...o,stream:!0}),...a?{signal:a}:{}})}catch(b){if(n?.signal?.aborted)return;yield pt(b,"connect");return}if(!u.ok){let b="";try{b=await u.text()}catch{}yield Zt(u.status,b,u.headers.get("retry-after"));return}if(!u.body){yield{t:"error",kind:"network",message:"Response has no body",recoverable:!0};return}let l=new te,c=new ue(e.model.provider),p=Date.now(),f,g=u.body.getReader();try{for(;;){let{done:b,value:R}=await g.read(),y=b?l.end():l.feed(R??new Uint8Array(0));for(let k of y)for(let x of c.push(k))if(f===void 0&&(x.t==="block_start"||x.t==="text_delta"||x.t==="thinking_delta"||x.t==="tool_args_delta")&&(f=Date.now()-p),x.t==="message_stop"&&f!==void 0?yield{...x,ttftMs:f}:yield x,x.t==="error")return;if(b)break}}catch(b){if(n?.signal?.aborted)return;yield pt(b,"stream");return}finally{try{await g.cancel()}catch{}}c.sawMessageStop||(yield{t:"error",kind:"stream_interrupted",message:"Stream ended before message_stop",recoverable:!0})}};function tn(t,e={}){let n=e.stream??!0,r=[],o=t.system.map(s=>s.text).join(`
|
|
7
7
|
|
|
@@ -11,15 +11,15 @@ import{a as M,b as G,c as $n,d as Ln,e as be,f as Wt,h as Kn,i as Hn,j as zn,k a
|
|
|
11
11
|
|
|
12
12
|
`)),r.push(l),r.push(...o),i.length>0&&r.push({role:"user",content:[...i]}),r}var Do="[image: see next user message]";function fr(t){let e=[],n=[];for(let r of t.content)r.t==="text"?n.push(r.text):(e.push({type:"image_url",image_url:{url:gr(r.mime,r.data)}}),n.push(Do));return{message:{role:"tool",tool_call_id:t.callId,content:n.join(`
|
|
13
13
|
`)},images:e}}function jo(t){if(t.length===0)return"";let e=t[0];return t.length===1&&e!==void 0&&e.type==="text"?e.text:t}function qo(t){if(typeof t=="string")return t;if(typeof t=="object"&&t!==null){let e=t.reasoning_content;if(typeof e=="string")return e}return null}function gr(t,e){return`data:${t};base64,${e}`}var nn=d.object({prompt_tokens:d.number().int().nonnegative().nullish(),completion_tokens:d.number().int().nonnegative().nullish(),prompt_tokens_details:d.object({cached_tokens:d.number().int().nonnegative().nullish()}).nullish(),completion_tokens_details:d.object({reasoning_tokens:d.number().int().nonnegative().nullish()}).nullish()}),yr=d.object({index:d.number().int().nullish(),id:d.string().nullish(),type:d.string().nullish(),function:d.object({name:d.string().nullish(),arguments:d.string().nullish()}).nullish()}),rn=d.object({model:d.string().nullish(),choices:d.array(d.object({index:d.number().int().nullish(),delta:d.object({role:d.string().nullish(),content:d.string().nullish(),reasoning_content:d.string().nullish(),tool_calls:d.array(yr).nullish()}).nullish(),finish_reason:d.string().nullish()})).nullish(),usage:nn.nullish(),error:d.unknown().optional()}),br=d.object({model:d.string().nullish(),choices:d.array(d.object({message:d.object({role:d.string().nullish(),content:d.string().nullish(),reasoning_content:d.string().nullish(),tool_calls:d.array(yr).nullish()}).nullish(),finish_reason:d.string().nullish()})).nullish(),usage:nn.nullish()}),No=d.object({data:d.array(d.object({id:d.string().nullish()})).nullish()});function Ae(t){let e=No.safeParse(t);return e.success?(e.data.data??[]).flatMap(n=>typeof n.id=="string"?[n.id]:[]):[]}function on(t){switch(t){case null:case void 0:case"stop":return"end_turn";case"tool_calls":return"tool_use";case"length":return"max_tokens";default:return t}}function mt(t,e){let n=t-e;return n<0?(process.emitWarning(`usage normalization: cached tokens (${e}) exceed total input tokens (${t}); inputTokens clamped to 0`,{code:"TANSR_USAGE_CACHED_EXCEEDS_TOTAL",type:"TansrProviderWarning"}),0):n}function sn(t){let e=t.prompt_tokens_details?.cached_tokens,n=t.completion_tokens_details?.reasoning_tokens;return{inputTokens:mt(t.prompt_tokens??0,e??0),outputTokens:t.completion_tokens??0,...e!=null?{cacheReadInputTokens:e}:{},...n!=null?{reasoningOutputTokens:n}:{}}}var kr=/context[ _-]?(length|window)|maximum context|too many tokens|prompt is too long|input (is )?too long|input length|token (count|limit)|tokens? exceed|exceeds .{0,32}(token|context)|context_length_exceeded/i;function Oe(t,e){return t===429?{kind:"rate_limited",recoverable:!0}:t===401||t===403?{kind:"auth",recoverable:!1}:t>=500?{kind:"server",recoverable:!0}:t===400&&kr.test(e)?{kind:"context_overflow",recoverable:!1}:{kind:"invalid_request",recoverable:!1}}function Rr(t){return/rate.?limit|too many requests|throttl/i.test(t)?{kind:"rate_limited",recoverable:!0}:kr.test(t)?{kind:"context_overflow",recoverable:!1}:/api.?key|unauthorized|authenticat|forbidden|permission denied/i.test(t)?{kind:"auth",recoverable:!1}:{kind:"server",recoverable:!0}}function de(t){let e="Provider returned an error payload",n="";if(typeof t=="string"&&t.length>0)e=t;else if(typeof t=="object"&&t!==null){let o=t;typeof o.message=="string"&&o.message.length>0&&(e=o.message),typeof o.code=="string"?n=o.code:typeof o.type=="string"&&(n=o.type)}let r=Rr(`${n} ${e}`);return{t:"error",kind:r.kind,message:e,recoverable:r.recoverable}}function Pe(t){let e=t.get("retry-after-ms");if(e!==null&&/^\d+$/.test(e.trim()))return j(Number(e.trim()));let n=t.get("retry-after");if(n===null)return;let r=n.trim();if(/^\d+$/.test(r))return j(Number(r)*1e3);let o=Date.parse(r);if(!Number.isNaN(o))return j(Math.max(0,o-Date.now()))}var Be="[DONE]",K=class{#e=new TextDecoder("utf-8");#t="";#o=[];push(e){let n=typeof e=="string"?e:this.#e.decode(e,{stream:!0});return this.#i(n,!1)}end(){return this.#i(this.#e.decode(),!0)}#i(e,n){this.#t+=e;let r=[],o=0,i=0;for(;i<this.#t.length;){let s=this.#t.charCodeAt(i);if(s===10)this.#r(this.#t.slice(o,i),r),i+=1,o=i;else if(s===13){if(i===this.#t.length-1&&!n)break;this.#r(this.#t.slice(o,i),r),i+=this.#t.charCodeAt(i+1)===10?2:1,o=i}else i+=1}return this.#t=this.#t.slice(o),n&&(this.#t!==""&&(this.#r(this.#t,r),this.#t=""),this.#n(r)),r}#r(e,n){if(e===""){this.#n(n);return}if(e.startsWith(":"))return;let r=e.indexOf(":"),o=r===-1?e:e.slice(0,r),i=r===-1?"":e.slice(r+1);i.startsWith(" ")&&(i=i.slice(1)),o==="data"&&this.#o.push(i)}#n(e){this.#o.length!==0&&(e.push(this.#o.join(`
|
|
14
|
-
`)),this.#o=[])}},oe=class{#e;#t=!1;#o=!1;#i=0;#r=null;#n=new Map;#a=null;#u=new Map;#c=-1;#s=null;#d;constructor(e={}){this.#e=e.fallbackModel??"unknown"}get ended(){return this.#o}handleData(e){if(this.#o)return[];if(e.trim()===Be)return this.#
|
|
14
|
+
`)),this.#o=[])}},oe=class{#e;#t=!1;#o=!1;#i=0;#r=null;#n=new Map;#a=null;#u=new Map;#c=-1;#s=null;#d;constructor(e={}){this.#e=e.fallbackModel??"unknown"}get ended(){return this.#o}handleData(e){if(this.#o)return[];if(e.trim()===Be)return this.#b();let n;try{n=JSON.parse(e)}catch{return[]}let r=rn.safeParse(n);if(!r.success)return[];let o=r.data;if(o.error!==void 0&&o.error!==null)return this.#o=!0,[de(o.error)];let i=[];this.#t||(i.push({t:"message_start",model:o.model??this.#e}),this.#t=!0),o.usage!=null&&(this.#d=sn(o.usage));let s=o.choices?.[0];if(s===void 0)return i;let a=s.delta;if(a!=null){if(a.reasoning_content!=null&&a.reasoning_content!==""){let u=this.#f("thinking",i);i.push({t:"thinking_delta",index:u,text:a.reasoning_content})}if(a.content!=null&&a.content!==""){let u=this.#f("text",i);i.push({t:"text_delta",index:u,text:a.content})}if(a.tool_calls!=null)for(let u of a.tool_calls)this.#p(u,i)}return s.finish_reason!=null&&(this.#s=on(s.finish_reason)),i}finish(){return this.#o?[]:this.#s===null?(this.#o=!0,[{t:"error",kind:"stream_interrupted",message:"Stream ended before finish_reason/[DONE] (likely truncated by upstream)",recoverable:!0}]):this.#b()}#f(e,n){if(this.#r!==null&&this.#r.kind===e)return this.#r.index;this.#h(n);let r=this.#i;return this.#i+=1,n.push({t:"block_start",index:r,block:e==="text"?{t:"text",text:""}:{t:"thinking",text:""}}),this.#r={kind:e,index:r},r}#h(e){this.#r!==null&&(e.push({t:"block_stop",index:this.#r.index}),this.#r=null)}#p(e,n){let r=e.index??this.#a??0;if(e.index==null&&e.id!=null&&e.id!==""){let s=this.#u.get(r);s!==void 0&&s!==e.id&&(r=this.#c,this.#c-=1)}this.#a=r;let o=this.#n.get(r);if(o===void 0){this.#h(n),o=this.#i,this.#i+=1,this.#n.set(r,o);let s=e.id!=null&&e.id!==""?e.id:`call_auto_${o}`;this.#u.set(r,s);let a=e.function?.name??"";n.push({t:"block_start",index:o,block:{t:"tool_call",id:s,name:a,args:{}}})}let i=e.function?.arguments;i!=null&&i!==""&&n.push({t:"tool_args_delta",index:o,json:i})}#b(){let e=[];this.#t||(e.push({t:"message_start",model:this.#e}),this.#t=!0);let n=[];this.#r!==null&&n.push(this.#r.index);for(let r of this.#n.values())n.push(r);n.sort((r,o)=>r-o);for(let r of n)e.push({t:"block_stop",index:r});return this.#r=null,this.#n.clear(),this.#u.clear(),e.push({t:"message_stop",stopReason:this.#s??"end_turn",...this.#d!==void 0?{usage:this.#d}:{}}),this.#o=!0,e}};function le(t){let e=t.connectTimeoutMs??15e3,n=t.idleTimeoutMs??17e4,r=t.totalTimeoutMs??t.timeoutMs,o=new AbortController,i=null,s=null,a=null,u=c=>{i=c,o.abort()},l=(c,p)=>{s!==null&&clearTimeout(s);let f=setTimeout(()=>u(c),p);f.unref?.(),s=f};return r!==void 0&&(a=setTimeout(()=>u("total"),r),a.unref?.()),{signal:o.signal,armConnect:()=>l("connect",e),armIdle:()=>l("idle",n),firedPhase:()=>i,timeoutMessage:()=>{switch(i){case"idle":return`Stream idle timeout: no data for ${n}ms`;case"total":return`Request timed out after ${r}ms`;default:return`Connect timeout: no response headers within ${e}ms`}},dispose:()=>{s!==null&&clearTimeout(s),a!==null&&clearTimeout(a),s=null,a=null}}}var Fo=600,ce=class{#e;#t;#o;#i;#r;#n;constructor(e){this.#e=e.baseUrl.replace(/\/+$/,""),this.#t=e.apiKey,this.#o=e.defaultHeaders??{},this.#i=e.fetchImpl??fetch,this.#r=e.echoThinking??!1,this.#n=e.onThinkingEcho}#a(e){if(!this.#r||this.#n===void 0)return;let n=0,r=0;for(let o of e.messages)o.role==="assistant"&&o.reasoning_content!==void 0&&o.reasoning_content!==""&&(n+=o.reasoning_content.length,r+=1);r>0&&this.#n({chars:n,messages:r})}#u(){let e=this.#t;return typeof e=="function"?e():e}async*stream(e,n={}){let r;try{r=this.#u()}catch(u){yield{t:"error",kind:"auth",message:u instanceof Error?u.message:String(u),recoverable:!1};return}let o=Date.now(),i=le(n),s=n.signal!==void 0?AbortSignal.any([n.signal,i.signal]):i.signal,a=tn(e,{stream:!0,echoThinking:this.#r});this.#a(a);try{i.armConnect();let u;try{u=await this.#i(`${this.#e}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",authorization:`Bearer ${r}`,...this.#o},body:JSON.stringify(a),signal:s})}catch(g){yield this.#c(g,n,i.timeoutMessage(),"connect");return}if(i.armIdle(),!u.ok){yield await this.#s(u);return}if(u.body===null){yield{t:"error",kind:"server",message:"Empty response body from provider",recoverable:!0};return}let l=new K,c=new oe({fallbackModel:e.model.model}),p,f=g=>(p===void 0&&(g.t==="block_start"||g.t==="text_delta"||g.t==="thinking_delta"||g.t==="tool_args_delta")&&(p=Date.now()),g.t==="message_stop"&&p!==void 0?{...g,ttftMs:p-o}:g);try{for await(let g of u.body){i.armIdle();for(let b of l.push(g))for(let R of c.handleData(b))yield f(R);if(c.ended)return}}catch(g){yield this.#c(g,n,i.timeoutMessage(),"stream");return}for(let g of l.end())for(let b of c.handleData(g))yield f(b);for(let g of c.finish())yield f(g)}finally{i.dispose()}}async listModels(e={}){let n=await this.#i(`${this.#e}/models`,{method:"GET",headers:{authorization:`Bearer ${this.#u()}`,...this.#o},...e.signal!==void 0?{signal:e.signal}:{}});if(!n.ok)throw new Error(`Failed to list models: HTTP ${n.status}`);return Ae(await n.json())}#c(e,n,r,o){if(n.signal?.aborted===!0)throw e;let i=J(e);if(i!==void 0)return i;let s=typeof e=="object"&&e!==null&&"name"in e?String(e.name):"",a=s==="TimeoutError"||s==="AbortError",u=a?r:Q(e);return Y({t:"error",kind:o==="stream"?"stream_interrupted":a?"connect":"network",message:u,recoverable:!0},e)}async#s(e){let n="";try{n=await e.text()}catch{}let{kind:r,recoverable:o}=Oe(e.status,n),i=Pe(e.headers);return{t:"error",kind:r,message:`HTTP ${e.status}: ${n.slice(0,Fo)||e.statusText}`,recoverable:o,...i!==void 0?{retryAfterMs:i}:{}}}};var an="reasoning.encrypted_content";function ft(t,e={}){let n=e.stream??!0,r=e.background??!1,o=[];for(let a of t.messages)o.push(...Go(a,t.model.provider));let i={model:t.model.model,max_output_tokens:t.maxTokens,input:o,store:r,include:[an]},s=t.system.map(a=>a.text).join(`
|
|
15
15
|
|
|
16
16
|
`);return t.system.length>0&&s!==""&&(i.instructions=s),t.tools.length>0&&(i.tools=t.tools.map(wr)),t.temperature!==void 0&&(i.temperature=t.temperature),n&&(i.stream=!0),r&&(i.background=!0),i}function wr(t){return{type:"function",name:t.name,description:t.description,parameters:t.inputSchema}}function Go(t,e){return t.role==="user"?$o(t):Lo(t,e)}function $o(t){let e=[],n=[];for(let o of t.blocks)switch(o.t){case"text":n.push({type:"input_text",text:o.text});break;case"image":n.push({type:"input_image",image_url:vr(o.mime,o.data)});break;case"tool_result":e.push(xr(o));break;default:break}let r=[...e];return(n.length>0||e.length===0)&&r.push({role:"user",content:Ho(n)}),r}function Lo(t,e){let n=[],r=[],o=()=>{r.length!==0&&(n.push({role:"assistant",content:r.join(`
|
|
17
17
|
|
|
18
18
|
`)}),r=[])};for(let i of t.blocks)switch(i.t){case"text":r.push(i.text);break;case"thinking":break;case"opaque":{i.provider===e&&zo(i.payload)&&(o(),n.push(i.payload));break}case"tool_call":o(),n.push({type:"function_call",call_id:i.id,name:i.name,arguments:JSON.stringify(i.args??{})});break;case"tool_result":o(),n.push(xr(i));break;case"image":r.push(`[image omitted: ${i.mime}]`);break}return o(),n}function xr(t){return t.content.some(n=>n.t==="image")?{type:"function_call_output",call_id:t.callId,output:t.content.map(Ko)}:{type:"function_call_output",call_id:t.callId,output:t.content.map(n=>n.t==="text"?n.text:"").join(`
|
|
19
|
-
`)}}function Ko(t){return t.t==="text"?{type:"input_text",text:t.text}:{type:"input_image",image_url:vr(t.mime,t.data)}}function Ho(t){if(t.length===0)return"";let e=t[0];return t.length===1&&e!==void 0&&e.type==="input_text"?e.text:t}function zo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vr(t,e){return`data:${t};base64,${e}`}var _r=d.object({input_tokens:d.number().int().nonnegative().nullish(),output_tokens:d.number().int().nonnegative().nullish(),input_tokens_details:d.object({cached_tokens:d.number().int().nonnegative().nullish(),cache_write_tokens:d.number().int().nonnegative().nullish()}).nullish(),output_tokens_details:d.object({reasoning_tokens:d.number().int().nonnegative().nullish()}).nullish()}),Jo=d.object({id:d.string().nullish(),model:d.string().nullish(),status:d.string().nullish(),usage:_r.nullish(),error:d.unknown().nullish(),incomplete_details:d.object({reason:d.string().nullish()}).nullish()}),un=d.object({type:d.string(),response:Jo.nullish(),output_index:d.number().int().nullish(),item:d.unknown().nullish(),item_id:d.string().nullish(),delta:d.unknown().nullish(),code:d.string().nullish(),message:d.string().nullish(),param:d.string().nullish()});function ht(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t,n=e.type;if(typeof n!="string"||n==="")return null;let r={type:n};return typeof e.id=="string"&&(r.id=e.id),typeof e.call_id=="string"&&(r.callId=e.call_id),typeof e.name=="string"&&(r.name=e.name),typeof e.arguments=="string"&&(r.arguments=e.arguments),typeof e.encrypted_content=="string"&&(r.encryptedContent=e.encrypted_content),r}function gt(t){let e=t.input_tokens_details?.cached_tokens,n=t.input_tokens_details?.cache_write_tokens,r=t.output_tokens_details?.reasoning_tokens;return{inputTokens:mt(t.input_tokens??0,e??0),outputTokens:t.output_tokens??0,...e!=null?{cacheReadInputTokens:e}:{},...n!=null?{cacheCreationInputTokens:n}:{},...r!=null?{reasoningOutputTokens:r}:{}}}function dn(t){return t==null||t===""?"incomplete":t==="max_output_tokens"?"max_tokens":t}var pe=class{#e;#t;#o;#i=!1;#r=!1;#n=0;#a=new Map;#u=new Map;#c=new Map;#s=null;#d=new Set;#f=!1;#h;#p=[];#
|
|
19
|
+
`)}}function Ko(t){return t.t==="text"?{type:"input_text",text:t.text}:{type:"input_image",image_url:vr(t.mime,t.data)}}function Ho(t){if(t.length===0)return"";let e=t[0];return t.length===1&&e!==void 0&&e.type==="input_text"?e.text:t}function zo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vr(t,e){return`data:${t};base64,${e}`}var _r=d.object({input_tokens:d.number().int().nonnegative().nullish(),output_tokens:d.number().int().nonnegative().nullish(),input_tokens_details:d.object({cached_tokens:d.number().int().nonnegative().nullish(),cache_write_tokens:d.number().int().nonnegative().nullish()}).nullish(),output_tokens_details:d.object({reasoning_tokens:d.number().int().nonnegative().nullish()}).nullish()}),Jo=d.object({id:d.string().nullish(),model:d.string().nullish(),status:d.string().nullish(),usage:_r.nullish(),error:d.unknown().nullish(),incomplete_details:d.object({reason:d.string().nullish()}).nullish()}),un=d.object({type:d.string(),response:Jo.nullish(),output_index:d.number().int().nullish(),item:d.unknown().nullish(),item_id:d.string().nullish(),delta:d.unknown().nullish(),code:d.string().nullish(),message:d.string().nullish(),param:d.string().nullish()});function ht(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t,n=e.type;if(typeof n!="string"||n==="")return null;let r={type:n};return typeof e.id=="string"&&(r.id=e.id),typeof e.call_id=="string"&&(r.callId=e.call_id),typeof e.name=="string"&&(r.name=e.name),typeof e.arguments=="string"&&(r.arguments=e.arguments),typeof e.encrypted_content=="string"&&(r.encryptedContent=e.encrypted_content),r}function gt(t){let e=t.input_tokens_details?.cached_tokens,n=t.input_tokens_details?.cache_write_tokens,r=t.output_tokens_details?.reasoning_tokens;return{inputTokens:mt(t.input_tokens??0,e??0),outputTokens:t.output_tokens??0,...e!=null?{cacheReadInputTokens:e}:{},...n!=null?{cacheCreationInputTokens:n}:{},...r!=null?{reasoningOutputTokens:r}:{}}}function dn(t){return t==null||t===""?"incomplete":t==="max_output_tokens"?"max_tokens":t}var pe=class{#e;#t;#o;#i=!1;#r=!1;#n=0;#a=new Map;#u=new Map;#c=new Map;#s=null;#d=new Set;#f=!1;#h;#p=[];#b=new Set;constructor(e={}){this.#e=e.fallbackModel??"unknown",this.#t=e.providerId??"",this.#o=e.onIgnoredOutputItem}get ended(){return this.#r}get ignoredItems(){return this.#p}handleData(e){if(this.#r)return[];if(e.trim()===Be)return this.#l("unknown");let n;try{n=JSON.parse(e)}catch{return[]}let r=un.safeParse(n);if(!r.success)return[];let o=r.data,i=[];switch(this.#i||(i.push({t:"message_start",model:o.response?.model??this.#e}),this.#i=!0),o.type){case"response.output_item.added":this.#m(o,i);break;case"response.output_item.done":this.#g(o,i);break;case"response.output_text.delta":this.#y(o,i);break;case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":this.#v(o,i);break;case"response.function_call_arguments.delta":this.#C(o,i);break;case"response.completed":{o.response?.usage!=null&&(this.#h=gt(o.response.usage)),i.push(...this.#l(this.#f?"tool_use":"end_turn"));break}case"response.incomplete":{o.response?.usage!=null&&(this.#h=gt(o.response.usage)),i.push(...this.#l(dn(o.response?.incomplete_details?.reason)));break}case"response.failed":{this.#r=!0,i.push(de(o.response?.error??"Response failed"));break}case"error":{this.#r=!0,i.push(de({...o.message!=null?{message:o.message}:{},...o.code!=null?{code:o.code}:{}}));break}default:break}return i}finish(){return this.#r?[]:this.#l("unknown")}#m(e,n){let r=ht(e.item);if(r!==null)switch(r.type){case"message":case"reasoning":break;case"function_call":this.#w(r.id??`#${e.output_index??0}`,r,n);break;default:this.#R(r,e.output_index);break}}#g(e,n){let r=ht(e.item);if(r!==null)switch(r.type){case"message":{let o=r.id??`#${e.output_index??0}`,i=this.#a.get(o);i!==void 0&&this.#d.has(i)&&this.#k(i,n);break}case"function_call":{let o=r.id??`#${e.output_index??0}`,i=this.#c.get(o)??this.#w(o,r,n);!i.argsSeen&&r.arguments!==void 0&&r.arguments!==""&&(n.push({t:"tool_args_delta",index:i.index,json:r.arguments}),i.argsSeen=!0),this.#d.has(i.index)&&this.#k(i.index,n);break}case"reasoning":{let o=r.id??`#${e.output_index??0}`,i=this.#u.get(o);if(i!==void 0&&this.#d.has(i)&&this.#k(i,n),r.encryptedContent!==void 0&&r.encryptedContent!==""){let s=this.#n;this.#n+=1,n.push({t:"block_start",index:s,block:{t:"opaque",provider:this.#t,payload:e.item}}),n.push({t:"block_stop",index:s})}break}default:this.#R(r,e.output_index);break}}#y(e,n){if(typeof e.delta!="string"||e.delta==="")return;let r=e.item_id??`#${e.output_index??0}`,o=this.#a.get(r);o===void 0&&(o=this.#n,this.#n+=1,this.#a.set(r,o),this.#d.add(o),n.push({t:"block_start",index:o,block:{t:"text",text:""}})),n.push({t:"text_delta",index:o,text:e.delta})}#v(e,n){if(typeof e.delta!="string"||e.delta==="")return;let r=e.item_id??`#${e.output_index??0}`,o=this.#u.get(r);o===void 0&&(o=this.#n,this.#n+=1,this.#u.set(r,o),this.#d.add(o),n.push({t:"block_start",index:o,block:{t:"thinking",text:""}})),n.push({t:"thinking_delta",index:o,text:e.delta})}#C(e,n){if(typeof e.delta!="string"||e.delta==="")return;let r=e.item_id??this.#s??`#${e.output_index??0}`,o=this.#c.get(r)??this.#w(r,{},n);o.argsSeen=!0,n.push({t:"tool_args_delta",index:o.index,json:e.delta})}#w(e,n,r){let o=this.#n;this.#n+=1;let i={index:o,argsSeen:!1};this.#c.set(e,i),this.#s=e,this.#d.add(o),this.#f=!0;let s=n.callId??(e.startsWith("#")?`call_auto_${o}`:e);return r.push({t:"block_start",index:o,block:{t:"tool_call",id:s,name:n.name??"",args:{}}}),i}#k(e,n){this.#d.delete(e),n.push({t:"block_stop",index:e})}#R(e,n){let r=e.id??`${e.type}#${n??-1}`;if(this.#b.has(r))return;this.#b.add(r);let o={type:e.type,...e.id!==void 0?{id:e.id}:{}};this.#p.push(o),this.#o?.(o)}#l(e){let n=[];this.#i||(n.push({t:"message_start",model:this.#e}),this.#i=!0);for(let r of[...this.#d].sort((o,i)=>o-i))n.push({t:"block_stop",index:r});return this.#d.clear(),n.push({t:"message_stop",stopReason:e,...this.#h!==void 0?{usage:this.#h}:{}}),this.#r=!0,n}};var Yo=600,me=class{#e;#t;#o;#i;#r;#n;constructor(e){this.#e=e.baseUrl.replace(/\/+$/,""),this.#t=e.apiKey,this.#o=e.defaultHeaders??{},this.#i=e.fetchImpl??fetch,this.#r=e.background??!1,this.#n=e.onIgnoredOutputItem}#a(){let e=this.#t;return typeof e=="function"?e():e}async*stream(e,n={}){let r;try{r=this.#a()}catch(a){yield{t:"error",kind:"auth",message:a instanceof Error?a.message:String(a),recoverable:!1};return}let o=Date.now(),i=le(n),s=n.signal!==void 0?AbortSignal.any([n.signal,i.signal]):i.signal;try{i.armConnect();let a;try{a=await this.#i(`${this.#e}/responses`,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",authorization:`Bearer ${r}`,...this.#o},body:JSON.stringify(ft(e,{stream:!0,background:this.#r})),signal:s})}catch(f){yield this.#u(f,n,i.timeoutMessage(),"connect");return}if(i.armIdle(),!a.ok){yield await this.#c(a);return}if(a.body===null){yield{t:"error",kind:"server",message:"Empty response body from provider",recoverable:!0};return}let u=new K,l=new pe({fallbackModel:e.model.model,providerId:e.model.provider,...this.#n!==void 0?{onIgnoredOutputItem:this.#n}:{}}),c,p=f=>(c===void 0&&(f.t==="block_start"||f.t==="text_delta"||f.t==="thinking_delta"||f.t==="tool_args_delta")&&(c=Date.now()),f.t==="message_stop"&&c!==void 0?{...f,ttftMs:c-o}:f);try{for await(let f of a.body){i.armIdle();for(let g of u.push(f))for(let b of l.handleData(g))yield p(b);if(l.ended)return}}catch(f){yield this.#u(f,n,i.timeoutMessage(),"stream");return}for(let f of u.end())for(let g of l.handleData(f))yield p(g);for(let f of l.finish())yield p(f)}finally{i.dispose()}}async listModels(e={}){let n=await this.#i(`${this.#e}/models`,{method:"GET",headers:{authorization:`Bearer ${this.#a()}`,...this.#o},...e.signal!==void 0?{signal:e.signal}:{}});if(!n.ok)throw new Error(`Failed to list models: HTTP ${n.status}`);return Ae(await n.json())}#u(e,n,r,o){if(n.signal?.aborted===!0)throw e;let i=J(e);if(i!==void 0)return i;let s=typeof e=="object"&&e!==null&&"name"in e?String(e.name):"",a=s==="TimeoutError"||s==="AbortError",u=a?r:Q(e);return Y({t:"error",kind:o==="stream"?"stream_interrupted":a?"connect":"network",message:u,recoverable:!0},e)}async#c(e){let n="";try{n=await e.text()}catch{}let{kind:r,recoverable:o}=Oe(e.status,n),i=Pe(e.headers);return{t:"error",kind:r,message:`HTTP ${e.status}: ${n.slice(0,Yo)||e.statusText}`,recoverable:o,...i!==void 0?{retryAfterMs:i}:{}}}};var ln="transportIdempotencyKey";function We(t){if(t===void 0)return;let e=t[ln];return typeof e=="string"&&e.length>0?e:void 0}function cn(t,e){return{...t,[ln]:e}}import{createHash as Cr,createHmac as Qo,randomBytes as Vo}from"node:crypto";var Er="TWP1-HMAC-SHA256",Tr=24;function pn(t){return Cr("sha256").update(t,"utf8").digest()}function Ir(t){return Cr("sha256").update(typeof t=="string"?Buffer.from(t,"utf8"):t).digest("hex")}function Mr(t=Vo){return t(Tr/2).toString("hex")}function Sr(t){return[Er,t.method.toUpperCase(),t.pathWithQuery,t.ts,t.nonce,t.bodyHashHex].join(`
|
|
20
20
|
`)}function Ar(t,e){return Qo("sha256",t).update(e,"utf8").digest("hex")}function mn(t){let e=Math.floor((t.now??Date.now)()/1e3).toString(10),n=t.nonce??Mr(),r=Ar(t.signingKey,Sr({method:t.method,pathWithQuery:t.pathWithQuery,ts:e,nonce:n,bodyHashHex:Ir(t.body??"")}));return{"x-tansr-ts":e,"x-tansr-nonce":n,"x-tansr-sign":r}}var Or="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function fe(t=Date.now(),e=Math.random){let n="",r=t;for(let o=0;o<10;o++)n=Or[r%32]+n,r=Math.floor(r/32);for(let o=0;o<16;o++)n+=Or[Math.floor(e()*32)];return n}var V=class extends Error{reason;role;mime;constructor(e,n,r){super(e==="gate_closed"?`twp image block blocked at wire layer: send gate closed (platform image-input feature or model capability not satisfied); whole request rejected — nothing sent, nothing billed (mime=${r}, role=${n})`:`twp image block blocked at wire layer: image blocks are only accepted on user messages (twp/1 vocabulary); whole request rejected — nothing sent, nothing billed (mime=${r}, role=${n})`),this.name="TwpImageWireError",this.reason=e,this.role=n,this.mime=r}};function Zo(t){return t.content.map(e=>e.t==="text"?e.text:"[image: see next user message]").join(`
|
|
21
|
-
`)}function ei(t,e,n){let r=[];for(let o of t)switch(o.t){case"text":r.push({t:"text",v:o.text});break;case"tool_call":r.push({t:"tool_use",id:o.id,name:o.name,input:o.args??{}});break;case"tool_result":r.push({t:"tool_result",toolUseId:o.callId,v:Zo(o),...o.isError!==void 0?{isError:o.isError}:{}});break;case"image":if(e!=="user")throw new V("role_not_user",e,o.mime);if(!n)throw new V("gate_closed",e,o.mime);r.push({t:"image",mime:o.mime,v:o.data});break;case"thinking":case"opaque":break}return r}function ti(t,e){let n=[];for(let o of t.blocks){if(o.t!=="tool_result")continue;let i=0;for(let s of o.content)if(s.t==="image"){if(t.role!=="user")throw new V("role_not_user",t.role,s.mime);if(!e)throw new V("gate_closed",t.role,s.mime);n.push({t:"text",v:`Tool output image (call ${o.callId}, image ${++i}):`}),n.push({t:"image",mime:s.mime,v:s.data})}}let r=ei(t.blocks,t.role,e);return r.length===0?[]:[{role:t.role,blocks:r},...n.length>0?[{role:"user",blocks:n}]:[]]}function ni(t){return t<=1024?"low":t<=4096?"medium":"high"}function fn(t,e={}){let n=e.sendImages??!1,r=e.cacheHints??!1,o=[],i=t.system.filter(u=>u.text!=="").map(u=>r&&u.cacheable===!0?{t:"text",v:u.text,cacheable:!0}:{t:"text",v:u.text});i.length>0&&o.push({role:"system",blocks:i});for(let u of t.messages)o.push(...ti(u,n));let s=r?{...t.skipCacheWrite===!0?{skipWrite:!0}:{},...e.cacheKey!==void 0?{key:e.cacheKey}:{}}:void 0,a=s!==void 0&&Object.keys(s).length>0;return{model:t.model.model,thread:o,...t.tools.length>0?{tools:t.tools.map(u=>({name:u.name,description:u.description,inputSchema:u.inputSchema}))}:{},params:{maxTokens:t.maxTokens,...t.temperature!==void 0?{temperature:t.temperature}:{},...t.stopSequences!==void 0&&t.stopSequences.length>0?{stop:[...t.stopSequences]}:{},...t.promptTokensEstimate!==void 0&&Math.ceil(t.promptTokensEstimate)>=1?{promptTokensEstimate:Math.ceil(t.promptTokensEstimate)}:{},...e.reasoningOff===!0&&t.thinking?.off===!0?{reasoning:"off"}:e.reasoningLevels===!0&&t.thinking?.off!==!0&&typeof t.thinking?.budget=="number"&&t.thinking.budget>0?{reasoning:ni(t.thinking.budget)}:{}},meta:{requestId:e.requestId??fe(),...e.sessionId!==void 0?{sessionId:e.sessionId}:{},...e.client!==void 0?{client:e.client}:{},...e.purpose!==void 0?{purpose:e.purpose}:{}},...a?{cache:s}:{},stream:e.stream??!0}}function bt(t){switch(t){case null:case void 0:case"end":return"end_turn";case"tool_use":return"tool_use";case"max_tokens":return"max_tokens";default:return t}}function yt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.round(t):0}var ri=/^-?\d+(?:\.\d+)?$/,oi=new Set(["in","out","cache_r","cache_w"]);function ii(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e={};for(let[n,r]of Object.entries(t))oi.has(n)||typeof r!="number"||!Number.isSafeInteger(r)||r<=0||(e[n]=r);return Object.keys(e).length>0?e:void 0}function De(t){let e=ii(t.dims),n=t.saved,r=typeof n=="string"&&ri.test(n.trim())?n.trim():void 0;return{inTokens:yt(t.inTokens),outTokens:yt(t.outTokens),cacheRTokens:yt(t.cacheRTokens),cacheWTokens:yt(t.cacheWTokens),...typeof t.cost=="string"?{cost:t.cost}:{},...typeof t.currency=="string"?{currency:t.currency}:{},...typeof t.balanceAfter=="string"?{balanceAfter:t.balanceAfter}:{},...e!==void 0?{dims:e}:{},...r!==void 0?{saved:r}:{},...t.estimated===!0?{estimated:!0}:{},...t.estimated===!0&&typeof t.estimatedReason=="string"&&t.estimatedReason!==""?{estimatedReason:t.estimatedReason}:{}}}function je(t){return{inputTokens:t.inTokens,outputTokens:t.outTokens,...t.cacheRTokens>0?{cacheReadInputTokens:t.cacheRTokens}:{},...t.cacheWTokens>0?{cacheCreationInputTokens:t.cacheWTokens}:{},...t.dims!==void 0?{dims:t.dims}:{},...t.saved!==void 0?{saved:t.saved}:{}}}var si=Mt;function ai(t){if(t===void 0)return;let e=t.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return j(Math.round(e));let n=t.retryAfterSec??t.retryAfterSeconds??t.retry_after;if(typeof n=="number"&&Number.isFinite(n)&&n>=0)return j(Math.round(n*1e3))}var Pr=new Set(["plan_concurrency_exceeded","plan_end_users_exceeded","plan_required","plan_tier_insufficient"]);function Br(t){return Pr.has(t)?{scope:"plan"}:void 0}function qe(t,e,n){let r=`${t}: ${e}`,o=ai(n),i=si[t],s=Br(t);return i!==void 0?{kind:i.kind,message:r,recoverable:n?.retryable===!1?!1:i.recoverable,...o!==void 0?{retryAfterMs:o}:{},...s!==void 0?{detail:s}:{}}:{kind:"invalid_request",message:r,recoverable:!1,...s!==void 0?{detail:s}:{}}}function hn(t,e){let n=`HTTP ${t}: ${e}`;return t===401||t===403?{kind:"auth",message:n,recoverable:!1}:t===429?{kind:"rate_limited",message:n,recoverable:!0}:t>=500?{kind:"server",message:n,recoverable:!0}:{kind:"invalid_request",message:n,recoverable:!1}}function Ue(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gn(t,e){if(!Ue(t))return[{t:"error",kind:"server",message:"twp non-stream response is not a JSON object",recoverable:!0}];let n=[];n.push({t:"message_start",model:typeof t.model=="string"?t.model:e});let r=Array.isArray(t.blocks)?t.blocks:[],o=0;for(let s of r)Ue(s)&&(s.t==="text"&&typeof s.v=="string"?(n.push({t:"block_start",index:o,block:{t:"text",text:s.v}}),n.push({t:"block_stop",index:o}),o+=1):s.t==="tool_use"&&typeof s.id=="string"&&typeof s.name=="string"&&(n.push({t:"block_start",index:o,block:{t:"tool_call",id:s.id,name:s.name,args:s.input??{}}}),n.push({t:"block_stop",index:o}),o+=1));let i=Ue(t.usage)?je(De(t.usage)):void 0;return n.push({t:"message_stop",stopReason:bt(typeof t.stop=="string"?t.stop:void 0),...i!==void 0?{usage:i}:{}}),n}function yn(t){return!Ue(t)||!Ue(t.usage)?null:De(t.usage)}var Ne=class{#e;#t=new Map;#o=null;#i=null;#r=!1;#n=!1;#a=null;constructor(e={}){this.#e=e}get ended(){return this.#n}handleFrame(e){if(this.#n)return[];let n;try{n=JSON.parse(e.data)}catch{return[]}let r=typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null;if(r===null)return[];switch(e.event){case Z.open:return this.#u(r);case Z.delta:return this.#c(r);case Z.usage:{let o=De(r);return this.#i=o,this.#e.onUsage?.(o),[]}case Z.warn:return this.#e.onWarn?.({code:typeof r.code=="string"?r.code:"unknown",message:typeof r.message=="string"?r.message:""}),[];case Z.close:return this.#d(r);case Z.err:return this.#f(r);default:return[]}}finish(){if(this.#n)return[];this.#n=!0;let e=this.#h();return e.push({t:"message_stop",stopReason:"unknown",...this.#i!==null?{usage:je(this.#i)}:{}}),e}#u(e){return this.#r?[]:(this.#r=!0,[{t:"message_start",model:typeof e.model=="string"?e.model:this.#e.fallbackModel??"unknown"}])}#c(e){let n=e.seq;if(typeof n=="number"&&Number.isInteger(n)){if(this.#a!==null&&n<=this.#a)return this.#n=!0,[{t:"error",kind:"server",message:`twp protocol error: t.delta.seq not monotonic (${n} after ${this.#a})`,recoverable:!1}];this.#a=n}let r=e.i;if(typeof r!="number"||!Number.isInteger(r)||r<0)return[];let o=[];this.#r||(this.#r=!0,o.push({t:"message_start",model:this.#e.fallbackModel??"unknown"}));let i=e.t;if(i==="text"){let s=e.v;return typeof s!="string"||(o.push(...this.#s(r,"text",e)),o.push({t:"text_delta",index:r,text:s})),o}if(i==="thinking"){let s=e.v;return typeof s!="string"||(o.push(...this.#s(r,"thinking",e)),o.push({t:"thinking_delta",index:r,text:s})),o}if(i==="tool_use"){o.push(...this.#s(r,"tool_use",e));let s=e.vJson;return typeof s=="string"&&s!==""&&o.push({t:"tool_args_delta",index:r,json:s}),o}return o}#s(e,n,r){let o=[];return this.#t.has(e)?(this.#o=e,o):(this.#o!==null&&this.#o!==e&&this.#t.has(this.#o)&&(o.push({t:"block_stop",index:this.#o}),this.#t.delete(this.#o)),n==="text"?o.push({t:"block_start",index:e,block:{t:"text",text:""}}):n==="thinking"?o.push({t:"block_start",index:e,block:{t:"thinking",text:""}}):o.push({t:"block_start",index:e,block:{t:"tool_call",id:typeof r.id=="string"?r.id:`tu_${e}`,name:typeof r.name=="string"?r.name:"",args:{}}}),this.#t.set(e,{kind:n}),this.#o=e,o)}#d(e){this.#n=!0;let n=this.#h();return n.push({t:"message_stop",stopReason:bt(typeof e.stop=="string"?e.stop:void 0),...this.#i!==null?{usage:je(this.#i)}:{}}),n}#f(e){this.#n=!0;let n=typeof e.code=="string"?e.code:"unknown",r=typeof e.message=="string"?e.message:"",o=e.detail,i=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:void 0;return this.#e.onErr?.({code:n,message:r,...typeof e.requestId=="string"?{requestId:e.requestId}:{},...i!==void 0?{detail:i}:{}}),[{t:"error",...qe(n,r,i)}]}#h(){let e=[];for(let n of this.#t.keys())e.push({t:"block_stop",index:n});return this.#t.clear(),this.#o=null,e}};import{createHash as ie,randomUUID as fi}from"node:crypto";var Fe=new WeakMap;function Wr(t,e){if(Fe.has(t))throw new Error("continuity target already registered");Fe.set(t,Object.freeze(e))}function aa(t,e){let n=Fe.get(t);if(!n)throw new Error("continuity target unavailable");return n.retire(e)}function ua(t,e){let n=Fe.get(t);if(!n)throw new Error("continuity target unavailable");n.adopt(e)}async function da(t,e){let n=Fe.get(t);if(!n)throw new Error("continuity target unavailable");await n.heartbeat(e)}var bn=new WeakMap;function Ur(t,e){if(bn.has(t))throw new Error("cache retirement target already registered");bn.set(t,Object.freeze(e))}function ca(t){let e=bn.get(t);if(!e)throw new Error("cache retirement target unavailable");return e.status()}import{createHash as ui}from"node:crypto";var $="sdk2-cache-v1",Ke="private-logical-cache-v1",kn="application/vnd.tansr.cache-exchange.v1",di=33554432,X=d.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._~-]*$/),li=d.string().refine(t=>[...t].length>0&&[...t].length<=512),Ge=d.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(t=>BigInt(t)<=9223372036854775807n),$e=d.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>Buffer.from(t,"base64url").toString("base64url")===t),Le=d.string().datetime({offset:!0}),He=d.literal($),H=d.object({operationEpoch:X,requestId:X}).strict(),kt=d.discriminatedUnion("kind",[d.object({kind:d.literal("new")}).strict(),d.object({kind:d.literal("import")}).strict(),d.object({kind:d.literal("resume"),ticket:$e}).strict(),d.object({kind:d.literal("fork"),parentTicket:$e}).strict()]),ci=d.object({projectionRef:X,revision:Ge,status:d.enum(["current","rebuild-required","missing"]),reason:d.enum(["unchanged","policy-changed","generation-changed","provider-changed","source-missing","legacy-missing","key-rotated"])}).strict(),ze=d.object({protocol:He,audience:d.literal("gateway-cache"),bindingId:X,logicalRef:X,revision:Ge,state:d.enum(["active","closed","revoked","expired"]),mode:d.literal("private-logical-v1"),groupGeneration:Ge,projection:ci.nullable(),expiresAt:Le,availability:d.literal("legacy-complete")}).strict(),Je=d.object({protocol:He,request:H,binding:ze,ticket:$e,ticketExpiresAt:Le,relation:d.enum(["new","resumed","forked","imported"])}).strict(),Rt=d.object({protocol:He,request:H,operation:d.enum(["open","renew","rotate","close","rebind"]),semanticDigest:d.object({algorithm:d.literal("hmac-sha256"),keyId:X,digest:d.string().regex(/^[a-f0-9]{64}$/)}).strict(),state:d.literal("completed"),binding:ze,ticket:$e.nullable(),ticketExpiresAt:Le.nullable()}).strict(),pi={controlBytes:[4096,65536],exchangeBytes:[1024,33554432],projectionBytes:[1024,262144],projectionSegments:[1,64],ticketTtlMs:[6e4,6048e5],mappingIdleMs:[6e4,6048e5],mappingLifetimeMs:[6e4,2592e6],bindingsPerLogical:[1,16],mappingsPerUser:[1,1e3],mappingsPerApplication:[1,1e4],mappingsGlobal:[1,1e5],mappingBytes:[1024,16384],receiptsGlobal:[1,1e5],receiptBytes:[1024,32768],receiptRetentionMs:[6e4,6048e5],epochLifetimeMs:[6e4,864e5],diagnosticRowsPerUser:[1,1e3],diagnosticRowsPerApplication:[1,1e4],diagnosticRowsGlobal:[1,1e5],diagnosticBytes:[1024,4096],diagnosticRetentionMs:[6e4,864e5],diagnosticSamplePerMillion:[0,1e6],diagnosticsPageRows:[1,100],negotiatedTtlMs:[1e3,6e4],retainedRowsPerUser:[1,1e4],retainedRowsPerApplication:[1,1e5],retainedRowsGlobal:[1,1e6],retainedBytesPerUser:[1,16777216],retainedBytesPerApplication:[1,268435456],retainedBytesGlobal:[1,2147483648]},mi=d.object(Object.fromEntries(Object.entries(pi).map(([t,[e,n]])=>[t,d.number().int().min(e).max(n)]))).strict(),Dr=d.object({protocol:He,audience:d.literal("gateway-cache"),features:d.array(d.literal(Ke)).max(1),gateway:d.literal("not-applicable"),availability:d.literal("legacy-complete"),revision:Ge,limits:mi,operationEpoch:d.object({id:X,issuedAt:Le,expiresAt:Le,state:d.literal("active")}).strict().nullable()}).strict().refine(t=>t.features.length===0||t.operationEpoch!==null),jr=d.object({protocol:He,requestId:X,code:d.enum(["invalid_request","protocol_version_mismatch","unauthorized","forbidden","stale_revision","stale_generation","request_id_conflict","projection_stale","ticket_expired","mapping_expired","receipt_expired","payload_too_large","unsupported_capability","capacity_exceeded","epoch_unavailable","mapping_unavailable","result_unknown"]),status:d.number().int().min(400).max(503),retryAction:d.enum(["none","same-request","query-status","refresh-projection"]),fallback:d.enum(["none","legacy-cold"]),message:d.string().min(1).max(256)}).strict();function F(t){return X.parse(t)}function wt(t){return li.parse(t)}function qr(t){return Ge.parse(t)}function xt(t){return $e.parse(t)}function Rn(t,e,n){let r=Buffer.from(n,"utf8");if(r.length<1||r.length>di||r.toString("utf8")!==n)throw new TypeError("invalid_request");let o=JSON.parse(n);if(!/^[A-Za-z0-9_-]{8,40}$/.test(e)||o?.meta?.requestId!==e||o.meta.sessionId!==t.runtimeSessionId)throw new TypeError("request_id_conflict");let i=M({protocol:$,bindingId:F(t.bindingId),ticket:xt(t.ticket),runtimeSessionId:wt(t.runtimeSessionId),projectionRef:F(t.projectionRef),payloadBytes:r.length,payloadSha256:ui("sha256").update(r).digest("hex")}),s=Buffer.allocUnsafe(4+i.length+r.length);return s.writeUInt32BE(i.length),s.set(i,4),s.set(r,4+i.length),s}var h=class extends Error{constructor(n,r,o,i="none"){super(`SDK2 cache: ${/^[a-z][a-z0-9_]{0,63}$/.test(n)?n:"invalid_response"}`);this.code=n;this.requestId=r;this.status=o;this.retryAction=i;this.name="GatewayCacheError"}code;requestId;status;retryAction;fallback="none"},wn=(t,e)=>`control/${ie("sha256").update(t).update("\0").update(e).digest("hex")}`;function Nr(t){let e=G(t.body);return{operation:t.operation,request:H.parse(e.request),bindingId:t.operation==="open"?null:F(e.bindingId??""),completed:!0}}var hi=d.object({applicationScopeId:d.string(),endUserId:d.string(),sourceNamespace:d.string(),intentDigest:d.string().regex(/^[a-f0-9]{64}$/),receiptDigest:d.string().regex(/^[a-f0-9]{64}$/),bindingId:d.string()}).strict(),$r=d.object({bindingId:d.string().refine(t=>{try{return F(t)===t}catch{return!1}}),kind:d.enum(["close","continuity-resume","continuity-delete"]),digest:d.string().regex(/^[a-f0-9]{64}$/)}).strict(),gi=d.object({format:d.literal("sdk2-cache-client-retired-v1"),baseUrl:d.string(),runtimeSessionId:d.string(),proof:$r,compactedControls:d.number().int().min(0).max(128),compactedExchanges:d.number().int().min(0).max(4096),continuityScope:d.object({applicationScopeId:d.string(),endUserId:d.string()}).strict().optional()}).strict(),vt=t=>/^[A-Za-z0-9_-]{8,40}$/.test(t),yi=d.object({protocol:d.literal($),rows:d.array(d.never()).max(0),next:d.null()}).strict();function Fr(t,e){let n=new AbortController,r=setTimeout(()=>n.abort(new DOMException("The operation was aborted due to timeout","TimeoutError")),t);return r.unref(),{signal:e?AbortSignal.any([e,n.signal]):n.signal,close:()=>clearTimeout(r)}}async function _t(t,e=65536){if(t.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()!=="application/json"||t.body===null)throw await t.body?.cancel(),new h("invalid_response");let r=t.body.getReader(),o=[],i=0;try{for(;;){let{done:s,value:a}=await r.read();if(s)break;if(i+=a.byteLength,i>e)throw await r.cancel(),new h("payload_too_large");o.push(a)}return e===1048576?$n(Buffer.concat(o)):G(Buffer.concat(o))}finally{r.releaseLock()}}async function he(t,e){try{let n=await _t(t),r=jr.safeParse(n);if(r.success&&r.data.status===t.status)return new h(r.data.code,e,t.status,r.data.retryAction);let o=d.object({error:d.object({code:d.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).passthrough()}).passthrough().safeParse(n);if(o.success)return new h(o.data.error.code,e,t.status)}catch{}return new h("result_unknown",e,t.status,"query-status")}function Gr(t){return{enabled:t.features.includes(Ke),operationEpoch:t.operationEpoch?{id:t.operationEpoch.id,expiresAt:t.operationEpoch.expiresAt}:null,limits:{controlBytes:t.limits.controlBytes,exchangeBytes:t.limits.exchangeBytes}}}var xn=class{#e;#t;#o;runtimeSessionId;#i;#r=!1;#n;#a;#u;#c;#s=new Map;#d=new Set;#f;#h=!1;#p;#R=!1;#m=new Map;#y;#b;#x=!1;#_=0;#w=0;constructor(e){let n=new URL(e.baseUrl);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash||!/\/t1\/?$/.test(n.pathname))throw new h("invalid_request");if(e.timeoutMs!==void 0&&(!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>3e5))throw new h("invalid_request");if(this.#e={...e,...e.continuityScope?{continuityScope:Object.freeze({applicationScopeId:F(e.continuityScope.applicationScopeId),endUserId:wt(e.continuityScope.endUserId)})}:{}},this.#t=e.baseUrl.replace(/\/+$/,""),this.#o=e.fetchImpl??fetch,this.runtimeSessionId=wt(e.runtimeSessionId),this.#f=Object.freeze({runtimeSessionId:this.runtimeSessionId,originalBody:r=>(this.#l(),this.#s.get(r)?.body),prepare:(r,o)=>this.#B(r,o),finish:r=>{this.#l();let o=this.#s.get(r);if(!o?.active)throw new h("result_unknown",r,void 0,"query-status");this.#g({put:[{key:`completed/${r}`,value:new Uint8Array}],delete:[`exchange/${r}`,`flight/${r}`,...o.core?[`core-exchange/${r}`]:[]]}),this.#s.delete(r),this.#d.add(r)},uncertain:r=>{this.#l();let o=this.#s.get(r);o?.active&&(o.uncertain=!0,o.active=!1)}}),e.persistence){let r=e.persistence.load({baseUrl:this.#t,runtimeSessionId:this.runtimeSessionId});r.length===0?this.#g({put:[{key:"meta",value:this.#C()}],delete:[]}):this.#W(r)}this.#w=this.#M(),this.#e.continuityScope&&e.persistence&&Wr(this,{adopt:r=>this.#D(r),heartbeat:r=>this.#T(r),retire:r=>this.#U(r)}),Ur(this,{status:()=>(this.#k(),this.#y?structuredClone(this.#y):void 0),retireClosed:()=>{if(this.#k(),!this.#e.persistence)throw new h("mapping_unavailable");let r=this.#y?.proof??this.#b;if(!r||r.kind!=="close")throw new h("mapping_unavailable");return this.#A(r)}})}#k(){if(this.#h)throw new h("storage_unknown",void 0,void 0,"query-status")}#l(){if(this.#k(),this.#y)throw new h("runtime_retired")}#g(e){if(this.#l(),!(!this.#e.persistence||this.#R))try{this.#e.persistence.commit(e)}catch{throw this.#h=!0,new h("storage_unknown",void 0,void 0,"query-status")}}#C(e=this.#a,n=this.#u,r=this.#c,o=this.#p,i=this.#b??null){return M({format:this.#x?"sdk2-cache-client-core-v1":"sdk2-cache-client-v1",baseUrl:this.#t,runtimeSessionId:this.runtimeSessionId,binding:e??null,opened:n??null,openedIntent:r??null,...o?{continuity:o}:{},...i?{terminalProof:i}:{}})}#I(e){return M({operation:e.operation,body:Buffer.from(e.body).toString("base64"),result:e.result})}pendingControl(){return this.#l(),this.#n?.handle}pendingExchanges(){return this.#l(),[...this.#s].map(([e,n])=>({requestId:e,uncertain:n.uncertain,active:n.active}))}#M(){return[...this.#s.values()].reduce((e,n)=>e+n.frame.length+Buffer.byteLength(n.body)+(n.core?se(n.core).byteLength:0),0)}readInventory(){this.#k();let e=this.#n?.body.byteLength??0,n=this.#M();return{retired:this.#y!==void 0,pendingControlBytes:e,pendingExchangeBytes:n,pendingBytes:e+n,pendingControls:+(this.#n!==void 0),pendingExchanges:this.#s.size,highWaterPendingControlBytes:this.#_,highWaterPendingExchangeBytes:this.#w,highWaterPendingBytes:Math.max(this.#_,this.#w),pendingControlCapBytes:65536,pendingExchangeCapBytes:67108864,pendingCapBytes:67108864}}async lookupPending(e,n,r){this.#l();let o=this.#s.get(e);if(!o?.core||!n.lookupCredential)throw new h("core_source_missing",e);if(o.active||this.#n)throw new h("pending_execution",e);let i=Fr(this.#e.timeoutMs??3e4,r),s=i.signal;try{n.assertCurrent(o.core);let a=await this.#e.token();if(typeof a!="string"||!a||a.trim()!==a||/[\r\n]/.test(a))throw new h("unauthorized",e);let u=await n.lookupCredential(structuredClone(o.core),s);if(n.assertCurrent(o.core),this.#l(),s.throwIfAborted(),this.#s.get(e)!==o||o.active||this.#n)throw new h("pending_execution",e);if(typeof u!="string"||u.length>8192||!/^[A-Za-z0-9_-]+$/.test(u))throw new h("invalid_request",e);let l=await this.#o(`${this.#t}${be}/exchange/lookup`,{method:"POST",redirect:"error",headers:{"content-type":kn,accept:"application/json","x-tansr-app-token":a,[Wt]:u},body:Buffer.from(o.frame),signal:s});if(l.status!==200)throw await he(l,e);let c=zn.parse(await _t(l,1048576));return this.#l(),n.assertCurrent(o.core),c}finally{i.close()}}readLocalBinding(){if(this.#l(),this.#n)return null;let e=this.#a?.view;return e?{revision:e.revision,state:e.state,mode:e.mode,groupGeneration:e.groupGeneration,projection:e.projection?{revision:e.projection.revision,status:e.projection.status,reason:e.projection.reason}:null,expiresAt:e.expiresAt,availability:e.availability}:null}async resumePendingControl(e,n){if(this.#l(),!this.#n||!["query","replay"].includes(e))throw new h("invalid_request");return e==="query"?this.#n.handle.query(n):this.#n.handle.execute(n)}prepareControlBytes(e,n){this.#l();let r=G(n);if(Buffer.compare(Buffer.from(M(r)),Buffer.from(n))!==0)throw new h("request_id_conflict");let o;if(e==="open"){let i=d.object({protocol:d.literal($),request:H,runtimeSessionId:d.literal(this.runtimeSessionId),intent:kt,requiredFeature:d.literal(Ke)}).strict().parse(r);o=this.prepareOpen(i)}else{let i=d.object({protocol:d.literal($),request:H,bindingId:d.string(),expectedRevision:d.string(),ticket:d.string().optional(),sessionId:d.string().optional(),reason:d.literal("manual").optional()}).strict().parse(r);o=this.prepareMutation(e,i)}if(Buffer.compare(Buffer.from(o.bytes()),Buffer.from(n))!==0)throw new h("request_id_conflict");return o}#W(e){this.#R=!0;try{let n=new Map(e.map(l=>[l.key,l.value]));if(n.size!==e.length||!n.has("meta"))throw new Error("inventory");let r=G(n.get("meta"));if(r.format==="sdk2-cache-client-retired-v1"){let l=gi.parse(r);if(e.length!==1||l.baseUrl!==this.#t||l.runtimeSessionId!==this.runtimeSessionId||l.continuityScope?.applicationScopeId!==this.#e.continuityScope?.applicationScopeId||l.continuityScope?.endUserId!==this.#e.continuityScope?.endUserId)throw new Error("retirement inventory");this.#y=l;return}let o=d.object({format:d.enum(["sdk2-cache-client-v1","sdk2-cache-client-core-v1"]),baseUrl:d.literal(this.#t),runtimeSessionId:d.literal(this.runtimeSessionId),binding:d.object({view:ze,ticket:d.string(),ticketExpiresAt:d.string()}).strict().nullable(),opened:Je.nullable(),openedIntent:d.string().nullable(),continuity:hi.optional(),terminalProof:$r.optional()}).strict().parse(r);if(this.#x=o.format==="sdk2-cache-client-core-v1",this.#p=o.continuity,this.#p&&(!this.#e.continuityScope||this.#p.applicationScopeId!==this.#e.continuityScope.applicationScopeId||this.#p.endUserId!==this.#e.continuityScope.endUserId||o.binding&&o.binding.view.bindingId!==this.#p.bindingId||o.opened!==null||o.openedIntent!==null))throw new Error("continuity inventory");if(this.#a=o.binding??void 0,this.#u=o.opened??void 0,this.#c=o.openedIntent??void 0,this.#b=o.terminalProof,this.#b&&(this.#b.kind!=="close"||this.#a||this.#b.bindingId!==(this.#p?.bindingId??this.#u?.binding.bindingId)))throw new Error("terminal proof inventory");this.#a&&(xt(this.#a.ticket),d.string().datetime({offset:!0}).parse(this.#a.ticketExpiresAt));let i=new Set,s=new Map;for(let l of e)if(!(l.key==="meta"||l.key==="pending-control"))if(l.key.startsWith("control/")){let c=d.object({operation:d.enum(["open","renew","rebind","rotate","close"]),body:d.string(),result:d.union([Je,Rt]).nullable()}).strict().parse(G(l.value)),p=Buffer.from(c.body,"base64");if(p.toString("base64")!==c.body||wn(c.operation,p)!==l.key)throw new Error("inventory");this.#m.set(l.key,{operation:c.operation,body:p,result:c.result})}else if(l.key.startsWith("exchange/")){let c=l.key.slice(9),p=Buffer.from(l.value);if(!vt(c)||p.length<5||p.length>33619972)throw new Error("inventory");let f=p.readUInt32BE(0);if(f>65536||f<1||p.length<=4+f)throw new Error("inventory");let g=G(p.subarray(4,4+f));if(g.runtimeSessionId!==this.runtimeSessionId)throw new Error("inventory");let b=p.subarray(4+f).toString("utf8");if(Buffer.compare(Rn(g,c,b),p)!==0)throw new Error("inventory");this.#s.set(c,{body:b,frame:p,uncertain:!0,active:!1})}else if(l.key.startsWith("core-exchange/")){if(!this.#x)throw new Error("Core inventory version");let c=l.key.slice(14),p=Jn(l.value);if(!vt(c)||p.requestId!==c||p.runtimeSessionId!==this.runtimeSessionId)throw new Error("Core inventory");s.set(c,p)}else if(l.key.startsWith("completed/")){let c=l.key.slice(10);if(!vt(c)||l.value.length!==0)throw new Error("inventory");this.#d.add(c)}else if(l.key.startsWith("flight/")){if(!vt(l.key.slice(7))||l.value.length!==0)throw new Error("inventory");i.add(l.key.slice(7))}else throw new Error("inventory");for(let[l,c]of s){let p=this.#s.get(l);if(!p||ie("sha256").update(p.body).digest("hex")!==c.payloadSha256)throw new Error("Core inventory");let f=G(p.frame.subarray(4,4+p.frame.readUInt32BE(0)));if(f.bindingId!==c.bindingId||f.projectionRef!==c.projectionRef)throw new Error("Core inventory");p.core=c}if(this.#m.size>128||this.#s.size>16||this.#d.size>4096||[...this.#s].some(([l])=>this.#d.has(l))||[...i].some(l=>!this.#s.has(l))||[...this.#s.values()].reduce((l,c)=>l+c.frame.length+Buffer.byteLength(c.body)+(c.core?se(c.core).byteLength:0),0)>67108864)throw new Error("inventory");let a=n.get("pending-control"),u=[...this.#m].filter(([,l])=>!("completed"in l)&&l.result===null);if(a){let l=Buffer.from(a).toString("utf8"),c=this.#m.get(l);if(!c||"completed"in c||c.result||u.length!==1||this.#s.size>0)throw new Error("inventory");this.prepareControlBytes(c.operation,c.body),this.#n.started=!0}else if(u.length!==0)throw new Error("inventory");if(this.#b&&![...this.#m.values()].some(l=>!("completed"in l)&&l.operation==="close"&&l.result&&l.result.binding.state==="closed"&&l.result.binding.bindingId===this.#b.bindingId&&this.#S(l.body,l.result).digest===this.#b.digest))throw new Error("terminal proof receipt");for(let[l,c]of this.#m)!("completed"in c)&&c.result!==null&&this.#m.set(l,Nr(c))}catch{throw this.#h=!0,new h("storage_unknown",void 0,void 0,"query-status")}finally{this.#R=!1}}#S(e,n){return{kind:"close",bindingId:n.binding.bindingId,digest:ie("sha256").update("tansr.sdk2.cache-retirement.close.v1\0").update(e).update("\0").update(M(n)).digest("hex")}}#A(e){if(this.#k(),this.#y){if(!Buffer.from(M(this.#y.proof)).equals(Buffer.from(M(e))))throw new h("request_id_conflict");return structuredClone(this.#y)}if(!this.#e.persistence)throw new h("mapping_unavailable");if(this.#n||this.#s.size>0||[...this.#m.values()].some(r=>!("completed"in r)&&r.result===null))throw new h("result_unknown",void 0,void 0,"query-status");let n={format:"sdk2-cache-client-retired-v1",baseUrl:this.#t,runtimeSessionId:this.runtimeSessionId,proof:{...e},compactedControls:this.#m.size,compactedExchanges:this.#d.size,...this.#e.continuityScope?{continuityScope:{...this.#e.continuityScope}}:{}};return this.#g({put:[{key:"meta",value:M(n)}],delete:[...this.#m.keys(),...[...this.#d].map(r=>`completed/${r}`)]}),this.#y=n,this.#m.clear(),this.#d.clear(),this.#a=void 0,this.#u=void 0,this.#c=void 0,this.#p=void 0,this.#b=void 0,this.#r=!1,this.#i=void 0,structuredClone(n)}#U(e){this.#k();let n=this.#e.continuityScope,{intent:r,receipt:o}=e;if(!n||!this.#e.persistence||e.baseUrl!==this.#t||e.scope.applicationScopeId!==n.applicationScopeId||e.scope.endUserId!==n.endUserId||!["resume","delete"].includes(r.operation)||r.previousRuntimeSessionId!==this.runtimeSessionId||(r.operation==="resume"?r.runtimeSessionId===this.runtimeSessionId:r.runtimeSessionId!==this.runtimeSessionId))throw new h("identity_conflict",r.requestId);let i=this.#y?.proof.bindingId??this.#a?.view.bindingId??this.#p?.bindingId??this.#u?.binding.bindingId;if(i!==r.bindingId)throw new h("identity_conflict",r.requestId);let s={kind:r.operation==="resume"?"continuity-resume":"continuity-delete",bindingId:i,digest:ie("sha256").update("tansr.sdk2.cache-retirement.continuity.v1\0").update(M({baseUrl:e.baseUrl,scope:e.scope,intent:r,receipt:o})).digest("hex")};return this.#A(s)}#D(e){this.#l();let n=this.#e.continuityScope,{intent:r,receipt:o}=e;if(!n||!this.#e.persistence||e.baseUrl!==this.#t||e.scope.applicationScopeId!==n.applicationScopeId||e.scope.endUserId!==n.endUserId||r.runtimeSessionId!==this.runtimeSessionId||o.source.runtimeSessionId!==this.runtimeSessionId||r.operation!=="resume"||!o.ticket||!o.ticketExpiresAt)throw new h("identity_conflict");if(this.#n||this.#s.size>0)throw new h("result_unknown",r.requestId,void 0,"query-status");let i={applicationScopeId:n.applicationScopeId,endUserId:n.endUserId,sourceNamespace:e.scope.sourceNamespace,intentDigest:ie("sha256").update(M(r)).digest("hex"),receiptDigest:ie("sha256").update(M(o)).digest("hex"),bindingId:o.binding.bindingId};if(this.#p){if(Buffer.from(M(this.#p)).equals(Buffer.from(M(i))))return;throw new h("request_id_conflict",r.requestId)}if(this.#a||this.#u||this.#m.size>0||this.#d.size>0)throw new h("identity_conflict",r.requestId);if(!this.#r||Date.parse(o.ticketExpiresAt)<=Date.now()||Date.parse(o.binding.expiresAt)<=Date.now())throw new h("mapping_unavailable",r.requestId);let s={view:structuredClone(o.binding),ticket:o.ticket,ticketExpiresAt:o.ticketExpiresAt};this.#g({put:[{key:"meta",value:this.#C(s,void 0,void 0,i)}],delete:[]}),this.#a=s,this.#p=i}async#O(e,n,r,o){this.#l();let i=await this.#e.token();if(this.#l(),typeof i!="string"||i.trim()!==i||i.length===0||/[\r\n]/.test(i))throw new h("unauthorized");let s=Fr(this.#e.timeoutMs??3e4,r);try{n&&e.startsWith("/cache/")&&this.#n&&this.#g({put:[{key:"pending-control",value:Buffer.from(wn(this.#n.operation,this.#n.body))}],delete:[]});let a=await this.#o(`${this.#t}${e}`,{method:n===void 0?"GET":"POST",redirect:"error",headers:{accept:"application/json","x-tansr-app-token":i,...n?{"content-type":"application/json"}:{}},...n?{body:Buffer.from(n)}:{},signal:s.signal});return await o(a)}finally{s.close()}}async#v(e,n,r,o){try{return await this.#O(e,n,o,async i=>{if(i.status!==200)throw await he(i);let s=await _t(i);return this.#l(),r.parse(s)})}catch(i){throw i instanceof h?i:new h("result_unknown",void 0,void 0,"query-status")}}async capabilities(e){let n=await this.#v("/cache/v1/capabilities",void 0,Dr,e);return this.#l(),this.#i={value:Gr(n),expires:Date.now()+n.limits.negotiatedTtlMs},structuredClone(n)}async#E(e){this.#l();let n=this.#i&&this.#i.expires>Date.now()?this.#i.value:Gr(await this.capabilities(e));if(this.#l(),!n.enabled||!n.operationEpoch||Date.parse(n.operationEpoch.expiresAt)<=Date.now())throw new h("unsupported_capability");return n}async#T(e){if(this.#l(),this.#r)return;let n=await this.#v("/heartbeat",M({client:"sdk",sessionId:this.runtimeSessionId}),d.object({sessionId:d.literal(this.runtimeSessionId)}).passthrough(),e);this.#l(),this.#r=n.sessionId===this.runtimeSessionId}async open(e={kind:"new"},n){if(this.#l(),this.#p)throw new h("mapping_unavailable");let r=kt.parse(G(M(e)));if(this.#n){let i=G(this.#n.body);if(this.#n.operation!=="open"||Buffer.compare(Buffer.from(M(i.intent)),Buffer.from(M(r)))!==0)throw new h("request_id_conflict");return this.#n.handle.execute(n)}if(this.#u){if(this.#c!==Buffer.from(M(r)).toString("utf8"))throw new h("request_id_conflict");if(!this.#a||this.#a.view.state!=="active")throw new h("mapping_unavailable");return structuredClone(this.#u)}await this.#T(n);let o=await this.#E(n);return this.prepareOpen({request:{operationEpoch:o.operationEpoch.id,requestId:fi()},intent:r}).execute(n)}prepareOpen(e){if(this.#l(),this.#p)throw new h("mapping_unavailable");let n=H.parse(e.request),r=kt.parse(e.intent);return this.#P("open","/cache/v1/bindings",null,{protocol:$,request:n,runtimeSessionId:this.runtimeSessionId,intent:r,requiredFeature:Ke})}prepareMutation(e,n){if(this.#l(),!["renew","rebind","rotate","close"].includes(e))throw new h("invalid_request");let r=F(n.bindingId),o=H.parse(n.request),i=qr(n.expectedRevision);if(this.#p&&r!==this.#p.bindingId)throw new h("identity_conflict",o.requestId);let s={protocol:$,request:o,bindingId:r,expectedRevision:i};if(e==="rebind"){if(n.sessionId!==this.runtimeSessionId||n.ticket!==void 0||n.reason!==void 0)throw new h("invalid_request");s.sessionId=this.runtimeSessionId}else{if(s.ticket=xt(n.ticket??""),n.sessionId!==void 0||e!=="rotate"&&n.reason!==void 0)throw new h("invalid_request");if(e==="rotate"){if(n.reason!=="manual")throw new h("invalid_request");s.reason="manual"}}return this.#P(e,`/cache/v1/bindings/${encodeURIComponent(r)}/${e}`,r,s)}#P(e,n,r,o){this.#l();let i=M(o),s=H.parse(o.request),a=wn(e,i);for(let[g,b]of this.#m){if(b.operation!==e)continue;let R="completed"in b?b:G(b.body);if(R.request.operationEpoch===s.operationEpoch&&R.request.requestId===s.requestId&&(R.bindingId??null)===r&&g!==a)throw new h("request_id_conflict",s.requestId)}let u=this.#m.get(a);if(u&&u.operation!==e)throw new h("request_id_conflict");if(u&&("completed"in u||u.result)){let g=b=>this.queryOperation({operation:e,request:s,bindingId:r},b);return Object.freeze({operation:e,request:Object.freeze({...s}),bytes:()=>new Uint8Array(i),execute:g,query:g})}if(this.#n){if(this.#n.operation!==e||Buffer.compare(Buffer.from(this.#n.body),Buffer.from(i))!==0)throw new h("request_id_conflict");return this.#n.handle}if(this.#s.size>0)throw new h("result_unknown",void 0,void 0,"query-status");if(this.#e.persistence&&!u&&this.#m.size>=128)throw new h("capacity_exceeded",s.requestId);let l=async(g,b)=>{if(this.#l(),p.sending)throw new h("result_unknown",s.requestId,void 0,"query-status");if(this.#n!==p)throw new h("request_id_conflict",s.requestId);p.sending=!0;try{!g&&e==="open"&&await this.#T(b),!g&&!p.started&&await this.#E(b),p.started=!0;let R=g?await this.queryOperation({operation:e,request:s,bindingId:r},b):await this.#v(n,i,d.union([Je,Rt]),b);if(R.request.operationEpoch!==s.operationEpoch||R.request.requestId!==s.requestId||r!==null&&R.binding.bindingId!==r||(e==="open"?!("relation"in R):!("operation"in R)||R.operation!==e))throw new h("invalid_response");let y=R.ticket&&R.ticketExpiresAt?{view:R.binding,ticket:R.ticket,ticketExpiresAt:R.ticketExpiresAt}:void 0,k="relation"in R?R:this.#u,x="relation"in R?Buffer.from(M(o.intent)).toString("utf8"):this.#c,_={operation:e,body:i,result:R},O=this.#e.persistence?Nr(_):void 0,m=e==="close"&&R.binding.state==="closed"&&this.#a?.view.bindingId===R.binding.bindingId?this.#S(i,R):null;return this.#g({put:[{key:"meta",value:this.#C(y??null,k,x,this.#p,m)},{key:a,value:this.#I(_)}],delete:["pending-control"]}),this.#a=y,this.#u=k,this.#c=x,this.#b=m??void 0,O&&this.#m.set(a,O),this.#n=void 0,structuredClone(R)}finally{p.sending=!1}},c=Object.freeze({operation:e,request:Object.freeze({...s}),bytes:()=>new Uint8Array(i),execute:g=>l(!1,g),query:g=>l(!0,g)}),p={operation:e,identity:s,body:i,path:n,bindingId:r,handle:c,sending:!1,started:!1},f={operation:e,body:i,result:null};return this.#g({put:[{key:a,value:this.#I(f)},{key:"pending-control",value:Buffer.from(a)}],delete:[]}),this.#e.persistence&&this.#m.set(a,f),this.#n=p,this.#_=Math.max(this.#_,i.byteLength),c}async queryOperation(e,n){let r=H.parse(e.request);if(!["open","renew","rebind","rotate","close"].includes(e.operation)||(e.operation==="open"?e.bindingId!==null:e.bindingId===null))throw new h("invalid_request");let o=new URLSearchParams({protocol:$,operation:e.operation,operationEpoch:r.operationEpoch,requestId:r.requestId,...e.bindingId===null?{}:{bindingId:F(e.bindingId)}}),i=await this.#v(`/cache/v1/operations?${o}`,void 0,d.union([Je,Rt]),n);if(i.request.operationEpoch!==r.operationEpoch||i.request.requestId!==r.requestId||(e.operation==="open"?!("relation"in i):!("operation"in i)||i.operation!==e.operation||i.binding.bindingId!==e.bindingId))throw new h("invalid_response");return i}async readBinding(e,n){let r=await this.#v(`/cache/v1/bindings/${encodeURIComponent(F(e))}?protocol=${$}`,void 0,ze,n);if(r.bindingId!==e)throw new h("invalid_response");return r}async diagnostics(e,n=null,r=100,o){if(!Number.isInteger(r)||r<1||r>100)throw new h("invalid_request");let i=new URLSearchParams({protocol:$,limit:String(r),...n===null?{}:{after:F(n)}});return this.#v(`/cache/v1/bindings/${encodeURIComponent(F(e))}/diagnostics?${i}`,void 0,yi,o)}async coreCapabilities(e){let n=await this.#v(`${be}/capabilities`,void 0,Kn,e);if(!n.features.includes("trusted-core-projection-v1"))throw new h("unsupported_capability");return n}async coreDiagnostics(e,n=null,r=100,o){if(!Number.isInteger(r)||r<1||r>100||n!==null&&(n.length>150||!/^[0-9]+\.[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(n)))throw new h("invalid_request");let i=new URLSearchParams({protocol:Ln,limit:String(r),...n===null?{}:{after:n}});return this.#O(`${be}/bindings/${encodeURIComponent(F(e))}/diagnostics?${i}`,void 0,o,async s=>{if(s.status!==200)throw await he(s);let a=Hn.parse(await _t(s));if(this.#l(),a.rows.length>r)throw new h("invalid_response");return a})}transport(e){if(this.#l(),!this.#a||this.#n)throw new h("mapping_unavailable");return e===void 0?this.#f:Object.freeze({...this.#f,coreProjection:!0,prepare:(n,r,o)=>this.#B(n,r,o,e)})}#B(e,n,r,o){if(this.#l(),this.#d.has(e))throw new h("receipt_expired",e);let i=this.#s.get(e);if(i){if(i.body!==n)throw new h("request_id_conflict",e)}else{if(this.#n||[...this.#s.values()].some(f=>f.uncertain))throw new h("result_unknown",e,void 0,"query-status");let a=o!==void 0&&!this.#x;if(a&&this.#s.size!==0)throw new h("pending_execution",e);let u=this.#a;if(!u||u.view.state!=="active"||!u.view.projection||u.view.projection.status==="rebuild-required"||Date.parse(u.ticketExpiresAt)<=Date.now())throw new h("mapping_unavailable",e);if(this.#s.size>=16||this.#d.size+this.#s.size>=4096)throw new h("capacity_exceeded",e);let l=Rn({bindingId:u.view.bindingId,ticket:u.ticket,runtimeSessionId:this.runtimeSessionId,projectionRef:u.view.projection.projectionRef},e,n),c;if(o!==void 0){if(!r)throw new h("core_source_missing",e);Ut(r),c=o.prepare({runtimeSessionId:this.runtimeSessionId,bindingId:u.view.bindingId,bindingRevision:u.view.revision,projectionRef:u.view.projection.projectionRef,requestId:e,payloadSha256:ie("sha256").update(n).digest("hex")},r)}let p=l.length+Buffer.byteLength(n)+(c?se(c).byteLength:0)+[...this.#s.values()].reduce((f,g)=>f+g.frame.length+Buffer.byteLength(g.body)+(g.core?se(g.core).byteLength:0),0);if(p>67108864)throw new h("capacity_exceeded",e);a&&(this.#x=!0),this.#g({put:[{key:`exchange/${e}`,value:l},...c?[{key:`core-exchange/${e}`,value:se(c)}]:[],...a?[{key:"meta",value:this.#C()}]:[]],delete:[]}),i={body:n,frame:l,uncertain:!1,active:!1,...c?{core:c}:{}},this.#s.set(e,i),this.#w=Math.max(this.#w,p)}if(i.core){if(!o||!r)throw new h("core_source_missing",e);if(Ut(r),!Buffer.from(M(r.facts)).equals(Buffer.from(M(i.core.core))))throw new h("request_id_conflict",e)}else if(o)throw new h("request_id_conflict",e);let s=i;return Object.freeze({requestId:e,send:async(a,u)=>{if(this.#l(),s.active)throw new h("result_unknown",e,void 0,"query-status");s.active=!0;let l=!1;try{if(!s.uncertain){let f=await this.#E(a);if(Buffer.byteLength(s.body)>f.limits.exchangeBytes||s.frame.readUInt32BE(0)>f.limits.controlBytes)throw new h("payload_too_large",e);s.core&&await this.coreCapabilities(a)}let c=await this.#e.token();if(this.#l(),typeof c!="string"||!c||c.trim()!==c||/[\r\n]/.test(c))throw new h("unauthorized",e);let p=s.core?await o.credential(structuredClone(s.core),a):void 0;if(s.core&&(r?.assertCurrent(),o.assertCurrent(s.core),typeof p!="string"||p.length>8192||!/^[A-Za-z0-9_-]+$/.test(p)))throw new h("invalid_request",e);return this.#l(),this.#g({put:[{key:`flight/${e}`,value:new Uint8Array}],delete:[]}),l=!0,await this.#o(`${this.#t}${s.core?be:"/cache/v1"}/exchange`,{method:"POST",redirect:"error",headers:{"content-type":kn,accept:u?"text/event-stream":"application/json","x-tansr-app-token":c,...p?{[Wt]:p}:{}},body:Buffer.from(s.frame),signal:a})}catch(c){throw l?(this.#f.uncertain(e),new h("result_unknown",e,void 0,"query-status")):(s.active=!1,c instanceof h,c)}}})}};var bi=17e4,Lr=17e4,ki=600,Ri=16,Ye=class{#e;#t;#o;#i=new Map;#r=null;constructor(e){this.#e=e,this.#t=e.baseUrl.replace(/\/+$/,""),this.#o=e.fetchImpl??fetch,e.gatewayCache?.coreProjection===!0&&Yn(this)}#n(){let e=this.#e.apiKey,n=this.#e.keyId,r=typeof e=="function"?e():e,o=typeof n=="function"?n():n??"",i=this.#r,s=i!==null&&i.sk===r?i.key:pn(r);return(i===null||i.sk!==r)&&(this.#r={sk:r,key:s}),{keyId:o,apiKey:r,signingKey:s}}async*stream(e,n={}){if(n.signal?.throwIfAborted(),this.#e.beforeExchange!==void 0){let m=n.signal,E;try{let v=Promise.resolve(this.#e.beforeExchange());if(m===void 0)await v;else{let w=new Promise((T,W)=>{E=()=>W(m.reason),m.addEventListener("abort",E,{once:!0}),m.aborted&&E()});await Promise.race([v,w])}}catch{m?.throwIfAborted()}finally{E!==void 0&&m?.removeEventListener("abort",E)}m?.throwIfAborted()}let r=Date.now(),o=n.connectTimeoutMs??n.timeoutMs??bi,i=n.idleTimeoutMs??this.#e.idleTimeoutMs??Lr,s=n.totalTimeoutMs??this.#e.totalTimeoutMs,a=new AbortController,u=null,l=null,c=null,p=(m,E)=>{u!==null&&clearTimeout(u);let v=setTimeout(()=>{c=m,a.abort()},E);v.unref?.(),u=v};s!==void 0&&Number.isFinite(s)&&s>0&&(l=setTimeout(()=>{c="total",a.abort()},s),l.unref?.());let f=()=>{u!==null&&clearTimeout(u),u=null,l!==null&&clearTimeout(l),l=null},g=()=>c==="idle"?`Stream idle timeout: no frames for ${i}ms`:c==="total"?`Request total timeout: exceeded ${s}ms wall clock (including stream)`:`Request timed out after ${o}ms`,b=n.signal!==void 0?AbortSignal.any([n.signal,a.signal]):a.signal,R=this.#e.stream??!0,y=We(n),k=y??this.#e.generateRequestId?.()??fe(),x=this.#e.gatewayCache?.originalBody(k)??(y!==void 0?this.#i.get(y):void 0);if(x===void 0){let m=this.#e.sessionId?.(),E=this.#a(n),v=Ot(this.#e.features?.(),this.#e.imageInput?.()),w=At(this.#e.features?.()),T=Pt(this.#e.features?.()),W=Bt(this.#e.features?.());try{x=JSON.stringify(fn(e,{stream:R,requestId:k,...this.#e.client!==void 0?{client:this.#e.client}:{},...m!==void 0?{sessionId:m}:{},...E!==void 0?{purpose:E}:{},...v?{sendImages:v}:{},...w?{cacheHints:w}:{},...w&&m!==void 0?{cacheKey:m}:{},...T?{reasoningOff:T}:{},...W?{reasoningLevels:W}:{}}))}catch(I){if(I instanceof V){yield{t:"error",kind:"invalid_request",message:I.message,recoverable:!1};return}throw I}y!==void 0&&this.#u(y,x)}let _;try{this.#e.gatewayCache===void 0&&(_=this.#n())}catch(m){yield{t:"error",kind:"auth",message:m instanceof Error?m.message:String(m),recoverable:!1};return}let O=`${this.#t}/exchange`;try{let m;p("connect",o);try{m=this.#e.gatewayCache!==void 0?await this.#e.gatewayCache.prepare(k,x,this.#e.gatewayCache.coreProjection?Vn(e):void 0).send(b,R):await this.#o(O,{method:"POST",headers:{"content-type":"application/json",accept:R?"text/event-stream":"application/json",[et]:_.keyId,[tt]:_.apiKey,...this.#e.signRequests!==!1?mn({signingKey:_.signingKey,method:"POST",pathWithQuery:wi(O),body:x}):{},...this.#e.defaultHeaders},body:x,signal:b})}catch(C){yield this.#s(C,n,g(),"connect",k);return}if(p("idle",i),!m.ok){if(this.#e.gatewayCache!==void 0)throw await he(m,k);yield await this.#f(m,k);return}if(m.status===202){if(this.#e.gatewayCache!==void 0)throw await he(m,k);yield await this.#d(m,k);return}if(!R){yield*this.#c(m,e,n,g,y,k);return}if((m.headers.get("content-type")??"").toLowerCase().includes("application/json")){yield*this.#c(m,e,n,g,y,k);return}if(m.body===null){if(this.#e.gatewayCache!==void 0)throw new h("result_unknown",k,void 0,"query-status");yield{t:"error",kind:"server",message:"Empty response body from twp endpoint",recoverable:!0};return}let v=new te,w=this.#e.onPlatformError,T=new Ne({fallbackModel:e.model.model,...this.#e.onUsage!==void 0?{onUsage:this.#e.onUsage}:{},...this.#e.onWarn!==void 0?{onWarn:this.#e.onWarn}:{},...w!==void 0?{onErr:C=>w({code:C.code,message:C.message,requestId:C.requestId??k,...C.detail!==void 0?{detail:C.detail}:{}})}:{}}),W,I,q=C=>{if(this.#e.gatewayCache!==void 0)try{let N=JSON.parse(C);if(!N||typeof N.stop!="string"||!nt.includes(N.stop))throw new Error}catch{throw new h("result_unknown",k,void 0,"query-status")}},D=C=>{if(this.#e.gatewayCache!==void 0&&C.t==="error")throw new h("result_unknown",k,void 0,"query-status");return W===void 0&&(C.t==="block_start"||C.t==="text_delta"||C.t==="tool_args_delta")&&(W=Date.now()),C.t==="message_stop"&&(this.#e.gatewayCache?.finish(k),y!==void 0&&C.stopReason!=="unknown"&&this.#i.delete(y),W!==void 0)?{...C,ttftMs:W-r}:C};try{let C=v.comments;e:for await(let N of m.body){let ye=v.feed(N);(ye.length>0||v.comments!==C)&&(C=v.comments,p("idle",i));for(let S of ye){if(this.#e.gatewayCache!==void 0&&S.event==="t.close"){q(S.data),I=T.handleFrame(S);break e}for(let ne of T.handleFrame(S))yield D(ne)}if(T.ended)return}}catch(C){yield this.#s(C,n,g(),"stream",k);return}if(I!==void 0){for(let C of I)yield D(C);return}for(let C of v.end()){C.event==="t.close"&&q(C.data);for(let N of T.handleFrame(C))yield D(N)}if(this.#e.gatewayCache!==void 0&&!T.ended)throw new h("result_unknown",k,void 0,"query-status");for(let C of T.finish())yield D(C)}finally{this.#e.gatewayCache?.uncertain(k),f()}}#a(e){return St(ke(e)?.purpose)}#u(e,n){if(this.#i.size>=Ri){let r=this.#i.keys().next();r.done!==!0&&this.#i.delete(r.value)}this.#i.set(e,n)}async*#c(e,n,r,o,i,s){let a;try{a=await e.json()}catch(p){yield this.#s(p,r,o(),"stream",s);return}let u=yn(a);if(this.#e.gatewayCache!==void 0){let p=a;if(!p||typeof p.exchangeId!="string"||typeof p.model!="string"||!Array.isArray(p.blocks)||typeof p.stop!="string"||!nt.includes(p.stop))throw new h("result_unknown",s,void 0,"query-status")}u!==null&&this.#e.onUsage?.(u);let l=gn(a,n.model.model);if(this.#e.gatewayCache!==void 0){if(l[l.length-1]?.t!=="message_stop")throw new h("result_unknown",void 0,void 0,"query-status");this.#e.gatewayCache.finish(s)}let c=l[l.length-1];i!==void 0&&c?.t==="message_stop"&&c.stopReason!=="unknown"&&this.#i.delete(i),yield*l}#s(e,n,r,o,i){if(this.#e.gatewayCache!==void 0)throw e instanceof h?e:new h("result_unknown",i,void 0,"query-status");if(n.signal?.aborted===!0)throw e;let s=J(e);if(s!==void 0)return s;let a=typeof e=="object"&&e!==null&&"name"in e?String(e.name):"",u=a==="TimeoutError"||a==="AbortError",l=u?r:Q(e);return Y({t:"error",kind:o==="stream"?"stream_interrupted":u?"connect":"network",message:l,recoverable:!0,...o==="stream"||u?{idempotencyConsumed:!0}:{}},e)}async#d(e,n){let r,o;try{let i=await e.json();typeof i?.retryAfterMs=="number"&&Number.isFinite(i.retryAfterMs)&&i.retryAfterMs>=0&&(r=j(Math.round(i.retryAfterMs))),typeof i?.requestId=="string"&&(o=i.requestId)}catch{}return{t:"error",kind:"server",message:`exchange in progress (HTTP 202): requestId ${o??n} still in flight; retrying with the same requestId`,recoverable:!0,...r!==void 0?{retryAfterMs:r}:{}}}async#f(e,n){let r="";try{r=await e.text()}catch{}let o;try{let u=JSON.parse(r);if(typeof u?.error?.code=="string"){let l=u.error.detail;o={code:u.error.code,message:typeof u.error.message=="string"?u.error.message:"",...typeof l=="object"&&l!==null&&!Array.isArray(l)?{detail:l}:{}}}}catch{}let i=o?.code==="idempotency_conflict"&&o.detail?.replayable===!1;if(o?.code!==void 0&&!i){let u=typeof o.detail?.requestId=="string"?o.detail.requestId:void 0;this.#e.onPlatformError?.({code:o.code,message:o.message??"",requestId:u??n,...o.detail!==void 0?{detail:o.detail}:{}})}let s=xi(e.headers);return i?{t:"error",kind:"server",message:`idempotency_conflict: ${o?.message??""}`,recoverable:!0,idempotencyConsumed:!0,...s!==void 0?{retryAfterMs:s}:{}}:{t:"error",...o?.code!==void 0?qe(o.code,o.message??"",o.detail):hn(e.status,r.slice(0,ki)||e.statusText),...s!==void 0?{retryAfterMs:s}:{}}}};function wi(t){try{let e=new URL(t);return e.pathname+e.search}catch{return t}}function xi(t){let e=t.get("retry-after");if(e===null)return;let n=Number(e);return Number.isFinite(n)&&n>=0?j(Math.round(n*1e3)):void 0}var Hr="TANSR_KEY_ID";function Kr(t,e){let n=t.providerProfile.auth;if(n===void 0)throw new ee(t.providerId);let r=e[n.env];if(r===void 0||r==="")throw new ee(t.providerId,n.env);return r}function vn(t,e={}){let n=e.env??process.env;Kr(t,n);let r=()=>Kr(t,n),o=e.governor!==void 0?e.fetchImpl!==void 0?e.governor.wrapFetch(e.fetchImpl):e.governor.fetch:e.fetchImpl,i={baseUrl:t.providerProfile.baseUrl,apiKey:r,...e.defaultHeaders!==void 0?{defaultHeaders:e.defaultHeaders}:{},...o!==void 0?{fetchImpl:o}:{}};switch(t.providerProfile.protocol){case"anthropic":return new Se({...i,messageCacheBreakpoint:t.capability.promptCaching.mode==="explicit"});case"openai":{let s=t.capability.thinking.mustEchoBack;return new ce({...i,echoThinking:s,...s&&n.TANSR_THINKING_ECHO_PROBE==="1"?{onThinkingEcho:a=>{process.stderr.write(`[thinking-echo] provider=${t.providerId} model=${t.modelName} reasoning_chars=${a.chars} assistant_messages=${a.messages}
|
|
21
|
+
`)}function ei(t,e,n){let r=[];for(let o of t)switch(o.t){case"text":r.push({t:"text",v:o.text});break;case"tool_call":r.push({t:"tool_use",id:o.id,name:o.name,input:o.args??{}});break;case"tool_result":r.push({t:"tool_result",toolUseId:o.callId,v:Zo(o),...o.isError!==void 0?{isError:o.isError}:{}});break;case"image":if(e!=="user")throw new V("role_not_user",e,o.mime);if(!n)throw new V("gate_closed",e,o.mime);r.push({t:"image",mime:o.mime,v:o.data});break;case"thinking":case"opaque":break}return r}function ti(t,e){let n=[];for(let o of t.blocks){if(o.t!=="tool_result")continue;let i=0;for(let s of o.content)if(s.t==="image"){if(t.role!=="user")throw new V("role_not_user",t.role,s.mime);if(!e)throw new V("gate_closed",t.role,s.mime);n.push({t:"text",v:`Tool output image (call ${o.callId}, image ${++i}):`}),n.push({t:"image",mime:s.mime,v:s.data})}}let r=ei(t.blocks,t.role,e);return r.length===0?[]:[{role:t.role,blocks:r},...n.length>0?[{role:"user",blocks:n}]:[]]}function ni(t){return t<=1024?"low":t<=4096?"medium":"high"}function fn(t,e={}){let n=e.sendImages??!1,r=e.cacheHints??!1,o=[],i=t.system.filter(u=>u.text!=="").map(u=>r&&u.cacheable===!0?{t:"text",v:u.text,cacheable:!0}:{t:"text",v:u.text});i.length>0&&o.push({role:"system",blocks:i});for(let u of t.messages)o.push(...ti(u,n));let s=r?{...t.skipCacheWrite===!0?{skipWrite:!0}:{},...e.cacheKey!==void 0?{key:e.cacheKey}:{}}:void 0,a=s!==void 0&&Object.keys(s).length>0;return{model:t.model.model,thread:o,...t.tools.length>0?{tools:t.tools.map(u=>({name:u.name,description:u.description,inputSchema:u.inputSchema}))}:{},params:{maxTokens:t.maxTokens,...t.temperature!==void 0?{temperature:t.temperature}:{},...t.stopSequences!==void 0&&t.stopSequences.length>0?{stop:[...t.stopSequences]}:{},...t.promptTokensEstimate!==void 0&&Math.ceil(t.promptTokensEstimate)>=1?{promptTokensEstimate:Math.ceil(t.promptTokensEstimate)}:{},...e.reasoningOff===!0&&t.thinking?.off===!0?{reasoning:"off"}:e.reasoningLevels===!0&&t.thinking?.off!==!0&&typeof t.thinking?.budget=="number"&&t.thinking.budget>0?{reasoning:ni(t.thinking.budget)}:{}},meta:{requestId:e.requestId??fe(),...e.sessionId!==void 0?{sessionId:e.sessionId}:{},...e.client!==void 0?{client:e.client}:{},...e.purpose!==void 0?{purpose:e.purpose}:{}},...a?{cache:s}:{},stream:e.stream??!0}}function bt(t){switch(t){case null:case void 0:case"end":return"end_turn";case"tool_use":return"tool_use";case"max_tokens":return"max_tokens";default:return t}}function yt(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.round(t):0}var ri=/^-?\d+(?:\.\d+)?$/,oi=new Set(["in","out","cache_r","cache_w"]);function ii(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e={};for(let[n,r]of Object.entries(t))oi.has(n)||typeof r!="number"||!Number.isSafeInteger(r)||r<=0||(e[n]=r);return Object.keys(e).length>0?e:void 0}function De(t){let e=ii(t.dims),n=t.saved,r=typeof n=="string"&&ri.test(n.trim())?n.trim():void 0;return{inTokens:yt(t.inTokens),outTokens:yt(t.outTokens),cacheRTokens:yt(t.cacheRTokens),cacheWTokens:yt(t.cacheWTokens),...typeof t.cost=="string"?{cost:t.cost}:{},...typeof t.currency=="string"?{currency:t.currency}:{},...typeof t.balanceAfter=="string"?{balanceAfter:t.balanceAfter}:{},...e!==void 0?{dims:e}:{},...r!==void 0?{saved:r}:{},...t.estimated===!0?{estimated:!0}:{},...t.estimated===!0&&typeof t.estimatedReason=="string"&&t.estimatedReason!==""?{estimatedReason:t.estimatedReason}:{}}}function je(t){return{inputTokens:t.inTokens,outputTokens:t.outTokens,...t.cacheRTokens>0?{cacheReadInputTokens:t.cacheRTokens}:{},...t.cacheWTokens>0?{cacheCreationInputTokens:t.cacheWTokens}:{},...t.dims!==void 0?{dims:t.dims}:{},...t.saved!==void 0?{saved:t.saved}:{}}}var si=Mt;function ai(t){if(t===void 0)return;let e=t.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return j(Math.round(e));let n=t.retryAfterSec??t.retryAfterSeconds??t.retry_after;if(typeof n=="number"&&Number.isFinite(n)&&n>=0)return j(Math.round(n*1e3))}var Pr=new Set(["plan_concurrency_exceeded","plan_end_users_exceeded","plan_required","plan_tier_insufficient"]);function Br(t){return Pr.has(t)?{scope:"plan"}:void 0}function qe(t,e,n){let r=`${t}: ${e}`,o=ai(n),i=si[t],s=Br(t);return i!==void 0?{kind:i.kind,message:r,recoverable:n?.retryable===!1?!1:i.recoverable,...o!==void 0?{retryAfterMs:o}:{},...s!==void 0?{detail:s}:{}}:{kind:"invalid_request",message:r,recoverable:!1,...s!==void 0?{detail:s}:{}}}function hn(t,e){let n=`HTTP ${t}: ${e}`;return t===401||t===403?{kind:"auth",message:n,recoverable:!1}:t===429?{kind:"rate_limited",message:n,recoverable:!0}:t>=500?{kind:"server",message:n,recoverable:!0}:{kind:"invalid_request",message:n,recoverable:!1}}function Ue(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gn(t,e){if(!Ue(t))return[{t:"error",kind:"server",message:"twp non-stream response is not a JSON object",recoverable:!0}];let n=[];n.push({t:"message_start",model:typeof t.model=="string"?t.model:e});let r=Array.isArray(t.blocks)?t.blocks:[],o=0;for(let s of r)Ue(s)&&(s.t==="text"&&typeof s.v=="string"?(n.push({t:"block_start",index:o,block:{t:"text",text:s.v}}),n.push({t:"block_stop",index:o}),o+=1):s.t==="tool_use"&&typeof s.id=="string"&&typeof s.name=="string"&&(n.push({t:"block_start",index:o,block:{t:"tool_call",id:s.id,name:s.name,args:s.input??{}}}),n.push({t:"block_stop",index:o}),o+=1));let i=Ue(t.usage)?je(De(t.usage)):void 0;return n.push({t:"message_stop",stopReason:bt(typeof t.stop=="string"?t.stop:void 0),...i!==void 0?{usage:i}:{}}),n}function yn(t){return!Ue(t)||!Ue(t.usage)?null:De(t.usage)}var Ne=class{#e;#t=new Map;#o=null;#i=null;#r=!1;#n=!1;#a=null;constructor(e={}){this.#e=e}get ended(){return this.#n}handleFrame(e){if(this.#n)return[];let n;try{n=JSON.parse(e.data)}catch{return[]}let r=typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null;if(r===null)return[];switch(e.event){case Z.open:return this.#u(r);case Z.delta:return this.#c(r);case Z.usage:{let o=De(r);return this.#i=o,this.#e.onUsage?.(o),[]}case Z.warn:return this.#e.onWarn?.({code:typeof r.code=="string"?r.code:"unknown",message:typeof r.message=="string"?r.message:""}),[];case Z.close:return this.#d(r);case Z.err:return this.#f(r);default:return[]}}finish(){if(this.#n)return[];this.#n=!0;let e=this.#h();return e.push({t:"message_stop",stopReason:"unknown",...this.#i!==null?{usage:je(this.#i)}:{}}),e}#u(e){return this.#r?[]:(this.#r=!0,[{t:"message_start",model:typeof e.model=="string"?e.model:this.#e.fallbackModel??"unknown"}])}#c(e){let n=e.seq;if(typeof n=="number"&&Number.isInteger(n)){if(this.#a!==null&&n<=this.#a)return this.#n=!0,[{t:"error",kind:"server",message:`twp protocol error: t.delta.seq not monotonic (${n} after ${this.#a})`,recoverable:!1}];this.#a=n}let r=e.i;if(typeof r!="number"||!Number.isInteger(r)||r<0)return[];let o=[];this.#r||(this.#r=!0,o.push({t:"message_start",model:this.#e.fallbackModel??"unknown"}));let i=e.t;if(i==="text"){let s=e.v;return typeof s!="string"||(o.push(...this.#s(r,"text",e)),o.push({t:"text_delta",index:r,text:s})),o}if(i==="thinking"){let s=e.v;return typeof s!="string"||(o.push(...this.#s(r,"thinking",e)),o.push({t:"thinking_delta",index:r,text:s})),o}if(i==="tool_use"){o.push(...this.#s(r,"tool_use",e));let s=e.vJson;return typeof s=="string"&&s!==""&&o.push({t:"tool_args_delta",index:r,json:s}),o}return o}#s(e,n,r){let o=[];return this.#t.has(e)?(this.#o=e,o):(this.#o!==null&&this.#o!==e&&this.#t.has(this.#o)&&(o.push({t:"block_stop",index:this.#o}),this.#t.delete(this.#o)),n==="text"?o.push({t:"block_start",index:e,block:{t:"text",text:""}}):n==="thinking"?o.push({t:"block_start",index:e,block:{t:"thinking",text:""}}):o.push({t:"block_start",index:e,block:{t:"tool_call",id:typeof r.id=="string"?r.id:`tu_${e}`,name:typeof r.name=="string"?r.name:"",args:{}}}),this.#t.set(e,{kind:n}),this.#o=e,o)}#d(e){this.#n=!0;let n=this.#h();return n.push({t:"message_stop",stopReason:bt(typeof e.stop=="string"?e.stop:void 0),...this.#i!==null?{usage:je(this.#i)}:{}}),n}#f(e){this.#n=!0;let n=typeof e.code=="string"?e.code:"unknown",r=typeof e.message=="string"?e.message:"",o=e.detail,i=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:void 0;return this.#e.onErr?.({code:n,message:r,...typeof e.requestId=="string"?{requestId:e.requestId}:{},...i!==void 0?{detail:i}:{}}),[{t:"error",...qe(n,r,i)}]}#h(){let e=[];for(let n of this.#t.keys())e.push({t:"block_stop",index:n});return this.#t.clear(),this.#o=null,e}};import{createHash as ie,randomUUID as fi}from"node:crypto";var Fe=new WeakMap;function Wr(t,e){if(Fe.has(t))throw new Error("continuity target already registered");Fe.set(t,Object.freeze(e))}function aa(t,e){let n=Fe.get(t);if(!n)throw new Error("continuity target unavailable");return n.retire(e)}function ua(t,e){let n=Fe.get(t);if(!n)throw new Error("continuity target unavailable");n.adopt(e)}async function da(t,e){let n=Fe.get(t);if(!n)throw new Error("continuity target unavailable");await n.heartbeat(e)}var bn=new WeakMap;function Ur(t,e){if(bn.has(t))throw new Error("cache retirement target already registered");bn.set(t,Object.freeze(e))}function ca(t){let e=bn.get(t);if(!e)throw new Error("cache retirement target unavailable");return e.status()}import{createHash as ui}from"node:crypto";var $="sdk2-cache-v1",Ke="private-logical-cache-v1",kn="application/vnd.tansr.cache-exchange.v1",di=33554432,X=d.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._~-]*$/),li=d.string().refine(t=>[...t].length>0&&[...t].length<=512),Ge=d.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(t=>BigInt(t)<=9223372036854775807n),$e=d.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>Buffer.from(t,"base64url").toString("base64url")===t),Le=d.string().datetime({offset:!0}),He=d.literal($),H=d.object({operationEpoch:X,requestId:X}).strict(),kt=d.discriminatedUnion("kind",[d.object({kind:d.literal("new")}).strict(),d.object({kind:d.literal("import")}).strict(),d.object({kind:d.literal("resume"),ticket:$e}).strict(),d.object({kind:d.literal("fork"),parentTicket:$e}).strict()]),ci=d.object({projectionRef:X,revision:Ge,status:d.enum(["current","rebuild-required","missing"]),reason:d.enum(["unchanged","policy-changed","generation-changed","provider-changed","source-missing","legacy-missing","key-rotated"])}).strict(),ze=d.object({protocol:He,audience:d.literal("gateway-cache"),bindingId:X,logicalRef:X,revision:Ge,state:d.enum(["active","closed","revoked","expired"]),mode:d.literal("private-logical-v1"),groupGeneration:Ge,projection:ci.nullable(),expiresAt:Le,availability:d.literal("legacy-complete")}).strict(),Je=d.object({protocol:He,request:H,binding:ze,ticket:$e,ticketExpiresAt:Le,relation:d.enum(["new","resumed","forked","imported"])}).strict(),Rt=d.object({protocol:He,request:H,operation:d.enum(["open","renew","rotate","close","rebind"]),semanticDigest:d.object({algorithm:d.literal("hmac-sha256"),keyId:X,digest:d.string().regex(/^[a-f0-9]{64}$/)}).strict(),state:d.literal("completed"),binding:ze,ticket:$e.nullable(),ticketExpiresAt:Le.nullable()}).strict(),pi={controlBytes:[4096,65536],exchangeBytes:[1024,33554432],projectionBytes:[1024,262144],projectionSegments:[1,64],ticketTtlMs:[6e4,6048e5],mappingIdleMs:[6e4,6048e5],mappingLifetimeMs:[6e4,2592e6],bindingsPerLogical:[1,16],mappingsPerUser:[1,1e3],mappingsPerApplication:[1,1e4],mappingsGlobal:[1,1e5],mappingBytes:[1024,16384],receiptsGlobal:[1,1e5],receiptBytes:[1024,32768],receiptRetentionMs:[6e4,6048e5],epochLifetimeMs:[6e4,864e5],diagnosticRowsPerUser:[1,1e3],diagnosticRowsPerApplication:[1,1e4],diagnosticRowsGlobal:[1,1e5],diagnosticBytes:[1024,4096],diagnosticRetentionMs:[6e4,864e5],diagnosticSamplePerMillion:[0,1e6],diagnosticsPageRows:[1,100],negotiatedTtlMs:[1e3,6e4],retainedRowsPerUser:[1,1e4],retainedRowsPerApplication:[1,1e5],retainedRowsGlobal:[1,1e6],retainedBytesPerUser:[1,16777216],retainedBytesPerApplication:[1,268435456],retainedBytesGlobal:[1,2147483648]},mi=d.object(Object.fromEntries(Object.entries(pi).map(([t,[e,n]])=>[t,d.number().int().min(e).max(n)]))).strict(),Dr=d.object({protocol:He,audience:d.literal("gateway-cache"),features:d.array(d.literal(Ke)).max(1),gateway:d.literal("not-applicable"),availability:d.literal("legacy-complete"),revision:Ge,limits:mi,operationEpoch:d.object({id:X,issuedAt:Le,expiresAt:Le,state:d.literal("active")}).strict().nullable()}).strict().refine(t=>t.features.length===0||t.operationEpoch!==null),jr=d.object({protocol:He,requestId:X,code:d.enum(["invalid_request","protocol_version_mismatch","unauthorized","forbidden","stale_revision","stale_generation","request_id_conflict","projection_stale","ticket_expired","mapping_expired","receipt_expired","payload_too_large","unsupported_capability","capacity_exceeded","epoch_unavailable","mapping_unavailable","result_unknown"]),status:d.number().int().min(400).max(503),retryAction:d.enum(["none","same-request","query-status","refresh-projection"]),fallback:d.enum(["none","legacy-cold"]),message:d.string().min(1).max(256)}).strict();function F(t){return X.parse(t)}function wt(t){return li.parse(t)}function qr(t){return Ge.parse(t)}function xt(t){return $e.parse(t)}function Rn(t,e,n){let r=Buffer.from(n,"utf8");if(r.length<1||r.length>di||r.toString("utf8")!==n)throw new TypeError("invalid_request");let o=JSON.parse(n);if(!/^[A-Za-z0-9_-]{8,40}$/.test(e)||o?.meta?.requestId!==e||o.meta.sessionId!==t.runtimeSessionId)throw new TypeError("request_id_conflict");let i=M({protocol:$,bindingId:F(t.bindingId),ticket:xt(t.ticket),runtimeSessionId:wt(t.runtimeSessionId),projectionRef:F(t.projectionRef),payloadBytes:r.length,payloadSha256:ui("sha256").update(r).digest("hex")}),s=Buffer.allocUnsafe(4+i.length+r.length);return s.writeUInt32BE(i.length),s.set(i,4),s.set(r,4+i.length),s}var h=class extends Error{constructor(n,r,o,i="none"){super(`SDK2 cache: ${/^[a-z][a-z0-9_]{0,63}$/.test(n)?n:"invalid_response"}`);this.code=n;this.requestId=r;this.status=o;this.retryAction=i;this.name="GatewayCacheError"}code;requestId;status;retryAction;fallback="none"},wn=(t,e)=>`control/${ie("sha256").update(t).update("\0").update(e).digest("hex")}`;function Nr(t){let e=G(t.body);return{operation:t.operation,request:H.parse(e.request),bindingId:t.operation==="open"?null:F(e.bindingId??""),completed:!0}}var hi=d.object({applicationScopeId:d.string(),endUserId:d.string(),sourceNamespace:d.string(),intentDigest:d.string().regex(/^[a-f0-9]{64}$/),receiptDigest:d.string().regex(/^[a-f0-9]{64}$/),bindingId:d.string()}).strict(),$r=d.object({bindingId:d.string().refine(t=>{try{return F(t)===t}catch{return!1}}),kind:d.enum(["close","continuity-resume","continuity-delete"]),digest:d.string().regex(/^[a-f0-9]{64}$/)}).strict(),gi=d.object({format:d.literal("sdk2-cache-client-retired-v1"),baseUrl:d.string(),runtimeSessionId:d.string(),proof:$r,compactedControls:d.number().int().min(0).max(128),compactedExchanges:d.number().int().min(0).max(4096),continuityScope:d.object({applicationScopeId:d.string(),endUserId:d.string()}).strict().optional()}).strict(),vt=t=>/^[A-Za-z0-9_-]{8,40}$/.test(t),yi=d.object({protocol:d.literal($),rows:d.array(d.never()).max(0),next:d.null()}).strict();function Fr(t,e){let n=new AbortController,r=setTimeout(()=>n.abort(new DOMException("The operation was aborted due to timeout","TimeoutError")),t);return r.unref(),{signal:e?AbortSignal.any([e,n.signal]):n.signal,close:()=>clearTimeout(r)}}async function _t(t,e=65536){if(t.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()!=="application/json"||t.body===null)throw await t.body?.cancel(),new h("invalid_response");let r=t.body.getReader(),o=[],i=0;try{for(;;){let{done:s,value:a}=await r.read();if(s)break;if(i+=a.byteLength,i>e)throw await r.cancel(),new h("payload_too_large");o.push(a)}return e===1048576?$n(Buffer.concat(o)):G(Buffer.concat(o))}finally{r.releaseLock()}}async function he(t,e){try{let n=await _t(t),r=jr.safeParse(n);if(r.success&&r.data.status===t.status)return new h(r.data.code,e,t.status,r.data.retryAction);let o=d.object({error:d.object({code:d.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).passthrough()}).passthrough().safeParse(n);if(o.success)return new h(o.data.error.code,e,t.status)}catch{}return new h("result_unknown",e,t.status,"query-status")}function Gr(t){return{enabled:t.features.includes(Ke),operationEpoch:t.operationEpoch?{id:t.operationEpoch.id,expiresAt:t.operationEpoch.expiresAt}:null,limits:{controlBytes:t.limits.controlBytes,exchangeBytes:t.limits.exchangeBytes}}}var xn=class{#e;#t;#o;runtimeSessionId;#i;#r=!1;#n;#a;#u;#c;#s=new Map;#d=new Set;#f;#h=!1;#p;#b=!1;#m=new Map;#g;#y;#v=!1;#C=!1;#w=0;#k=0;constructor(e){let n=new URL(e.baseUrl);if(!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash||!/\/t1\/?$/.test(n.pathname))throw new h("invalid_request");if(e.timeoutMs!==void 0&&(!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>3e5))throw new h("invalid_request");if(this.#e={...e,...e.continuityScope?{continuityScope:Object.freeze({applicationScopeId:F(e.continuityScope.applicationScopeId),endUserId:wt(e.continuityScope.endUserId)})}:{}},this.#t=e.baseUrl.replace(/\/+$/,""),this.#o=e.fetchImpl??fetch,this.runtimeSessionId=wt(e.runtimeSessionId),this.#f=Object.freeze({runtimeSessionId:this.runtimeSessionId,originalBody:r=>(this.#l(),this.#s.get(r)?.body),prepare:(r,o)=>this.#W(r,o),finish:r=>{this.#l();let o=this.#s.get(r);if(!o?.active)throw new h("result_unknown",r,void 0,"query-status");this.#x({put:[{key:`completed/${r}`,value:new Uint8Array}],delete:[`exchange/${r}`,`flight/${r}`,...o.core?[`core-exchange/${r}`]:[]]}),this.#s.delete(r),this.#d.add(r)},uncertain:r=>{this.#l();let o=this.#s.get(r);o?.active&&(o.uncertain=!0,o.active=!1)}}),e.persistence){let r=e.persistence.load({baseUrl:this.#t,runtimeSessionId:this.runtimeSessionId});r.length===0?this.#x({put:[{key:"meta",value:this.#E()}],delete:[]}):this.#U(r)}this.#k=this.#S(),this.#e.continuityScope&&e.persistence&&Wr(this,{adopt:r=>this.#j(r),heartbeat:r=>this.#I(r),retire:r=>this.#D(r)}),Ur(this,{status:()=>(this.#R(),this.#g?structuredClone(this.#g):void 0),retireClosed:()=>{if(this.#R(),!this.#e.persistence)throw new h("mapping_unavailable");let r=this.#g?.proof??this.#y;if(!r||r.kind!=="close")throw new h("mapping_unavailable");return this.#O(r)}})}#R(){if(this.#h)throw new h("storage_unknown",void 0,void 0,"query-status")}#l(){if(this.#R(),this.#g)throw new h("runtime_retired")}#x(e){if(this.#l(),!(!this.#e.persistence||this.#b)){try{this.#e.persistence.commit(e)}catch{throw this.#h=!0,new h("storage_unknown",void 0,void 0,"query-status")}this.#C&&e.put.some(n=>n.key==="meta")&&(this.#C=!1)}}#E(e=this.#a,n=this.#u,r=this.#c,o=this.#p,i=this.#y??null){return M({format:this.#v?"sdk2-cache-client-core-v1":"sdk2-cache-client-v1",baseUrl:this.#t,runtimeSessionId:this.runtimeSessionId,binding:e??null,opened:n??null,openedIntent:r??null,...o?{continuity:o}:{},...i?{terminalProof:i}:{}})}#M(e){return M({operation:e.operation,body:Buffer.from(e.body).toString("base64"),result:e.result})}pendingControl(){return this.#l(),this.#n?.handle}pendingExchanges(){return this.#l(),[...this.#s].map(([e,n])=>({requestId:e,uncertain:n.uncertain,active:n.active}))}#S(){return[...this.#s.values()].reduce((e,n)=>e+n.frame.length+Buffer.byteLength(n.body)+(n.core?se(n.core).byteLength:0),0)}readInventory(){this.#R();let e=this.#n?.body.byteLength??0,n=this.#S();return{retired:this.#g!==void 0,pendingControlBytes:e,pendingExchangeBytes:n,pendingBytes:e+n,pendingControls:+(this.#n!==void 0),pendingExchanges:this.#s.size,highWaterPendingControlBytes:this.#w,highWaterPendingExchangeBytes:this.#k,highWaterPendingBytes:Math.max(this.#w,this.#k),pendingControlCapBytes:65536,pendingExchangeCapBytes:67108864,pendingCapBytes:67108864}}async lookupPending(e,n,r){this.#l();let o=this.#s.get(e);if(!o?.core||!n.lookupCredential)throw new h("core_source_missing",e);if(o.active||this.#n)throw new h("pending_execution",e);let i=Fr(this.#e.timeoutMs??3e4,r),s=i.signal;try{n.assertCurrent(o.core);let a=await this.#e.token();if(typeof a!="string"||!a||a.trim()!==a||/[\r\n]/.test(a))throw new h("unauthorized",e);let u=await n.lookupCredential(structuredClone(o.core),s);if(n.assertCurrent(o.core),this.#l(),s.throwIfAborted(),this.#s.get(e)!==o||o.active||this.#n)throw new h("pending_execution",e);if(typeof u!="string"||u.length>8192||!/^[A-Za-z0-9_-]+$/.test(u))throw new h("invalid_request",e);let l=await this.#o(`${this.#t}${be}/exchange/lookup`,{method:"POST",redirect:"error",headers:{"content-type":kn,accept:"application/json","x-tansr-app-token":a,[Wt]:u},body:Buffer.from(o.frame),signal:s});if(l.status!==200)throw await he(l,e);let c=zn.parse(await _t(l,1048576));return this.#l(),n.assertCurrent(o.core),c}finally{i.close()}}readLocalBinding(){if(this.#l(),this.#n)return null;let e=this.#a?.view;return e?{revision:e.revision,state:e.state,mode:e.mode,groupGeneration:e.groupGeneration,projection:e.projection?{revision:e.projection.revision,status:e.projection.status,reason:e.projection.reason}:null,expiresAt:e.expiresAt,availability:e.availability}:null}async resumePendingControl(e,n){if(this.#l(),!this.#n||!["query","replay"].includes(e))throw new h("invalid_request");return e==="query"?this.#n.handle.query(n):this.#n.handle.execute(n)}prepareControlBytes(e,n){this.#l();let r=G(n);if(Buffer.compare(Buffer.from(M(r)),Buffer.from(n))!==0)throw new h("request_id_conflict");let o;if(e==="open"){let i=d.object({protocol:d.literal($),request:H,runtimeSessionId:d.literal(this.runtimeSessionId),intent:kt,requiredFeature:d.literal(Ke)}).strict().parse(r);o=this.prepareOpen(i)}else{let i=d.object({protocol:d.literal($),request:H,bindingId:d.string(),expectedRevision:d.string(),ticket:d.string().optional(),sessionId:d.string().optional(),reason:d.literal("manual").optional()}).strict().parse(r);o=this.prepareMutation(e,i)}if(Buffer.compare(Buffer.from(o.bytes()),Buffer.from(n))!==0)throw new h("request_id_conflict");return o}#U(e){this.#b=!0;try{let n=new Map(e.map(l=>[l.key,l.value]));if(n.size!==e.length||!n.has("meta"))throw new Error("inventory");let r=G(n.get("meta"));if(r.format==="sdk2-cache-client-retired-v1"){let l=gi.parse(r);if(e.length!==1||l.baseUrl!==this.#t||l.runtimeSessionId!==this.runtimeSessionId||l.continuityScope?.applicationScopeId!==this.#e.continuityScope?.applicationScopeId||l.continuityScope?.endUserId!==this.#e.continuityScope?.endUserId)throw new Error("retirement inventory");this.#g=l;return}let o=d.object({format:d.enum(["sdk2-cache-client-v1","sdk2-cache-client-core-v1"]),baseUrl:d.literal(this.#t),runtimeSessionId:d.literal(this.runtimeSessionId),binding:d.object({view:ze,ticket:d.string(),ticketExpiresAt:d.string()}).strict().nullable(),opened:Je.nullable(),openedIntent:d.string().nullable(),continuity:hi.optional(),terminalProof:$r.optional()}).strict().parse(r);if(this.#v=o.format==="sdk2-cache-client-core-v1",this.#p=o.continuity,this.#p&&(!this.#e.continuityScope||this.#p.applicationScopeId!==this.#e.continuityScope.applicationScopeId||this.#p.endUserId!==this.#e.continuityScope.endUserId||o.binding&&o.binding.view.bindingId!==this.#p.bindingId||o.opened!==null||o.openedIntent!==null))throw new Error("continuity inventory");if(this.#a=o.binding??void 0,this.#u=o.opened??void 0,this.#c=o.openedIntent??void 0,this.#y=o.terminalProof,this.#y&&(this.#y.kind!=="close"||this.#a||this.#y.bindingId!==(this.#p?.bindingId??this.#u?.binding.bindingId)))throw new Error("terminal proof inventory");this.#a&&(xt(this.#a.ticket),d.string().datetime({offset:!0}).parse(this.#a.ticketExpiresAt));let i=new Set,s=new Map;for(let l of e)if(!(l.key==="meta"||l.key==="pending-control"))if(l.key.startsWith("control/")){let c=d.object({operation:d.enum(["open","renew","rebind","rotate","close"]),body:d.string(),result:d.union([Je,Rt]).nullable()}).strict().parse(G(l.value)),p=Buffer.from(c.body,"base64");if(p.toString("base64")!==c.body||wn(c.operation,p)!==l.key)throw new Error("inventory");this.#m.set(l.key,{operation:c.operation,body:p,result:c.result})}else if(l.key.startsWith("exchange/")){let c=l.key.slice(9),p=Buffer.from(l.value);if(!vt(c)||p.length<5||p.length>33619972)throw new Error("inventory");let f=p.readUInt32BE(0);if(f>65536||f<1||p.length<=4+f)throw new Error("inventory");let g=G(p.subarray(4,4+f));if(g.runtimeSessionId!==this.runtimeSessionId)throw new Error("inventory");let b=p.subarray(4+f).toString("utf8");if(Buffer.compare(Rn(g,c,b),p)!==0)throw new Error("inventory");this.#s.set(c,{body:b,frame:p,uncertain:!0,active:!1,durable:!1})}else if(l.key.startsWith("core-exchange/")){if(!this.#v)throw new Error("Core inventory version");let c=l.key.slice(14),p=Jn(l.value);if(!vt(c)||p.requestId!==c||p.runtimeSessionId!==this.runtimeSessionId)throw new Error("Core inventory");s.set(c,p)}else if(l.key.startsWith("completed/")){let c=l.key.slice(10);if(!vt(c)||l.value.length!==0)throw new Error("inventory");this.#d.add(c)}else if(l.key.startsWith("flight/")){if(!vt(l.key.slice(7))||l.value.length!==0)throw new Error("inventory");i.add(l.key.slice(7))}else throw new Error("inventory");for(let[l,c]of s){let p=this.#s.get(l);if(!p||ie("sha256").update(p.body).digest("hex")!==c.payloadSha256)throw new Error("Core inventory");let f=G(p.frame.subarray(4,4+p.frame.readUInt32BE(0)));if(f.bindingId!==c.bindingId||f.projectionRef!==c.projectionRef)throw new Error("Core inventory");p.core=c}for(let[l,c]of this.#s)c.durable=i.has(l);if(this.#m.size>128||this.#s.size>16||this.#d.size>4096||[...this.#s].some(([l])=>this.#d.has(l))||[...i].some(l=>!this.#s.has(l))||[...this.#s.values()].reduce((l,c)=>l+c.frame.length+Buffer.byteLength(c.body)+(c.core?se(c.core).byteLength:0),0)>67108864)throw new Error("inventory");let a=n.get("pending-control"),u=[...this.#m].filter(([,l])=>!("completed"in l)&&l.result===null);if(a){let l=Buffer.from(a).toString("utf8"),c=this.#m.get(l);if(!c||"completed"in c||c.result||u.length!==1||this.#s.size>0)throw new Error("inventory");this.prepareControlBytes(c.operation,c.body),this.#n.started=!0}else if(u.length!==0)throw new Error("inventory");if(this.#y&&![...this.#m.values()].some(l=>!("completed"in l)&&l.operation==="close"&&l.result&&l.result.binding.state==="closed"&&l.result.binding.bindingId===this.#y.bindingId&&this.#A(l.body,l.result).digest===this.#y.digest))throw new Error("terminal proof receipt");for(let[l,c]of this.#m)!("completed"in c)&&c.result!==null&&this.#m.set(l,Nr(c))}catch{throw this.#h=!0,new h("storage_unknown",void 0,void 0,"query-status")}finally{this.#b=!1}}#A(e,n){return{kind:"close",bindingId:n.binding.bindingId,digest:ie("sha256").update("tansr.sdk2.cache-retirement.close.v1\0").update(e).update("\0").update(M(n)).digest("hex")}}#O(e){if(this.#R(),this.#g){if(!Buffer.from(M(this.#g.proof)).equals(Buffer.from(M(e))))throw new h("request_id_conflict");return structuredClone(this.#g)}if(!this.#e.persistence)throw new h("mapping_unavailable");if(this.#n||this.#s.size>0||[...this.#m.values()].some(r=>!("completed"in r)&&r.result===null))throw new h("result_unknown",void 0,void 0,"query-status");let n={format:"sdk2-cache-client-retired-v1",baseUrl:this.#t,runtimeSessionId:this.runtimeSessionId,proof:{...e},compactedControls:this.#m.size,compactedExchanges:this.#d.size,...this.#e.continuityScope?{continuityScope:{...this.#e.continuityScope}}:{}};return this.#x({put:[{key:"meta",value:M(n)}],delete:[...this.#m.keys(),...[...this.#d].map(r=>`completed/${r}`)]}),this.#g=n,this.#m.clear(),this.#d.clear(),this.#a=void 0,this.#u=void 0,this.#c=void 0,this.#p=void 0,this.#y=void 0,this.#r=!1,this.#i=void 0,structuredClone(n)}#D(e){this.#R();let n=this.#e.continuityScope,{intent:r,receipt:o}=e;if(!n||!this.#e.persistence||e.baseUrl!==this.#t||e.scope.applicationScopeId!==n.applicationScopeId||e.scope.endUserId!==n.endUserId||!["resume","delete"].includes(r.operation)||r.previousRuntimeSessionId!==this.runtimeSessionId||(r.operation==="resume"?r.runtimeSessionId===this.runtimeSessionId:r.runtimeSessionId!==this.runtimeSessionId))throw new h("identity_conflict",r.requestId);let i=this.#g?.proof.bindingId??this.#a?.view.bindingId??this.#p?.bindingId??this.#u?.binding.bindingId;if(i!==r.bindingId)throw new h("identity_conflict",r.requestId);let s={kind:r.operation==="resume"?"continuity-resume":"continuity-delete",bindingId:i,digest:ie("sha256").update("tansr.sdk2.cache-retirement.continuity.v1\0").update(M({baseUrl:e.baseUrl,scope:e.scope,intent:r,receipt:o})).digest("hex")};return this.#O(s)}#j(e){this.#l();let n=this.#e.continuityScope,{intent:r,receipt:o}=e;if(!n||!this.#e.persistence||e.baseUrl!==this.#t||e.scope.applicationScopeId!==n.applicationScopeId||e.scope.endUserId!==n.endUserId||r.runtimeSessionId!==this.runtimeSessionId||o.source.runtimeSessionId!==this.runtimeSessionId||r.operation!=="resume"||!o.ticket||!o.ticketExpiresAt)throw new h("identity_conflict");if(this.#n||this.#s.size>0)throw new h("result_unknown",r.requestId,void 0,"query-status");let i={applicationScopeId:n.applicationScopeId,endUserId:n.endUserId,sourceNamespace:e.scope.sourceNamespace,intentDigest:ie("sha256").update(M(r)).digest("hex"),receiptDigest:ie("sha256").update(M(o)).digest("hex"),bindingId:o.binding.bindingId};if(this.#p){if(Buffer.from(M(this.#p)).equals(Buffer.from(M(i))))return;throw new h("request_id_conflict",r.requestId)}if(this.#a||this.#u||this.#m.size>0||this.#d.size>0)throw new h("identity_conflict",r.requestId);if(!this.#r||Date.parse(o.ticketExpiresAt)<=Date.now()||Date.parse(o.binding.expiresAt)<=Date.now())throw new h("mapping_unavailable",r.requestId);let s={view:structuredClone(o.binding),ticket:o.ticket,ticketExpiresAt:o.ticketExpiresAt};this.#x({put:[{key:"meta",value:this.#E(s,void 0,void 0,i)}],delete:[]}),this.#a=s,this.#p=i}async#P(e,n,r,o){this.#l();let i=await this.#e.token();if(this.#l(),typeof i!="string"||i.trim()!==i||i.length===0||/[\r\n]/.test(i))throw new h("unauthorized");let s=Fr(this.#e.timeoutMs??3e4,r);try{n&&e.startsWith("/cache/")&&this.#n&&this.#x({put:[{key:"pending-control",value:Buffer.from(wn(this.#n.operation,this.#n.body))}],delete:[]});let a=await this.#o(`${this.#t}${e}`,{method:n===void 0?"GET":"POST",redirect:"error",headers:{accept:"application/json","x-tansr-app-token":i,...n?{"content-type":"application/json"}:{}},...n?{body:Buffer.from(n)}:{},signal:s.signal});return await o(a)}finally{s.close()}}async#_(e,n,r,o){try{return await this.#P(e,n,o,async i=>{if(i.status!==200)throw await he(i);let s=await _t(i);return this.#l(),r.parse(s)})}catch(i){throw i instanceof h?i:new h("result_unknown",void 0,void 0,"query-status")}}async capabilities(e){let n=await this.#_("/cache/v1/capabilities",void 0,Dr,e);return this.#l(),this.#i={value:Gr(n),expires:Date.now()+n.limits.negotiatedTtlMs},structuredClone(n)}async#T(e){this.#l();let n=this.#i&&this.#i.expires>Date.now()?this.#i.value:Gr(await this.capabilities(e));if(this.#l(),!n.enabled||!n.operationEpoch||Date.parse(n.operationEpoch.expiresAt)<=Date.now())throw new h("unsupported_capability");return n}async#I(e){if(this.#l(),this.#r)return;let n=await this.#_("/heartbeat",M({client:"sdk",sessionId:this.runtimeSessionId}),d.object({sessionId:d.literal(this.runtimeSessionId)}).passthrough(),e);this.#l(),this.#r=n.sessionId===this.runtimeSessionId}async open(e={kind:"new"},n){if(this.#l(),this.#p)throw new h("mapping_unavailable");let r=kt.parse(G(M(e)));if(this.#n){let i=G(this.#n.body);if(this.#n.operation!=="open"||Buffer.compare(Buffer.from(M(i.intent)),Buffer.from(M(r)))!==0)throw new h("request_id_conflict");return this.#n.handle.execute(n)}if(this.#u){if(this.#c!==Buffer.from(M(r)).toString("utf8"))throw new h("request_id_conflict");if(!this.#a||this.#a.view.state!=="active")throw new h("mapping_unavailable");return structuredClone(this.#u)}await this.#I(n);let o=await this.#T(n);return this.prepareOpen({request:{operationEpoch:o.operationEpoch.id,requestId:fi()},intent:r}).execute(n)}prepareOpen(e){if(this.#l(),this.#p)throw new h("mapping_unavailable");let n=H.parse(e.request),r=kt.parse(e.intent);return this.#B("open","/cache/v1/bindings",null,{protocol:$,request:n,runtimeSessionId:this.runtimeSessionId,intent:r,requiredFeature:Ke})}prepareMutation(e,n){if(this.#l(),!["renew","rebind","rotate","close"].includes(e))throw new h("invalid_request");let r=F(n.bindingId),o=H.parse(n.request),i=qr(n.expectedRevision);if(this.#p&&r!==this.#p.bindingId)throw new h("identity_conflict",o.requestId);let s={protocol:$,request:o,bindingId:r,expectedRevision:i};if(e==="rebind"){if(n.sessionId!==this.runtimeSessionId||n.ticket!==void 0||n.reason!==void 0)throw new h("invalid_request");s.sessionId=this.runtimeSessionId}else{if(s.ticket=xt(n.ticket??""),n.sessionId!==void 0||e!=="rotate"&&n.reason!==void 0)throw new h("invalid_request");if(e==="rotate"){if(n.reason!=="manual")throw new h("invalid_request");s.reason="manual"}}return this.#B(e,`/cache/v1/bindings/${encodeURIComponent(r)}/${e}`,r,s)}#B(e,n,r,o){this.#l();let i=M(o),s=H.parse(o.request),a=wn(e,i);for(let[g,b]of this.#m){if(b.operation!==e)continue;let R="completed"in b?b:G(b.body);if(R.request.operationEpoch===s.operationEpoch&&R.request.requestId===s.requestId&&(R.bindingId??null)===r&&g!==a)throw new h("request_id_conflict",s.requestId)}let u=this.#m.get(a);if(u&&u.operation!==e)throw new h("request_id_conflict");if(u&&("completed"in u||u.result)){let g=b=>this.queryOperation({operation:e,request:s,bindingId:r},b);return Object.freeze({operation:e,request:Object.freeze({...s}),bytes:()=>new Uint8Array(i),execute:g,query:g})}if(this.#n){if(this.#n.operation!==e||Buffer.compare(Buffer.from(this.#n.body),Buffer.from(i))!==0)throw new h("request_id_conflict");return this.#n.handle}if(this.#s.size>0)throw new h("result_unknown",void 0,void 0,"query-status");if(this.#e.persistence&&!u&&this.#m.size>=128)throw new h("capacity_exceeded",s.requestId);let l=async(g,b)=>{if(this.#l(),p.sending)throw new h("result_unknown",s.requestId,void 0,"query-status");if(this.#n!==p)throw new h("request_id_conflict",s.requestId);p.sending=!0;try{!g&&e==="open"&&await this.#I(b),!g&&!p.started&&await this.#T(b),p.started=!0;let R=g?await this.queryOperation({operation:e,request:s,bindingId:r},b):await this.#_(n,i,d.union([Je,Rt]),b);if(R.request.operationEpoch!==s.operationEpoch||R.request.requestId!==s.requestId||r!==null&&R.binding.bindingId!==r||(e==="open"?!("relation"in R):!("operation"in R)||R.operation!==e))throw new h("invalid_response");let y=R.ticket&&R.ticketExpiresAt?{view:R.binding,ticket:R.ticket,ticketExpiresAt:R.ticketExpiresAt}:void 0,k="relation"in R?R:this.#u,x="relation"in R?Buffer.from(M(o.intent)).toString("utf8"):this.#c,_={operation:e,body:i,result:R},O=this.#e.persistence?Nr(_):void 0,m=e==="close"&&R.binding.state==="closed"&&this.#a?.view.bindingId===R.binding.bindingId?this.#A(i,R):null;return this.#x({put:[{key:"meta",value:this.#E(y??null,k,x,this.#p,m)},{key:a,value:this.#M(_)}],delete:["pending-control"]}),this.#a=y,this.#u=k,this.#c=x,this.#y=m??void 0,O&&this.#m.set(a,O),this.#n=void 0,structuredClone(R)}finally{p.sending=!1}},c=Object.freeze({operation:e,request:Object.freeze({...s}),bytes:()=>new Uint8Array(i),execute:g=>l(!1,g),query:g=>l(!0,g)}),p={operation:e,identity:s,body:i,path:n,bindingId:r,handle:c,sending:!1,started:!1},f={operation:e,body:i,result:null};return this.#x({put:[{key:a,value:this.#M(f)},{key:"pending-control",value:Buffer.from(a)}],delete:[]}),this.#e.persistence&&this.#m.set(a,f),this.#n=p,this.#w=Math.max(this.#w,i.byteLength),c}async queryOperation(e,n){let r=H.parse(e.request);if(!["open","renew","rebind","rotate","close"].includes(e.operation)||(e.operation==="open"?e.bindingId!==null:e.bindingId===null))throw new h("invalid_request");let o=new URLSearchParams({protocol:$,operation:e.operation,operationEpoch:r.operationEpoch,requestId:r.requestId,...e.bindingId===null?{}:{bindingId:F(e.bindingId)}}),i=await this.#_(`/cache/v1/operations?${o}`,void 0,d.union([Je,Rt]),n);if(i.request.operationEpoch!==r.operationEpoch||i.request.requestId!==r.requestId||(e.operation==="open"?!("relation"in i):!("operation"in i)||i.operation!==e.operation||i.binding.bindingId!==e.bindingId))throw new h("invalid_response");return i}async readBinding(e,n){let r=await this.#_(`/cache/v1/bindings/${encodeURIComponent(F(e))}?protocol=${$}`,void 0,ze,n);if(r.bindingId!==e)throw new h("invalid_response");return r}async diagnostics(e,n=null,r=100,o){if(!Number.isInteger(r)||r<1||r>100)throw new h("invalid_request");let i=new URLSearchParams({protocol:$,limit:String(r),...n===null?{}:{after:F(n)}});return this.#_(`/cache/v1/bindings/${encodeURIComponent(F(e))}/diagnostics?${i}`,void 0,yi,o)}async coreCapabilities(e){let n=await this.#_(`${be}/capabilities`,void 0,Kn,e);if(!n.features.includes("trusted-core-projection-v1"))throw new h("unsupported_capability");return n}async coreDiagnostics(e,n=null,r=100,o){if(!Number.isInteger(r)||r<1||r>100||n!==null&&(n.length>150||!/^[0-9]+\.[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(n)))throw new h("invalid_request");let i=new URLSearchParams({protocol:Ln,limit:String(r),...n===null?{}:{after:n}});return this.#P(`${be}/bindings/${encodeURIComponent(F(e))}/diagnostics?${i}`,void 0,o,async s=>{if(s.status!==200)throw await he(s);let a=Hn.parse(await _t(s));if(this.#l(),a.rows.length>r)throw new h("invalid_response");return a})}transport(e){if(this.#l(),!this.#a||this.#n)throw new h("mapping_unavailable");return e===void 0?this.#f:Object.freeze({...this.#f,coreProjection:!0,prepare:(n,r,o)=>this.#W(n,r,o,e)})}#W(e,n,r,o){if(this.#l(),this.#d.has(e))throw new h("receipt_expired",e);let i=this.#s.get(e);if(i){if(i.body!==n)throw new h("request_id_conflict",e)}else{if(this.#n||[...this.#s.values()].some(f=>f.uncertain))throw new h("result_unknown",e,void 0,"query-status");let a=o!==void 0&&!this.#v;if(a&&this.#s.size!==0)throw new h("pending_execution",e);let u=this.#a;if(!u||u.view.state!=="active"||!u.view.projection||u.view.projection.status==="rebuild-required"||Date.parse(u.ticketExpiresAt)<=Date.now())throw new h("mapping_unavailable",e);if(this.#s.size>=16||this.#d.size+this.#s.size>=4096)throw new h("capacity_exceeded",e);let l=Rn({bindingId:u.view.bindingId,ticket:u.ticket,runtimeSessionId:this.runtimeSessionId,projectionRef:u.view.projection.projectionRef},e,n),c;if(o!==void 0){if(!r)throw new h("core_source_missing",e);Ut(r),c=o.prepare({runtimeSessionId:this.runtimeSessionId,bindingId:u.view.bindingId,bindingRevision:u.view.revision,projectionRef:u.view.projection.projectionRef,requestId:e,payloadSha256:ie("sha256").update(n).digest("hex")},r)}let p=l.length+Buffer.byteLength(n)+(c?se(c).byteLength:0)+[...this.#s.values()].reduce((f,g)=>f+g.frame.length+Buffer.byteLength(g.body)+(g.core?se(g.core).byteLength:0),0);if(p>67108864)throw new h("capacity_exceeded",e);a&&(this.#v=!0,this.#C=!0),i={body:n,frame:l,uncertain:!1,active:!1,durable:!1,...c?{core:c}:{}},this.#s.set(e,i),this.#k=Math.max(this.#k,p)}if(i.core){if(!o||!r)throw new h("core_source_missing",e);if(Ut(r),!Buffer.from(M(r.facts)).equals(Buffer.from(M(i.core.core))))throw new h("request_id_conflict",e)}else if(o)throw new h("request_id_conflict",e);let s=i;return Object.freeze({requestId:e,send:async(a,u)=>{if(this.#l(),s.active)throw new h("result_unknown",e,void 0,"query-status");s.active=!0;let l=!1;try{if(!s.uncertain){let f=await this.#T(a);if(Buffer.byteLength(s.body)>f.limits.exchangeBytes||s.frame.readUInt32BE(0)>f.limits.controlBytes)throw new h("payload_too_large",e);s.core&&await this.coreCapabilities(a)}let c=await this.#e.token();if(this.#l(),typeof c!="string"||!c||c.trim()!==c||/[\r\n]/.test(c))throw new h("unauthorized",e);let p=s.core?await o.credential(structuredClone(s.core),a):void 0;if(s.core&&(r?.assertCurrent(),o.assertCurrent(s.core),typeof p!="string"||p.length>8192||!/^[A-Za-z0-9_-]+$/.test(p)))throw new h("invalid_request",e);return this.#l(),s.durable||(this.#x({put:[{key:`exchange/${e}`,value:s.frame},...s.core?[{key:`core-exchange/${e}`,value:se(s.core)}]:[],...this.#C?[{key:"meta",value:this.#E()}]:[],{key:`flight/${e}`,value:new Uint8Array}],delete:[]}),s.durable=!0),l=!0,await this.#o(`${this.#t}${s.core?be:"/cache/v1"}/exchange`,{method:"POST",redirect:"error",headers:{"content-type":kn,accept:u?"text/event-stream":"application/json","x-tansr-app-token":c,...p?{[Wt]:p}:{}},body:Buffer.from(s.frame),signal:a})}catch(c){throw l?(this.#f.uncertain(e),new h("result_unknown",e,void 0,"query-status")):(s.active=!1,c instanceof h,c)}}})}};var bi=17e4,Lr=17e4,ki=600,Ri=16,Ye=class{#e;#t;#o;#i=new Map;#r=null;constructor(e){this.#e=e,this.#t=e.baseUrl.replace(/\/+$/,""),this.#o=e.fetchImpl??fetch,e.gatewayCache?.coreProjection===!0&&Yn(this)}#n(){let e=this.#e.apiKey,n=this.#e.keyId,r=typeof e=="function"?e():e,o=typeof n=="function"?n():n??"",i=this.#r,s=i!==null&&i.sk===r?i.key:pn(r);return(i===null||i.sk!==r)&&(this.#r={sk:r,key:s}),{keyId:o,apiKey:r,signingKey:s}}async*stream(e,n={}){if(n.signal?.throwIfAborted(),this.#e.beforeExchange!==void 0){let m=n.signal,E;try{let v=Promise.resolve(this.#e.beforeExchange());if(m===void 0)await v;else{let w=new Promise((T,W)=>{E=()=>W(m.reason),m.addEventListener("abort",E,{once:!0}),m.aborted&&E()});await Promise.race([v,w])}}catch{m?.throwIfAborted()}finally{E!==void 0&&m?.removeEventListener("abort",E)}m?.throwIfAborted()}let r=Date.now(),o=n.connectTimeoutMs??n.timeoutMs??bi,i=n.idleTimeoutMs??this.#e.idleTimeoutMs??Lr,s=n.totalTimeoutMs??this.#e.totalTimeoutMs,a=new AbortController,u=null,l=null,c=null,p=(m,E)=>{u!==null&&clearTimeout(u);let v=setTimeout(()=>{c=m,a.abort()},E);v.unref?.(),u=v};s!==void 0&&Number.isFinite(s)&&s>0&&(l=setTimeout(()=>{c="total",a.abort()},s),l.unref?.());let f=()=>{u!==null&&clearTimeout(u),u=null,l!==null&&clearTimeout(l),l=null},g=()=>c==="idle"?`Stream idle timeout: no frames for ${i}ms`:c==="total"?`Request total timeout: exceeded ${s}ms wall clock (including stream)`:`Request timed out after ${o}ms`,b=n.signal!==void 0?AbortSignal.any([n.signal,a.signal]):a.signal,R=this.#e.stream??!0,y=We(n),k=y??this.#e.generateRequestId?.()??fe(),x=this.#e.gatewayCache?.originalBody(k)??(y!==void 0?this.#i.get(y):void 0);if(x===void 0){let m=this.#e.sessionId?.(),E=this.#a(n),v=Ot(this.#e.features?.(),this.#e.imageInput?.()),w=At(this.#e.features?.()),T=Pt(this.#e.features?.()),W=Bt(this.#e.features?.());try{x=JSON.stringify(fn(e,{stream:R,requestId:k,...this.#e.client!==void 0?{client:this.#e.client}:{},...m!==void 0?{sessionId:m}:{},...E!==void 0?{purpose:E}:{},...v?{sendImages:v}:{},...w?{cacheHints:w}:{},...w&&m!==void 0?{cacheKey:m}:{},...T?{reasoningOff:T}:{},...W?{reasoningLevels:W}:{}}))}catch(I){if(I instanceof V){yield{t:"error",kind:"invalid_request",message:I.message,recoverable:!1};return}throw I}y!==void 0&&this.#u(y,x)}let _;try{this.#e.gatewayCache===void 0&&(_=this.#n())}catch(m){yield{t:"error",kind:"auth",message:m instanceof Error?m.message:String(m),recoverable:!1};return}let O=`${this.#t}/exchange`;try{let m;p("connect",o);try{m=this.#e.gatewayCache!==void 0?await this.#e.gatewayCache.prepare(k,x,this.#e.gatewayCache.coreProjection?Vn(e):void 0).send(b,R):await this.#o(O,{method:"POST",headers:{"content-type":"application/json",accept:R?"text/event-stream":"application/json",[et]:_.keyId,[tt]:_.apiKey,...this.#e.signRequests!==!1?mn({signingKey:_.signingKey,method:"POST",pathWithQuery:wi(O),body:x}):{},...this.#e.defaultHeaders},body:x,signal:b})}catch(C){yield this.#s(C,n,g(),"connect",k);return}if(p("idle",i),!m.ok){if(this.#e.gatewayCache!==void 0)throw await he(m,k);yield await this.#f(m,k);return}if(m.status===202){if(this.#e.gatewayCache!==void 0)throw await he(m,k);yield await this.#d(m,k);return}if(!R){yield*this.#c(m,e,n,g,y,k);return}if((m.headers.get("content-type")??"").toLowerCase().includes("application/json")){yield*this.#c(m,e,n,g,y,k);return}if(m.body===null){if(this.#e.gatewayCache!==void 0)throw new h("result_unknown",k,void 0,"query-status");yield{t:"error",kind:"server",message:"Empty response body from twp endpoint",recoverable:!0};return}let v=new te,w=this.#e.onPlatformError,T=new Ne({fallbackModel:e.model.model,...this.#e.onUsage!==void 0?{onUsage:this.#e.onUsage}:{},...this.#e.onWarn!==void 0?{onWarn:this.#e.onWarn}:{},...w!==void 0?{onErr:C=>w({code:C.code,message:C.message,requestId:C.requestId??k,...C.detail!==void 0?{detail:C.detail}:{}})}:{}}),W,I,q=C=>{if(this.#e.gatewayCache!==void 0)try{let N=JSON.parse(C);if(!N||typeof N.stop!="string"||!nt.includes(N.stop))throw new Error}catch{throw new h("result_unknown",k,void 0,"query-status")}},D=C=>{if(this.#e.gatewayCache!==void 0&&C.t==="error")throw new h("result_unknown",k,void 0,"query-status");return W===void 0&&(C.t==="block_start"||C.t==="text_delta"||C.t==="tool_args_delta")&&(W=Date.now()),C.t==="message_stop"&&(this.#e.gatewayCache?.finish(k),y!==void 0&&C.stopReason!=="unknown"&&this.#i.delete(y),W!==void 0)?{...C,ttftMs:W-r}:C};try{let C=v.comments;e:for await(let N of m.body){let ye=v.feed(N);(ye.length>0||v.comments!==C)&&(C=v.comments,p("idle",i));for(let S of ye){if(this.#e.gatewayCache!==void 0&&S.event==="t.close"){q(S.data),I=T.handleFrame(S);break e}for(let ne of T.handleFrame(S))yield D(ne)}if(T.ended)return}}catch(C){yield this.#s(C,n,g(),"stream",k);return}if(I!==void 0){for(let C of I)yield D(C);return}for(let C of v.end()){C.event==="t.close"&&q(C.data);for(let N of T.handleFrame(C))yield D(N)}if(this.#e.gatewayCache!==void 0&&!T.ended)throw new h("result_unknown",k,void 0,"query-status");for(let C of T.finish())yield D(C)}finally{this.#e.gatewayCache?.uncertain(k),f()}}#a(e){return St(ke(e)?.purpose)}#u(e,n){if(this.#i.size>=Ri){let r=this.#i.keys().next();r.done!==!0&&this.#i.delete(r.value)}this.#i.set(e,n)}async*#c(e,n,r,o,i,s){let a;try{a=await e.json()}catch(p){yield this.#s(p,r,o(),"stream",s);return}let u=yn(a);if(this.#e.gatewayCache!==void 0){let p=a;if(!p||typeof p.exchangeId!="string"||typeof p.model!="string"||!Array.isArray(p.blocks)||typeof p.stop!="string"||!nt.includes(p.stop))throw new h("result_unknown",s,void 0,"query-status")}u!==null&&this.#e.onUsage?.(u);let l=gn(a,n.model.model);if(this.#e.gatewayCache!==void 0){if(l[l.length-1]?.t!=="message_stop")throw new h("result_unknown",void 0,void 0,"query-status");this.#e.gatewayCache.finish(s)}let c=l[l.length-1];i!==void 0&&c?.t==="message_stop"&&c.stopReason!=="unknown"&&this.#i.delete(i),yield*l}#s(e,n,r,o,i){if(this.#e.gatewayCache!==void 0)throw e instanceof h?e:new h("result_unknown",i,void 0,"query-status");if(n.signal?.aborted===!0)throw e;let s=J(e);if(s!==void 0)return s;let a=typeof e=="object"&&e!==null&&"name"in e?String(e.name):"",u=a==="TimeoutError"||a==="AbortError",l=u?r:Q(e);return Y({t:"error",kind:o==="stream"?"stream_interrupted":u?"connect":"network",message:l,recoverable:!0,...o==="stream"||u?{idempotencyConsumed:!0}:{}},e)}async#d(e,n){let r,o;try{let i=await e.json();typeof i?.retryAfterMs=="number"&&Number.isFinite(i.retryAfterMs)&&i.retryAfterMs>=0&&(r=j(Math.round(i.retryAfterMs))),typeof i?.requestId=="string"&&(o=i.requestId)}catch{}return{t:"error",kind:"server",message:`exchange in progress (HTTP 202): requestId ${o??n} still in flight; retrying with the same requestId`,recoverable:!0,...r!==void 0?{retryAfterMs:r}:{}}}async#f(e,n){let r="";try{r=await e.text()}catch{}let o;try{let u=JSON.parse(r);if(typeof u?.error?.code=="string"){let l=u.error.detail;o={code:u.error.code,message:typeof u.error.message=="string"?u.error.message:"",...typeof l=="object"&&l!==null&&!Array.isArray(l)?{detail:l}:{}}}}catch{}let i=o?.code==="idempotency_conflict"&&o.detail?.replayable===!1;if(o?.code!==void 0&&!i){let u=typeof o.detail?.requestId=="string"?o.detail.requestId:void 0;this.#e.onPlatformError?.({code:o.code,message:o.message??"",requestId:u??n,...o.detail!==void 0?{detail:o.detail}:{}})}let s=xi(e.headers);return i?{t:"error",kind:"server",message:`idempotency_conflict: ${o?.message??""}`,recoverable:!0,idempotencyConsumed:!0,...s!==void 0?{retryAfterMs:s}:{}}:{t:"error",...o?.code!==void 0?qe(o.code,o.message??"",o.detail):hn(e.status,r.slice(0,ki)||e.statusText),...s!==void 0?{retryAfterMs:s}:{}}}};function wi(t){try{let e=new URL(t);return e.pathname+e.search}catch{return t}}function xi(t){let e=t.get("retry-after");if(e===null)return;let n=Number(e);return Number.isFinite(n)&&n>=0?j(Math.round(n*1e3)):void 0}var Hr="TANSR_KEY_ID";function Kr(t,e){let n=t.providerProfile.auth;if(n===void 0)throw new ee(t.providerId);let r=e[n.env];if(r===void 0||r==="")throw new ee(t.providerId,n.env);return r}function vn(t,e={}){let n=e.env??process.env;Kr(t,n);let r=()=>Kr(t,n),o=e.governor!==void 0?e.fetchImpl!==void 0?e.governor.wrapFetch(e.fetchImpl):e.governor.fetch:e.fetchImpl,i={baseUrl:t.providerProfile.baseUrl,apiKey:r,...e.defaultHeaders!==void 0?{defaultHeaders:e.defaultHeaders}:{},...o!==void 0?{fetchImpl:o}:{}};switch(t.providerProfile.protocol){case"anthropic":return new Se({...i,messageCacheBreakpoint:t.capability.promptCaching.mode==="explicit"});case"openai":{let s=t.capability.thinking.mustEchoBack;return new ce({...i,echoThinking:s,...s&&n.TANSR_THINKING_ECHO_PROBE==="1"?{onThinkingEcho:a=>{process.stderr.write(`[thinking-echo] provider=${t.providerId} model=${t.modelName} reasoning_chars=${a.chars} assistant_messages=${a.messages}
|
|
22
22
|
`)}}:{}})}case"openai-responses":return new me(i);case"twp":{let s=e.twp;return new Ye({...i,...s?.gatewayCache!==void 0?{gatewayCache:s.gatewayCache}:{},keyId:()=>s?.keyId??n[Hr]??"",...s?.client!==void 0?{client:s.client}:{},...s?.sessionId!==void 0?{sessionId:s.sessionId}:{},...s?.onUsage!==void 0?{onUsage:s.onUsage}:{},...s?.onWarn!==void 0?{onWarn:s.onWarn}:{},...s?.onPlatformError!==void 0?{onPlatformError:s.onPlatformError}:{},...s?.stream!==void 0?{stream:s.stream}:{},...s?.beforeExchange!==void 0?{beforeExchange:s.beforeExchange}:{},...s?.idleTimeoutMs!==void 0?{idleTimeoutMs:s.idleTimeoutMs}:{},...s?.totalTimeoutMs!==void 0?{totalTimeoutMs:s.totalTimeoutMs}:{},...s?.signRequests!==void 0?{signRequests:s.signRequests}:{},...s?.features!==void 0?{features:s.features}:{},imageInput:s?.imageInput??(()=>Ft(t.capability))})}}}function _n(t,e){let n=[];return Jr(t,e,[],n,new Set),n}function zr(t,e,n){let r=`${n.providerId}/${n.modelName}`;e.has(r)||(e.add(r),t.push(n))}function Jr(t,e,n,r,o){if(n.includes(e))throw new xe([...n,e]);let i=[...n,e];zr(r,o,Te(t,e));for(let s of t.fallbacks[e]??[])s.includes("/")?zr(r,o,Ee(t,s)):Jr(t,s,i,r,o)}var Yr=class{#e;#t;constructor(e,n={}){this.#e=e,this.#t=n}resolveAlias(e){return Te(this.#e,e)}createClient(e,n={}){return vn(e,{...this.#t.env!==void 0?{env:this.#t.env}:{},...this.#t.fetchImpl!==void 0?{fetchImpl:this.#t.fetchImpl}:{},...this.#t.twp!==void 0?{twp:this.#t.twp}:{},...this.#t.governor!==void 0?{governor:this.#t.governor}:{},...n})}get governor(){return this.#t.governor}get usesGatewayCache(){return this.#t.twp?.gatewayCache!==void 0}fallbacksFor(e){return _n(this.#e,e)}};function ru(t,e,n){if(n!==void 0)try{return n.resolveAlias(`${t}/${e}`).capability}catch{}return Ce(t,e)?.capability}var vi={connect:"connect",network:"network",rate_limited:"rate_limited",server:"server",stream_interrupted:"stream_interrupted"};function Cn(t){return t.recoverable?vi[t.kind]??"server":t.kind==="policy_denied"?"quota":"terminal"}function En(t){return t==="connect"||t==="network"}function Tn(t){return t==="quota"||t==="terminal"}var In=["title","memory"],Mn=2;function Sn(t){return t===void 0||t==="main"}async function _i(t,e){let n=t.next();if(e===void 0){let i=await n;return i.done===!0?{t:"done"}:{t:"event",event:i.value}}let r,o=new Promise(i=>{r=e.timers.setTimeout(()=>i({t:"idle_timeout"}),e.idleMs)});try{return await Promise.race([n.then(i=>i.done===!0?{t:"done"}:{t:"event",event:i.value}),o])}finally{e.timers.clearTimeout(r)}}async function*Ct(t,e){let{callerSignal:n,watchdog:r}=e,o=[],i=!1,s=!1;try{for(;;){let a=await _i(t,r);if(n?.aborted===!0)return{t:"aborted"};if(a.t==="idle_timeout"){if(r===void 0)throw new Error("pumpStream invariant: idle_timeout without watchdog");r.abortAttempt();let l={t:"error",kind:"stream_interrupted",message:`Idle watchdog: no stream event within ${r.idleMs}ms`,recoverable:!0,idempotencyConsumed:!0};return i?(yield l,{t:"error_post_content",error:l,idleTimeout:!0}):{t:"error_pre_content",error:l,idleTimeout:!0}}if(a.t==="done"){for(let l of o)yield l;return{t:"success"}}let u=a.event;if(s||(s=!0,e.onFirstEvent?.()),u.t==="error")return i?(e.onErrorForwarded?.(u),yield u,{t:"error_post_content",error:u}):{t:"error_pre_content",error:u};if(!i&&u.t==="message_start"){o.push(u);continue}if(!i){i=!0,e.onContentStart?.();for(let l of o)yield l;o.length=0}u.t==="message_stop"&&e.onMessageStop?.(u),yield u}}finally{t.return(void 0).catch(()=>{})}}var An=(t,e)=>new Promise(n=>{if(t<=0||e?.aborted===!0){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e?.removeEventListener("abort",r),n()},t);e?.addEventListener("abort",r,{once:!0})}),On={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)};function Pn(t,e){return t!==void 0&&e!==void 0?AbortSignal.any([t,e]):t??e}function Bn(t,e,n,r){let o={start:e.start,...e.firstEventAtMs!==void 0?{firstEventAtMs:e.firstEventAtMs}:{},endedAtMs:r,durationMs:Math.max(0,r-e.start.startedAtMs),outcome:n.outcome,...n.errorKind!==void 0?{errorKind:n.errorKind}:{},...n.transportCode!==void 0?{transportCode:n.transportCode}:{},...n.errorRecoverable!==void 0?{errorRecoverable:n.errorRecoverable}:{},...n.retryAfterMs!==void 0?{retryAfterMs:n.retryAfterMs}:{},willRetry:n.willRetry,...n.nextRetryDelayMs!==void 0?{nextRetryDelayMs:n.nextRetryDelayMs}:{},...n.maxAttempts!==void 0?{maxAttempts:n.maxAttempts}:{},...n.tierFailures!==void 0?{tierFailures:n.tierFailures}:{},...n.retryBudgetDenied===!0?{retryBudgetDenied:!0}:{}};jt(()=>t.onAttemptFinished?.(o))}var Qe=class{#e;#t;#o;#i;#r;#n;#a;#u;#c;#s;#d;constructor(e,n={}){if(this.#e=e,this.#t=Qt(n.retry),n.idleMs!==void 0&&!(n.idleMs>0))throw new TypeError(`idleMs 必须为正数,收到 ${n.idleMs}`);this.#o=n.idleMs,this.#i=n.sleep??An,this.#r=n.timers??On,this.#n=n.attemptObserver,this.#a=n.attemptContext??{},this.#u=n.now??Date.now,this.#c=n.generateIdempotencyKey??(()=>fe()),this.#s=n.hasNextCandidate,this.#d=n.retryBudget}async*stream(e,n){let r=n?.signal,o=this.#n,i=ke(n),s=this.#u(),a,u=!1,l,c=We(n)??this.#c(),p=i?.purpose!==void 0&&In.includes(i.purpose),f=p?Math.min(Mn,this.#t.maxAttempts):this.#t.maxAttempts,g=!p&&this.#t.maxAttempts>1&&Sn(i?.purpose),b=0,R=0,y,k=0,x=this.#u();this.#d?.noteRequest();try{for(let _=0;;_+=1){let O=cn(n,c),m=O,E;if(this.#o!==void 0){let S=new AbortController;m={...O,signal:Pn(r,S.signal)},E={idleMs:this.#o,timers:this.#r,abortAttempt:()=>S.abort()}}if(o!==void 0){let S={...i!==void 0?{meta:i}:{},context:this.#a,attempt:_,streamStartedAtMs:s,startedAtMs:this.#u()};a={start:S,firstEventAtMs:void 0},jt(()=>o.onAttemptStarted?.(S))}k+=1,u=!1,l=void 0;let v=yield*Ct(this.#e.stream(e,m),{callerSignal:r,watchdog:E,onMessageStop:S=>{S.stopReason==="unknown"?o!==void 0&&(l={t:"error",kind:"stream_interrupted",message:"model stream ended with stopReason='unknown'",recoverable:!0}):u=!0},onErrorForwarded:S=>{l=S},...o!==void 0?{onFirstEvent:()=>{a!==void 0&&a.firstEventAtMs===void 0&&(a.firstEventAtMs=this.#u())}}:{}});if(v.t!=="error_pre_content"){if(o!==void 0&&a!==void 0){let S=v.t==="success"?l===void 0?{outcome:"success",willRetry:!1}:{outcome:"error",errorKind:"stream_interrupted",errorRecoverable:!0,willRetry:!1}:v.t==="aborted"?{outcome:"aborted",willRetry:!1}:{outcome:v.idleTimeout===!0?"timeout":"error",errorKind:v.error.kind,transportCode:ct(v.error),errorRecoverable:v.error.recoverable,...v.error.retryAfterMs!==void 0?{retryAfterMs:v.error.retryAfterMs}:{},willRetry:!1};Bn(o,a,S,this.#u()),a=void 0}return}let w=v.error,T=Cn(w),W=this.#s?.()===!0,I=this.#u(),q,D,C=!1,N;if(Tn(T))q=!1,D=void 0;else if(g&&En(T)){C=!0,N=R+1,y??=I;let S=I-y,ne=this.#t.patient.wallMs,It=ne-S,co=S>=ne,po=W&&S>=ne/2,mo=w.retryAfterMs!==void 0&&w.retryAfterMs>It;if(q=!co&&!po&&!mo,q){let Fn=Vt(R,this.#t.patient,It,this.#t.random),fo=w.retryAfterMs!==void 0?Math.max(Fn,Math.round(lt(w.retryAfterMs,this.#t.retryAfterJitter,this.#t.random))):Fn;D=Math.min(fo,It),R+=1}}else{b+=1,N=b;let S=b>=f,ne=W&&b>=Math.ceil(f/2);q=!S&&!ne,q&&(D=Yt(b-1,{baseMs:this.#t.baseMs,maxMs:this.#t.maxMs,random:this.#t.random,retryAfterJitter:this.#t.retryAfterJitter,...w.retryAfterMs!==void 0?{retryAfterMs:w.retryAfterMs}:{}}))}let ye=!1;if(q&&this.#d!==void 0&&!this.#d.tryAcquireRetry()&&(q=!1,D=void 0,ye=!0),o!==void 0&&a!==void 0&&(Bn(o,a,{outcome:v.idleTimeout===!0?"timeout":"error",errorKind:w.kind,transportCode:ct(w),errorRecoverable:w.recoverable,...w.retryAfterMs!==void 0?{retryAfterMs:w.retryAfterMs}:{},willRetry:q,...D!==void 0?{nextRetryDelayMs:D}:{},...C?{}:{maxAttempts:f},...N!==void 0?{tierFailures:N}:{},...ye?{retryBudgetDenied:!0}:{}},this.#u()),a=void 0),!q||D===void 0){yield{...w,retrySummary:{attempts:k,elapsedMs:Math.max(0,this.#u()-x)}};return}if(w.idempotencyConsumed===!0&&(c=this.#c()),await this.#i(D,r),r?.aborted===!0)return}}finally{if(o!==void 0&&a!==void 0){let _=u?{outcome:"success",willRetry:!1}:l!==void 0?{outcome:"error",errorKind:l.kind,transportCode:ct(l),errorRecoverable:l.recoverable,willRetry:!1}:{outcome:"aborted",willRetry:!1};Bn(o,a,_,this.#u()),a=void 0}}}};function Et(t){return t?.dataClassification??"internal"}function Xe(t,e,n){if(t===void 0)return;let r=Et(t),o=t.providerAllowlist;if(o!==void 0&&o.length>0)return o.includes(e)?void 0:{providerId:e,dataClassification:r,reason:"provider-not-allowlisted",allowedProviders:[...o]};if(r==="sensitive"&&e!==n)return{providerId:e,dataClassification:r,reason:"sensitive-cross-provider",allowedProviders:[n]}}function Tt(t){let e=t.reason==="provider-not-allowlisted"?`providerAllowlist [${t.allowedProviders.join(", ")}]`:`primary provider "${t.allowedProviders[0]??""}" (sensitive without allowlist)`;return`data boundary: provider "${t.providerId}" is outside ${e} (dataClassification=${t.dataClassification}); fail-closed, no bytes sent`}var Ve=class extends Error{code="ProviderBoundary";denial;constructor(e){super(Tt(e)),this.name="ProviderBoundaryError",this.denial=e}};function Ci(t,e){let n=t instanceof ee?"auth":"invalid_request",r=t instanceof Error?t.message:String(t);return{t:"error",kind:n,message:`createClient failed for provider "${e.providerId}": ${r}`,recoverable:!1}}var Ze=class{#e;#t;#o;#i;#r;#n;#a;#u;#c;#s;#d;#f;constructor(e){if(e.entries.length===0)throw new TypeError("FallbackModelClient 需要至少一个 entry");this.#e=e.entries,this.#t=e.createClient,this.#o=e.wrapRetry??!0,this.#i=e.retry,this.#r=e.idleMs,this.#n=e.sleep,this.#a=e.timers,this.#u=e.onProviderSelected,this.#c=e.boundary,this.#s=e.attemptObserver,this.#d=e.retryBudget,this.#f=new Array(e.entries.length).fill(void 0)}#h(e,n){let r=this.#f[e];if(r!==void 0)return r;let o=this.#t(n),i=this.#o?new Qe(o,{...this.#i!==void 0?{retry:this.#i}:{},...this.#r!==void 0?{idleMs:this.#r}:{},...this.#n!==void 0?{sleep:this.#n}:{},...this.#a!==void 0?{timers:this.#a}:{},hasNextCandidate:()=>e<this.#e.length-1,...this.#d!==void 0?{retryBudget:this.#d}:{},...this.#s!==void 0?{attemptObserver:this.#s,attemptContext:{providerId:n.providerId,modelName:n.modelName,fallbackIndex:e,endpointKey:Dt(n.providerProfile.baseUrl)}}:{}}):o;return this.#f[e]=i,i}async*stream(e,n){let r=n?.signal,o=this.#c,i=this.#e[0]?.providerId??"",s=[],a=!1,u=(p,f)=>{if(a)return;a=!0;let g=this.#e[p];g!==void 0&&this.#u?.({providerId:g.providerId,modelName:g.modelName,index:p,entry:g,outcome:f,failures:[...s],...o!==void 0?{dataClassification:Et(o)}:{}})},l=(p,f,g,b)=>{s.push({providerId:f.providerId,modelName:f.modelName,index:p,error:g,...b!==void 0?{boundaryDenial:b}:{}})};for(let p=0;p<this.#e.length;p+=1){let f=this.#e[p];if(f===void 0)continue;let g=Xe(o,f.providerId,i);if(g!==void 0){l(p,f,{t:"error",kind:"invalid_request",message:Tt(g),recoverable:!1},g);continue}let b;try{b=this.#h(p,f)}catch(y){l(p,f,Ci(y,f));continue}let R=yield*Ct(b.stream(e,n),{callerSignal:r,onContentStart:()=>u(p,"served")});if(R.t==="aborted")return;if(R.t==="success"){u(p,"served");return}if(R.t==="error_post_content")return;l(p,f,R.error)}let c=s[s.length-1];if(c===void 0)throw new Error("FallbackModelClient invariant: no failure recorded");u(c.index,"exhausted"),yield c.error}};var L={now:()=>Date.now(),setTimeout:(t,e)=>{let n=setTimeout(t,e);return n.unref?.(),n},clearTimeout:t=>clearTimeout(t)};function ge(t){let e=t?.reason;if(e instanceof Error)return e;let n=new Error(typeof e=="string"?e:"This operation was aborted");return n.name="AbortError",n}var Qr=1024,Vr=1e4;function Wn(t,e={}){let n=e.clock??L,r=e.maxConcurrent??Number.POSITIVE_INFINITY,o=e.maxQueue??Qr,i=e.queueTimeoutMs??Vr;if(!(r>0))throw new TypeError(`bulkhead.maxConcurrent 必须为正数,收到 ${r}`);if(!(o>=0))throw new TypeError(`bulkhead.maxQueue 必须为非负数,收到 ${o}`);if(!(i>0))throw new TypeError(`bulkhead.queueTimeoutMs 必须为正数,收到 ${i}`);let s=0,a=!1,u=0,l=0,c=[],p=()=>{let y=!1;return()=>{y||(y=!0,s=Math.max(0,s-1),g())}},f=y=>{y.timer!==void 0&&n.clearTimeout(y.timer),y.signal!==void 0&&y.onAbort!==void 0&&y.signal.removeEventListener("abort",y.onAbort)},g=()=>{for(;!a&&s<r&&c.length>0;){let y=c.shift();f(y),s+=1,l+=1,y.resolve(p())}},b=()=>`inflight ${s}/${r}, queued ${c.length}/${o}`;return{acquire:y=>a?Promise.reject(new B("closed",t)):y?.aborted===!0?Promise.reject(ge(y)):s<r?(s+=1,Promise.resolve(p())):c.length>=o?Promise.reject(new B("saturated",t,{detail:b()})):new Promise((k,x)=>{let _={resolve:k,reject:x,timer:void 0,signal:y,onAbort:void 0},O=()=>{let m=c.indexOf(_);return m===-1?!1:(c.splice(m,1),f(_),!0)};Number.isFinite(i)&&(_.timer=n.setTimeout(()=>{O()&&x(new B("queue_timeout",t,{detail:`waited ${i}ms; ${b()}`}))},i)),y!==void 0&&(_.onAbort=()=>{O()&&x(ge(y))},y.addEventListener("abort",_.onAbort,{once:!0})),c.push(_),u+=1}),stats:()=>({inflight:s,queued:c.length,maxConcurrent:r,maxQueue:o,queueTimeoutMs:i,queuedTotal:u,dequeuedTotal:l}),close:()=>{if(a)return;a=!0;let y=c.splice(0,c.length);for(let k of y)f(k),k.reject(new B("closed",t))},get closed(){return a}}}var Un={closed:0,open:1,half_open:2},Xr=5,Zr=3e4,eo=1e3;function Dn(t={}){let e=t.clock??L,n=t.failureThreshold??Xr,r=t.openMs??Zr,o=t.probeRetryAfterMs??eo;if(!(n>=1))throw new TypeError(`breaker.failureThreshold 必须 ≥ 1,收到 ${n}`);if(!(r>0))throw new TypeError(`breaker.openMs 必须为正数,收到 ${r}`);let i="closed",s=0,a=0,u=!1,l=0,c=0,p=R=>{if(R===i)return;let y=i;if(i=R,t.onStateChange!==void 0)try{t.onStateChange(R,y)}catch{}},f=()=>{a=e.now(),u=!1,l+=1,p("open")},g=()=>{i==="open"&&e.now()-a>=r&&p("half_open")},b=()=>i==="open"?Math.max(0,r-(e.now()-a)):0;return{state:()=>(g(),i),tryAcquire:()=>(g(),i==="closed"?{ok:!0}:i==="open"?(c+=1,{ok:!1,retryAfterMs:Math.max(1,b())}):u?(c+=1,{ok:!1,retryAfterMs:o}):(u=!0,{ok:!0})),onSuccess:()=>{s=0,i==="half_open"&&(u=!1,p("closed"))},onFailure:()=>{if(i==="half_open"){s=n,f();return}i!=="open"&&(s+=1,s>=n&&f())},onNeutral:()=>{i==="half_open"&&(u=!1)},stats:()=>(g(),{state:i,consecutiveFailures:s,openedTotal:l,rejectedTotal:c,failureThreshold:n,openMs:r,openRemainingMs:b()})}}var to=1e4,no=.1,ro=0,Ei=10;function jn(t={}){let e=t.clock??L,n=t.windowMs??to,r=t.ratio??no,o=t.minRetries??ro;if(!(n>0))throw new TypeError(`retryBudget.windowMs 必须为正数,收到 ${n}`);if(!(r>=0))throw new TypeError(`retryBudget.ratio 必须为非负数,收到 ${r}`);if(!(o>=0))throw new TypeError(`retryBudget.minRetries 必须为非负数,收到 ${o}`);let i=Math.max(1,n/Ei),s=[],a=0,u=0,l=()=>{let p=e.now(),f=p-n;for(;s.length>0&&s[0].startAt+i<=f;)s.shift();let g=Math.floor(p/i)*i,b=s[s.length-1];if(b!==void 0&&b.startAt===g)return b;let R={startAt:g,requests:0,retries:0};return s.push(R),R},c=()=>{l();let p=0,f=0;for(let g of s)p+=g.requests,f+=g.retries;return{requests:p,retries:f}};return{noteRequest:()=>{l().requests+=1},tryAcquireRetry:()=>{let p=l(),{requests:f,retries:g}=c();return g+1<=f*r+o?(p.retries+=1,a+=1,!0):(u+=1,!1)},stats:()=>{let{requests:p,retries:f}=c();return{windowMs:n,ratio:r,minRetries:o,requests:p,retries:f,allowedTotal:a,deniedTotal:u}}}}var oo=1024,io=1e4;function qn(t,e){let n=e.clock??L,r=e.ratePerMinute;if(!(r>0)||!Number.isFinite(r))throw new TypeError(`tokenBucket.ratePerMinute 必须为正有限数,收到 ${r}`);let o=e.burst??r,i=e.maxQueue??oo,s=e.queueTimeoutMs??io;if(!(o>=1))throw new TypeError(`tokenBucket.burst 必须 ≥ 1,收到 ${o}`);if(!(i>=0))throw new TypeError(`tokenBucket.maxQueue 必须为非负数,收到 ${i}`);if(!(s>0))throw new TypeError(`tokenBucket.queueTimeoutMs 必须为正数,收到 ${s}`);let a=r/6e4,u=o,l=n.now(),c=!1,p,f=0,g=0,b=[],R=()=>{let m=n.now(),E=Math.max(0,m-l);l=m,u=Math.min(o,u+E*a)},y=m=>{m.timer!==void 0&&n.clearTimeout(m.timer),m.signal!==void 0&&m.onAbort!==void 0&&m.signal.removeEventListener("abort",m.onAbort)},k=()=>{for(R();b.length>0&&u>=1;){let m=b.shift();y(m),u-=1,g+=1,m.resolve()}x()},x=()=>{if(c||b.length===0||p!==void 0)return;let m=Math.max(0,1-u),E=Math.max(1,Math.ceil(m/a));p=n.setTimeout(()=>{p=void 0,k()},E)},_=()=>`tokens ${u.toFixed(2)}/${o} @ ${r}/min, queued ${b.length}/${i}`;return{acquire:m=>c?Promise.reject(new B("closed",t)):m?.aborted===!0?Promise.reject(ge(m)):(R(),b.length===0&&u>=1?(u-=1,f+=1,Promise.resolve()):b.length>=i?Promise.reject(new B("saturated",t,{detail:_()})):new Promise((E,v)=>{let w={resolve:E,reject:v,timer:void 0,signal:m,onAbort:void 0},T=()=>{let W=b.indexOf(w);return W===-1?!1:(b.splice(W,1),y(w),!0)};Number.isFinite(s)&&(w.timer=n.setTimeout(()=>{T()&&v(new B("queue_timeout",t,{detail:`waited ${s}ms; ${_()}`}))},s)),m!==void 0&&(w.onAbort=()=>{T()&&v(ge(m))},m.addEventListener("abort",w.onAbort,{once:!0})),b.push(w),x()})),stats:()=>(R(),{tokens:u,queued:b.length,ratePerMinute:r,burst:o,grantedImmediately:f,grantedAfterWait:g}),close:()=>{if(c)return;c=!0,p!==void 0&&(n.clearTimeout(p),p=void 0);let m=b.splice(0,b.length);for(let E of m)y(E),E.reject(new B("closed",t))}}}function uo(t){try{let e=typeof t=="string"?new URL(t):t instanceof URL?t:new URL(t.url);return e.host!==""?e.host:"(unknown)"}catch{return"(invalid)"}}function so(){let t={};for(let e of at)t[e]=0;return t}function ao(t,e){return e?.aborted===!0?!0:t?.name==="AbortError"}function Ti(t,e){let n=t.getReader(),r=!1,o=()=>{r||(r=!0,e())};return new ReadableStream({async pull(i){let s;try{s=await n.read()}catch(a){o(),i.error(a);return}if(s.done){o(),i.close();return}i.enqueue(s.value)},async cancel(i){o(),await n.cancel(i).catch(()=>{})}})}function Ii(t={}){let e=t.clock??L,n=t.fetch??fetch,r=t.dispatcher,o=new Map,i=!1,s=y=>{if(t.onEvent!==void 0)try{t.onEvent(y)}catch{}},a=t.retryBudget!==void 0?jn({...t.retryBudget,clock:e}):void 0,u=a===void 0?void 0:{noteRequest:()=>a.noteRequest(),tryAcquireRetry:()=>{let y=a.tryAcquireRetry();return y||s({type:"retry.budget_denied"}),y},stats:()=>a.stats()},l={...t.retry?.retryAfterJitter!==void 0?{retryAfterJitter:t.retry.retryAfterJitter}:{},...t.retry?.patientJitter!==void 0?{patientJitter:t.retry.patientJitter}:{}},c=y=>{let k=o.get(y);if(k!==void 0)return k;let x={origin:y,bulkhead:Wn(y,{...t.bulkhead??{},clock:e}),breaker:t.breaker!==void 0?Dn({...t.breaker,clock:e,onStateChange:_=>{s(_==="open"?{type:"breaker.opened",origin:y}:_==="half_open"?{type:"breaker.half_open",origin:y}:{type:"breaker.closed",origin:y})}}):void 0,tokens:t.tokenBucket!==void 0?qn(y,{...t.tokenBucket,clock:e}):void 0,requests:0,failures:0,rejected:so()};return o.set(y,x),x},p=(y,k)=>(y.rejected[k.reason]+=1,s({type:"upstream.rejected",origin:y.origin,reason:k.reason,...k.retryAfterMs!==void 0?{retryAfterMs:k.retryAfterMs}:{}}),k),f=(y,k)=>{throw ut(k)?p(y,k):k},g=y=>async(x,_)=>{let O=uo(x),m=c(O);if(i)throw p(m,new B("closed",O));let E=_?.signal??(typeof Request<"u"&&x instanceof Request?x.signal:void 0),v=!1;if(m.breaker!==void 0&&m.breaker.state()==="open"){let I=m.breaker.tryAcquire();if(!I.ok)throw p(m,new B("breaker_open",O,{retryAfterMs:I.retryAfterMs}));v=!0}if(m.tokens!==void 0)try{await m.tokens.acquire(E)}catch(I){v&&m.breaker?.onNeutral(),f(m,I)}if(m.breaker!==void 0&&!v){let I=m.breaker.tryAcquire();if(!I.ok)throw p(m,new B("breaker_open",O,{retryAfterMs:I.retryAfterMs}));v=!0}let w;try{w=await m.bulkhead.acquire(E)}catch(I){return v&&m.breaker?.onNeutral(),f(m,I)}if(m.breaker!==void 0&&m.breaker.state()==="open")throw w(),p(m,new B("breaker_open",O,{retryAfterMs:Math.max(1,m.breaker.stats().openRemainingMs)}));m.requests+=1;let T;try{let I=r!==void 0?{..._??{},dispatcher:r}:_;T=await y(x,I)}catch(I){throw w(),m.breaker!==void 0?ao(I,E)?m.breaker.onNeutral():(m.failures+=1,m.breaker.onFailure()):ao(I,E)||(m.failures+=1),I}if(T.status>=500?(m.failures+=1,m.breaker?.onFailure()):m.breaker?.onSuccess(),T.body===null)return w(),T;let W=Ti(T.body,w);return new Response(W,{status:T.status,statusText:T.statusText,headers:T.headers})};return{fetch:g(n),wrapFetch:g,retryBudget:u,retryPolicy:l,stats:()=>{let y=[],k={inflight:0,queued:0,tokenQueued:0,tokenWaits:0,requests:0,failures:0,rejected:so(),retriesBudgeted:u?.stats().deniedTotal??0,retriesAllowed:u?.stats().allowedTotal??0};for(let _ of o.values()){let O=_.bulkhead.stats(),m=_.tokens?.stats(),E=_.breaker?.stats(),v=E?.state??"disabled",w={origin:_.origin,inflight:O.inflight,queued:O.queued,tokenQueued:m?.queued??0,tokenWaits:m?.grantedAfterWait??0,breakerState:v,breakerStateCode:v==="disabled"?0:Un[v],breakerOpenedTotal:E?.openedTotal??0,requests:_.requests,failures:_.failures,rejected:{..._.rejected}};y.push(w),k.inflight+=w.inflight,k.queued+=w.queued,k.tokenQueued+=w.tokenQueued,k.tokenWaits+=w.tokenWaits,k.requests+=w.requests,k.failures+=w.failures;for(let T of at)k.rejected[T]+=w.rejected[T]}let x=u?.stats();return{closed:i,origins:y,totals:k,...x!==void 0?{retryBudget:x}:{},limits:{maxConcurrent:t.bulkhead?.maxConcurrent??Number.POSITIVE_INFINITY,maxQueue:t.bulkhead?.maxQueue??1024,queueTimeoutMs:t.bulkhead?.queueTimeoutMs??1e4,breaker:t.breaker!==void 0?{failureThreshold:t.breaker.failureThreshold??5,openMs:t.breaker.openMs??3e4}:null,tokenBucket:t.tokenBucket!==void 0?{ratePerMinute:t.tokenBucket.ratePerMinute,burst:t.tokenBucket.burst??t.tokenBucket.ratePerMinute}:null,retryBudget:x!==void 0?{windowMs:x.windowMs,ratio:x.ratio,minRetries:x.minRetries}:null}}},close:()=>{if(!i){i=!0;for(let y of o.values())y.bulkhead.close(),y.tokens?.close()}},get closed(){return i}}}function Mi(t={}){let e=t.connections??256,n=t.keepAliveTimeout??6e4,r=t.pipelining??1;if(!(e>0))throw new TypeError(`agent.connections 必须为正数,收到 ${e}`);if(!(n>0))throw new TypeError(`agent.keepAliveTimeout 必须为正数,收到 ${n}`);if(!(r>=1))throw new TypeError(`agent.pipelining 必须 ≥ 1,收到 ${r}`);return{connections:e,keepAliveTimeout:n,pipelining:r}}function Si(t,e,n={}){let r=t.resolveAlias(e);if(n.boundary!==void 0){let u=Xe(n.boundary,r.providerId,r.providerId);if(u!==void 0)throw new Ve(u)}let o=t.createClient(r);if(t.usesGatewayCache){if(r.providerProfile.protocol!=="twp")throw new Error("Gateway cache requires the TWP protocol");return{client:o,resolved:r}}let i=t.fallbacksFor(e),s=n.governor??t.governor;return{client:new Ze({entries:i,createClient:u=>u===i[0]?o:t.createClient(u),...n.onProviderSelected!==void 0?{onProviderSelected:n.onProviderSelected}:{},...n.boundary!==void 0?{boundary:n.boundary}:{},...n.attemptObserver!==void 0?{attemptObserver:n.attemptObserver}:{},...lo(s)}),resolved:r}}function lo(t){return t===void 0?{}:{...t.retryBudget!==void 0?{retryBudget:t.retryBudget}:{},...Object.keys(t.retryPolicy).length>0?{retry:t.retryPolicy}:{}}}function Ai(t){if(t.index===0)return null;let e=t.failures[0];return e===void 0?null:{type:"cost.provider.switched",from:`${e.providerId}/${e.modelName}`,to:`${t.providerId}/${t.modelName}`,reason:e.error.kind,attempts:t.index+1,failures:t.failures.map(n=>({provider:`${n.providerId}/${n.modelName}`,kind:n.error.kind}))}}var Wi={insufficient_balance:"balance_insufficient",quota_exceeded:"quota_exceeded",rate_limited:"rate_limited",plan_concurrency_exceeded:"rate_limited",upstream_timeout:"upstream_timeout",upstream_connect_timeout:"upstream_timeout",upstream_ttfb_timeout:"upstream_timeout",upstream_idle_timeout:"upstream_timeout",upstream_total_timeout:"upstream_timeout"};function Ui(t){return Wi[t]??"api_error"}import{mkdirSync as Fi,writeFileSync as Gi}from"node:fs";import{join as $i}from"node:path";var Nn=class{#e;#t;#o;#i;#r;#n;#a=0;recorded=[];constructor(e){this.#e=e.inner,Qn(this,e.inner),this.#t=e.dir,this.#o=e.name,this.#i=e.source??"unknown";let n=e.env??process.env;this.#r=n.TANSR_RECORD==="1",this.#n=e.now??(()=>new Date)}get enabled(){return this.#r}async*stream(e,n){if(!this.#r){yield*this.#e.stream(e,n);return}this.#a+=1;let r=this.#a,o=[];try{for await(let i of this.#e.stream(e,n))o.push(i),yield i}finally{this.#u(o,r)}}#u(e,n){let r=n===1?`${this.#o}.ndjson`:`${this.#o}-${n}.ndjson`,o=[`# 来源:${rt(this.#i)}`,`# 录制日期:${this.#n().toISOString()}`,"# 由 RecordingModelClient 录制(IRStreamEvent NDJSON;已脱敏)",...e.map(s=>JSON.stringify(ot(s)))];Fi(this.#t,{recursive:!0});let i=$i(this.#t,r);Gi(i,`${o.join(`
|
|
23
23
|
`)}
|
|
24
24
|
`,"utf8"),this.recorded.push({path:i,eventCount:e.length})}};export{Dt as a,yo as b,pn as c,mn as d,fe as e,aa as f,ua as g,da as h,ca as i,$ as j,Ke as k,H as l,kt as m,ze as n,jr as o,F as p,wt as q,qr as r,xt as s,h as t,xn as u,Ui as v,Ce as w,Ft as x,re as y,we as z,ae as A,ee as B,Te as C,Yr as D,ru as E,Ze as F,Nn as G,uo as H,Ii as I,Mi as J,Si as K,lo as L,Ai as M};
|
|
25
|
-
//# sourceMappingURL=tansr-chunk-
|
|
25
|
+
//# sourceMappingURL=tansr-chunk-2C6JKHKM.mjs.map
|